@flopay/js 1.9.13 → 1.9.15
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/README.md +81 -4
- package/dist/{card-setup-B99UpW1_.d.cts → card-setup-Bste6_2o.d.cts} +37 -2
- package/dist/{card-setup-B99UpW1_.d.ts → card-setup-Bste6_2o.d.ts} +37 -2
- package/dist/card-setup.cjs +1 -1
- package/dist/card-setup.d.cts +1 -1
- package/dist/card-setup.d.ts +1 -1
- package/dist/card-setup.mjs +1 -1
- package/dist/chunk-53ZIPQCZ.mjs +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +2 -2
- package/dist/chunk-XDZDZIW2.mjs +0 -1
package/README.md
CHANGED
|
@@ -329,6 +329,46 @@ try {
|
|
|
329
329
|
}
|
|
330
330
|
```
|
|
331
331
|
|
|
332
|
+
### Server-side card gateways (Worldpay)
|
|
333
|
+
|
|
334
|
+
The billing API can process hosted-vault cards through an approved Worldpay
|
|
335
|
+
Corporate Gateway entirely server-side (TeamFloPay/backend#1563), but only for a
|
|
336
|
+
session whose creating client opts in. An inline create that collects payment —
|
|
337
|
+
`PaymentAPI.createAndFetchSession` or `createDetachedSession` in Full mode
|
|
338
|
+
without `tokenizedData` — sends:
|
|
339
|
+
|
|
340
|
+
```http
|
|
341
|
+
x-flo-sdk-capabilities: worldpay-corporate-gateway-v1
|
|
342
|
+
```
|
|
343
|
+
|
|
344
|
+
The billing API persists that decision for the session's claim, reads, and card
|
|
345
|
+
capture, and may then route its cards to Worldpay. Everything else stays
|
|
346
|
+
provider-neutral, so existing integrations change nothing:
|
|
347
|
+
|
|
348
|
+
- Cards still go through the hosted vault widget, from the embedded `vault`
|
|
349
|
+
block or `getVaultCapture()`. There is no Worldpay browser SDK, key, or
|
|
350
|
+
credential: `gateways.worldpayCorporateGateway` carries
|
|
351
|
+
`publishableKey: null` and no enabled methods, and it never appears in the
|
|
352
|
+
normalized `providers` list.
|
|
353
|
+
- Outcomes arrive as the same `complete` / `decline` / `error` widget events.
|
|
354
|
+
Declines carry Flo's decline taxonomy, never a raw refusal code. An ambiguous
|
|
355
|
+
submission stays pending until the billing API reconciles it; the hosted form
|
|
356
|
+
reports that as an `error`, never a success, and a later session read returns
|
|
357
|
+
the reconciled status.
|
|
358
|
+
- In the merged billing API version, Worldpay takes one-time item carts only
|
|
359
|
+
and offers no 3DS authentication, stored credentials, or card setup; the
|
|
360
|
+
billing API keeps subscription carts on another card gateway. No
|
|
361
|
+
client-visible authentication continuation exists for Worldpay.
|
|
362
|
+
|
|
363
|
+
Auto, Confirm, and pre-tokenized creates send no capability (they charge a
|
|
364
|
+
stored payment method, which the Worldpay route does not accept) and keep the
|
|
365
|
+
released Stripe and PayPal routing. So do `createCheckoutSession` and
|
|
366
|
+
`createCheckoutSessionWithRetries`, which redirect to a hosted page this SDK
|
|
367
|
+
does not render. Clients that never send the token, including older SDKs, are
|
|
368
|
+
never routed to Worldpay. If you build a create request yourself for a checkout
|
|
369
|
+
this SDK renders, send `resolveSessionCreateCapabilities(draft)` from
|
|
370
|
+
`@flopay/shared` in `FLO_SDK_CAPABILITIES_HEADER`.
|
|
371
|
+
|
|
332
372
|
## API Reference
|
|
333
373
|
|
|
334
374
|
## Privacy-safe operational telemetry
|
|
@@ -437,7 +477,8 @@ payment-success outcomes.
|
|
|
437
477
|
```ts
|
|
438
478
|
// 1. Obtain the vault capture block — use an embedded block when supplied, or
|
|
439
479
|
// fetch it through the explicit recovery route for a session whose Stripe
|
|
440
|
-
// enabledPaymentMethods explicitly includes `card
|
|
480
|
+
// enabledPaymentMethods explicitly includes `card`, or that advertises a
|
|
481
|
+
// server-side card gateway (`gateways.worldpayCorporateGateway`). The first
|
|
441
482
|
// argument is the checkout session id (`getVaultCapture(checkoutSessionId, nonce?)`):
|
|
442
483
|
const vault = session.vault ??
|
|
443
484
|
await new PaymentAPI(billingApiUrl).getVaultCapture(checkoutSessionId, nonce);
|
|
@@ -468,6 +509,14 @@ capture.on('error', (e) => onError(e.message));
|
|
|
468
509
|
await capture.mount(container, { html, messageToken, expectedOrigin });
|
|
469
510
|
```
|
|
470
511
|
|
|
512
|
+
`e.intentId` is the processing gateway's own reference for the attempt. It is a
|
|
513
|
+
Stripe PaymentIntent (or SetupIntent) id only when Stripe took the card; when
|
|
514
|
+
the session advertises a server-side card gateway such as
|
|
515
|
+
`gateways.worldpayCorporateGateway`, it may be an opaque processor order
|
|
516
|
+
reference instead. Reconcile by `paymentId` and the session rather than
|
|
517
|
+
treating it as a Stripe object. `FloPayCheckout` and `SplitCardForm` omit
|
|
518
|
+
`paymentIntentId` from `onComplete` for those sessions.
|
|
519
|
+
|
|
471
520
|
`capture.applyTheme(theme)` re-skins the mounted widget without remounting it.
|
|
472
521
|
Pass the `VaultCardThemeColors` the React components compute: the flat keys
|
|
473
522
|
every hosted asset understands plus the optional `submitButton` snapshot
|
|
@@ -479,14 +528,40 @@ directive so a widget that becomes ready later replays it. Theming is cosmetic
|
|
|
479
528
|
and failure-tolerant — an unsupported member never blocks capture or touches
|
|
480
529
|
card data.
|
|
481
530
|
|
|
531
|
+
`capture.setSubmitLabel(label)` sets the hosted card form's final submit
|
|
532
|
+
wording live (billing API v1.9.35+), for example `'Pay $10'`, without
|
|
533
|
+
remounting the widget or clearing entered card data. Pass final,
|
|
534
|
+
already-localized plain text; the hosted form normalizes it, renders it as
|
|
535
|
+
inert text, and shows its session default — `CONFIRM PAYMENT`, or `ADD CARD`
|
|
536
|
+
for card setup — for blank or invalid text. `capture.setSubmitLabel(null)` is
|
|
537
|
+
the explicit reset to that default, and a `submitLabel` mount option sets the
|
|
538
|
+
initial wording. The adapter retains the latest label and replays it
|
|
539
|
+
every time the widget reports an authenticated `ready`, so a late or remounted
|
|
540
|
+
form still receives it. Because the directive carries merchant text, it is
|
|
541
|
+
posted only when the vault block supplied both `messageToken` and
|
|
542
|
+
`expectedOrigin`, bound to the mounted `sessionId`, with the exact
|
|
543
|
+
`expectedOrigin` as the `postMessage` target — never `'*'`:
|
|
544
|
+
|
|
545
|
+
```ts
|
|
546
|
+
{ source: 'flopay-vault-host', type: 'submitLabel', sessionId, messageToken, label }
|
|
547
|
+
```
|
|
548
|
+
|
|
549
|
+
A widget mounted without those fields (an older backend) keeps its default.
|
|
550
|
+
The label is never added to telemetry or breadcrumbs. The other host directives
|
|
551
|
+
(theme, submit gate, field order, and the 3DS `action_completed` signal) also
|
|
552
|
+
target the exact `expectedOrigin` when one was supplied, falling back to `'*'`
|
|
553
|
+
only for a widget mounted without it.
|
|
554
|
+
|
|
482
555
|
Calling `cardCapture()` emits the separate `vault.capture.requested` lifecycle
|
|
483
556
|
signal. The machine-duration `vault_ready` measurement starts when `mount()`
|
|
484
557
|
begins and ends at the first validated widget `ready` message, so time before
|
|
485
558
|
mount (including buyer time on a payment-method picker) is excluded. Duplicate
|
|
486
559
|
`ready` messages do not emit additional readiness samples.
|
|
487
560
|
|
|
488
|
-
`CardCaptureAdapter` methods: `mount(container, { html, messageToken?, expectedOrigin? })`,
|
|
489
|
-
`on(event, handler)` (`'ready' | 'complete' | 'decline' | 'error'`), `unmount()
|
|
561
|
+
`CardCaptureAdapter` methods: `mount(container, { html, messageToken?, expectedOrigin?, submitLabel? })`,
|
|
562
|
+
`on(event, handler)` (`'ready' | 'complete' | 'decline' | 'error'`), `unmount()`, plus
|
|
563
|
+
the optional live controls `applyTheme()`, `setSubmitGate()`, `setCardFieldOrder()`,
|
|
564
|
+
and `setSubmitLabel()`.
|
|
490
565
|
Outcome events arrive via a `window.postMessage` from the widget shaped
|
|
491
566
|
`{ source: 'flopay-vault', type, sessionId, messageToken?, intentId?, declineReason?, message?, paymentMethod? }`.
|
|
492
567
|
The widget is injected **same-window**, so `source` alone is forgeable: the
|
|
@@ -496,7 +571,9 @@ supplied), or that arrive from a non-matching `expectedOrigin` (when set).
|
|
|
496
571
|
|
|
497
572
|
> Backend contract: TeamFloPay/backend#823. Starting with SDK 1.4.9, an explicit
|
|
498
573
|
> `card` entry in `gateways.stripe.enabledPaymentMethods` advertises that hosted
|
|
499
|
-
> capture can be recovered without an embedded `vault` block.
|
|
574
|
+
> capture can be recovered without an embedded `vault` block. A
|
|
575
|
+
> `gateways.worldpayCorporateGateway` entry on an open session advertises the
|
|
576
|
+
> same (TeamFloPay/backend#1563).
|
|
500
577
|
> `PaymentAPI.getVaultCapture()` coalesces concurrent callers, aborts a stalled
|
|
501
578
|
> attempt after ten seconds, and keeps bounded transient-network retry on the
|
|
502
579
|
> idempotent `POST /v1/checkouts/sessions/{id}/vault/capture` route.
|
|
@@ -528,6 +528,12 @@ declare class PciVaultCardCapture implements CardCaptureAdapter {
|
|
|
528
528
|
/** Latest card-field order + autofocus directive to push into the widget. */
|
|
529
529
|
private cardFieldOrder;
|
|
530
530
|
private cardAutoFocus;
|
|
531
|
+
/**
|
|
532
|
+
* Latest merchant submit wording: a label, `null` for the explicit reset to
|
|
533
|
+
* the hosted session default, or `undefined` when the host has never set
|
|
534
|
+
* one — nothing is posted then, so the widget keeps its own default.
|
|
535
|
+
*/
|
|
536
|
+
private submitLabel;
|
|
531
537
|
/** Monotonic start of the current widget mount-to-ready machine interval. */
|
|
532
538
|
private mountStartedAt;
|
|
533
539
|
private vaultReadyReported;
|
|
@@ -566,7 +572,10 @@ declare class PciVaultCardCapture implements CardCaptureAdapter {
|
|
|
566
572
|
* can validate merchant-DOM fields (AVS) first. Stored so `ready` re-pushes it.
|
|
567
573
|
*/
|
|
568
574
|
setSubmitGate(blocked: boolean): void;
|
|
569
|
-
/**
|
|
575
|
+
/**
|
|
576
|
+
* postMessage the current submit-gate state to the widget's document. If it
|
|
577
|
+
* cannot be delivered, the host still validates and surfaces errors on its side.
|
|
578
|
+
*/
|
|
570
579
|
private postSubmitGate;
|
|
571
580
|
/**
|
|
572
581
|
* Push the card-field order + autofocus directive into the widget (live). The
|
|
@@ -576,6 +585,30 @@ declare class PciVaultCardCapture implements CardCaptureAdapter {
|
|
|
576
585
|
setCardFieldOrder(order: VaultCardFieldKey[] | null, autoFocus: boolean): void;
|
|
577
586
|
/** postMessage the current field order + autofocus to the widget's document. */
|
|
578
587
|
private postCardFieldOrder;
|
|
588
|
+
/**
|
|
589
|
+
* Replace the hosted form's final submit wording (live, no remount). The
|
|
590
|
+
* text is forwarded verbatim — the hosted form owns normalization and falls
|
|
591
|
+
* back to its session default for blank or invalid text; `null` is the
|
|
592
|
+
* explicit reset. Stored so `ready` re-pushes it.
|
|
593
|
+
*/
|
|
594
|
+
setSubmitLabel(label: string | null): void;
|
|
595
|
+
/**
|
|
596
|
+
* postMessage the current submit-label directive to the widget's document.
|
|
597
|
+
* Unlike the other host directives it carries merchant text, so it is sent
|
|
598
|
+
* only with the session + message-token binding the hosted form checks, and
|
|
599
|
+
* only to the vault block's exact origin — never to `'*'`.
|
|
600
|
+
*/
|
|
601
|
+
private postSubmitLabel;
|
|
602
|
+
/** The mounted widget's (cross-origin) document window, once its iframe exists. */
|
|
603
|
+
private hostedWindow;
|
|
604
|
+
/** postMessage a host directive to the widget's document once its iframe exists. */
|
|
605
|
+
private postToHostedWindow;
|
|
606
|
+
/**
|
|
607
|
+
* `postMessage` target for the cosmetic host directives: the vault block's
|
|
608
|
+
* exact origin when known. A widget mounted without `expectedOrigin` (e.g. an
|
|
609
|
+
* opaque `srcdoc` form, which no origin can target) falls back to `'*'`.
|
|
610
|
+
*/
|
|
611
|
+
private directiveTargetOrigin;
|
|
579
612
|
private emit;
|
|
580
613
|
/**
|
|
581
614
|
* Render the provider-hosted verification challenge (e.g. Stripe 3DS-2) in a
|
|
@@ -597,7 +630,9 @@ declare class PciVaultCardCapture implements CardCaptureAdapter {
|
|
|
597
630
|
* challenge. The widget responds by POSTing `/3ds/complete` — its
|
|
598
631
|
* sub-300ms sync resolver writes the follow-up attempt row immediately,
|
|
599
632
|
* so the next `/status` poll resolves to a terminal outcome instead of
|
|
600
|
-
* waiting for the eventual provider webhook.
|
|
633
|
+
* waiting for the eventual provider webhook. Best-effort — even if the
|
|
634
|
+
* postMessage fails the widget's poll loop will eventually catch the
|
|
635
|
+
* terminal state from the provider webhook.
|
|
601
636
|
*/
|
|
602
637
|
private postActionCompleted;
|
|
603
638
|
private abandonActionRequiredOverlay;
|
|
@@ -528,6 +528,12 @@ declare class PciVaultCardCapture implements CardCaptureAdapter {
|
|
|
528
528
|
/** Latest card-field order + autofocus directive to push into the widget. */
|
|
529
529
|
private cardFieldOrder;
|
|
530
530
|
private cardAutoFocus;
|
|
531
|
+
/**
|
|
532
|
+
* Latest merchant submit wording: a label, `null` for the explicit reset to
|
|
533
|
+
* the hosted session default, or `undefined` when the host has never set
|
|
534
|
+
* one — nothing is posted then, so the widget keeps its own default.
|
|
535
|
+
*/
|
|
536
|
+
private submitLabel;
|
|
531
537
|
/** Monotonic start of the current widget mount-to-ready machine interval. */
|
|
532
538
|
private mountStartedAt;
|
|
533
539
|
private vaultReadyReported;
|
|
@@ -566,7 +572,10 @@ declare class PciVaultCardCapture implements CardCaptureAdapter {
|
|
|
566
572
|
* can validate merchant-DOM fields (AVS) first. Stored so `ready` re-pushes it.
|
|
567
573
|
*/
|
|
568
574
|
setSubmitGate(blocked: boolean): void;
|
|
569
|
-
/**
|
|
575
|
+
/**
|
|
576
|
+
* postMessage the current submit-gate state to the widget's document. If it
|
|
577
|
+
* cannot be delivered, the host still validates and surfaces errors on its side.
|
|
578
|
+
*/
|
|
570
579
|
private postSubmitGate;
|
|
571
580
|
/**
|
|
572
581
|
* Push the card-field order + autofocus directive into the widget (live). The
|
|
@@ -576,6 +585,30 @@ declare class PciVaultCardCapture implements CardCaptureAdapter {
|
|
|
576
585
|
setCardFieldOrder(order: VaultCardFieldKey[] | null, autoFocus: boolean): void;
|
|
577
586
|
/** postMessage the current field order + autofocus to the widget's document. */
|
|
578
587
|
private postCardFieldOrder;
|
|
588
|
+
/**
|
|
589
|
+
* Replace the hosted form's final submit wording (live, no remount). The
|
|
590
|
+
* text is forwarded verbatim — the hosted form owns normalization and falls
|
|
591
|
+
* back to its session default for blank or invalid text; `null` is the
|
|
592
|
+
* explicit reset. Stored so `ready` re-pushes it.
|
|
593
|
+
*/
|
|
594
|
+
setSubmitLabel(label: string | null): void;
|
|
595
|
+
/**
|
|
596
|
+
* postMessage the current submit-label directive to the widget's document.
|
|
597
|
+
* Unlike the other host directives it carries merchant text, so it is sent
|
|
598
|
+
* only with the session + message-token binding the hosted form checks, and
|
|
599
|
+
* only to the vault block's exact origin — never to `'*'`.
|
|
600
|
+
*/
|
|
601
|
+
private postSubmitLabel;
|
|
602
|
+
/** The mounted widget's (cross-origin) document window, once its iframe exists. */
|
|
603
|
+
private hostedWindow;
|
|
604
|
+
/** postMessage a host directive to the widget's document once its iframe exists. */
|
|
605
|
+
private postToHostedWindow;
|
|
606
|
+
/**
|
|
607
|
+
* `postMessage` target for the cosmetic host directives: the vault block's
|
|
608
|
+
* exact origin when known. A widget mounted without `expectedOrigin` (e.g. an
|
|
609
|
+
* opaque `srcdoc` form, which no origin can target) falls back to `'*'`.
|
|
610
|
+
*/
|
|
611
|
+
private directiveTargetOrigin;
|
|
579
612
|
private emit;
|
|
580
613
|
/**
|
|
581
614
|
* Render the provider-hosted verification challenge (e.g. Stripe 3DS-2) in a
|
|
@@ -597,7 +630,9 @@ declare class PciVaultCardCapture implements CardCaptureAdapter {
|
|
|
597
630
|
* challenge. The widget responds by POSTing `/3ds/complete` — its
|
|
598
631
|
* sub-300ms sync resolver writes the follow-up attempt row immediately,
|
|
599
632
|
* so the next `/status` poll resolves to a terminal outcome instead of
|
|
600
|
-
* waiting for the eventual provider webhook.
|
|
633
|
+
* waiting for the eventual provider webhook. Best-effort — even if the
|
|
634
|
+
* postMessage fails the widget's poll loop will eventually catch the
|
|
635
|
+
* terminal state from the provider webhook.
|
|
601
636
|
*/
|
|
602
637
|
private postActionCompleted;
|
|
603
638
|
private abandonActionRequiredOverlay;
|
package/dist/card-setup.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var B=Object.defineProperty;var fe=Object.getOwnPropertyDescriptor;var Ce=Object.getOwnPropertyNames;var ve=Object.prototype.hasOwnProperty;var Te=(s,e)=>{for(var t in e)B(s,t,{get:e[t],enumerable:!0})},be=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ce(e))!ve.call(s,n)&&n!==t&&B(s,n,{get:()=>e[n],enumerable:!(r=fe(e,n))||r.enumerable});return s};var ke=s=>be(B({},"__esModule",{value:!0}),s);var et={};Te(et,{PaymentAPI:()=>L,PciVaultCardCapture:()=>N});module.exports=ke(et);var a=require("@flopay/shared");function W(s){return typeof s=="string"&&s.trim()?s:void 0}function J(s){if(typeof s=="string")return s.trim()?s:void 0;if(Array.isArray(s))return s.filter(t=>typeof t=="string"&&t.trim().length>0).join("; ")||void 0}function A(s=12e3){let e=Number.isFinite(s)&&s>=0?s:12e3,t=new AbortController,r=setTimeout(()=>t.abort(),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function _e(){return Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function x(s,e){let t=150*2**s,r=Math.round(t*(.75+Math.random()*.5));return new Promise((n,o)=>{let i,u=()=>e.removeEventListener("abort",c),c=()=>{i!==void 0&&clearTimeout(i),u(),o(_e())};if(e.aborted){c();return}i=setTimeout(()=>{u(),n()},r),e.addEventListener("abort",c,{once:!0})})}var Me="flopay_session_display:";var O=new Map;function q(s){return`${Me}${s}`}function j(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function H(s,e,t){if(!s)return;let r=t?.ttlMs??36e5,n={data:e,expiresAt:Date.now()+r},o=j();if(o)try{o.setItem(q(s),JSON.stringify(n));return}catch{}O.set(s,n)}function Q(s){if(!s)return null;let e=j();if(e)try{let r=e.getItem(q(s));if(r){let n=JSON.parse(r);if(n&&typeof n.expiresAt=="number"&&n.expiresAt>Date.now())return n.data;e.removeItem(q(s))}}catch{}let t=O.get(s);if(t){if(t.expiresAt>Date.now())return t.data;O.delete(s)}return null}function X(s){if(!s)return;O.delete(s);let e=j();if(e)try{e.removeItem(q(s))}catch{}}var v=require("@flopay/shared"),Se="/v1/sdk-telemetry/events",K=16,Ae=64,Re=1500,Z=1e3,Ee=64,we="00000000-0000-4000-8000-000000000000",Ie={technical_error:8,lifecycle:32,expected_outcome:32,performance:24};function R(){try{return globalThis.crypto.randomUUID()}catch{let s=new Uint8Array(16);try{globalThis.crypto.getRandomValues(s)}catch{for(let t=0;t<s.length;t+=1)s[t]=Math.floor(Math.random()*256)}s[6]=(s[6]??0)&15|64,s[8]=(s[8]??0)&63|128;let e=[...s].map(t=>t.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}}function Pe(s){try{return new TextEncoder().encode(s).byteLength}catch{return s.length}}function De(s){return JSON.stringify([s.code,s.failureCategory,s.stage,s.provider,s.attempt,s.statusClass,s.requestCategory,s.paymentMethodCategory,s.walletType,s.operationOutcome,s.checkoutMode,s.layout,s.inAppBrowser,s.appFamily,s.popupCapability,s.presentationMode,s.terminalReason])}function b(){return globalThis.performance?.now()??0}var k=class{constructor(e){this.ingestionDisabled=!1;this.queue=[];this.sequence=0;this.flushTimer=null;this.flushInFlight=null;this.reportedFailures=new Map;this.checkoutContext={};this.checkoutStartedAt=null;this.destroyed=!1;this.observers=new Set;this.pageExitHandler=()=>{this.drainQueue()};this.visibilityHandler=()=>{document.visibilityState==="hidden"&&this.flush()};this.eventCounts={technical_error:0,lifecycle:0,expected_outcome:0,performance:0};this.endpoint=`${e.billingApiUrl.replace(/\/+$/,"")}${Se}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=R(),this.merchantEnabled=e.enabled!==!1,this.clock=e.clock??b,this.browserTransportAvailable=typeof window<"u"&&typeof document<"u",this.browserTransportAvailable&&(window.addEventListener("pagehide",this.pageExitHandler),document.addEventListener("visibilitychange",this.visibilityHandler))}log(e){this.notify({...e,class:"lifecycle"}),this.canCollect()&&this.enqueue((0,v.buildTelemetryLogEvent)({...this.checkoutContext,...e,eventId:R(),sequence:this.sequence++}))}error(e){if(this.notify({...e,class:"technical_error"}),!this.canCollect())return;let t=(0,v.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:we,sequence:0}),r=De(t),n=this.now();this.pruneReportedFailures(n);let o=this.reportedFailures.get(r);if(o!==void 0&&n>=o&&n-o<Z){this.log({name:"operation.deduplicated",stage:e.stage,provider:e.provider,paymentMethodCategory:e.paymentMethodCategory,attempt:e.attempt,inAppBrowser:e.inAppBrowser,appFamily:e.appFamily,popupCapability:e.popupCapability,presentationMode:e.presentationMode,terminalReason:e.terminalReason});return}this.rememberReportedFailure(r,n),this.enqueue((0,v.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:R(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue((0,v.buildTelemetryPerformanceEvent)({...this.checkoutContext,...e,eventId:R(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue((0,v.buildTelemetryTerminalEvent)({...this.checkoutContext,...e,eventId:R(),sequence:this.sequence++})),e.outcome!=="action_required"&&this.checkoutStartedAt!==null)){let t=this.checkoutStartedAt;this.checkoutStartedAt=null,this.performance({...e,stage:"total_journey",durationMs:Math.max(0,this.now()-t),durationMode:"total"})}}now(){try{return this.clock()}catch{return b()}}subscribe(e){return this.destroyed?()=>{}:(this.observers.add(e),()=>this.observers.delete(e))}notify(e){if(!this.destroyed)for(let t of this.observers)try{t(e)}catch{}}pruneReportedFailures(e){for(let[t,r]of this.reportedFailures)(e<r||e-r>=Z)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=Ee;){let r=this.reportedFailures.keys().next();if(r.done)break;this.reportedFailures.delete(r.value)}this.reportedFailures.set(e,t)}setCheckoutContext(e){this.checkoutContext={checkoutMode:e.checkoutMode,layout:e.layout}}beginCheckout(e={}){return this.canCollect()?(this.drainQueue(),this.setCheckoutContext(e),this.sequence=0,this.reportedFailures.clear(),this.eventCounts={technical_error:0,lifecycle:0,expected_outcome:0,performance:0},this.checkoutStartedAt=this.now(),this.checkoutStartedAt):0}enqueue(e){if(this.canCollect()&&!(this.queue.length>=Ae||this.eventCounts[e.class]>=Ie[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=K){this.flush();return}this.scheduleFlush()}}canCollect(){return this.browserTransportAvailable&&this.merchantEnabled&&!this.ingestionDisabled&&!this.destroyed}async flush(){if(this.flushInFlight!==null)return this.flushInFlight;if(!this.browserTransportAvailable||this.destroyed||this.ingestionDisabled||this.queue.length===0)return;this.clearFlushTimer();let e=this.queue.splice(0,K);return this.flushInFlight=this.sendBatch(e).finally(()=>{this.flushInFlight=null,this.queue.length>0&&this.scheduleFlush()}),this.flushInFlight}destroy(){this.destroyed||(this.drainQueue(),this.destroyed=!0,this.clearFlushTimer(),this.browserTransportAvailable&&(window.removeEventListener("pagehide",this.pageExitHandler),document.removeEventListener("visibilitychange",this.visibilityHandler)),this.queue.splice(0),this.reportedFailures.clear(),this.observers.clear())}disable(){this.merchantEnabled=!1,this.queue.splice(0),this.reportedFailures.clear(),this.clearFlushTimer()}drainQueue(){if(!(!this.browserTransportAvailable||this.destroyed||this.ingestionDisabled||this.queue.length===0))for(this.clearFlushTimer();this.queue.length>0;){let e=this.queue.splice(0,K);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=(0,v.serializeTelemetryBatch)(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:R()});if(Pe(t)>v.TELEMETRY_MAX_BATCH_BYTES)return;let r=typeof AbortController>"u"?null:new AbortController,n=null;try{let o=fetch(this.endpoint,{method:"POST",headers:{"content-type":"text/plain;charset=UTF-8"},body:t,credentials:"omit",keepalive:!0,referrerPolicy:"no-referrer",signal:r?.signal}).then(async c=>{if(c.status!==202)return null;let l=null;try{l=await c.json()}catch{}return l?.status==="disabled"?"disabled":null}).catch(()=>null),i=new Promise(c=>{n=setTimeout(()=>{r?.abort(),c(null)},Re)});await Promise.race([o,i])==="disabled"&&this.disableFromIngestion()}catch{}finally{n&&clearTimeout(n)}}disableFromIngestion(){this.ingestionDisabled=!0,this.queue.splice(0),this.reportedFailures.clear(),this.clearFlushTimer()}scheduleFlush(){this.flushTimer||this.destroyed||this.ingestionDisabled||(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush()},0))}clearFlushTimer(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null)}},ee=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),te=globalThis;te[ee]===void 0&&Object.defineProperty(te,ee,{configurable:!0,enumerable:!1,writable:!1,value:s=>new k(s)});var re=0,xe=500,Oe=15e3,qe=3e3,Fe=1e4,Ue=1e4;function Le(s){return typeof s=="object"&&s!==null}function E(s,e){return W(s?.[e])}function se(s,e){return J(s?.[e])}function Ve(s,e){let t=s?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function ie(s){return new Promise(e=>setTimeout(e,s))}function Ne(s){return s instanceof Error&&s.name==="AbortError"}function F(){return new a.FloPayError("Checkout is still processing. Please try again shortly.","api_error",{code:"checkout_processing_timeout"})}async function _(s,e){let t=await s.json().catch(()=>null),r=Le(t?.error)?t.error:null,n=se(t,"message")??se(r,"message")??e,o=E(t,"code")??E(t,"gatewayErrorCode")??E(r,"code")??`http_${s.status}`;return new a.FloPayError(n,"api_error",{code:o,statusCode:s.status})}async function ze(s){let e=s.status===400?await s.clone().json().catch(()=>null):null;return(0,a.classifyPaymentRejection)(s.status,e)}function ne(s){return s===400||s===422}var U=2;async function $(s,e,t=U,r,n){let o;for(let i=0;;i++)try{return n?.(i),await fetch(s,e)}catch(u){if(e?.signal?.aborted||u instanceof Error&&u.name==="AbortError")throw u;if(o=u,i>=t)throw o;try{r?.(i+1)}catch{}await ie(150*2**i)}}var Be=Symbol.for("@flopay/js.session-create.telemetry.v1");function je(s){return s[Be]}function He(s){return"now"in s||"onFirstByte"in s||"onSessionCreateFailure"in s||"onRetry"in s}function ae(s){let e=(0,a.isCardHolderNamePlaceholder)(s.firstName,s.lastName);return{userId:s.userId,firstName:e?null:s.firstName??null,lastName:e?null:s.lastName??null,email:s.email,country:s.country??null,gender:s.gender??null,city:s.city??null,state:s.state??null,zip:s.zip??null,addressLine1:s.addressLine1??null,addressLine2:s.addressLine2??null}}function ce(s,e){e.checkoutMetadata!==void 0&&(s.checkoutMetadata=e.checkoutMetadata),e.tagsData&&(s.tagsData=e.tagsData),e.utmMetadata&&e.utmMetadata.length>0&&(s.utmMetadata=e.utmMetadata),e.avsCheck!==void 0&&(s.avsCheck=e.avsCheck),e.checkoutType&&(s.checkoutType=e.checkoutType),e.checkoutLayout&&(s.checkoutLayout=e.checkoutLayout),e.avsConfig&&(s.avsConfig=e.avsConfig)}function Ke(s,e){let t={clientId:s.clientId,checkoutVersion:a.SDK_VERSION,successUrl:s.successUrl,cancelUrl:s.cancelUrl,currency:e,checkoutMode:"full",deferDataAttachment:!0};return s.captureMethod==="manual"&&(t.captureMethod=s.captureMethod),s.account.country&&(t.accountData={country:s.account.country}),ce(t,s),t}function oe(s,e,t){return{currency:e,products:t.map(r=>(0,a.buildProductPayload)(r,e)),couponCodes:s.couponCodes??[],accountData:ae(s.account)}}function $e(s,e,t){return{currency:e,products:t.map(r=>(0,a.buildProductPayload)(r,e)),couponCodes:s.couponCodes??[]}}function Ge(s){let e={},t=(0,a.isCardHolderNamePlaceholder)(s.firstName,s.lastName);for(let[r,n]of Object.entries(s)){if(t&&r.endsWith("Name")||typeof n!="string")continue;let o=n.trim();o&&(e[r]=o)}return{accountData:e}}var M=class M{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let r=He(t);this.telemetryHooks=r?t:void 0,this.directTelemetry=r||t.telemetry===!1?void 0:new k({billingApiUrl:this.baseUrl,sdkVersion:a.SDK_VERSION})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,r,n,o="unknown"){let i=(0,a.classifyTelemetryFailure)(e,t);this.directTelemetry?.error({...i,stage:r,requestCategory:n,paymentMethodCategory:o})}reportAccountSnapshotFailure(e,t){let r=(0,a.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED");if(t==="best_effort"&&r.errorCode==="REQUEST_TIMEOUT"){this.directTelemetry?.log({name:"operation.fallback",stage:"processing",requestCategory:"account_snapshot",statusClass:"timeout"});return}this.directTelemetry?.error({...r,stage:"processing",requestCategory:"account_snapshot",paymentMethodCategory:"unknown"})}telemetryTimestamp(){try{return this.telemetryHooks?.now?.()??this.directTelemetry?.now()??b()}catch{return b()}}beginDirectTelemetryCheckout(e){!this.directTelemetry||this.directTelemetryCheckoutId===e||(this.directTelemetryCheckoutId=e,this.directTelemetry.beginCheckout())}beginDirectTelemetryOperation(){this.directTelemetry&&(this.directTelemetryCheckoutId=void 0,this.directTelemetry.beginCheckout())}adoptDirectTelemetryCheckout(e){e&&(this.directTelemetryCheckoutId=e)}async getCheckoutSession(e,t){return this.fetchCheckoutSession(e,t)}async fetchCheckoutSession(e,t,r=!0){this.beginDirectTelemetryCheckout(e);let n=this.telemetryTimestamp(),o=n,i=0;this.directTelemetry?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let u={[a.FLO_SDK_VERSION_HEADER]:a.SDK_VERSION};t&&(u["x-checkout-session-token"]=t);try{let c=await $(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:u},U,m=>{this.telemetryHooks?.onRetry?.("session_read",m),this.directTelemetry?.log({name:"operation.retry",stage:"session_read",requestCategory:"session_read",attempt:m})},m=>{i=m,o=this.telemetryTimestamp()}),l=Math.max(0,this.telemetryTimestamp()-o);try{this.telemetryHooks?.onFirstByte?.(l,i)}catch{}let d=`${Math.floor(c.status/100)}xx`;if(this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:d,attempt:i}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:l,durationMode:"machine",requestCategory:"session_read",statusClass:d,attempt:i}),!c.ok)throw await _(c,"Failed to get checkout session");let p=await c.json();return this.directTelemetry?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:d}),this.directTelemetry?.performance({stage:"session_complete",durationMs:Math.max(0,this.telemetryTimestamp()-n),durationMode:"machine",requestCategory:"session_read",statusClass:d}),{...p,data:this.mergeCachedDisplayData(p.data)}}catch(c){throw r&&this.directTelemetry?.error({...(0,a.classifyTelemetryFailure)(c,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),c}}cacheSessionDisplayData(e,t,r){H(e,t,r)}clearSessionDisplayData(e){X(e)}async getVaultCapture(e,t){let r=`${this.baseUrl}\0${e}\0${t??""}`,n=M.activeVaultCaptureRequests.get(r);if(n)return n;let o=this.requestVaultCapture(e,t);M.activeVaultCaptureRequests.set(r,o);try{return await o}finally{M.activeVaultCaptureRequests.get(r)===o&&M.activeVaultCaptureRequests.delete(r)}}async requestVaultCapture(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(),Ue);this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"vault.capture.requested",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card"});let i={"Content-Type":"application/json"};t&&(i["x-checkout-session-token"]=t);try{let u=await $(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:i,signal:r.signal},U,l=>{this.telemetryHooks?.onRetry?.("vault_capture",l),this.directTelemetry?.log({name:"operation.retry",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card",attempt:l})});if(!u.ok)throw await _(u,"Failed to load the secure card form");let c=await u.json();return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(c)}catch(u){let c=r.signal.aborted?new a.FloPayError("Timed out while loading the secure card form. Please try again.","api_error",{code:"vault_capture_timeout"}):u;throw this.reportDirectFailure(c,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),c}finally{clearTimeout(n)}}async getUnifiedCheckoutSession(e,t){let r=await this.getCheckoutSession(e,t);return this.normalizeCheckoutSessionResponse(r)}async getUnifiedCheckoutSessionForRecovery(e,t){let r=await this.fetchCheckoutSession(e,t,!1);return this.normalizeCheckoutSessionResponse(r)}normalizeCheckoutSessionResponse(e){let t=this.normalizeRawSession(e.data),r=e.vault;return r&&t.data.session&&(t.data.session.vault=this.toVaultBlock(r)),t}async processPayment(e,t,r){this.beginDirectTelemetryCheckout(t.sessionId);let n=t.paymentMethodCategory??"unknown";if(!t.nonce)throw this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:n}),new a.FloPayError("processPayment requires `nonce` \u2014 pass the value returned from session creation.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.processing.started",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:n});let{nonce:i,paymentMethodCategory:u,...c}=t,l;try{l=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(t.sessionId)}/process`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":i},body:JSON.stringify(c)})}catch(d){if(Ne(d))throw this.reportDirectFailure(d,"PAYMENT_PROCESSING_FAILED","processing","process_payment",n),d;l=await this.reconcileProcessPayment(t.sessionId,{...r,nonce:i,paymentMethodCategory:n})}if(!l.ok&&l.status!==202){let d=await ze(l);return d?this.directTelemetry?.terminal({outcome:d,stage:"processing",requestCategory:"process_payment",statusClass:"4xx",paymentMethodCategory:n}):this.directTelemetry?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",requestCategory:"process_payment",statusClass:(0,a.telemetryStatusClass)(l.status),failureCategory:l.status>=500?"server_error":void 0,paymentMethodCategory:n}),l}try{let d=await this.resolveProcessResponse(l,t.sessionId,{...r,nonce:i,paymentMethodCategory:n});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:(0,a.telemetryStatusClass)(d.status),paymentMethodCategory:n}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"process_payment",statusClass:(0,a.telemetryStatusClass)(d.status),paymentMethodCategory:n}),d}catch(d){throw d instanceof a.FloPayError&&d.code==="checkout_processing_timeout"||this.reportDirectFailure(d,"PAYMENT_PROCESSING_FAILED","processing","process_payment",n),d}}async patchAccountSnapshot(e,t,r,n){this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let i=n?.timeoutMs??Fe,u=new AbortController,c=()=>u.abort();n?.signal&&(n.signal.aborted?u.abort():n.signal.addEventListener("abort",c,{once:!0}));let l=setTimeout(()=>u.abort(),i);try{let d;try{d=await $(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/account`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(r),signal:u.signal},U,p=>{this.telemetryHooks?.onRetry?.("account_snapshot",p),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:p})})}finally{clearTimeout(l),n?.signal?.removeEventListener("abort",c)}if(!d.ok)throw await _(d,"Failed to persist account snapshot");this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"account_snapshot",statusClass:"2xx"})}catch(d){throw this.reportAccountSnapshotFailure(d,n?.telemetryMode??"blocking"),d}}async createSessionIntent(e,t,r,n){if(!t)throw new a.FloPayError("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=r,i=o.paymentMethodType,u=typeof i=="string"&&i.trim().toLowerCase()==="card",c=typeof i=="string"&&i.length>0&&!u&&(typeof o.paymentMethodId=="string"||o.paymentMethodId===null),l=o.provider==="stripe"&&(o.paymentMethodCategory==="wallet"||o.paymentMethodCategory==="apm")&&(o.intentKind==="payment"||o.intentKind==="setup"),d=o.provider==="paypal"&&o.paymentMethodCategory==="wallet"&&o.paymentMethodId===null&&(o.paymentMethodType==="paypal"&&o.intentKind==="payment"||o.paymentMethodType===a.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&(o.intentKind==="payment"||o.intentKind==="setup"));if(!c||!l&&!d)throw new a.FloPayError("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let p=o.authorizationAttemptId;if(p!==void 0&&!(0,a.isUuidV4)(p))throw new a.FloPayError("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let m=(0,a.isUuidV4)(p)?p:(0,a.randomUuidV4)();this.beginDirectTelemetryCheckout(e);let f=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.intent.started",stage:"processing",requestCategory:"intent_create"});let g={"Content-Type":"application/json","x-checkout-session-token":t,[a.IDEMPOTENCY_KEY_HEADER]:n?.idempotencyKey||m},T=!1;try{let y=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:g,body:JSON.stringify({...r,authorizationAttemptId:m}),signal:n?.signal});if(!y.ok){T=!0;let z=await _(y,"Failed to create checkout intent"),ge=(0,a.classifyTelemetryFailure)(z,"PAYMENT_PROCESSING_FAILED");throw ne(z.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...ge,stage:"processing",requestCategory:"intent_create"}),z}let w=(await y.json()).data;if(!w||typeof w!="object")throw new a.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let h=w,Y=h.paymentMethodType,me=(h.paymentMethodCategory==="wallet"||h.paymentMethodCategory==="apm")&&typeof Y=="string"&&Y.trim().toLowerCase()!=="card"&&(typeof h.paymentMethodId=="string"||h.paymentMethodId===null)&&typeof h.providerObjectId=="string",pe=h.provider==="stripe"&&(h.intentKind==="payment"||h.intentKind==="setup")&&typeof h.clientSecret=="string",ye=h.provider==="paypal"&&h.paymentMethodCategory==="wallet"&&h.paymentMethodId===null&&(h.paymentMethodType==="paypal"&&h.intentKind==="payment"&&(h.providerObjectType==="order"||h.providerObjectType==="subscription")||h.paymentMethodType===a.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&h.intentKind==="payment"&&h.providerObjectType==="order"||h.paymentMethodType===a.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&h.intentKind==="setup"&&h.providerObjectType==="setup_token")&&h.clientSecret===null,he=h.provider===r.provider&&h.paymentMethodCategory===r.paymentMethodCategory&&h.paymentMethodType===r.paymentMethodType&&h.paymentMethodId===r.paymentMethodId&&h.intentKind===r.intentKind;if(!me||!pe&&!ye||!he)throw new a.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:(0,a.telemetryStatusClass)(y.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-f),durationMode:"machine",requestCategory:"intent_create",statusClass:(0,a.telemetryStatusClass)(y.status)}),h}catch(y){throw T||this.reportDirectFailure(y,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),y}}async reportSessionIntentDecline(e,t,r,n){if(!t)throw new a.FloPayError("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=r,i=o.providerDeclineReason,u=o.paymentMethodType,c=o.providerIntentId,l=typeof i=="string"&&/^[a-z0-9][a-z0-9_.:-]{0,63}$/i.test(i)&&!/^(?:pm|pi|seti|tok|src|cus|sess|sk|pk)_/i.test(i),d=typeof u=="string"&&u.length>0&&u.trim().toLowerCase()!=="card"&&l,p=o.provider==="stripe"&&(o.paymentMethodCategory==="wallet"||o.paymentMethodCategory==="apm")&&(c===void 0||typeof c=="string"&&/^pi_[a-z0-9_]{1,252}$/i.test(c)),m=o.provider==="paypal"&&o.paymentMethodCategory==="wallet"&&o.paymentMethodType==="paypal"&&c===void 0;if(!d||!p&&!m)throw new a.FloPayError("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let f=m?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:i}:{provider:"stripe",paymentMethodCategory:o.paymentMethodCategory,paymentMethodType:o.paymentMethodType,providerDeclineReason:i,...typeof c=="string"?{providerIntentId:c}:{}},g=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents/decline`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(f),signal:n?.signal});if(!g.ok)throw await _(g,"Failed to report checkout decline")}async getPaymentsByEmail(e,t){this.beginDirectTelemetryOperation();let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved"});let n=t?.page??1,o=t?.limit??1,i=new URLSearchParams({email:e,page:String(n),limit:String(o),sortField:"createdAt",sortDirection:"DESC"});try{let u=await fetch(`${this.baseUrl}/v1/payments?${i.toString()}`,{method:"GET",signal:t?.signal,keepalive:!0});if(!u.ok)throw new a.FloPayError("Failed to fetch payments","api_error",{statusCode:u.status});let c=await u.json();return this.directTelemetry?.log({name:"operation.recovery.completed",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),this.directTelemetry?.performance({stage:"recovery",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),c}catch(u){throw this.reportDirectFailure(u,"RECOVERY_FAILED","recovery","other","saved"),u}}async createAndFetchSession(e){if((0,a.isDetachedSessionEligible)(e)){let o=e.account.email?.trim();if(o&&!(0,a.isValidEmail)(o))throw new a.FloPayError("Buyer email must be valid when supplied.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"});return(await this.createDetachedSession(e)).claimed}this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),r=A(e.timeoutMs??12e3),n={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});try{let o=await this.createAndFetchSessionRequest(e,r.signal,n);return this.adoptDirectTelemetryCheckout(o.data.session?.id),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:n.statusClass}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:n.statusClass,attempt:n.attempt}),o}catch(o){throw this.reportSessionCreateFailure(o,t,n),o}finally{r.clear()}}async createAndFetchSessionRequest(e,t,r){let n=e.products??(0,a.foldIntoProducts)(e.items,e.subscriptions);(0,a.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:n});let o=(0,a.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,n);if(!o)throw new a.FloPayError("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let i={clientId:e.clientId,checkoutVersion:a.SDK_VERSION,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:o,checkoutMode:e.checkoutMode??"full",products:n.map(p=>(0,a.buildProductPayload)(p,o)),accountData:ae(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(i.captureMethod=e.captureMethod),e.tokenizedData&&(i.tokenizedData=e.tokenizedData),ce(i,e);let c=await(await this.postCheckoutSessionCreate(i,e,t,r)).json();if(c.data&&"gateways"in c.data){this.autoCacheDisplayData(c.data.uuid,e);let p=this.mergeCachedDisplayData(c.data),m=this.normalizeRawSession(p);return c.vault&&m.data.session&&(m.data.session.vault=this.toVaultBlock(c.vault)),{...m,autoProcessingError:c.autoProcessingError,autoProcessingAttempted:c.autoProcessingAttempted,autoProcessingPending:c.autoProcessingPending}}let l=c.data?.uuid;if(!l)throw new a.FloPayError("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(l,e),this.adoptDirectTelemetryCheckout(l),{...await this.getUnifiedCheckoutSession(l),autoProcessingError:c.autoProcessingError,autoProcessingAttempted:c.autoProcessingAttempted,autoProcessingPending:c.autoProcessingPending}}async postCheckoutSessionCreate(e,t,r,n){let o={"Content-Type":"application/json",[a.FLO_SDK_VERSION_HEADER]:a.SDK_VERSION},i=(0,a.resolveIdempotencyKey)(t.idempotencyKey);i&&(o[a.IDEMPOTENCY_KEY_HEADER]=i);let u,c=!1,l=je(t),d=(m,f,g)=>{c||(c=!0,this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:g,attempt:m}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:Math.max(0,this.telemetryTimestamp()-f),durationMode:"machine",requestCategory:"session_create",statusClass:g,attempt:m}))},p=m=>{try{this.telemetryHooks?.onRetry?.("session_create",m),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:m})}catch{}};for(let m=0;m<3;m++){n.attempt=m;let f=this.telemetryTimestamp();try{l?.onAttempt?.(m)}catch{}try{u=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:o,body:JSON.stringify(e),signal:r})}catch(y){if(n.statusClass=r.aborted||y instanceof Error&&y.name==="AbortError"?"timeout":"network_error",r.aborted||y instanceof Error&&y.name==="AbortError"||m>=2)throw y;let S=m+1;p(S),await x(m,r);continue}let g=(0,a.telemetryStatusClass)(u.status);if(n.statusClass=g,u.status===204)throw d(m,f,g),new a.FloPayError("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(u.ok){d(m,f,g);break}let T=await _(u,"Failed to create checkout session");if(T.code===a.IDEMPOTENCY_IN_PROGRESS_CODE&&m<2){p(m+1),await x(m,r);continue}throw d(m,f,g),T}if(!u)throw new TypeError("Checkout-session creation exhausted its retry budget.");return u}async createDetachedSession(e){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),r=A(e.timeoutMs??12e3),n={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let o=e.products??(0,a.foldIntoProducts)(e.items,e.subscriptions);try{(0,a.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:o})}catch(y){throw r.clear(),this.reportSessionCreateFailure(y,t,n),y}let i=(0,a.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,o);if(!i)throw r.clear(),this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),new a.FloPayError("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});try{oe(e,i,o)}catch(y){throw r.clear(),this.reportSessionCreateFailure(y,t,n),y}let u,c;try{if(c=await(await this.postCheckoutSessionCreate(Ke(e,i),e,r.signal,n)).json(),!c.data||!("gateways"in c.data))throw new a.FloPayError("The billing API returned no session shell for a detached create. It must support `deferDataAttachment` (TeamFloPay/backend#1099).","api_error",{code:"InvalidCheckoutSessionResponse"});u=this.normalizeRawSession(this.mergeCachedDisplayData(c.data)),c.vault&&u.data.session&&(u.data.session.vault=this.toVaultBlock(c.vault))}catch(y){throw r.clear(),this.reportSessionCreateFailure(y,t,n),y}let l=u.data.session?.id??c.data.uuid??"",d=u.data.session?.clientSecret??c.data.nonce??"";if(!l||!d){r.clear();let y=new a.FloPayError("Checkout session shell was created without a session id or nonce.","api_error",{code:"InvalidCheckoutSessionResponse"});throw this.reportSessionCreateFailure(y,t,n),y}r.clear(),this.adoptDirectTelemetryCheckout(l),this.directTelemetry?.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",statusClass:n.statusClass,paymentMethodCategory:"card"}),this.directTelemetry?.performance({stage:"session_shell",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:n.statusClass,attempt:n.attempt,paymentMethodCategory:"card"});let p=!e.account.email?.trim(),m=A(e.timeoutMs??12e3),f=this.claimCheckoutSession(l,d,p?$e(e,i,o):oe(e,i,o),{params:e,startedAt:t,deadline:m,createAttempt:n.attempt}),g=p?void 0:f,T=(y={})=>{if(g)return g;let S={...e,account:{...e.account,...y,email:y.email?.trim()||e.account.email?.trim()}};return(0,a.isValidEmail)(S.account.email)?(g=f.then(()=>{let w=this.telemetryTimestamp();return this.claimCheckoutSession(l,d,Ge(S.account),{params:S,startedAt:w,deadline:A(e.timeoutMs??12e3),createAttempt:0})}),g.catch(()=>{}),g):Promise.reject(new a.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}))};return f.catch(()=>{}),{shell:u,sessionId:l,nonce:d,claimed:f,claim:T}}async claimCheckoutSession(e,t,r,n){let o=n?.startedAt??this.telemetryTimestamp(),i=this.telemetryTimestamp(),u=n?.deadline??A(12e3),c=JSON.stringify(r),l="unknown",d=0;this.directTelemetry?.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"});try{let p;for(d=0;d<3;d++){try{p=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/claim`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t,[a.FLO_SDK_VERSION_HEADER]:a.SDK_VERSION},body:c,signal:u.signal})}catch(g){let T=u.signal.aborted||g instanceof Error&&g.name==="AbortError";if(l=T?"timeout":"network_error",T||d>=2)throw g;try{this.telemetryHooks?.onRetry?.("session_claim",d+1),this.directTelemetry?.log({name:"operation.retry",stage:"session_claim",requestCategory:"session_claim",attempt:d+1})}catch{}await x(d,u.signal);continue}if(l=(0,a.telemetryStatusClass)(p.status),p.ok)break;throw await _(p,"Failed to attach checkout session data")}if(!p)throw new TypeError("Checkout-session claim exhausted its retry budget.");let m=await p.json();if(!m.data?.gateways)throw new a.FloPayError("The billing API returned no checkout session with gateways after claiming it.","api_error",{code:"InvalidCheckoutSessionResponse"});n?.params&&this.autoCacheDisplayData(m.data.uuid??e,n.params);let f=this.normalizeRawSession(this.mergeCachedDisplayData(m.data));return m.vault&&f.data.session&&(f.data.session.vault=this.toVaultBlock(m.vault)),this.directTelemetry?.log({name:"session.claim.completed",stage:"session_claim",requestCategory:"session_claim",statusClass:l}),this.directTelemetry?.performance({stage:"session_claim",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"session_claim",statusClass:l,attempt:d}),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:l}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"session_create",statusClass:l,attempt:n?.createAttempt??d}),f}catch(p){throw this.reportSessionCreateFailure(p,i,{attempt:d,statusClass:l},"session_claim"),p}finally{u.clear()}}reportSessionCreateFailure(e,t,r,n="session_create"){if(!(e instanceof a.FloPayError&&e.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(e)}catch{}let o=(0,a.classifyTelemetryFailure)(e,"CHECKOUT_SESSION_CREATE_FAILED");if(this.directTelemetry?.performance({stage:n,durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:n==="session_claim"?"session_claim":"session_create",statusClass:o.statusClass,attempt:r.attempt}),e instanceof a.FloPayError&&e.type==="validation_error"||e instanceof a.FloPayError&&ne(e.statusCode)){this.directTelemetry?.terminal({outcome:"validation_rejected",stage:n,requestCategory:n==="session_claim"?"session_claim":"session_create",...e.type==="validation_error"?{}:{statusClass:"4xx"}});return}e instanceof a.FloPayError&&e.code==="session_auto_completed"||this.directTelemetry?.error({...o,stage:n,requestCategory:n==="session_claim"?"session_claim":"session_create"})}async waitForCheckoutSessionCompletion(e,t){this.beginDirectTelemetryCheckout(e);let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:t?.paymentMethodCategory??"saved"});let n=t?.timeoutMs??Oe,o=Date.now()+n,i=this.clampRetryAfterMs(t?.initialDelayMs??re),u=0;try{for(;;){let c=o-Date.now();if(c<=0)throw F();if(i>0){try{u+=1,this.telemetryHooks?.onRetry?.("session_read",u),this.directTelemetry?.log({name:"operation.retry",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:t?.paymentMethodCategory??"saved",attempt:u})}catch{}if(await ie(Math.min(i,c)),Date.now()>=o)throw F()}let l=await this.getUnifiedCheckoutSessionForRecovery(e,t?.nonce),d=l.data.session?.status;if(d==="authorized"||d==="complete"||d==="expired")return this.directTelemetry?.log({name:"operation.recovery.completed",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:t?.paymentMethodCategory??"saved"}),this.directTelemetry?.performance({stage:"recovery",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"session_read",paymentMethodCategory:t?.paymentMethodCategory??"saved"}),l;if(Date.now()>=o)throw F();i=this.clampRetryAfterMs(Math.max(i*2,xe))}}catch(c){throw this.reportDirectFailure(c,"RECOVERY_FAILED","recovery","session_read",t?.paymentMethodCategory??"saved"),c}}normalizeRawSession(e){let t=e.gateways??{},r=[],n={session:this.toCheckoutSession(e)},o=t.stripe;if(o?.publishableKey){r.push("stripe");let c=[e.stripeClientSecret,o.stripeClientSecret].find(l=>typeof l=="string"&&l.length>0);n.stripe={clientSecret:c??"",publishableKey:o.publishableKey??void 0,paypalPublishableKey:o.paypalPublishableKey??void 0,environment:o.environment,enabledPaymentMethods:Array.isArray(o.enabledPaymentMethods)?o.enabledPaymentMethods.filter(l=>typeof l=="string"):void 0}}let i=t.paypal;return i?.publishableKey&&(r.push("paypal"),n.paypal={publishableKey:i.publishableKey,environment:i.environment,providerObjectType:i.providerObjectType,approvalPresentation:i.approvalPresentation}),{providers:r,mode:"tokenize",...e.checkoutMetadata===void 0?{}:{checkoutMetadata:e.checkoutMetadata},data:n,raw:{data:e}}}toCheckoutSession(e){let t=e.products??[],r=typeof e.totalAmount=="number"&&Number.isFinite(e.totalAmount),n=t.reduce((l,d)=>l+(d.overrideAmount??d.totalAmount??0),0),o=r?e.totalAmount:n,i=Math.round(o*100),u=e.currency??t[0]?.currency??"USD",c="payment";return e.checkoutMode==="setup"?c="setup":t.some(l=>l.type==="subscription")&&(c="subscription"),{id:e.uuid,clientSecret:e.nonce,mode:c,status:this.toCheckoutSessionStatus(e.status),amount:i,currency:u,captureMethod:e.captureMethod,paymentId:e.paymentId,authorizationExpiresAt:e.authorizationExpiresAt,failureOutcome:(0,a.normalizeCheckoutFailureOutcome)(e.outcome)??(0,a.normalizeCheckoutFailureOutcome)(e.failureReason)??(e.status==="expired"&&e.captureMethod==="manual"?"authorization_expired":void 0),customer:{id:e.accountData.userId??void 0,email:e.accountData.email??void 0,firstName:e.accountData.firstName??void 0,lastName:e.accountData.lastName??void 0,country:e.accountData.country??void 0,city:e.accountData.city??void 0,state:e.accountData.state??void 0,zip:e.accountData.zip??void 0,gender:e.accountData.gender??void 0,line1:e.accountData.addressLine1??void 0,line2:e.accountData.addressLine2??void 0},...e.checkoutMetadata===void 0?{}:{checkoutMetadata:e.checkoutMetadata},metadata:{},checkoutMode:e.checkoutMode,buyerIdentified:e.buyerIdentified,providerPaymentMethodId:typeof e.providerPaymentMethodId=="string"?e.providerPaymentMethodId:null,products:t.map(l=>({...l,totalAmount:typeof l.totalAmount=="number"?l.totalAmount:void 0,overrideAmount:typeof l.overrideAmount=="number"?l.overrideAmount:null,currency:typeof l.currency=="string"?l.currency:void 0,metadata:l.metadata??null})),successUrl:e.successUrl,cancelUrl:e.cancelUrl,coupons:e.coupons,subtotalAmount:e.subtotalAmount,discountAmount:e.discountAmount,totalAmount:e.totalAmount,createdAt:e.createdAt,gateways:e.gateways,accountData:e.accountData,tagsData:e.tagsData}}toVaultBlock(e){return{html:typeof e.html=="string"?e.html:void 0,url:typeof e.url=="string"?e.url:void 0,messageToken:typeof e.messageToken=="string"?e.messageToken:void 0,expectedOrigin:typeof e.expectedOrigin=="string"?e.expectedOrigin:void 0}}toCheckoutSessionStatus(e){return e==="completed"?"complete":e==="authorized"?"authorized":e==="expired"?"expired":"open"}async resolveProcessResponse(e,t,r){if(e.status!==202)return e;let n=await e.json().catch(()=>null),o=this.toCheckoutProcessingPending(n,e,t),i=await this.waitForCheckoutSessionCompletion(o.sessionId,{initialDelayMs:o.retryAfterMs,timeoutMs:r?.pollTimeoutMs,nonce:r?.nonce,paymentMethodCategory:r?.paymentMethodCategory});return this.toProcessResponseFromSession(i,t)}async reconcileProcessPayment(e,t){let r=await this.waitForCheckoutSessionCompletion(e,{initialDelayMs:0,timeoutMs:t?.pollTimeoutMs,nonce:t?.nonce,paymentMethodCategory:t?.paymentMethodCategory});return this.toProcessResponseFromSession(r,e)}toProcessResponseFromSession(e,t){if(e.data.session?.status==="complete")return new Response(null,{status:204,statusText:"No Content"});if(e.data.session?.status==="authorized"){let r=e.data.session;return new Response(JSON.stringify({status:"authorized",paymentId:r.paymentId,sessionId:r.id||t,authorizationExpiresAt:r.authorizationExpiresAt}),{status:200,headers:{"Content-Type":"application/json"}})}if(e.data.session?.status==="expired"){let r=e.data.session.failureOutcome==="authorization_expired"||e.data.session.captureMethod==="manual";throw new a.FloPayError(r?"Authorization has expired.":"Checkout session has expired.","api_error",{code:r?"authorization_expired":"checkout_session_expired"})}throw F()}toCheckoutProcessingPending(e,t,r){let n=t.headers.get("Retry-After"),o=n===null||n.trim()===""?void 0:Number(n),i=o!==void 0&&Number.isFinite(o)?o*1e3:void 0;return{type:"checkout_processing",sessionId:E(e,"sessionId")??r,retryAfterMs:this.clampRetryAfterMs(Ve(e,"retryAfterMs")??i??re),statusUrl:E(e,"statusUrl"),sessionUrl:E(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,qe))}autoCacheDisplayData(e,t){if(!e)return;let r=t.products??(0,a.foldIntoProducts)(t.items,t.subscriptions);if(r.length===0&&!t.currency)return;let n=t.products!==void 0,o=(0,a.resolveSessionCurrency)(t.currency,n?void 0:t.items,n?void 0:t.subscriptions,r);H(e,{currency:o??void 0,products:r.map(i=>({code:i.code??i.providerItemId??i.providerPlanId,type:i.type,name:i.name??i.itemName??i.providerItemName??i.subscriptionName??i.providerPlanName??null,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency??o??void 0}))})}mergeCachedDisplayData(e){let t=Q(e.uuid),r=new Map,n=i=>i?`code:${i}`:void 0;for(let i of t?.products??[]){let u=n(i.code);u&&r.set(u,i)}let o=(e.products??[]).map(i=>{let u=n(i.code),c=u?r.get(u):void 0;return{...i,name:i.name??c?.name??null,totalAmount:i.totalAmount??c?.totalAmount,overrideAmount:i.overrideAmount??c?.overrideAmount,currency:i.currency??c?.currency}});return{...e,currency:e.currency??t?.currency,products:o}}};M.activeVaultCaptureRequests=new Map;var L=M;var C=require("@flopay/shared");var G="flopay-vault",ue={ready:["vault.widget.ready","vault_ready"],submitting:["vault.submission.started","vault_submit"],blocked:["operation.state_transition","vault_submit"],action_required:["vault.action.required","three_ds_handoff"]};function Ye(s){return s.class==="lifecycle"?s.name:s.class==="technical_error"?s.code:s.class==="expected_outcome"?s.outcome:"sdk.performance"}function D(s){let e={class:s.class,stage:s.stage};"code"in s&&(e.code=s.code),"provider"in s&&s.provider&&(e.provider=s.provider),"paymentMethodCategory"in s&&s.paymentMethodCategory&&(e.paymentMethodCategory=s.paymentMethodCategory),"outcome"in s&&(e.outcome=s.outcome),"durationMs"in s&&s.durationMs!==void 0&&(e.durationMs=s.durationMs),"durationMode"in s&&s.durationMode&&(e.durationMode=s.durationMode);try{globalThis.Sentry?.addBreadcrumb?.({category:"flopay.telemetry",level:s.class==="technical_error"?"error":"info",message:Ye(s),data:e})}catch{}}function V(s,e){return(0,C.buildTelemetryLogEvent)({eventId:"11111111-1111-4111-8111-111111111111",name:s,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}function le(s){return s?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime"}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function de(s,e,t="checkout"){return t==="card_setup"?s.type==="decline"?"card_setup_declined":"card_setup_succeeded":s.type==="decline"?"payment_declined":s.outcome==="authorized"||e==="manual"?"payment_authorized":"payment_succeeded"}function We(s,e,t,r="checkout"){let{type:n}=s;if(n==="complete"||n==="decline")return(0,C.buildTelemetryTerminalEvent)({eventId:"22222222-2222-4222-8222-222222222222",outcome:de(s,t,r),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(n==="error"){let u=le(e);return(0,C.buildTelemetryErrorEvent)({eventId:"33333333-3333-4333-8333-333333333333",...u,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[o,i]=ue[n];return V(o,i)}function Je(s){if(typeof s!="object"||s===null)return!1;let e=s;return e.source===G&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function Qe(s){if(typeof s!="object"||s===null)return;let e=s,t=e.status;if(!(typeof e.id!="string"||e.id.trim()===""||typeof e.brand!="string"||e.brand.trim()===""||typeof e.lastFour!="string"||!/^\d{4}$/.test(e.lastFour)||typeof e.expiryMonth!="number"||!Number.isInteger(e.expiryMonth)||e.expiryMonth<1||e.expiryMonth>12||typeof e.expiryYear!="number"||!Number.isInteger(e.expiryYear)||e.expiryYear<1970||e.expiryYear>9999||t!=="pending"&&t!=="active"&&t!=="deleted"))return{id:e.id,brand:e.brand,lastFour:e.lastFour,expiryMonth:e.expiryMonth,expiryYear:e.expiryYear,status:t}}function Xe(s){if(typeof s!="object"||s===null)return!1;let e=s;return e.source===G&&e.type==="validation"&&Array.isArray(e.messages)}function Ze(s){if(typeof s!="object"||s===null)return!1;let e=s;return e.source===G&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}var N=class{constructor(e={},t){this.provider="pcivault";this.container=null;this.messageHandler=null;this.actionOverlay=null;this.threeDsReturnHandler=null;this.messageToken=null;this.expectedOrigin=null;this.theme=void 0;this.submitGateBlocked=!1;this.cardFieldOrder=null;this.cardAutoFocus=!0;this.mountStartedAt=0;this.vaultReadyReported=!1;this.submissionStarted=!1;this.submissionStartedAt=null;this.listeners=new Map;this.config=e,this.ownsTelemetryReporter=!t&&e.telemetry!==!1,this.telemetryReporter=t?.reporter??(this.ownsTelemetryReporter?new k({billingApiUrl:(0,C.resolveBillingApiUrl)(e.billingApiUrl),sdkVersion:C.SDK_VERSION}):void 0)}async mount(e,t){this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new k({billingApiUrl:(0,C.resolveBillingApiUrl)(this.config.billingApiUrl),sdkVersion:C.SDK_VERSION}));let r=this.telemetryReporter;if(this.config.operation==="card_setup"&&r&&this.setupTelemetryReporter!==r){this.setupTelemetryReporter=r;try{r.beginCheckout({checkoutMode:"setup"})}catch{}}if(this.mountStartedAt=this.telemetryReporter?.now?.()??b(),this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),new C.FloPayError("The vault card form is only available in the browser.","api_error",{code:"card_capture_no_window"});if(!t?.html?.trim())throw this.reportVaultLoadFailure(),new C.FloPayError("No vault capture widget HTML was provided to mount the secure card form.","api_error",{code:"card_capture_no_widget_html"});this.container=e,this.messageToken=t.messageToken??null,this.expectedOrigin=t.expectedOrigin??this.config.expectedOrigin??null,this.theme=t.theme;try{this.attachMessageListener(),this.injectWidget(e,t.html)}catch(n){throw this.reportVaultLoadFailure(),n}this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),D(V("vault.widget.mounted","vault_mount")),this.telemetryReporter?.log({name:"vault.widget.mounted",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?.performance?.({stage:"vault_mount",durationMs:Math.max(0,(this.telemetryReporter.now?.()??b())-this.mountStartedAt),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),this.emit("ready",{sessionId:this.config.sessionId})}reportVaultLoadFailure(){this.telemetryReporter?.error({errorCode:"VAULT_LOAD_FAILED",failureCategory:"provider_runtime",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"})}on(e,t){let r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(t),()=>{this.listeners.get(e)?.delete(t)}}unmount(){this.hideActionRequiredOverlay(),this.messageHandler&&(window.removeEventListener("message",this.messageHandler),this.messageHandler=null),this.container&&(this.container.replaceChildren(),this.container=null),this.messageToken=null,this.expectedOrigin=null,this.ownsTelemetryReporter&&(this.telemetryReporter?.destroy(),this.telemetryReporter=void 0)}injectWidget(e,t){e.innerHTML=t;let r=Array.from(e.querySelectorAll("script"));for(let n of r){let o=document.createElement("script");for(let i of Array.from(n.attributes))o.setAttribute(i.name,i.value);o.text=n.text,n.replaceWith(o)}}attachMessageListener(){if(this.messageHandler)return;let e=t=>{if(this.expectedOrigin&&t.origin!==this.expectedOrigin)return;let r=t.data;if(Ze(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;this.applyHeight(r.height);return}if(Xe(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;let c=r.messages.filter(l=>typeof l=="string"&&l.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:c||void 0});return}if(!Je(r)||this.messageToken&&r.messageToken!==this.messageToken)return;let n=this.config.sessionId,o=typeof r.sessionId=="string"?r.sessionId:void 0;if(n&&o&&o!==n||(r.type==="complete"||r.type==="decline")&&n&&o!==n)return;let i=Qe(r.paymentMethod),u={...r.sessionId??this.config.sessionId?{sessionId:r.sessionId??this.config.sessionId}:{},...r.outcome?{outcome:r.outcome}:{},...r.paymentId?{paymentId:r.paymentId}:{},...r.authorizationExpiresAt?{authorizationExpiresAt:r.authorizationExpiresAt}:{},...r.failureOutcome?{failureOutcome:r.failureOutcome}:{},...r.intentId?{intentId:r.intentId}:{},...r.declineReason?{declineReason:r.declineReason}:{},...r.message?{message:r.message}:{},...i?{paymentMethod:i}:{}};r.type==="submitting"&&(this.submissionStarted=!0,this.submissionStartedAt=this.telemetryReporter?.now?.()??b()),D(We(r,this.submissionStarted,this.config.captureMethod,this.config.operation)),this.reportOutcome(r),r.type==="ready"&&(this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder()),r.type==="action_required"&&r.nextActionRedirectUrl&&this.showActionRequiredOverlay(r.nextActionRedirectUrl),(r.type==="complete"||r.type==="decline"||r.type==="error"||r.type==="submitting")&&this.hideActionRequiredOverlay(),r.type!=="action_required"&&this.emit(r.type,u)};this.messageHandler=e,window.addEventListener("message",e)}reportOutcome(e){let t=this.telemetryReporter;if(!t)return;let{type:r}=e;if(r==="ready"&&!this.vaultReadyReported&&(this.vaultReadyReported=!0,t.performance({stage:"vault_ready",durationMs:Math.max(0,t.now()-this.mountStartedAt),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card",requestCategory:"provider_sdk"})),r==="complete"||r==="decline"){t.log({name:"vault.terminal",stage:"completion",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:de(e,this.config.captureMethod,this.config.operation),provider:"pcivault",paymentMethodCategory:"card"});return}if(r==="error"){let i=le(this.submissionStarted);t.log({name:"vault.terminal",stage:i.stage,provider:"pcivault",paymentMethodCategory:"card"}),t.error({...i,provider:"pcivault",paymentMethodCategory:"card"});return}if(r==="action_required"){t.log({name:"vault.action.required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"}),t.log({name:"vault.three_ds.handoff",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});let i=this.submissionStartedAt;this.submissionStartedAt=null,i!==null&&t.performance({stage:"three_ds_handoff",durationMs:Math.max(0,t.now()-i),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});return}let[n,o]=ue[r];t.log({name:n,stage:o,provider:"pcivault",paymentMethodCategory:"card"})}applyTheme(e){this.theme=e,this.postTheme()}postTheme(){if(this.theme===void 0||!this.container)return;let t=this.container.querySelector("iframe")?.contentWindow;if(t)try{t.postMessage({source:"flopay-vault-host",type:"theme",theme:this.theme},"*")}catch{}}setSubmitGate(e){this.submitGateBlocked=e,this.postSubmitGate()}postSubmitGate(){if(!this.container)return;let t=this.container.querySelector("iframe")?.contentWindow;if(t)try{t.postMessage({source:"flopay-vault-host",type:"gate",blocked:this.submitGateBlocked},"*")}catch{}}setCardFieldOrder(e,t){this.cardFieldOrder=e,this.cardAutoFocus=t,this.postCardFieldOrder()}postCardFieldOrder(){if(!this.container)return;let t=this.container.querySelector("iframe")?.contentWindow;if(t)try{t.postMessage({source:"flopay-vault-host",type:"fieldOrder",order:this.cardFieldOrder,autoFocus:this.cardAutoFocus},"*")}catch{}}emit(e,t){for(let r of this.listeners.get(e)??[])r(t)}showActionRequiredOverlay(e){if(typeof document>"u")return;if(this.actionOverlay){let i=this.actionOverlay.querySelector("iframe");i instanceof HTMLIFrameElement&&(i.src=e);return}let t=document.createElement("div");t.setAttribute("data-flopay-action-required","1"),t.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let r=document.createElement("iframe");r.setAttribute("title","Card authentication"),r.setAttribute("allow","payment"),r.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),r.src=e,t.appendChild(r);let n=document.createElement("button");n.type="button",n.setAttribute("aria-label","Close card authentication"),n.textContent="\xD7",n.style.cssText=["position:fixed","top:20px","right:20px","width:40px","height:40px","border:0","border-radius:9999px","background:#fff","color:#0f172a","font-size:28px","line-height:40px","cursor:pointer","box-shadow:0 4px 14px rgba(0,0,0,0.25)"].join(";"),n.addEventListener("click",()=>this.abandonActionRequiredOverlay()),t.appendChild(n),t.addEventListener("click",i=>{i.target===t&&this.abandonActionRequiredOverlay()});let o=i=>{if(i.source!==r.contentWindow)return;let u=i.data;if(!u||typeof u!="object")return;let c=u;c.source==="flopay-vault-3ds-return"&&(D(V("vault.three_ds.returned","three_ds_return")),this.telemetryReporter?.log({name:"vault.three_ds.returned",stage:"three_ds_return",provider:"pcivault",paymentMethodCategory:"card"}),this.hideActionRequiredOverlay(),this.postActionCompleted(c.status))};window.addEventListener("message",o),this.threeDsReturnHandler=o,document.body.appendChild(t),this.actionOverlay=t,D(V("vault.three_ds.handoff","three_ds_handoff"))}postActionCompleted(e){if(!this.container)return;let r=this.container.querySelector("iframe")?.contentWindow;if(r)try{r.postMessage({source:"flopay-vault-host",type:"action_completed",status:typeof e=="string"?e:"unknown"},"*")}catch{}}abandonActionRequiredOverlay(){if(!this.actionOverlay)return;let e=(0,C.buildTelemetryTerminalEvent)({eventId:"77777777-7777-4777-8777-777777777777",outcome:"customer_abandoned",stage:"three_ds_handoff",sequence:0,provider:"pcivault",paymentMethodCategory:"card"});D(e),this.telemetryReporter?.terminal({outcome:"customer_abandoned",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"}),this.hideActionRequiredOverlay(),this.postActionCompleted("abandoned")}hideActionRequiredOverlay(){this.threeDsReturnHandler&&(window.removeEventListener("message",this.threeDsReturnHandler),this.threeDsReturnHandler=null),this.actionOverlay&&(this.actionOverlay.parentNode?.removeChild(this.actionOverlay),this.actionOverlay=null)}applyHeight(e){let t=this.container?.querySelector("iframe");if(!t)return;let r=Math.max(0,Math.min(Math.ceil(e),2e3));t.style.height=`${r}px`}};0&&(module.exports={PaymentAPI,PciVaultCardCapture});
|
|
1
|
+
"use strict";var B=Object.defineProperty;var fe=Object.getOwnPropertyDescriptor;var Ce=Object.getOwnPropertyNames;var ve=Object.prototype.hasOwnProperty;var Te=(s,e)=>{for(var t in e)B(s,t,{get:e[t],enumerable:!0})},be=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ce(e))!ve.call(s,o)&&o!==t&&B(s,o,{get:()=>e[o],enumerable:!(r=fe(e,o))||r.enumerable});return s};var ke=s=>be(B({},"__esModule",{value:!0}),s);var et={};Te(et,{PaymentAPI:()=>U,PciVaultCardCapture:()=>N});module.exports=ke(et);var a=require("@flopay/shared");function W(s){return typeof s=="string"&&s.trim()?s:void 0}function J(s){if(typeof s=="string")return s.trim()?s:void 0;if(Array.isArray(s))return s.filter(t=>typeof t=="string"&&t.trim().length>0).join("; ")||void 0}function R(s=12e3){let e=Number.isFinite(s)&&s>=0?s:12e3,t=new AbortController,r=setTimeout(()=>t.abort(),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function _e(){return Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function x(s,e){let t=150*2**s,r=Math.round(t*(.75+Math.random()*.5));return new Promise((o,n)=>{let i,u=()=>e.removeEventListener("abort",c),c=()=>{i!==void 0&&clearTimeout(i),u(),n(_e())};if(e.aborted){c();return}i=setTimeout(()=>{u(),o()},r),e.addEventListener("abort",c,{once:!0})})}var Me="flopay_session_display:";var O=new Map;function q(s){return`${Me}${s}`}function H(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function j(s,e,t){if(!s)return;let r=t?.ttlMs??36e5,o={data:e,expiresAt:Date.now()+r},n=H();if(n)try{n.setItem(q(s),JSON.stringify(o));return}catch{}O.set(s,o)}function Q(s){if(!s)return null;let e=H();if(e)try{let r=e.getItem(q(s));if(r){let o=JSON.parse(r);if(o&&typeof o.expiresAt=="number"&&o.expiresAt>Date.now())return o.data;e.removeItem(q(s))}}catch{}let t=O.get(s);if(t){if(t.expiresAt>Date.now())return t.data;O.delete(s)}return null}function X(s){if(!s)return;O.delete(s);let e=H();if(e)try{e.removeItem(q(s))}catch{}}var T=require("@flopay/shared"),Se="/v1/sdk-telemetry/events",K=16,Ae=64,Re=1500,Z=1e3,we=64,Ee="00000000-0000-4000-8000-000000000000",Ie={technical_error:8,lifecycle:32,expected_outcome:32,performance:24};function w(){try{return globalThis.crypto.randomUUID()}catch{let s=new Uint8Array(16);try{globalThis.crypto.getRandomValues(s)}catch{for(let t=0;t<s.length;t+=1)s[t]=Math.floor(Math.random()*256)}s[6]=(s[6]??0)&15|64,s[8]=(s[8]??0)&63|128;let e=[...s].map(t=>t.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}}function Pe(s){try{return new TextEncoder().encode(s).byteLength}catch{return s.length}}function De(s){return JSON.stringify([s.code,s.failureCategory,s.stage,s.provider,s.attempt,s.statusClass,s.requestCategory,s.paymentMethodCategory,s.walletType,s.operationOutcome,s.checkoutMode,s.layout,s.inAppBrowser,s.appFamily,s.popupCapability,s.presentationMode,s.terminalReason])}function k(){return globalThis.performance?.now()??0}var _=class{constructor(e){this.ingestionDisabled=!1;this.queue=[];this.sequence=0;this.flushTimer=null;this.flushInFlight=null;this.reportedFailures=new Map;this.checkoutContext={};this.checkoutStartedAt=null;this.destroyed=!1;this.observers=new Set;this.pageExitHandler=()=>{this.drainQueue()};this.visibilityHandler=()=>{document.visibilityState==="hidden"&&this.flush()};this.eventCounts={technical_error:0,lifecycle:0,expected_outcome:0,performance:0};this.endpoint=`${e.billingApiUrl.replace(/\/+$/,"")}${Se}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=w(),this.merchantEnabled=e.enabled!==!1,this.clock=e.clock??k,this.browserTransportAvailable=typeof window<"u"&&typeof document<"u",this.browserTransportAvailable&&(window.addEventListener("pagehide",this.pageExitHandler),document.addEventListener("visibilitychange",this.visibilityHandler))}log(e){this.notify({...e,class:"lifecycle"}),this.canCollect()&&this.enqueue((0,T.buildTelemetryLogEvent)({...this.checkoutContext,...e,eventId:w(),sequence:this.sequence++}))}error(e){if(this.notify({...e,class:"technical_error"}),!this.canCollect())return;let t=(0,T.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:Ee,sequence:0}),r=De(t),o=this.now();this.pruneReportedFailures(o);let n=this.reportedFailures.get(r);if(n!==void 0&&o>=n&&o-n<Z){this.log({name:"operation.deduplicated",stage:e.stage,provider:e.provider,paymentMethodCategory:e.paymentMethodCategory,attempt:e.attempt,inAppBrowser:e.inAppBrowser,appFamily:e.appFamily,popupCapability:e.popupCapability,presentationMode:e.presentationMode,terminalReason:e.terminalReason});return}this.rememberReportedFailure(r,o),this.enqueue((0,T.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:w(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue((0,T.buildTelemetryPerformanceEvent)({...this.checkoutContext,...e,eventId:w(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue((0,T.buildTelemetryTerminalEvent)({...this.checkoutContext,...e,eventId:w(),sequence:this.sequence++})),e.outcome!=="action_required"&&this.checkoutStartedAt!==null)){let t=this.checkoutStartedAt;this.checkoutStartedAt=null,this.performance({...e,stage:"total_journey",durationMs:Math.max(0,this.now()-t),durationMode:"total"})}}now(){try{return this.clock()}catch{return k()}}subscribe(e){return this.destroyed?()=>{}:(this.observers.add(e),()=>this.observers.delete(e))}notify(e){if(!this.destroyed)for(let t of this.observers)try{t(e)}catch{}}pruneReportedFailures(e){for(let[t,r]of this.reportedFailures)(e<r||e-r>=Z)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=we;){let r=this.reportedFailures.keys().next();if(r.done)break;this.reportedFailures.delete(r.value)}this.reportedFailures.set(e,t)}setCheckoutContext(e){this.checkoutContext={checkoutMode:e.checkoutMode,layout:e.layout}}beginCheckout(e={}){return this.canCollect()?(this.drainQueue(),this.setCheckoutContext(e),this.sequence=0,this.reportedFailures.clear(),this.eventCounts={technical_error:0,lifecycle:0,expected_outcome:0,performance:0},this.checkoutStartedAt=this.now(),this.checkoutStartedAt):0}enqueue(e){if(this.canCollect()&&!(this.queue.length>=Ae||this.eventCounts[e.class]>=Ie[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=K){this.flush();return}this.scheduleFlush()}}canCollect(){return this.browserTransportAvailable&&this.merchantEnabled&&!this.ingestionDisabled&&!this.destroyed}async flush(){if(this.flushInFlight!==null)return this.flushInFlight;if(!this.browserTransportAvailable||this.destroyed||this.ingestionDisabled||this.queue.length===0)return;this.clearFlushTimer();let e=this.queue.splice(0,K);return this.flushInFlight=this.sendBatch(e).finally(()=>{this.flushInFlight=null,this.queue.length>0&&this.scheduleFlush()}),this.flushInFlight}destroy(){this.destroyed||(this.drainQueue(),this.destroyed=!0,this.clearFlushTimer(),this.browserTransportAvailable&&(window.removeEventListener("pagehide",this.pageExitHandler),document.removeEventListener("visibilitychange",this.visibilityHandler)),this.queue.splice(0),this.reportedFailures.clear(),this.observers.clear())}disable(){this.merchantEnabled=!1,this.queue.splice(0),this.reportedFailures.clear(),this.clearFlushTimer()}drainQueue(){if(!(!this.browserTransportAvailable||this.destroyed||this.ingestionDisabled||this.queue.length===0))for(this.clearFlushTimer();this.queue.length>0;){let e=this.queue.splice(0,K);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=(0,T.serializeTelemetryBatch)(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:w()});if(Pe(t)>T.TELEMETRY_MAX_BATCH_BYTES)return;let r=typeof AbortController>"u"?null:new AbortController,o=null;try{let n=fetch(this.endpoint,{method:"POST",headers:{"content-type":"text/plain;charset=UTF-8"},body:t,credentials:"omit",keepalive:!0,referrerPolicy:"no-referrer",signal:r?.signal}).then(async c=>{if(c.status!==202)return null;let l=null;try{l=await c.json()}catch{}return l?.status==="disabled"?"disabled":null}).catch(()=>null),i=new Promise(c=>{o=setTimeout(()=>{r?.abort(),c(null)},Re)});await Promise.race([n,i])==="disabled"&&this.disableFromIngestion()}catch{}finally{o&&clearTimeout(o)}}disableFromIngestion(){this.ingestionDisabled=!0,this.queue.splice(0),this.reportedFailures.clear(),this.clearFlushTimer()}scheduleFlush(){this.flushTimer||this.destroyed||this.ingestionDisabled||(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush()},0))}clearFlushTimer(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null)}},ee=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),te=globalThis;te[ee]===void 0&&Object.defineProperty(te,ee,{configurable:!0,enumerable:!1,writable:!1,value:s=>new _(s)});var re=0,xe=500,Oe=15e3,qe=3e3,Fe=1e4,Le=1e4;function Ue(s){return typeof s=="object"&&s!==null}function E(s,e){return W(s?.[e])}function se(s,e){return J(s?.[e])}function Ve(s,e){let t=s?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function ie(s){return new Promise(e=>setTimeout(e,s))}function Ne(s){return s instanceof Error&&s.name==="AbortError"}function F(){return new a.FloPayError("Checkout is still processing. Please try again shortly.","api_error",{code:"checkout_processing_timeout"})}async function S(s,e){let t=await s.json().catch(()=>null),r=Ue(t?.error)?t.error:null,o=se(t,"message")??se(r,"message")??e,n=E(t,"code")??E(t,"gatewayErrorCode")??E(r,"code")??`http_${s.status}`;return new a.FloPayError(o,"api_error",{code:n,statusCode:s.status})}async function ze(s){let e=s.status===400?await s.clone().json().catch(()=>null):null;return(0,a.classifyPaymentRejection)(s.status,e)}function oe(s){return s===400||s===422}var L=2;async function $(s,e,t=L,r,o){let n;for(let i=0;;i++)try{return o?.(i),await fetch(s,e)}catch(u){if(e?.signal?.aborted||u instanceof Error&&u.name==="AbortError")throw u;if(n=u,i>=t)throw n;try{r?.(i+1)}catch{}await ie(150*2**i)}}var Be=Symbol.for("@flopay/js.session-create.telemetry.v1");function He(s){return s[Be]}function je(s){return"now"in s||"onFirstByte"in s||"onSessionCreateFailure"in s||"onRetry"in s}function ae(s){let e=(0,a.isCardHolderNamePlaceholder)(s.firstName,s.lastName);return{userId:s.userId,firstName:e?null:s.firstName??null,lastName:e?null:s.lastName??null,email:s.email,country:s.country??null,gender:s.gender??null,city:s.city??null,state:s.state??null,zip:s.zip??null,addressLine1:s.addressLine1??null,addressLine2:s.addressLine2??null}}function ce(s,e){e.checkoutMetadata!==void 0&&(s.checkoutMetadata=e.checkoutMetadata),e.tagsData&&(s.tagsData=e.tagsData),e.utmMetadata&&e.utmMetadata.length>0&&(s.utmMetadata=e.utmMetadata),e.avsCheck!==void 0&&(s.avsCheck=e.avsCheck),e.checkoutType&&(s.checkoutType=e.checkoutType),e.checkoutLayout&&(s.checkoutLayout=e.checkoutLayout),e.avsConfig&&(s.avsConfig=e.avsConfig)}function Ke(s,e){let t={clientId:s.clientId,checkoutVersion:a.SDK_VERSION,successUrl:s.successUrl,cancelUrl:s.cancelUrl,currency:e,checkoutMode:"full",deferDataAttachment:!0};return s.captureMethod==="manual"&&(t.captureMethod=s.captureMethod),s.account.country&&(t.accountData={country:s.account.country}),ce(t,s),t}function ne(s,e,t){return{currency:e,products:t.map(r=>(0,a.buildProductPayload)(r,e)),couponCodes:s.couponCodes??[],accountData:ae(s.account)}}function $e(s,e,t){return{currency:e,products:t.map(r=>(0,a.buildProductPayload)(r,e)),couponCodes:s.couponCodes??[]}}function Ge(s){let e={},t=(0,a.isCardHolderNamePlaceholder)(s.firstName,s.lastName);for(let[r,o]of Object.entries(s)){if(t&&r.endsWith("Name")||typeof o!="string")continue;let n=o.trim();n&&(e[r]=n)}return{accountData:e}}var A=class A{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let r=je(t);this.telemetryHooks=r?t:void 0,this.directTelemetry=r||t.telemetry===!1?void 0:new _({billingApiUrl:this.baseUrl,sdkVersion:a.SDK_VERSION})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,r,o,n="unknown"){let i=(0,a.classifyTelemetryFailure)(e,t);this.directTelemetry?.error({...i,stage:r,requestCategory:o,paymentMethodCategory:n})}reportAccountSnapshotFailure(e,t){let r=(0,a.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED");if(t==="best_effort"&&r.errorCode==="REQUEST_TIMEOUT"){this.directTelemetry?.log({name:"operation.fallback",stage:"processing",requestCategory:"account_snapshot",statusClass:"timeout"});return}this.directTelemetry?.error({...r,stage:"processing",requestCategory:"account_snapshot",paymentMethodCategory:"unknown"})}telemetryTimestamp(){try{return this.telemetryHooks?.now?.()??this.directTelemetry?.now()??k()}catch{return k()}}beginDirectTelemetryCheckout(e){!this.directTelemetry||this.directTelemetryCheckoutId===e||(this.directTelemetryCheckoutId=e,this.directTelemetry.beginCheckout())}beginDirectTelemetryOperation(){this.directTelemetry&&(this.directTelemetryCheckoutId=void 0,this.directTelemetry.beginCheckout())}adoptDirectTelemetryCheckout(e){e&&(this.directTelemetryCheckoutId=e)}async getCheckoutSession(e,t){return this.fetchCheckoutSession(e,t)}async fetchCheckoutSession(e,t,r=!0){this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp(),n=o,i=0;this.directTelemetry?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let u={[a.FLO_SDK_VERSION_HEADER]:a.SDK_VERSION};t&&(u["x-checkout-session-token"]=t);try{let c=await $(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:u},L,g=>{this.telemetryHooks?.onRetry?.("session_read",g),this.directTelemetry?.log({name:"operation.retry",stage:"session_read",requestCategory:"session_read",attempt:g})},g=>{i=g,n=this.telemetryTimestamp()}),l=Math.max(0,this.telemetryTimestamp()-n);try{this.telemetryHooks?.onFirstByte?.(l,i)}catch{}let d=`${Math.floor(c.status/100)}xx`;if(this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:d,attempt:i}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:l,durationMode:"machine",requestCategory:"session_read",statusClass:d,attempt:i}),!c.ok)throw await S(c,"Failed to get checkout session");let m=await c.json();return this.directTelemetry?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:d}),this.directTelemetry?.performance({stage:"session_complete",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"session_read",statusClass:d}),{...m,data:this.mergeCachedDisplayData(m.data)}}catch(c){throw r&&this.directTelemetry?.error({...(0,a.classifyTelemetryFailure)(c,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),c}}cacheSessionDisplayData(e,t,r){j(e,t,r)}clearSessionDisplayData(e){X(e)}async getVaultCapture(e,t){let r=`${this.baseUrl}\0${e}\0${t??""}`,o=A.activeVaultCaptureRequests.get(r);if(o)return o;let n=this.requestVaultCapture(e,t);A.activeVaultCaptureRequests.set(r,n);try{return await n}finally{A.activeVaultCaptureRequests.get(r)===n&&A.activeVaultCaptureRequests.delete(r)}}async requestVaultCapture(e,t){let r=new AbortController,o=setTimeout(()=>r.abort(),Le);this.beginDirectTelemetryCheckout(e);let n=this.telemetryTimestamp();this.directTelemetry?.log({name:"vault.capture.requested",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card"});let i={"Content-Type":"application/json"};t&&(i["x-checkout-session-token"]=t);try{let u=await $(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:i,signal:r.signal},L,l=>{this.telemetryHooks?.onRetry?.("vault_capture",l),this.directTelemetry?.log({name:"operation.retry",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card",attempt:l})});if(!u.ok)throw await S(u,"Failed to load the secure card form");let c=await u.json();return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-n),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(c)}catch(u){let c=r.signal.aborted?new a.FloPayError("Timed out while loading the secure card form. Please try again.","api_error",{code:"vault_capture_timeout"}):u;throw this.reportDirectFailure(c,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),c}finally{clearTimeout(o)}}async getUnifiedCheckoutSession(e,t){let r=await this.getCheckoutSession(e,t);return this.normalizeCheckoutSessionResponse(r)}async getUnifiedCheckoutSessionForRecovery(e,t){let r=await this.fetchCheckoutSession(e,t,!1);return this.normalizeCheckoutSessionResponse(r)}normalizeCheckoutSessionResponse(e){let t=this.normalizeRawSession(e.data),r=e.vault;return r&&t.data.session&&(t.data.session.vault=this.toVaultBlock(r)),t}async processPayment(e,t,r){this.beginDirectTelemetryCheckout(t.sessionId);let o=t.paymentMethodCategory??"unknown";if(!t.nonce)throw this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:o}),new a.FloPayError("processPayment requires `nonce` \u2014 pass the value returned from session creation.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let n=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.processing.started",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:o});let{nonce:i,paymentMethodCategory:u,...c}=t,l;try{l=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(t.sessionId)}/process`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":i},body:JSON.stringify(c)})}catch(d){if(Ne(d))throw this.reportDirectFailure(d,"PAYMENT_PROCESSING_FAILED","processing","process_payment",o),d;l=await this.reconcileProcessPayment(t.sessionId,{...r,nonce:i,paymentMethodCategory:o})}if(!l.ok&&l.status!==202){let d=await ze(l);return d?this.directTelemetry?.terminal({outcome:d,stage:"processing",requestCategory:"process_payment",statusClass:"4xx",paymentMethodCategory:o}):this.directTelemetry?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",requestCategory:"process_payment",statusClass:(0,a.telemetryStatusClass)(l.status),failureCategory:l.status>=500?"server_error":void 0,paymentMethodCategory:o}),l}try{let d=await this.resolveProcessResponse(l,t.sessionId,{...r,nonce:i,paymentMethodCategory:o});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:(0,a.telemetryStatusClass)(d.status),paymentMethodCategory:o}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-n),durationMode:"machine",requestCategory:"process_payment",statusClass:(0,a.telemetryStatusClass)(d.status),paymentMethodCategory:o}),d}catch(d){throw d instanceof a.FloPayError&&d.code==="checkout_processing_timeout"||this.reportDirectFailure(d,"PAYMENT_PROCESSING_FAILED","processing","process_payment",o),d}}async patchAccountSnapshot(e,t,r,o){this.beginDirectTelemetryCheckout(e);let n=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let i=o?.timeoutMs??Fe,u=new AbortController,c=()=>u.abort();o?.signal&&(o.signal.aborted?u.abort():o.signal.addEventListener("abort",c,{once:!0}));let l=setTimeout(()=>u.abort(),i);try{let d;try{d=await $(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/account`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(r),signal:u.signal},L,m=>{this.telemetryHooks?.onRetry?.("account_snapshot",m),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:m})})}finally{clearTimeout(l),o?.signal?.removeEventListener("abort",c)}if(!d.ok)throw await S(d,"Failed to persist account snapshot");this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-n),durationMode:"machine",requestCategory:"account_snapshot",statusClass:"2xx"})}catch(d){throw this.reportAccountSnapshotFailure(d,o?.telemetryMode??"blocking"),d}}async createSessionIntent(e,t,r,o){if(!t)throw new a.FloPayError("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let n=r,i=n.paymentMethodType,u=typeof i=="string"&&i.trim().toLowerCase()==="card",c=typeof i=="string"&&i.length>0&&!u&&(typeof n.paymentMethodId=="string"||n.paymentMethodId===null),l=n.provider==="stripe"&&(n.paymentMethodCategory==="wallet"||n.paymentMethodCategory==="apm")&&(n.intentKind==="payment"||n.intentKind==="setup"),d=n.provider==="paypal"&&n.paymentMethodCategory==="wallet"&&n.paymentMethodId===null&&(n.paymentMethodType==="paypal"&&n.intentKind==="payment"||n.paymentMethodType===a.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&(n.intentKind==="payment"||n.intentKind==="setup"));if(!c||!l&&!d)throw new a.FloPayError("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let m=n.authorizationAttemptId;if(m!==void 0&&!(0,a.isUuidV4)(m))throw new a.FloPayError("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let g=(0,a.isUuidV4)(m)?m:(0,a.randomUuidV4)();this.beginDirectTelemetryCheckout(e);let p=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.intent.started",stage:"processing",requestCategory:"intent_create"});let f={"Content-Type":"application/json","x-checkout-session-token":t,[a.IDEMPOTENCY_KEY_HEADER]:o?.idempotencyKey||g},v=!1;try{let y=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:f,body:JSON.stringify({...r,authorizationAttemptId:g}),signal:o?.signal});if(!y.ok){v=!0;let z=await S(y,"Failed to create checkout intent"),ge=(0,a.classifyTelemetryFailure)(z,"PAYMENT_PROCESSING_FAILED");throw oe(z.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...ge,stage:"processing",requestCategory:"intent_create"}),z}let M=(await y.json()).data;if(!M||typeof M!="object")throw new a.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let h=M,Y=h.paymentMethodType,me=(h.paymentMethodCategory==="wallet"||h.paymentMethodCategory==="apm")&&typeof Y=="string"&&Y.trim().toLowerCase()!=="card"&&(typeof h.paymentMethodId=="string"||h.paymentMethodId===null)&&typeof h.providerObjectId=="string",pe=h.provider==="stripe"&&(h.intentKind==="payment"||h.intentKind==="setup")&&typeof h.clientSecret=="string",he=h.provider==="paypal"&&h.paymentMethodCategory==="wallet"&&h.paymentMethodId===null&&(h.paymentMethodType==="paypal"&&h.intentKind==="payment"&&(h.providerObjectType==="order"||h.providerObjectType==="subscription")||h.paymentMethodType===a.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&h.intentKind==="payment"&&h.providerObjectType==="order"||h.paymentMethodType===a.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&h.intentKind==="setup"&&h.providerObjectType==="setup_token")&&h.clientSecret===null,ye=h.provider===r.provider&&h.paymentMethodCategory===r.paymentMethodCategory&&h.paymentMethodType===r.paymentMethodType&&h.paymentMethodId===r.paymentMethodId&&h.intentKind===r.intentKind;if(!me||!pe&&!he||!ye)throw new a.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:(0,a.telemetryStatusClass)(y.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-p),durationMode:"machine",requestCategory:"intent_create",statusClass:(0,a.telemetryStatusClass)(y.status)}),h}catch(y){throw v||this.reportDirectFailure(y,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),y}}async reportSessionIntentDecline(e,t,r,o){if(!t)throw new a.FloPayError("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let n=r,i=n.providerDeclineReason,u=n.paymentMethodType,c=n.providerIntentId,l=typeof i=="string"&&/^[a-z0-9][a-z0-9_.:-]{0,63}$/i.test(i)&&!/^(?:pm|pi|seti|tok|src|cus|sess|sk|pk)_/i.test(i),d=typeof u=="string"&&u.length>0&&u.trim().toLowerCase()!=="card"&&l,m=n.provider==="stripe"&&(n.paymentMethodCategory==="wallet"||n.paymentMethodCategory==="apm")&&(c===void 0||typeof c=="string"&&/^pi_[a-z0-9_]{1,252}$/i.test(c)),g=n.provider==="paypal"&&n.paymentMethodCategory==="wallet"&&n.paymentMethodType==="paypal"&&c===void 0;if(!d||!m&&!g)throw new a.FloPayError("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let p=g?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:i}:{provider:"stripe",paymentMethodCategory:n.paymentMethodCategory,paymentMethodType:n.paymentMethodType,providerDeclineReason:i,...typeof c=="string"?{providerIntentId:c}:{}},f=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents/decline`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(p),signal:o?.signal});if(!f.ok)throw await S(f,"Failed to report checkout decline")}async getPaymentsByEmail(e,t){this.beginDirectTelemetryOperation();let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved"});let o=t?.page??1,n=t?.limit??1,i=new URLSearchParams({email:e,page:String(o),limit:String(n),sortField:"createdAt",sortDirection:"DESC"});try{let u=await fetch(`${this.baseUrl}/v1/payments?${i.toString()}`,{method:"GET",signal:t?.signal,keepalive:!0});if(!u.ok)throw new a.FloPayError("Failed to fetch payments","api_error",{statusCode:u.status});let c=await u.json();return this.directTelemetry?.log({name:"operation.recovery.completed",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),this.directTelemetry?.performance({stage:"recovery",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),c}catch(u){throw this.reportDirectFailure(u,"RECOVERY_FAILED","recovery","other","saved"),u}}async createAndFetchSession(e){if((0,a.isDetachedSessionEligible)(e)){let n=e.account.email?.trim();if(n&&!(0,a.isValidEmail)(n))throw new a.FloPayError("Buyer email must be valid when supplied.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"});return(await this.createDetachedSession(e)).claimed}this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),r=R(e.timeoutMs??12e3),o={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});try{let n=await this.createAndFetchSessionRequest(e,r.signal,o);return this.adoptDirectTelemetryCheckout(n.data.session?.id),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:o.statusClass}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:o.statusClass,attempt:o.attempt}),n}catch(n){throw this.reportSessionCreateFailure(n,t,o),n}finally{r.clear()}}async createAndFetchSessionRequest(e,t,r){let o=e.products??(0,a.foldIntoProducts)(e.items,e.subscriptions);(0,a.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:o});let n=(0,a.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,o);if(!n)throw new a.FloPayError("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let i={clientId:e.clientId,checkoutVersion:a.SDK_VERSION,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:n,checkoutMode:e.checkoutMode??"full",products:o.map(m=>(0,a.buildProductPayload)(m,n)),accountData:ae(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(i.captureMethod=e.captureMethod),e.tokenizedData&&(i.tokenizedData=e.tokenizedData),ce(i,e);let c=await(await this.postCheckoutSessionCreate(i,e,t,r)).json();if(c.data&&"gateways"in c.data){this.autoCacheDisplayData(c.data.uuid,e);let m=this.mergeCachedDisplayData(c.data),g=this.normalizeRawSession(m);return c.vault&&g.data.session&&(g.data.session.vault=this.toVaultBlock(c.vault)),{...g,autoProcessingError:c.autoProcessingError,autoProcessingAttempted:c.autoProcessingAttempted,autoProcessingPending:c.autoProcessingPending}}let l=c.data?.uuid;if(!l)throw new a.FloPayError("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(l,e),this.adoptDirectTelemetryCheckout(l),{...await this.getUnifiedCheckoutSession(l),autoProcessingError:c.autoProcessingError,autoProcessingAttempted:c.autoProcessingAttempted,autoProcessingPending:c.autoProcessingPending}}async postCheckoutSessionCreate(e,t,r,o){let n={"Content-Type":"application/json",[a.FLO_SDK_VERSION_HEADER]:a.SDK_VERSION},i=(0,a.resolveIdempotencyKey)(t.idempotencyKey);i&&(n[a.IDEMPOTENCY_KEY_HEADER]=i);let u=(0,a.resolveSessionCreateCapabilities)(t);u&&(n[a.FLO_SDK_CAPABILITIES_HEADER]=u);let c,l=!1,d=He(t),m=(p,f,v)=>{l||(l=!0,this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:v,attempt:p}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:Math.max(0,this.telemetryTimestamp()-f),durationMode:"machine",requestCategory:"session_create",statusClass:v,attempt:p}))},g=p=>{try{this.telemetryHooks?.onRetry?.("session_create",p),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:p})}catch{}};for(let p=0;p<3;p++){o.attempt=p;let f=this.telemetryTimestamp();try{d?.onAttempt?.(p)}catch{}try{c=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:n,body:JSON.stringify(e),signal:r})}catch(b){if(o.statusClass=r.aborted||b instanceof Error&&b.name==="AbortError"?"timeout":"network_error",r.aborted||b instanceof Error&&b.name==="AbortError"||p>=2)throw b;let M=p+1;g(M),await x(p,r);continue}let v=(0,a.telemetryStatusClass)(c.status);if(o.statusClass=v,c.status===204)throw m(p,f,v),new a.FloPayError("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(c.ok){m(p,f,v);break}let y=await S(c,"Failed to create checkout session");if(y.code===a.IDEMPOTENCY_IN_PROGRESS_CODE&&p<2){g(p+1),await x(p,r);continue}throw m(p,f,v),y}if(!c)throw new TypeError("Checkout-session creation exhausted its retry budget.");return c}async createDetachedSession(e){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),r=R(e.timeoutMs??12e3),o={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let n=e.products??(0,a.foldIntoProducts)(e.items,e.subscriptions);try{(0,a.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:n})}catch(y){throw r.clear(),this.reportSessionCreateFailure(y,t,o),y}let i=(0,a.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,n);if(!i)throw r.clear(),this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),new a.FloPayError("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});try{ne(e,i,n)}catch(y){throw r.clear(),this.reportSessionCreateFailure(y,t,o),y}let u,c;try{if(c=await(await this.postCheckoutSessionCreate(Ke(e,i),e,r.signal,o)).json(),!c.data||!("gateways"in c.data))throw new a.FloPayError("The billing API returned no session shell for a detached create. It must support `deferDataAttachment` (TeamFloPay/backend#1099).","api_error",{code:"InvalidCheckoutSessionResponse"});u=this.normalizeRawSession(this.mergeCachedDisplayData(c.data)),c.vault&&u.data.session&&(u.data.session.vault=this.toVaultBlock(c.vault))}catch(y){throw r.clear(),this.reportSessionCreateFailure(y,t,o),y}let l=u.data.session?.id??c.data.uuid??"",d=u.data.session?.clientSecret??c.data.nonce??"";if(!l||!d){r.clear();let y=new a.FloPayError("Checkout session shell was created without a session id or nonce.","api_error",{code:"InvalidCheckoutSessionResponse"});throw this.reportSessionCreateFailure(y,t,o),y}r.clear(),this.adoptDirectTelemetryCheckout(l),this.directTelemetry?.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",statusClass:o.statusClass,paymentMethodCategory:"card"}),this.directTelemetry?.performance({stage:"session_shell",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:o.statusClass,attempt:o.attempt,paymentMethodCategory:"card"});let m=!e.account.email?.trim(),g=R(e.timeoutMs??12e3),p=this.claimCheckoutSession(l,d,m?$e(e,i,n):ne(e,i,n),{params:e,startedAt:t,deadline:g,createAttempt:o.attempt}),f=m?void 0:p,v=(y={})=>{if(f)return f;let b={...e,account:{...e.account,...y,email:y.email?.trim()||e.account.email?.trim()}};return(0,a.isValidEmail)(b.account.email)?(f=p.then(()=>{let M=this.telemetryTimestamp();return this.claimCheckoutSession(l,d,Ge(b.account),{params:b,startedAt:M,deadline:R(e.timeoutMs??12e3),createAttempt:0})}),f.catch(()=>{}),f):Promise.reject(new a.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}))};return p.catch(()=>{}),{shell:u,sessionId:l,nonce:d,claimed:p,claim:v}}async claimCheckoutSession(e,t,r,o){let n=o?.startedAt??this.telemetryTimestamp(),i=this.telemetryTimestamp(),u=o?.deadline??R(12e3),c=JSON.stringify(r),l="unknown",d=0;this.directTelemetry?.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"});try{let m;for(d=0;d<3;d++){try{m=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/claim`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t,[a.FLO_SDK_VERSION_HEADER]:a.SDK_VERSION},body:c,signal:u.signal})}catch(f){let v=u.signal.aborted||f instanceof Error&&f.name==="AbortError";if(l=v?"timeout":"network_error",v||d>=2)throw f;try{this.telemetryHooks?.onRetry?.("session_claim",d+1),this.directTelemetry?.log({name:"operation.retry",stage:"session_claim",requestCategory:"session_claim",attempt:d+1})}catch{}await x(d,u.signal);continue}if(l=(0,a.telemetryStatusClass)(m.status),m.ok)break;throw await S(m,"Failed to attach checkout session data")}if(!m)throw new TypeError("Checkout-session claim exhausted its retry budget.");let g=await m.json();if(!g.data?.gateways)throw new a.FloPayError("The billing API returned no checkout session with gateways after claiming it.","api_error",{code:"InvalidCheckoutSessionResponse"});o?.params&&this.autoCacheDisplayData(g.data.uuid??e,o.params);let p=this.normalizeRawSession(this.mergeCachedDisplayData(g.data));return g.vault&&p.data.session&&(p.data.session.vault=this.toVaultBlock(g.vault)),this.directTelemetry?.log({name:"session.claim.completed",stage:"session_claim",requestCategory:"session_claim",statusClass:l}),this.directTelemetry?.performance({stage:"session_claim",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"session_claim",statusClass:l,attempt:d}),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:l}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-n),durationMode:"machine",requestCategory:"session_create",statusClass:l,attempt:o?.createAttempt??d}),p}catch(m){throw this.reportSessionCreateFailure(m,i,{attempt:d,statusClass:l},"session_claim"),m}finally{u.clear()}}reportSessionCreateFailure(e,t,r,o="session_create"){if(!(e instanceof a.FloPayError&&e.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(e)}catch{}let n=(0,a.classifyTelemetryFailure)(e,"CHECKOUT_SESSION_CREATE_FAILED");if(this.directTelemetry?.performance({stage:o,durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:o==="session_claim"?"session_claim":"session_create",statusClass:n.statusClass,attempt:r.attempt}),e instanceof a.FloPayError&&e.type==="validation_error"||e instanceof a.FloPayError&&oe(e.statusCode)){this.directTelemetry?.terminal({outcome:"validation_rejected",stage:o,requestCategory:o==="session_claim"?"session_claim":"session_create",...e.type==="validation_error"?{}:{statusClass:"4xx"}});return}e instanceof a.FloPayError&&e.code==="session_auto_completed"||this.directTelemetry?.error({...n,stage:o,requestCategory:o==="session_claim"?"session_claim":"session_create"})}async waitForCheckoutSessionCompletion(e,t){this.beginDirectTelemetryCheckout(e);let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:t?.paymentMethodCategory??"saved"});let o=t?.timeoutMs??Oe,n=Date.now()+o,i=this.clampRetryAfterMs(t?.initialDelayMs??re),u=0;try{for(;;){let c=n-Date.now();if(c<=0)throw F();if(i>0){try{u+=1,this.telemetryHooks?.onRetry?.("session_read",u),this.directTelemetry?.log({name:"operation.retry",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:t?.paymentMethodCategory??"saved",attempt:u})}catch{}if(await ie(Math.min(i,c)),Date.now()>=n)throw F()}let l=await this.getUnifiedCheckoutSessionForRecovery(e,t?.nonce),d=l.data.session?.status;if(d==="authorized"||d==="complete"||d==="expired")return this.directTelemetry?.log({name:"operation.recovery.completed",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:t?.paymentMethodCategory??"saved"}),this.directTelemetry?.performance({stage:"recovery",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"session_read",paymentMethodCategory:t?.paymentMethodCategory??"saved"}),l;if(Date.now()>=n)throw F();i=this.clampRetryAfterMs(Math.max(i*2,xe))}}catch(c){throw this.reportDirectFailure(c,"RECOVERY_FAILED","recovery","session_read",t?.paymentMethodCategory??"saved"),c}}normalizeRawSession(e){let t=e.gateways??{},r=[],o={session:this.toCheckoutSession(e)},n=t.stripe;if(n?.publishableKey){r.push("stripe");let c=[e.stripeClientSecret,n.stripeClientSecret].find(l=>typeof l=="string"&&l.length>0);o.stripe={clientSecret:c??"",publishableKey:n.publishableKey??void 0,paypalPublishableKey:n.paypalPublishableKey??void 0,environment:n.environment,enabledPaymentMethods:Array.isArray(n.enabledPaymentMethods)?n.enabledPaymentMethods.filter(l=>typeof l=="string"):void 0}}let i=t.paypal;return i?.publishableKey&&(r.push("paypal"),o.paypal={publishableKey:i.publishableKey,environment:i.environment,providerObjectType:i.providerObjectType,approvalPresentation:i.approvalPresentation}),{providers:r,mode:"tokenize",...e.checkoutMetadata===void 0?{}:{checkoutMetadata:e.checkoutMetadata},data:o,raw:{data:e}}}toCheckoutSession(e){let t=e.products??[],r=typeof e.totalAmount=="number"&&Number.isFinite(e.totalAmount),o=t.reduce((l,d)=>l+(d.overrideAmount??d.totalAmount??0),0),n=r?e.totalAmount:o,i=Math.round(n*100),u=e.currency??t[0]?.currency??"USD",c="payment";return e.checkoutMode==="setup"?c="setup":t.some(l=>l.type==="subscription")&&(c="subscription"),{id:e.uuid,clientSecret:e.nonce,mode:c,status:this.toCheckoutSessionStatus(e.status),amount:i,currency:u,captureMethod:e.captureMethod,paymentId:e.paymentId,authorizationExpiresAt:e.authorizationExpiresAt,failureOutcome:(0,a.normalizeCheckoutFailureOutcome)(e.outcome)??(0,a.normalizeCheckoutFailureOutcome)(e.failureReason)??(e.status==="expired"&&e.captureMethod==="manual"?"authorization_expired":void 0),customer:{id:e.accountData.userId??void 0,email:e.accountData.email??void 0,firstName:e.accountData.firstName??void 0,lastName:e.accountData.lastName??void 0,country:e.accountData.country??void 0,city:e.accountData.city??void 0,state:e.accountData.state??void 0,zip:e.accountData.zip??void 0,gender:e.accountData.gender??void 0,line1:e.accountData.addressLine1??void 0,line2:e.accountData.addressLine2??void 0},...e.checkoutMetadata===void 0?{}:{checkoutMetadata:e.checkoutMetadata},metadata:{},checkoutMode:e.checkoutMode,buyerIdentified:e.buyerIdentified,providerPaymentMethodId:typeof e.providerPaymentMethodId=="string"?e.providerPaymentMethodId:null,products:t.map(l=>({...l,totalAmount:typeof l.totalAmount=="number"?l.totalAmount:void 0,overrideAmount:typeof l.overrideAmount=="number"?l.overrideAmount:null,currency:typeof l.currency=="string"?l.currency:void 0,metadata:l.metadata??null})),successUrl:e.successUrl,cancelUrl:e.cancelUrl,coupons:e.coupons,subtotalAmount:e.subtotalAmount,discountAmount:e.discountAmount,totalAmount:e.totalAmount,createdAt:e.createdAt,gateways:e.gateways,accountData:e.accountData,tagsData:e.tagsData}}toVaultBlock(e){return{html:typeof e.html=="string"?e.html:void 0,url:typeof e.url=="string"?e.url:void 0,messageToken:typeof e.messageToken=="string"?e.messageToken:void 0,expectedOrigin:typeof e.expectedOrigin=="string"?e.expectedOrigin:void 0}}toCheckoutSessionStatus(e){return e==="completed"?"complete":e==="authorized"?"authorized":e==="expired"?"expired":"open"}async resolveProcessResponse(e,t,r){if(e.status!==202)return e;let o=await e.json().catch(()=>null),n=this.toCheckoutProcessingPending(o,e,t),i=await this.waitForCheckoutSessionCompletion(n.sessionId,{initialDelayMs:n.retryAfterMs,timeoutMs:r?.pollTimeoutMs,nonce:r?.nonce,paymentMethodCategory:r?.paymentMethodCategory});return this.toProcessResponseFromSession(i,t)}async reconcileProcessPayment(e,t){let r=await this.waitForCheckoutSessionCompletion(e,{initialDelayMs:0,timeoutMs:t?.pollTimeoutMs,nonce:t?.nonce,paymentMethodCategory:t?.paymentMethodCategory});return this.toProcessResponseFromSession(r,e)}toProcessResponseFromSession(e,t){if(e.data.session?.status==="complete")return new Response(null,{status:204,statusText:"No Content"});if(e.data.session?.status==="authorized"){let r=e.data.session;return new Response(JSON.stringify({status:"authorized",paymentId:r.paymentId,sessionId:r.id||t,authorizationExpiresAt:r.authorizationExpiresAt}),{status:200,headers:{"Content-Type":"application/json"}})}if(e.data.session?.status==="expired"){let r=e.data.session.failureOutcome==="authorization_expired"||e.data.session.captureMethod==="manual";throw new a.FloPayError(r?"Authorization has expired.":"Checkout session has expired.","api_error",{code:r?"authorization_expired":"checkout_session_expired"})}throw F()}toCheckoutProcessingPending(e,t,r){let o=t.headers.get("Retry-After"),n=o===null||o.trim()===""?void 0:Number(o),i=n!==void 0&&Number.isFinite(n)?n*1e3:void 0;return{type:"checkout_processing",sessionId:E(e,"sessionId")??r,retryAfterMs:this.clampRetryAfterMs(Ve(e,"retryAfterMs")??i??re),statusUrl:E(e,"statusUrl"),sessionUrl:E(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,qe))}autoCacheDisplayData(e,t){if(!e)return;let r=t.products??(0,a.foldIntoProducts)(t.items,t.subscriptions);if(r.length===0&&!t.currency)return;let o=t.products!==void 0,n=(0,a.resolveSessionCurrency)(t.currency,o?void 0:t.items,o?void 0:t.subscriptions,r);j(e,{currency:n??void 0,products:r.map(i=>({code:i.code??i.providerItemId??i.providerPlanId,type:i.type,name:i.name??i.itemName??i.providerItemName??i.subscriptionName??i.providerPlanName??null,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency??n??void 0}))})}mergeCachedDisplayData(e){let t=Q(e.uuid),r=new Map,o=i=>i?`code:${i}`:void 0;for(let i of t?.products??[]){let u=o(i.code);u&&r.set(u,i)}let n=(e.products??[]).map(i=>{let u=o(i.code),c=u?r.get(u):void 0;return{...i,name:i.name??c?.name??null,totalAmount:i.totalAmount??c?.totalAmount,overrideAmount:i.overrideAmount??c?.overrideAmount,currency:i.currency??c?.currency}});return{...e,currency:e.currency??t?.currency,products:n}}};A.activeVaultCaptureRequests=new Map;var U=A;var C=require("@flopay/shared");var G="flopay-vault",ue={ready:["vault.widget.ready","vault_ready"],submitting:["vault.submission.started","vault_submit"],blocked:["operation.state_transition","vault_submit"],action_required:["vault.action.required","three_ds_handoff"]};function Ye(s){return s.class==="lifecycle"?s.name:s.class==="technical_error"?s.code:s.class==="expected_outcome"?s.outcome:"sdk.performance"}function D(s){let e={class:s.class,stage:s.stage};"code"in s&&(e.code=s.code),"provider"in s&&s.provider&&(e.provider=s.provider),"paymentMethodCategory"in s&&s.paymentMethodCategory&&(e.paymentMethodCategory=s.paymentMethodCategory),"outcome"in s&&(e.outcome=s.outcome),"durationMs"in s&&s.durationMs!==void 0&&(e.durationMs=s.durationMs),"durationMode"in s&&s.durationMode&&(e.durationMode=s.durationMode);try{globalThis.Sentry?.addBreadcrumb?.({category:"flopay.telemetry",level:s.class==="technical_error"?"error":"info",message:Ye(s),data:e})}catch{}}function V(s,e){return(0,C.buildTelemetryLogEvent)({eventId:"11111111-1111-4111-8111-111111111111",name:s,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}function le(s){return s?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime"}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function de(s,e,t="checkout"){return t==="card_setup"?s.type==="decline"?"card_setup_declined":"card_setup_succeeded":s.type==="decline"?"payment_declined":s.outcome==="authorized"||e==="manual"?"payment_authorized":"payment_succeeded"}function We(s,e,t,r="checkout"){let{type:o}=s;if(o==="complete"||o==="decline")return(0,C.buildTelemetryTerminalEvent)({eventId:"22222222-2222-4222-8222-222222222222",outcome:de(s,t,r),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(o==="error"){let u=le(e);return(0,C.buildTelemetryErrorEvent)({eventId:"33333333-3333-4333-8333-333333333333",...u,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[n,i]=ue[o];return V(n,i)}function Je(s){if(typeof s!="object"||s===null)return!1;let e=s;return e.source===G&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function Qe(s){if(typeof s!="object"||s===null)return;let e=s,t=e.status;if(!(typeof e.id!="string"||e.id.trim()===""||typeof e.brand!="string"||e.brand.trim()===""||typeof e.lastFour!="string"||!/^\d{4}$/.test(e.lastFour)||typeof e.expiryMonth!="number"||!Number.isInteger(e.expiryMonth)||e.expiryMonth<1||e.expiryMonth>12||typeof e.expiryYear!="number"||!Number.isInteger(e.expiryYear)||e.expiryYear<1970||e.expiryYear>9999||t!=="pending"&&t!=="active"&&t!=="deleted"))return{id:e.id,brand:e.brand,lastFour:e.lastFour,expiryMonth:e.expiryMonth,expiryYear:e.expiryYear,status:t}}function Xe(s){if(typeof s!="object"||s===null)return!1;let e=s;return e.source===G&&e.type==="validation"&&Array.isArray(e.messages)}function Ze(s){if(typeof s!="object"||s===null)return!1;let e=s;return e.source===G&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}var N=class{constructor(e={},t){this.provider="pcivault";this.container=null;this.messageHandler=null;this.actionOverlay=null;this.threeDsReturnHandler=null;this.messageToken=null;this.expectedOrigin=null;this.theme=void 0;this.submitGateBlocked=!1;this.cardFieldOrder=null;this.cardAutoFocus=!0;this.submitLabel=void 0;this.mountStartedAt=0;this.vaultReadyReported=!1;this.submissionStarted=!1;this.submissionStartedAt=null;this.listeners=new Map;this.config=e,this.ownsTelemetryReporter=!t&&e.telemetry!==!1,this.telemetryReporter=t?.reporter??(this.ownsTelemetryReporter?new _({billingApiUrl:(0,C.resolveBillingApiUrl)(e.billingApiUrl),sdkVersion:C.SDK_VERSION}):void 0)}async mount(e,t){this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new _({billingApiUrl:(0,C.resolveBillingApiUrl)(this.config.billingApiUrl),sdkVersion:C.SDK_VERSION}));let r=this.telemetryReporter;if(this.config.operation==="card_setup"&&r&&this.setupTelemetryReporter!==r){this.setupTelemetryReporter=r;try{r.beginCheckout({checkoutMode:"setup"})}catch{}}if(this.mountStartedAt=this.telemetryReporter?.now?.()??k(),this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),new C.FloPayError("The vault card form is only available in the browser.","api_error",{code:"card_capture_no_window"});if(!t?.html?.trim())throw this.reportVaultLoadFailure(),new C.FloPayError("No vault capture widget HTML was provided to mount the secure card form.","api_error",{code:"card_capture_no_widget_html"});this.container=e,this.messageToken=t.messageToken??null,this.expectedOrigin=t.expectedOrigin??this.config.expectedOrigin??null,this.theme=t.theme,t.submitLabel!==void 0&&(this.submitLabel=t.submitLabel);try{this.attachMessageListener(),this.injectWidget(e,t.html)}catch(o){throw this.reportVaultLoadFailure(),o}this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postSubmitLabel(),D(V("vault.widget.mounted","vault_mount")),this.telemetryReporter?.log({name:"vault.widget.mounted",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?.performance?.({stage:"vault_mount",durationMs:Math.max(0,(this.telemetryReporter.now?.()??k())-this.mountStartedAt),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),this.emit("ready",{sessionId:this.config.sessionId})}reportVaultLoadFailure(){this.telemetryReporter?.error({errorCode:"VAULT_LOAD_FAILED",failureCategory:"provider_runtime",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"})}on(e,t){let r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(t),()=>{this.listeners.get(e)?.delete(t)}}unmount(){this.hideActionRequiredOverlay(),this.messageHandler&&(window.removeEventListener("message",this.messageHandler),this.messageHandler=null),this.container&&(this.container.replaceChildren(),this.container=null),this.messageToken=null,this.expectedOrigin=null,this.ownsTelemetryReporter&&(this.telemetryReporter?.destroy(),this.telemetryReporter=void 0)}injectWidget(e,t){e.innerHTML=t;let r=Array.from(e.querySelectorAll("script"));for(let o of r){let n=document.createElement("script");for(let i of Array.from(o.attributes))n.setAttribute(i.name,i.value);n.text=o.text,o.replaceWith(n)}}attachMessageListener(){if(this.messageHandler)return;let e=t=>{if(this.expectedOrigin&&t.origin!==this.expectedOrigin)return;let r=t.data;if(Ze(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;this.applyHeight(r.height);return}if(Xe(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;let c=r.messages.filter(l=>typeof l=="string"&&l.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:c||void 0});return}if(!Je(r)||this.messageToken&&r.messageToken!==this.messageToken)return;let o=this.config.sessionId,n=typeof r.sessionId=="string"?r.sessionId:void 0;if(o&&n&&n!==o||(r.type==="complete"||r.type==="decline")&&o&&n!==o)return;let i=Qe(r.paymentMethod),u={...r.sessionId??this.config.sessionId?{sessionId:r.sessionId??this.config.sessionId}:{},...r.outcome?{outcome:r.outcome}:{},...r.paymentId?{paymentId:r.paymentId}:{},...r.authorizationExpiresAt?{authorizationExpiresAt:r.authorizationExpiresAt}:{},...r.failureOutcome?{failureOutcome:r.failureOutcome}:{},...r.intentId?{intentId:r.intentId}:{},...r.declineReason?{declineReason:r.declineReason}:{},...r.message?{message:r.message}:{},...i?{paymentMethod:i}:{}};r.type==="submitting"&&(this.submissionStarted=!0,this.submissionStartedAt=this.telemetryReporter?.now?.()??k()),D(We(r,this.submissionStarted,this.config.captureMethod,this.config.operation)),this.reportOutcome(r),r.type==="ready"&&(this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postSubmitLabel()),r.type==="action_required"&&r.nextActionRedirectUrl&&this.showActionRequiredOverlay(r.nextActionRedirectUrl),(r.type==="complete"||r.type==="decline"||r.type==="error"||r.type==="submitting")&&this.hideActionRequiredOverlay(),r.type!=="action_required"&&this.emit(r.type,u)};this.messageHandler=e,window.addEventListener("message",e)}reportOutcome(e){let t=this.telemetryReporter;if(!t)return;let{type:r}=e;if(r==="ready"&&!this.vaultReadyReported&&(this.vaultReadyReported=!0,t.performance({stage:"vault_ready",durationMs:Math.max(0,t.now()-this.mountStartedAt),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card",requestCategory:"provider_sdk"})),r==="complete"||r==="decline"){t.log({name:"vault.terminal",stage:"completion",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:de(e,this.config.captureMethod,this.config.operation),provider:"pcivault",paymentMethodCategory:"card"});return}if(r==="error"){let i=le(this.submissionStarted);t.log({name:"vault.terminal",stage:i.stage,provider:"pcivault",paymentMethodCategory:"card"}),t.error({...i,provider:"pcivault",paymentMethodCategory:"card"});return}if(r==="action_required"){t.log({name:"vault.action.required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"}),t.log({name:"vault.three_ds.handoff",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});let i=this.submissionStartedAt;this.submissionStartedAt=null,i!==null&&t.performance({stage:"three_ds_handoff",durationMs:Math.max(0,t.now()-i),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});return}let[o,n]=ue[r];t.log({name:o,stage:n,provider:"pcivault",paymentMethodCategory:"card"})}applyTheme(e){this.theme=e,this.postTheme()}postTheme(){this.theme!==void 0&&this.postToHostedWindow({source:"flopay-vault-host",type:"theme",theme:this.theme},this.directiveTargetOrigin())}setSubmitGate(e){this.submitGateBlocked=e,this.postSubmitGate()}postSubmitGate(){this.postToHostedWindow({source:"flopay-vault-host",type:"gate",blocked:this.submitGateBlocked},this.directiveTargetOrigin())}setCardFieldOrder(e,t){this.cardFieldOrder=e,this.cardAutoFocus=t,this.postCardFieldOrder()}postCardFieldOrder(){this.postToHostedWindow({source:"flopay-vault-host",type:"fieldOrder",order:this.cardFieldOrder,autoFocus:this.cardAutoFocus},this.directiveTargetOrigin())}setSubmitLabel(e){this.submitLabel=e,this.postSubmitLabel()}postSubmitLabel(){let e=this.submitLabel,t=this.config.sessionId,{messageToken:r,expectedOrigin:o}=this;e===void 0||!t||!r||!o||this.postToHostedWindow({source:"flopay-vault-host",type:"submitLabel",sessionId:t,messageToken:r,label:e},o)}hostedWindow(){return this.container?.querySelector("iframe")?.contentWindow??null}postToHostedWindow(e,t){let r=this.hostedWindow();if(r)try{r.postMessage(e,t)}catch{}}directiveTargetOrigin(){return this.expectedOrigin??"*"}emit(e,t){for(let r of this.listeners.get(e)??[])r(t)}showActionRequiredOverlay(e){if(typeof document>"u")return;if(this.actionOverlay){let i=this.actionOverlay.querySelector("iframe");i instanceof HTMLIFrameElement&&(i.src=e);return}let t=document.createElement("div");t.setAttribute("data-flopay-action-required","1"),t.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let r=document.createElement("iframe");r.setAttribute("title","Card authentication"),r.setAttribute("allow","payment"),r.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),r.src=e,t.appendChild(r);let o=document.createElement("button");o.type="button",o.setAttribute("aria-label","Close card authentication"),o.textContent="\xD7",o.style.cssText=["position:fixed","top:20px","right:20px","width:40px","height:40px","border:0","border-radius:9999px","background:#fff","color:#0f172a","font-size:28px","line-height:40px","cursor:pointer","box-shadow:0 4px 14px rgba(0,0,0,0.25)"].join(";"),o.addEventListener("click",()=>this.abandonActionRequiredOverlay()),t.appendChild(o),t.addEventListener("click",i=>{i.target===t&&this.abandonActionRequiredOverlay()});let n=i=>{if(i.source!==r.contentWindow)return;let u=i.data;if(!u||typeof u!="object")return;let c=u;c.source==="flopay-vault-3ds-return"&&(D(V("vault.three_ds.returned","three_ds_return")),this.telemetryReporter?.log({name:"vault.three_ds.returned",stage:"three_ds_return",provider:"pcivault",paymentMethodCategory:"card"}),this.hideActionRequiredOverlay(),this.postActionCompleted(c.status))};window.addEventListener("message",n),this.threeDsReturnHandler=n,document.body.appendChild(t),this.actionOverlay=t,D(V("vault.three_ds.handoff","three_ds_handoff"))}postActionCompleted(e){this.postToHostedWindow({source:"flopay-vault-host",type:"action_completed",status:typeof e=="string"?e:"unknown"},this.directiveTargetOrigin())}abandonActionRequiredOverlay(){if(!this.actionOverlay)return;let e=(0,C.buildTelemetryTerminalEvent)({eventId:"77777777-7777-4777-8777-777777777777",outcome:"customer_abandoned",stage:"three_ds_handoff",sequence:0,provider:"pcivault",paymentMethodCategory:"card"});D(e),this.telemetryReporter?.terminal({outcome:"customer_abandoned",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"}),this.hideActionRequiredOverlay(),this.postActionCompleted("abandoned")}hideActionRequiredOverlay(){this.threeDsReturnHandler&&(window.removeEventListener("message",this.threeDsReturnHandler),this.threeDsReturnHandler=null),this.actionOverlay&&(this.actionOverlay.parentNode?.removeChild(this.actionOverlay),this.actionOverlay=null)}applyHeight(e){let t=this.container?.querySelector("iframe");if(!t)return;let r=Math.max(0,Math.min(Math.ceil(e),2e3));t.style.height=`${r}px`}};0&&(module.exports={PaymentAPI,PciVaultCardCapture});
|
package/dist/card-setup.d.cts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export { C as CardCaptureOperation, P as PaymentAPI, a as PciVaultCardCapture, b as PciVaultCardCaptureConfig } from './card-setup-
|
|
1
|
+
export { C as CardCaptureOperation, P as PaymentAPI, a as PciVaultCardCapture, b as PciVaultCardCaptureConfig } from './card-setup-Bste6_2o.cjs';
|
|
2
2
|
import '@flopay/shared';
|
package/dist/card-setup.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export { C as CardCaptureOperation, P as PaymentAPI, a as PciVaultCardCapture, b as PciVaultCardCaptureConfig } from './card-setup-
|
|
1
|
+
export { C as CardCaptureOperation, P as PaymentAPI, a as PciVaultCardCapture, b as PciVaultCardCaptureConfig } from './card-setup-Bste6_2o.js';
|
|
2
2
|
import '@flopay/shared';
|
package/dist/card-setup.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{k as r,m as a}from"./chunk-
|
|
1
|
+
import{k as r,m as a}from"./chunk-53ZIPQCZ.mjs";export{r as PaymentAPI,a as PciVaultCardCapture};
|