@lockerverse/react 0.2.222 → 0.2.223-dev.1

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/MIGRATIONS.md CHANGED
@@ -4,6 +4,18 @@ This file ships in both @lockerverse/sdk and @lockerverse/react. Use the copy in
4
4
  the target installed release. This is an agent-run procedure, not an install
5
5
  script. Installing a package does not edit host code or guarantee these steps ran.
6
6
 
7
+ ## 0.2.223-dev.1 — optional bookings
8
+
9
+ - No change is required for existing checkout, signup, auction or event consumers.
10
+ - Booking hosts must import the separate `@lockerverse/sdk/bookings` and
11
+ `@lockerverse/react/bookings` entries and read `guides/bookings.md`.
12
+ - Load `@lockerverse/react/booking-payment` only when a recovered attempt can pay.
13
+ Follow the optional Stripe peers in the target package manifest.
14
+ - Move business credentials and payment/booking work to the Lockerverse backend.
15
+ Keep host access storage private and update the hook sessionKey on access changes.
16
+ - Do not release an unknown payment outcome by clearing local state. Recover the
17
+ saved server attempt before permitting another payment.
18
+
7
19
  ## Upgrade procedure
8
20
 
9
21
  1. Before installation, record the resolved installed version of each package
@@ -314,7 +326,7 @@ No host prop change is required.
314
326
  - **Check:** inspect a wide and a tall photo on desktop and mobile. Confirm all
315
327
  edges remain visible in the item gallery, thumbnails, and full-screen viewer.
316
328
 
317
- ## 0.2.191 — auction item additional charges
329
+ ## 0.2.192-dev.1 — auction item additional charges
318
330
 
319
331
  - **Affected:** Core auction item data, purchase quotes, and React auction checkout.
320
332
  - **Automatic:** optional `additionalCharge` charges the first-item amount plus the
@@ -332,7 +344,7 @@ No host prop change is required.
332
344
  - **Check:** compare one, two, and maximum quantity totals with the server quote,
333
345
  verify the per-order limit, and inspect the named charge row before payment.
334
346
 
335
- ## 0.2.189 — widget load recovery and Sentry releases
347
+ ## 0.2.190-dev.1 — widget load recovery and Sentry releases
336
348
 
337
349
  - **Affected:** Core widget loading and SDK failure reporting.
338
350
  - **Automatic:** a widget GET retries once after a network failure or request
@@ -359,6 +371,7 @@ No host prop change is required.
359
371
  - **Check:** select one, two, and the maximum allowed trigger quantity. Confirm the
360
372
  local summary and server quote agree; removing all trigger items removes shipping.
361
373
 
374
+
362
375
  ## 0.2.184 — single focus boundary for form fields
363
376
 
364
377
  - **Affected:** React form controls and the shared phone field in payment and signup.
@@ -378,7 +391,7 @@ Widgets can now use a private contact list for email eligibility, a fixed amount
378
391
  Required shipping appears in `catalog.widget.requiredShipping`. Do not offer this product as a separate shopper choice. The SDK adds its quantity once when a trigger product is selected; the server also enforces this rule. Render authoritative quote line items and totals, including shipping. The built-in launcher and payment summary handle this automatically.
379
392
 
380
393
 
381
- ## 0.2.177 — Secure checkout loading recovery
394
+ ## 0.2.176-dev.1 — Secure checkout loading recovery
382
395
 
383
396
  - **Affected:** React payment widget Stripe fields.
384
397
  - **Automatic:** failed field or script loads show a reload action. Fields that
@@ -390,9 +403,23 @@ Required shipping appears in `catalog.widget.requiredShipping`. Do not offer thi
390
403
  - Reload is an explicit customer action and can clear unsaved form entries.
391
404
  Saved payment recovery remains in session storage.
392
405
 
393
-
394
406
  ## 0.2.175 — Match Stripe Elements payment method configuration
395
407
 
408
+ - **Affected:** Core checkout submission and React payment widgets.
409
+ - **Automatic:** React configures explicit card, Link, and community-enabled bank
410
+ methods in Stripe Elements and marks the confirmation request with
411
+ `paymentMethodConfiguration: "explicit"`. This matches the backend's Stripe
412
+ PaymentIntent configuration.
413
+ - **Required:** deploy the backend that supports this optional marker before
414
+ upgrading React. Keep Core and React matched. Existing Core-only callers omit
415
+ the marker and retain automatic payment methods. Custom Elements integrations
416
+ must send the marker only when they use the explicit method list.
417
+ - **Check:** submit card and bank payments through Stripe Elements in test mode,
418
+ including recurring checkout. Confirm pending recovery and settlement.
419
+
420
+
421
+ ## 0.2.174-dev.1 — Match Stripe Elements payment method configuration
422
+
396
423
  - **Affected:** Core checkout submission and React payment widgets.
397
424
  - **Automatic:** React configures explicit card, Link, and community-enabled bank
398
425
  methods in Stripe Elements and marks the confirmation request with
@@ -466,7 +493,39 @@ Required shipping appears in `catalog.widget.requiredShipping`. Do not offer thi
466
493
  verify a changed selection cannot discard it. Check both paid and free order
467
494
  confirmation panels. Do not submit a live transaction for this check.
468
495
 
469
- ## 0.2.170 — six-month payment widgets
496
+ ## 0.2.172-dev.1 — Check pending payment status
497
+
498
+ - **Affected:** React payment widgets with unresolved payments.
499
+ - **Automatic behavior:** the existing pending-payment screen now offers Check
500
+ payment status. It checks the saved payment reference and cannot submit a new
501
+ payment. The control is disabled while the check runs.
502
+ - **Required host changes:** none. Update Core and React together.
503
+ - **Verification:** complete a test bank payment, return to its pending checkout,
504
+ and check its status. Confirm completion clears recovery storage.
505
+
506
+ ## 0.2.171-dev.1 — SDK payment recovery and completion UI
507
+
508
+ - **Affected:** React payment widgets and custom hosts that persist payment recovery.
509
+ - **Optional adoption:** pass `recoveryStorageKey` to `LockerversePayment` to let
510
+ the SDK save and restore the pending payment in session storage. Use a stable
511
+ key scoped to the API environment, community, and widget. Remove the host's
512
+ storage code and recovery-driven component key. Do not combine automatic
513
+ persistence with a second host persistence writer.
514
+ - **Compatibility:** the SDK reads the hosted Next app's existing version 1
515
+ records when the same key is used. It writes version 2 records with widget
516
+ identity. It checks widget and selection identity before recovery and keeps
517
+ an unresolved record if those details differ. Recovery uses the saved connected
518
+ account even if current payment routing has changed. Storage is read after hydration,
519
+ before the payable form mounts. No contact details or payment tokens are saved.
520
+ - **Optional UI adoption:** use `completionView="summary"` for the SDK confirmation
521
+ panel and remove the host's duplicate success panel. Completion callbacks still
522
+ run. The default inline message and explicit `resumePayment` integrations remain
523
+ supported. Auctions and legacy custom checkout forms are unchanged.
524
+ - **Check:** reload a pending checkout and confirm the existing payment is checked;
525
+ verify a changed selection cannot discard it. Check both paid and free order
526
+ confirmation panels. Do not submit a live transaction for this check.
527
+
528
+ ## 0.2.169-dev.1 — six-month payment widgets
470
529
 
471
530
  Affected: @lockerverse/sdk checkout and @lockerverse/react payment widgets.
472
531
 
@@ -482,6 +541,31 @@ Affected: @lockerverse/sdk checkout and @lockerverse/react payment widgets.
482
541
  submission. Do not submit a live payment for an integration check.
483
542
 
484
543
 
544
+ ## 0.2.168-dev.1 — bank authorization terms
545
+
546
+ - **Affected:** React payment widgets with ACH enabled.
547
+ - **Automatic:** Stripe displays its bank authorization terms before payment confirmation.
548
+ - **Adoption:** update the matching SDK/React development pair. No prop changes are required.
549
+ - **Check:** confirm that the bank authorization text is visible when a bank account is selected.
550
+
551
+ ## 0.2.167-dev.1 — widget ACH and subscription payment recovery
552
+
553
+ - **Affected:** Core checkout data and React payment widgets.
554
+ - **Automatic:** bank payment availability follows the organization default and
555
+ community override returned by the backend. Missing policy remains disabled.
556
+ Pending payments keep their existing payment reference. A failed subscription
557
+ invoice can return `action_required` with `requiresAction: false` and `retryUrl`;
558
+ React shows a link to pay the same invoice instead of creating a second subscription.
559
+ - **Required for custom payment UI:** preserve the reference for pending and
560
+ action-required results. Handle `retryUrl` by opening that invoice, and recover
561
+ status before permitting a new checkout. Do not treat submission as settlement.
562
+ - **Adoption:** deploy the matching backend policy and recovery contract before
563
+ enabling ACH. Existing React hosts need no component prop changes. Keep Core and
564
+ React versions matched when upgrading. Auction payment methods are unchanged.
565
+ - **Check:** verify disabled/inherited/enabled bank visibility and pending, bank
566
+ verification, invoice retry, success, and terminal failure in Stripe test mode.
567
+ Do not create a live transaction for this check.
568
+
485
569
  ## 0.2.166 — single dropdown arrow
486
570
 
487
571
  - **Affected:** native single-select custom fields in React signup and payment forms.
@@ -0,0 +1,18 @@
1
+ import { ReactNode } from "react";
2
+ import { LockerverseBookingAttempt } from "@lockerverse/sdk/bookings";
3
+ //#region src/booking-payment.d.ts
4
+ type LockerverseBookingPaymentProps = {
5
+ publishableKey: string;
6
+ amountCents: number;
7
+ currency: "USD";
8
+ onConfirm: (confirmationToken: string) => Promise<LockerverseBookingAttempt> | Promise<void>;
9
+ disabled?: boolean;
10
+ className?: string;
11
+ buttonClassName?: string;
12
+ buttonLabel?: ReactNode;
13
+ };
14
+ /** Import this entry only when the recovered attempt is ready for card entry. */
15
+ declare function LockerverseBookingPayment(props: LockerverseBookingPaymentProps): import("react").JSX.Element;
16
+ //#endregion
17
+ export { LockerverseBookingPayment, type LockerverseBookingPaymentProps };
18
+ //# sourceMappingURL=booking-payment.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"booking-payment.d.ts","names":[],"sources":["../src/booking-payment.tsx"],"mappings":";;;KAaY;EACV;EACA;EACA;EACA,YACE,8BACG,QAAQ,6BAA6B;EAC1C;EACA;EACA;EACA,cAAc;;;iBAwEA,0BACd,OAAO,iDAA8B,IAAA"}
@@ -0,0 +1,2 @@
1
+ import{useEffect as e,useRef as t,useState as n}from"react";import{jsx as r,jsxs as i}from"react/jsx-runtime";import{Elements as a,PaymentElement as o,useElements as s,useStripe as c}from"@stripe/react-stripe-js";import{loadStripe as l}from"@stripe/stripe-js/pure/index.js";const u=/^pk_(?:test|live)_/;function d(e){let a=c(),l=s(),u=t(!1),d=t(!1),[f,p]=n(!1),[m,h]=n(!1),[g,_]=n(``);async function v(){if(!(!(a&&l&&m)||e.disabled||u.current||d.current)){u.current=!0,p(!0),_(``);try{if((await l.submit()).error){_(`Check your card details.`);return}let t=await a.createConfirmationToken({elements:l});if(t.error||!t.confirmationToken){_(`Card details could not be confirmed. No payment was submitted.`);return}d.current=!0,await e.onConfirm(t.confirmationToken.id)}catch{_(`Check the saved booking state before trying payment again.`)}finally{u.current=!1,p(!1)}}}return i(`div`,{className:e.className,children:[r(o,{onLoadError:()=>{h(!1),_(`Card entry could not load. Reload the page and recover this booking; do not start another payment.`)},onReady:()=>h(!0),options:{wallets:{applePay:`never`,googlePay:`never`}}}),!(m||g)&&r(`p`,{role:`status`,children:`Loading secure card entry…`}),g&&r(`p`,{role:`alert`,children:g}),r(`button`,{className:e.buttonClassName,disabled:!m||f||d.current||e.disabled,onClick:v,type:`button`,children:f?`Checking payment…`:e.buttonLabel??`Pay and book`})]})}function f(t){let[i,o]=n(null),[s,c]=n(!1),f=`${t.publishableKey}:${t.amountCents}:${t.currency}`,[p]=n(f);if(f!==p)throw Error(`Remount booking payment when its confirmed payment configuration changes.`);if(!(u.test(t.publishableKey)&&Number.isSafeInteger(t.amountCents))||t.amountCents<=0||t.currency!==`USD`)throw TypeError(`A valid server-provided booking payment configuration is required.`);return e(()=>{let e=!0;return l(t.publishableKey).then(t=>{e&&(o(t),c(!t))}).catch(()=>{e&&c(!0)}),()=>{e=!1}},[t.publishableKey]),s?r(`p`,{role:`alert`,children:`Secure card entry could not load. Recover this booking after reloading the page.`}):i?r(a,{options:{allowedPaymentMethodTypes:[`card`],amount:t.amountCents,currency:`usd`,mode:`payment`,setupFutureUsage:`off_session`},stripe:i,children:r(d,{...t})}):r(`p`,{role:`status`,children:`Loading secure card entry…`})}export{f as LockerverseBookingPayment};
2
+ //# sourceMappingURL=booking-payment.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"booking-payment.js","names":[],"sources":["../src/booking-payment.tsx"],"sourcesContent":["import type { LockerverseBookingAttempt } from \"@lockerverse/sdk/bookings\";\nimport {\n Elements,\n PaymentElement,\n useElements,\n useStripe,\n} from \"@stripe/react-stripe-js\";\nimport type { Stripe } from \"@stripe/stripe-js\";\nimport { loadStripe } from \"@stripe/stripe-js/pure\";\nimport { type ReactNode, useEffect, useRef, useState } from \"react\";\n\nconst publishableKeyPattern = /^pk_(?:test|live)_/;\n\nexport type LockerverseBookingPaymentProps = {\n publishableKey: string;\n amountCents: number;\n currency: \"USD\";\n onConfirm: (\n confirmationToken: string\n ) => Promise<LockerverseBookingAttempt> | Promise<void>;\n disabled?: boolean;\n className?: string;\n buttonClassName?: string;\n buttonLabel?: ReactNode;\n};\n\nfunction BookingCardForm(props: LockerverseBookingPaymentProps) {\n const stripe = useStripe();\n const elements = useElements();\n const submitting = useRef(false);\n const sentToBackend = useRef(false);\n const [busy, setBusy] = useState(false);\n const [ready, setReady] = useState(false);\n const [error, setError] = useState(\"\");\n async function submit() {\n if (\n !(stripe && elements && ready) ||\n props.disabled ||\n submitting.current ||\n sentToBackend.current\n ) {\n return;\n }\n submitting.current = true;\n setBusy(true);\n setError(\"\");\n try {\n const submitted = await elements.submit();\n if (submitted.error) {\n setError(\"Check your card details.\");\n return;\n }\n const result = await stripe.createConfirmationToken({ elements });\n if (result.error || !result.confirmationToken) {\n setError(\n \"Card details could not be confirmed. No payment was submitted.\"\n );\n return;\n }\n sentToBackend.current = true;\n await props.onConfirm(result.confirmationToken.id);\n } catch {\n setError(\"Check the saved booking state before trying payment again.\");\n } finally {\n submitting.current = false;\n setBusy(false);\n }\n }\n return (\n <div className={props.className}>\n <PaymentElement\n onLoadError={() => {\n setReady(false);\n setError(\n \"Card entry could not load. Reload the page and recover this booking; do not start another payment.\"\n );\n }}\n onReady={() => setReady(true)}\n options={{ wallets: { applePay: \"never\", googlePay: \"never\" } }}\n />\n {!(ready || error) && <p role=\"status\">Loading secure card entry…</p>}\n {error && <p role=\"alert\">{error}</p>}\n <button\n className={props.buttonClassName}\n disabled={!ready || busy || sentToBackend.current || props.disabled}\n onClick={submit}\n type=\"button\"\n >\n {busy ? \"Checking payment…\" : (props.buttonLabel ?? \"Pay and book\")}\n </button>\n </div>\n );\n}\n\n/** Import this entry only when the recovered attempt is ready for card entry. */\nexport function LockerverseBookingPayment(\n props: LockerverseBookingPaymentProps\n) {\n const [stripe, setStripe] = useState<Stripe | null>(null);\n const [failed, setFailed] = useState(false);\n const identity = `${props.publishableKey}:${props.amountCents}:${props.currency}`;\n const [initialIdentity] = useState(identity);\n if (identity !== initialIdentity) {\n throw new Error(\n \"Remount booking payment when its confirmed payment configuration changes.\"\n );\n }\n if (\n !(\n publishableKeyPattern.test(props.publishableKey) &&\n Number.isSafeInteger(props.amountCents)\n ) ||\n props.amountCents <= 0 ||\n props.currency !== \"USD\"\n ) {\n throw new TypeError(\n \"A valid server-provided booking payment configuration is required.\"\n );\n }\n useEffect(() => {\n let active = true;\n loadStripe(props.publishableKey)\n .then((result) => {\n if (active) {\n setStripe(result);\n setFailed(!result);\n }\n })\n .catch(() => {\n if (active) {\n setFailed(true);\n }\n });\n return () => {\n active = false;\n };\n }, [props.publishableKey]);\n if (failed) {\n return (\n <p role=\"alert\">\n Secure card entry could not load. Recover this booking after reloading\n the page.\n </p>\n );\n }\n if (!stripe) {\n return <p role=\"status\">Loading secure card entry…</p>;\n }\n return (\n <Elements\n options={{\n allowedPaymentMethodTypes: [\"card\"],\n amount: props.amountCents,\n currency: \"usd\",\n mode: \"payment\",\n setupFutureUsage: \"off_session\",\n }}\n stripe={stripe}\n >\n <BookingCardForm {...props} />\n </Elements>\n );\n}\n"],"mappings":"kRAWA,MAAM,EAAwB,qBAe9B,SAAS,EAAgB,EAAuC,CAC9D,IAAM,EAAS,EAAU,EACnB,EAAW,EAAY,EACvB,EAAa,EAAO,EAAK,EACzB,EAAgB,EAAO,EAAK,EAC5B,CAAC,EAAM,GAAW,EAAS,EAAK,EAChC,CAAC,EAAO,GAAY,EAAS,EAAK,EAClC,CAAC,EAAO,GAAY,EAAS,EAAE,EACrC,eAAe,GAAS,CAEpB,OAAE,GAAU,GAAY,IACxB,EAAM,UACN,EAAW,SACX,EAAc,SAMhB,CAFA,EAAW,QAAU,GACrB,EAAQ,EAAI,EACZ,EAAS,EAAE,EACX,GAAI,CAEF,IAAI,MADoB,EAAS,OAAO,EAAA,CAC1B,MAAO,CACnB,EAAS,0BAA0B,EACnC,MACF,CACA,IAAM,EAAS,MAAM,EAAO,wBAAwB,CAAE,UAAS,CAAC,EAChE,GAAI,EAAO,OAAS,CAAC,EAAO,kBAAmB,CAC7C,EACE,gEACF,EACA,MACF,CACA,EAAc,QAAU,GACxB,MAAM,EAAM,UAAU,EAAO,kBAAkB,EAAE,CACnD,MAAQ,CACN,EAAS,4DAA4D,CACvE,QAAU,CACR,EAAW,QAAU,GACrB,EAAQ,EAAK,CACf,CArBW,CAsBb,CACA,OACE,EAAC,MAAD,CAAK,UAAW,EAAM,UAAtB,SAAA,CACE,EAAC,EAAD,CACE,gBAAmB,CACjB,EAAS,EAAK,EACd,EACE,oGACF,CACF,EACA,YAAe,EAAS,EAAI,EAC5B,QAAS,CAAE,QAAS,CAAE,SAAU,QAAS,UAAW,OAAQ,CAAE,CAC/D,CAAA,EACA,EAAE,GAAS,IAAU,EAAC,IAAD,CAAG,KAAK,SAAS,SAAA,4BAA6B,CAAA,EACnE,GAAS,EAAC,IAAD,CAAG,KAAK,QAAS,SAAA,CAAS,CAAA,EACpC,EAAC,SAAD,CACE,UAAW,EAAM,gBACjB,SAAU,CAAC,GAAS,GAAQ,EAAc,SAAW,EAAM,SAC3D,QAAS,EACT,KAAK,SAEJ,SAAA,EAAO,oBAAuB,EAAM,aAAe,cAC9C,CAAA,CACL,GAET,CAGA,SAAgB,EACd,EACA,CACA,GAAM,CAAC,EAAQ,GAAa,EAAwB,IAAI,EAClD,CAAC,EAAQ,GAAa,EAAS,EAAK,EACpC,EAAW,GAAG,EAAM,eAAe,GAAG,EAAM,YAAY,GAAG,EAAM,WACjE,CAAC,GAAmB,EAAS,CAAQ,EAC3C,GAAI,IAAa,EACf,MAAU,MACR,2EACF,EAEF,GACE,EACE,EAAsB,KAAK,EAAM,cAAc,GAC/C,OAAO,cAAc,EAAM,WAAW,IAExC,EAAM,aAAe,GACrB,EAAM,WAAa,MAEnB,MAAU,UACR,oEACF,EA+BF,OA7BA,MAAgB,CACd,IAAI,EAAS,GAab,OAZA,EAAW,EAAM,cAAc,CAAC,CAC7B,KAAM,GAAW,CACZ,IACF,EAAU,CAAM,EAChB,EAAU,CAAC,CAAM,EAErB,CAAC,CAAC,CACD,UAAY,CACP,GACF,EAAU,EAAI,CAElB,CAAC,MACU,CACX,EAAS,EACX,CACF,EAAG,CAAC,EAAM,cAAc,CAAC,EACrB,EAEA,EAAC,IAAD,CAAG,KAAK,QAAQ,SAAA,kFAGb,CAAA,EAGF,EAIH,EAAC,EAAD,CACE,QAAS,CACP,0BAA2B,CAAC,MAAM,EAClC,OAAQ,EAAM,YACd,SAAU,MACV,KAAM,UACN,iBAAkB,aACpB,EACQ,SAER,SAAA,EAAC,EAAD,CAAiB,GAAI,CAAQ,CAAA,CACrB,CAAA,EAdH,EAAC,IAAD,CAAG,KAAK,SAAS,SAAA,4BAA6B,CAAA,CAgBzD"}
@@ -0,0 +1,28 @@
1
+ import { LockerverseBookingAttempt, LockerverseBookingAttempt as LockerverseBookingAttempt$1, LockerverseBookingAvailability, LockerverseBookingBusiness, LockerverseBookingConfiguration, LockerverseBookingConfiguration as LockerverseBookingConfiguration$1, LockerverseBookingSelection, LockerverseBookingStatus, LockerverseBookingsClient, LockerverseSdkError } from "@lockerverse/sdk/bookings";
2
+ //#region src/use-lockerverse-bookings.d.ts
3
+ type UseLockerverseBookingsOptions = {
4
+ enabled?: boolean;
5
+ /** Non-secret generation value. Change it when the access session changes. */
6
+ sessionKey?: string | number;
7
+ };
8
+ type UseLockerverseBookingsResult = {
9
+ configuration: LockerverseBookingConfiguration$1 | null;
10
+ slots: string[];
11
+ availabilityMessage: string;
12
+ attempt: LockerverseBookingAttempt$1 | null;
13
+ busy: boolean;
14
+ recovering: boolean;
15
+ recovered: boolean;
16
+ error: LockerverseSdkError | null;
17
+ canPay: boolean;
18
+ refresh: () => Promise<void>;
19
+ findTimes: (date: string) => Promise<LockerverseBookingAvailability>;
20
+ initialize: (selection: LockerverseBookingSelection) => Promise<LockerverseBookingAttempt$1>;
21
+ confirm: (confirmationToken: string) => Promise<LockerverseBookingAttempt$1>;
22
+ recover: () => Promise<LockerverseBookingAttempt$1 | null>;
23
+ };
24
+ /** Recover the business-scoped attempt before permitting a payment submission. */
25
+ declare function useLockerverseBookings(client: LockerverseBookingsClient, { enabled, sessionKey }?: UseLockerverseBookingsOptions): UseLockerverseBookingsResult;
26
+ //#endregion
27
+ export { type LockerverseBookingAttempt, type LockerverseBookingBusiness, type LockerverseBookingConfiguration, type LockerverseBookingStatus, type UseLockerverseBookingsOptions, type UseLockerverseBookingsResult, useLockerverseBookings };
28
+ //# sourceMappingURL=bookings.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bookings.d.ts","names":[],"sources":["../src/use-lockerverse-bookings.ts"],"mappings":";;KAUY;EACV;;EAEA;;KAEU;EACV,eAAe;EACf;EACA;EACA,SAAS;EACT;EACA;EACA;EACA,OAAO;EACP;EACA,eAAe;EACf,YAAY,iBAAiB,QAAQ;EACrC,aACE,WAAW,gCACR,QAAQ;EACb,UAAU,8BAA8B,QAAQ;EAChD,eAAe,QAAQ;;;iBA4CT,uBACd,QAAQ,6BACN,SAAgB,eAAkB,gCACnC"}
@@ -0,0 +1,2 @@
1
+ import{useCallback as e,useEffect as t,useRef as n,useState as r}from"react";import{LockerverseSdkError as i}from"@lockerverse/sdk/bookings";const a=()=>({attempt:null,availabilityMessage:``,busy:!1,configuration:null,error:null,recovered:!1,recovering:!1,slots:[]});function o(e){return new i({code:`booking_request_failed`,message:e,operation:`recover_booking`,recoveryRecommended:!0,reportable:!1})}function s(e){return e instanceof i?e:o(`The booking request could not be completed. Check the saved state before paying.`)}function c(i,{enabled:c=!0,sessionKey:l=0}={}){if(n(i).current!==i)throw Error(`Keep the booking client stable. Remount for another business.`);let[u,d]=r(a),f=n(u),p=n(0),m=n(!1),h=n(l),g=n(!1),_=e(e=>{f.current={...f.current,...e},d(f.current)},[]),v=e(async(e,t,n,r=!1)=>{if(!(c&&m.current)||h.current!==l||g.current)throw o(`A booking request is already in progress or access is disabled.`);g.current=!0;let i=p.current,a=()=>i===p.current;_({busy:!0,error:null,recovered:!n&&f.current.recovered,recovering:r});try{let n=await e();if(!a())throw o(`The booking access session changed. Recover the current session.`);return _(t(n)),n}catch(e){let t=s(e);throw a()&&_({error:t,recovered:!n&&f.current.recovered}),t}finally{i===p.current&&(g.current=!1,_({busy:!1,recovering:!1}))}},[_,c,l]),y=e(async()=>{await v(async()=>{let e=await i.configuration();return{attempt:await i.recover(),configuration:e}},e=>({...e,recovered:!0}),!0,!0)},[i,v]),b=e(()=>v(()=>i.recover(),e=>({attempt:e,recovered:!0}),!0,!0),[i,v]),x=e(e=>v(()=>i.availability(e),e=>({availabilityMessage:e.message,slots:e.slots}),!1),[i,v]),S=e(e=>{let t=f.current;return!(t.configuration?.ready&&t.recovered)||t.attempt?Promise.reject(o(`Recover the saved booking before selecting a new session.`)):v(()=>i.initialize(e),e=>({attempt:e,recovered:!0}),!0)},[i,v]),C=e(e=>{let t=f.current;return t.configuration?.ready&&t.recovered&&t.attempt?.status===`review`?v(()=>i.confirm(e),e=>({attempt:e,recovered:e.status!==`review`}),!0):Promise.reject(o(`Recover this attempt before submitting a payment.`))},[i,v]);return t(()=>(p.current+=1,g.current=!1,m.current=c,h.current=l,f.current=a(),d(f.current),c&&y().catch(()=>void 0),()=>{m.current=!1,p.current+=1}),[c,l,y]),{...u,canPay:!!(c&&h.current===l&&u.configuration?.ready&&u.recovered&&u.attempt?.status===`review`&&!u.busy),confirm:C,findTimes:x,initialize:S,recover:b,refresh:y}}export{c as useLockerverseBookings};
2
+ //# sourceMappingURL=bookings.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bookings.js","names":[],"sources":["../src/use-lockerverse-bookings.ts"],"sourcesContent":["import {\n type LockerverseBookingAttempt,\n type LockerverseBookingAvailability,\n type LockerverseBookingConfiguration,\n type LockerverseBookingSelection,\n type LockerverseBookingsClient,\n LockerverseSdkError,\n} from \"@lockerverse/sdk/bookings\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\n\nexport type UseLockerverseBookingsOptions = {\n enabled?: boolean;\n /** Non-secret generation value. Change it when the access session changes. */\n sessionKey?: string | number;\n};\nexport type UseLockerverseBookingsResult = {\n configuration: LockerverseBookingConfiguration | null;\n slots: string[];\n availabilityMessage: string;\n attempt: LockerverseBookingAttempt | null;\n busy: boolean;\n recovering: boolean;\n recovered: boolean;\n error: LockerverseSdkError | null;\n canPay: boolean;\n refresh: () => Promise<void>;\n findTimes: (date: string) => Promise<LockerverseBookingAvailability>;\n initialize: (\n selection: LockerverseBookingSelection\n ) => Promise<LockerverseBookingAttempt>;\n confirm: (confirmationToken: string) => Promise<LockerverseBookingAttempt>;\n recover: () => Promise<LockerverseBookingAttempt | null>;\n};\n\ntype BookingState = Pick<\n UseLockerverseBookingsResult,\n | \"configuration\"\n | \"slots\"\n | \"availabilityMessage\"\n | \"attempt\"\n | \"busy\"\n | \"recovering\"\n | \"recovered\"\n | \"error\"\n>;\nconst initialState = (): BookingState => ({\n attempt: null,\n availabilityMessage: \"\",\n busy: false,\n configuration: null,\n error: null,\n recovered: false,\n recovering: false,\n slots: [],\n});\nfunction stateError(message: string) {\n return new LockerverseSdkError({\n code: \"booking_request_failed\",\n message,\n operation: \"recover_booking\",\n recoveryRecommended: true,\n reportable: false,\n });\n}\n\n// oxlint-disable-next-line anti-slop/no-unknown-parameters -- Promise rejection values are untrusted and are normalized here.\nfunction safeBookingError(error: unknown): LockerverseSdkError {\n return error instanceof LockerverseSdkError\n ? error\n : stateError(\n \"The booking request could not be completed. Check the saved state before paying.\"\n );\n}\n\n/** Recover the business-scoped attempt before permitting a payment submission. */\nexport function useLockerverseBookings(\n client: LockerverseBookingsClient,\n { enabled = true, sessionKey = 0 }: UseLockerverseBookingsOptions = {}\n): UseLockerverseBookingsResult {\n const identity = useRef(client);\n if (identity.current !== client) {\n throw new Error(\n \"Keep the booking client stable. Remount for another business.\"\n );\n }\n const [state, setState] = useState<BookingState>(initialState);\n const current = useRef(state);\n const generation = useRef(0);\n const active = useRef(false);\n const activeSession = useRef(sessionKey);\n const inFlight = useRef(false);\n const commit = useCallback((change: Partial<BookingState>) => {\n current.current = { ...current.current, ...change };\n setState(current.current);\n }, []);\n\n const run = useCallback(\n async <T>(\n operation: () => Promise<T>,\n accept: (result: T) => Partial<BookingState>,\n changesPaymentState: boolean,\n recovering = false\n ): Promise<T> => {\n if (\n !(enabled && active.current) ||\n activeSession.current !== sessionKey ||\n inFlight.current\n ) {\n throw stateError(\n \"A booking request is already in progress or access is disabled.\"\n );\n }\n inFlight.current = true;\n const version = generation.current;\n const isCurrent = () => version === generation.current;\n commit({\n busy: true,\n error: null,\n recovered: changesPaymentState ? false : current.current.recovered,\n recovering,\n });\n try {\n const result = await operation();\n if (!isCurrent()) {\n throw stateError(\n \"The booking access session changed. Recover the current session.\"\n );\n }\n commit(accept(result));\n return result;\n } catch (error) {\n const safeError = safeBookingError(error);\n if (isCurrent()) {\n commit({\n error: safeError,\n recovered: changesPaymentState ? false : current.current.recovered,\n });\n }\n throw safeError;\n } finally {\n if (version === generation.current) {\n inFlight.current = false;\n commit({ busy: false, recovering: false });\n }\n }\n },\n [commit, enabled, sessionKey]\n );\n\n const refresh = useCallback(async () => {\n await run(\n async () => {\n const configuration = await client.configuration();\n const attempt = await client.recover();\n return { attempt, configuration };\n },\n (result) => ({ ...result, recovered: true }),\n true,\n true\n );\n }, [client, run]);\n const recover = useCallback(\n () =>\n run(\n () => client.recover(),\n (attempt) => ({ attempt, recovered: true }),\n true,\n true\n ),\n [client, run]\n );\n const findTimes = useCallback(\n (date: string) =>\n run(\n () => client.availability(date),\n (result) => ({\n availabilityMessage: result.message,\n slots: result.slots,\n }),\n false\n ),\n [client, run]\n );\n const initialize = useCallback(\n (selection: LockerverseBookingSelection) => {\n const saved = current.current;\n if (!(saved.configuration?.ready && saved.recovered) || saved.attempt) {\n return Promise.reject(\n stateError(\n \"Recover the saved booking before selecting a new session.\"\n )\n );\n }\n return run(\n () => client.initialize(selection),\n (attempt) => ({ attempt, recovered: true }),\n true\n );\n },\n [client, run]\n );\n const confirm = useCallback(\n (confirmationToken: string) => {\n const saved = current.current;\n if (\n !(\n saved.configuration?.ready &&\n saved.recovered &&\n saved.attempt?.status === \"review\"\n )\n ) {\n return Promise.reject(\n stateError(\"Recover this attempt before submitting a payment.\")\n );\n }\n return run(\n () => client.confirm(confirmationToken),\n (attempt) => ({ attempt, recovered: attempt.status !== \"review\" }),\n true\n );\n },\n [client, run]\n );\n\n useEffect(() => {\n generation.current += 1;\n inFlight.current = false;\n active.current = enabled;\n activeSession.current = sessionKey;\n current.current = initialState();\n setState(current.current);\n if (enabled) {\n refresh().catch(() => undefined);\n }\n return () => {\n active.current = false;\n generation.current += 1;\n };\n }, [enabled, sessionKey, refresh]);\n\n return {\n ...state,\n canPay: Boolean(\n enabled &&\n activeSession.current === sessionKey &&\n state.configuration?.ready &&\n state.recovered &&\n state.attempt?.status === \"review\" &&\n !state.busy\n ),\n confirm,\n findTimes,\n initialize,\n recover,\n refresh,\n };\n}\n"],"mappings":"6IA6CA,MAAM,OAAoC,CACxC,QAAS,KACT,oBAAqB,GACrB,KAAM,GACN,cAAe,KACf,MAAO,KACP,UAAW,GACX,WAAY,GACZ,MAAO,CAAC,CACV,GACA,SAAS,EAAW,EAAiB,CACnC,OAAO,IAAI,EAAoB,CAC7B,KAAM,yBACN,UACA,UAAW,kBACX,oBAAqB,GACrB,WAAY,EACd,CAAC,CACH,CAGA,SAAS,EAAiB,EAAqC,CAC7D,OAAO,aAAiB,EACpB,EACA,EACE,kFACF,CACN,CAGA,SAAgB,EACd,EACA,CAAE,UAAU,GAAM,aAAa,GAAqC,CAAC,EACvC,CAE9B,GADiB,EAAO,CACb,CAAC,CAAC,UAAY,EACvB,MAAU,MACR,+DACF,EAEF,GAAM,CAAC,EAAO,GAAY,EAAuB,CAAY,EACvD,EAAU,EAAO,CAAK,EACtB,EAAa,EAAO,CAAC,EACrB,EAAS,EAAO,EAAK,EACrB,EAAgB,EAAO,CAAU,EACjC,EAAW,EAAO,EAAK,EACvB,EAAS,EAAa,GAAkC,CAC5D,EAAQ,QAAU,CAAE,GAAG,EAAQ,QAAS,GAAG,CAAO,EAClD,EAAS,EAAQ,OAAO,CAC1B,EAAG,CAAC,CAAC,EAEC,EAAM,EACV,MACE,EACA,EACA,EACA,EAAa,KACE,CACf,GACE,EAAE,GAAW,EAAO,UACpB,EAAc,UAAY,GAC1B,EAAS,QAET,MAAM,EACJ,iEACF,EAEF,EAAS,QAAU,GACnB,IAAM,EAAU,EAAW,QACrB,MAAkB,IAAY,EAAW,QAC/C,EAAO,CACL,KAAM,GACN,MAAO,KACP,UAAW,IAA8B,EAAQ,QAAQ,UACzD,YACF,CAAC,EACD,GAAI,CACF,IAAM,EAAS,MAAM,EAAU,EAC/B,GAAI,CAAC,EAAU,EACb,MAAM,EACJ,kEACF,EAGF,OADA,EAAO,EAAO,CAAM,CAAC,EACd,CACT,OAAS,EAAO,CACd,IAAM,EAAY,EAAiB,CAAK,EAOxC,MANI,EAAU,GACZ,EAAO,CACL,MAAO,EACP,UAAW,IAA8B,EAAQ,QAAQ,SAC3D,CAAC,EAEG,CACR,QAAU,CACJ,IAAY,EAAW,UACzB,EAAS,QAAU,GACnB,EAAO,CAAE,KAAM,GAAO,WAAY,EAAM,CAAC,EAE7C,CACF,EACA,CAAC,EAAQ,EAAS,CAAU,CAC9B,EAEM,EAAU,EAAY,SAAY,CACtC,MAAM,EACJ,SAAY,CACV,IAAM,EAAgB,MAAM,EAAO,cAAc,EAEjD,MAAO,CAAE,QAAA,MADa,EAAO,QAAQ,EACnB,eAAc,CAClC,EACC,IAAY,CAAE,GAAG,EAAQ,UAAW,EAAK,GAC1C,GACA,EACF,CACF,EAAG,CAAC,EAAQ,CAAG,CAAC,EACV,EAAU,MAEZ,MACQ,EAAO,QAAQ,EACpB,IAAa,CAAE,UAAS,UAAW,EAAK,GACzC,GACA,EACF,EACF,CAAC,EAAQ,CAAG,CACd,EACM,EAAY,EACf,GACC,MACQ,EAAO,aAAa,CAAI,EAC7B,IAAY,CACX,oBAAqB,EAAO,QAC5B,MAAO,EAAO,KAChB,GACA,EACF,EACF,CAAC,EAAQ,CAAG,CACd,EACM,EAAa,EAChB,GAA2C,CAC1C,IAAM,EAAQ,EAAQ,QAQtB,MAPI,EAAE,EAAM,eAAe,OAAS,EAAM,YAAc,EAAM,QACrD,QAAQ,OACb,EACE,2DACF,CACF,EAEK,MACC,EAAO,WAAW,CAAS,EAChC,IAAa,CAAE,UAAS,UAAW,EAAK,GACzC,EACF,CACF,EACA,CAAC,EAAQ,CAAG,CACd,EACM,EAAU,EACb,GAA8B,CAC7B,IAAM,EAAQ,EAAQ,QAYtB,OATI,EAAM,eAAe,OACrB,EAAM,WACN,EAAM,SAAS,SAAW,SAOvB,MACC,EAAO,QAAQ,CAAiB,EACrC,IAAa,CAAE,UAAS,UAAW,EAAQ,SAAW,QAAS,GAChE,EACF,EARS,QAAQ,OACb,EAAW,mDAAmD,CAChE,CAOJ,EACA,CAAC,EAAQ,CAAG,CACd,EAkBA,OAhBA,OACE,EAAW,SAAW,EACtB,EAAS,QAAU,GACnB,EAAO,QAAU,EACjB,EAAc,QAAU,EACxB,EAAQ,QAAU,EAAa,EAC/B,EAAS,EAAQ,OAAO,EACpB,GACF,EAAQ,CAAC,CAAC,UAAY,IAAA,EAAS,MAEpB,CACX,EAAO,QAAU,GACjB,EAAW,SAAW,CACxB,GACC,CAAC,EAAS,EAAY,CAAO,CAAC,EAE1B,CACL,GAAG,EACH,OAAQ,GACN,GACE,EAAc,UAAY,GAC1B,EAAM,eAAe,OACrB,EAAM,WACN,EAAM,SAAS,SAAW,UAC1B,CAAC,EAAM,MAEX,UACA,YACA,aACA,UACA,SACF,CACF"}
@@ -1,2 +1,2 @@
1
- import{t as e}from"./format-money.js";import{d as t,i as n,n as r,p as i,t as a,u as o}from"./phone-field.js";import{t as s}from"./host-callback.js";import{n as c,t as l}from"./accent-contrast.js";import{a as u,i as d,n as f,r as p,s as m}from"./custom-fields.js";import{t as h}from"./form-skeleton.js";import{t as g}from"./payment-summary.js";import{i as _,n as v,r as y,t as b}from"./stripe-loader.js";import{useCallback as x,useEffect as S,useId as C,useLayoutEffect as w,useMemo as T,useReducer as E,useRef as D,useState as O}from"react";import{Fragment as k,jsx as A,jsxs as j}from"react/jsx-runtime";import{array as M,literal as N,minLength as P,minValue as F,nonEmpty as I,nullable as L,number as R,object as z,optional as ee,pipe as B,regex as te,safeInteger as V,safeParse as ne,strictObject as re,string as H,trim as U,union as W}from"valibot";import{LockerverseSdkError as ie,estimateLockerverseCheckout as G}from"@lockerverse/sdk/checkout";import{AddressElement as ae,Elements as K,PaymentElement as oe,useElements as se,useStripe as ce}from"@stripe/react-stripe-js";function le({ariaDescribedBy:e,ariaLabel:t,ariaLabelledBy:n,className:r,id:i,invalid:a=!1,name:o,onValueChange:s,options:c,value:l}){return A(`select`,{"aria-describedby":e,"aria-invalid":a||void 0,"aria-label":t,"aria-labelledby":n,className:[`lockerverse-form__control`,`lockerverse-form__select`,r].filter(Boolean).join(` `),id:i,name:o,onChange:e=>s(e.currentTarget.value),value:l,children:c.map(e=>A(`option`,{value:e.value,children:e.label},e.value))})}const ue=[`XS`,`S`,`M`,`L`,`XL`,`XXL`,`XXXL`],de=[`15`,`12`,`10`,`5`],q=[...de,`custom`];function fe({enabled:e,error:t,errorId:n,onChange:r,values:i}){if(!e)return null;let a=e=>r({...i,...e}),o=(e,t)=>{let n=q.indexOf(t),r;switch(e.key){case`ArrowDown`:case`ArrowRight`:r=(n+1)%q.length;break;case`ArrowLeft`:case`ArrowUp`:r=(n-1+q.length)%q.length;break;case`Home`:r=0;break;case`End`:r=q.length-1;break;default:return}e.preventDefault();let i=q[r];i&&((e.currentTarget.closest(`[role="radiogroup"]`)?.querySelectorAll(`input[type="radio"]`))?.[r]?.focus(),a({tipPercent:i}))};return j(`div`,{className:`lockerverse-payment__tip-box`,children:[A(`p`,{children:`Add a tip to support the Lockerverse platform`}),j(`div`,{"aria-label":`Tip amount`,role:`radiogroup`,children:[de.map(e=>j(`label`,{className:`lockerverse-payment__tip-choice`,children:[A(`input`,{checked:i.tipPercent===e,name:`tipPercent`,onChange:()=>a({tipPercent:e}),onKeyDown:t=>o(t,e),tabIndex:i.tipPercent===e?0:-1,type:`radio`,value:e}),j(`span`,{children:[e,`%`]})]},e)),j(`label`,{className:`lockerverse-payment__tip-choice`,children:[A(`input`,{checked:i.tipPercent===`custom`,name:`tipPercent`,onChange:()=>a({tipPercent:`custom`}),onKeyDown:e=>o(e,`custom`),tabIndex:i.tipPercent===`custom`?0:-1,type:`radio`,value:`custom`}),A(`span`,{children:`Other`})]})]}),i.tipPercent===`custom`?j(`label`,{children:[A(`span`,{children:`Custom tip`}),j(`span`,{className:`lockerverse-payment__money-input`,children:[A(`span`,{"aria-hidden":`true`,children:`$`}),A(`input`,{"aria-describedby":t?n:void 0,"aria-invalid":t?`true`:void 0,inputMode:`decimal`,name:`tip`,onChange:e=>a({customTip:e.currentTarget.value}),placeholder:`0.00`,value:i.customTip})]}),t?A(`span`,{className:`lockerverse-payment__field-message`,id:n,children:t}):null]}):A(`input`,{name:`tip`,type:`hidden`,value:i.tipPercent})]})}function pe({checked:e,children:t,name:n,onChange:r}){let i=C();return j(`label`,{className:`lockerverse-payment__check-row`,htmlFor:i,children:[A(o,{checked:e,id:i,name:n,onChange:e=>r(e.currentTarget.checked)}),A(`span`,{children:t})]})}function me({customFields:e,errors:t,fields:n,idPrefix:r,isPromoApplying:i,memberIdLabel:a,onChange:o,onApplyPromo:s,promoError:c,values:l}){let u=e=>o({...l,...e});return j(`div`,{className:`lockerverse-payment__additional-fields`,children:[n.memberId?j(`label`,{children:[A(`span`,{children:a?.trim()||`Member ID`}),A(`input`,{name:`memberId`,onChange:e=>u({memberId:e.currentTarget.value}),placeholder:`Optional`,value:l.memberId})]}):null,n.merchSize?j(`div`,{className:`lockerverse-payment__field`,children:[A(`span`,{id:`${r}-merch-size-label`,children:`Size`}),A(le,{ariaLabelledBy:`${r}-merch-size-label`,name:`merchSize`,onValueChange:e=>{let t=ue.find(t=>t===e);t&&u({merchSize:t})},options:ue.map(e=>({label:e,value:e})),value:l.merchSize})]}):null,n.promoCode?j(`div`,{className:`lockerverse-payment__field`,children:[A(`span`,{id:`${r}-promo-code-label`,children:`Promo code`}),j(`div`,{className:`lockerverse-payment__promo-control`,children:[A(`input`,{"aria-describedby":c?`${r}-promo-code-error`:void 0,"aria-invalid":c?`true`:void 0,"aria-labelledby":`${r}-promo-code-label`,name:`promoCode`,onChange:e=>u({promoCode:e.currentTarget.value}),placeholder:`Optional`,value:l.promoCode}),A(`button`,{disabled:!l.promoCode.trim()||i,onClick:s,type:`button`,children:i?`Applying…`:`Apply`})]}),c?A(`p`,{className:`lockerverse-payment__field-message`,id:`${r}-promo-code-error`,role:`alert`,children:c}):null]}):null,A(f,{choiceClassName:`lockerverse-payment__check-row`,errorClassName:`lockerverse-payment__field-message`,errors:t,fields:e,idPrefix:r,onChange:e=>u({customFields:e}),values:l.customFields})]})}function J({amountCents:t,enabled:n,onChange:r,values:i}){return n?j(pe,{checked:i.includeServiceFee,name:`includeServiceFee`,onChange:e=>r({...i,includeServiceFee:e}),children:[`Add `,e(t),` to help cover processing fees`]}):null}function Y(e){return{error:void 0,message:void 0,status:e?`recovering`:`editing`}}function X(e,t,n){return t.includes(e.status)?{...e,...n}:e}function he(e,t){if(t.type===`recovery_started`&&e.status===`unresolved`)return{...e,message:void 0,status:`recovering`};if(e.status===`sold_out`||e.status===`succeeded`||e.status===`unresolved`)return e;switch(t.type){case`field_changed`:return X(e,[`editing`,`invalid`,`refreshing_quote`],{error:void 0,status:`editing`});case`validation_failed`:return X(e,[`editing`],{status:`invalid`});case`quote_refresh_started`:return X(e,[`editing`,`invalid`],{status:`refreshing_quote`});case`quote_refresh_succeeded`:return X(e,[`refreshing_quote`],{error:void 0,status:`editing`});case`quote_refresh_failed`:return X(e,[`refreshing_quote`],{error:t.error??e.error,status:`editing`});case`submission_started`:return X(e,[`editing`,`invalid`,`refreshing_quote`],{error:void 0,status:`submitting`});case`submission_validation_failed`:return X(e,[`submitting`],{error:void 0,status:`invalid`});case`quote_changed`:return X(e,[`submitting`],{status:`editing`});case`retryable_failure`:return X(e,[`editing`,`invalid`,`submitting`],{error:t.error,status:`editing`});case`recovery_failed`:return X(e,[`recovering`],{error:t.error,retryUrl:void 0,status:`editing`});case`sold_out`:return{error:void 0,message:void 0,status:`sold_out`};case`succeeded`:return X(e,[`recovering`,`submitting`],{message:t.message,retryUrl:void 0,status:`succeeded`});case`unresolved`:return X(e,[`recovering`,`submitting`],{message:t.message,retryUrl:t.retryUrl,status:`unresolved`});default:return e}}function ge(e){return e.status===`editing`||e.status===`invalid`||e.status===`refreshing_quote`?e.error:void 0}function Z(e){return e.status===`sold_out`?`sold_out`:e.status===`succeeded`?`success`:e.status===`unresolved`?`unresolved`:e.status===`submitting`||e.status===`recovering`?`submitting`:e.status===`invalid`?`invalid`:ge(e)?`error`:`idle`}function Q(e){return e.status===`submitting`}const _e=[`amountCents`,`discountableSubtotalCents`,`discountCents`,`serviceFeeCents`,`subtotalCents`,`tipCents`,`totalCents`],ve=[`discountableSubtotalCents`,`discountCents`,`subtotalCents`];function ye(e,t,n,r){return(n===t.totalCents?ve:_e).some(n=>e[n]!==t[n])||r!==t.payment.connectedAccountId||e.authoritative&&(e.payment.connectedAccountId!==r||e.payment.currency!==t.payment.currency)||JSON.stringify(e.appliedDiscount)!==JSON.stringify(t.appliedDiscount)||JSON.stringify(e.lineItems)!==JSON.stringify(t.lineItems)}function be(e){if(e.checkoutStatus===`success`)return{kind:`success`,payment:e};if(e.checkoutStatus===`failed`)return{kind:`failed`,payment:e};let t={kind:`unresolved`,paymentReference:e.paymentReference,reason:e.checkoutStatus===`action_required`?`action_required`:`pending`};return e.retryUrl&&(t.retryUrl=e.retryUrl),t}async function xe(e,t,n){if(t.checkoutStatus!==`action_required`||!t.requiresAction)return be(t);if(!n)return{kind:`unresolved`,paymentReference:t.paymentReference,reason:`action_required`};if(t.clientSecret)try{await n.handleNextAction({clientSecret:t.clientSecret})}catch{}try{return be(await e.getPaymentStatus(t.paymentReference))}catch{return{kind:`unresolved`,paymentReference:t.paymentReference,reason:`action_required`}}}async function Se(e,t,n){let r;try{r=await e.submitPayment(t)}catch(n){if(!(n instanceof ie&&n.recoveryRecommended))throw n;try{r=await e.getPaymentStatus(t.checkout.paymentReference)}catch{return{kind:`unresolved`,paymentReference:t.checkout.paymentReference,reason:`recovery_failed`}}}return xe(e,r,n)}async function Ce(e,t,n){try{return xe(e,await e.getPaymentStatus(t),n)}catch{return{kind:`unresolved`,paymentReference:t,reason:`recovery_failed`}}}const we=B(H(),U(),I()),Te=B(R(),V(),F(1)),Ee=B(M(W([re({amountCents:Te,productSlug:we}),re({productSlug:we,quantity:Te}),re({productSlug:we})])),P(1)),De=B(H(),U(),te(/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/,`Enter a valid tip amount.`));function Oe(e){let t=ne(De,e);if(!t.success)return{message:t.issues[0]?.message??`Enter a valid tip amount.`,success:!1};let[n=`0`,r=``]=t.output.split(`.`),i=BigInt(n)*100n+BigInt(r.padEnd(2,`0`));return i>BigInt(2**53-1)?{message:`Enter a valid tip amount.`,success:!1}:{cents:Number(i),success:!0}}function ke(e){let t=ne(Ee,e);return t.success?{success:!0,value:t.output}:{message:`Lockerverse payment configuration is invalid.`,success:!1}}const Ae=`This promo code is invalid or cannot be applied.`;function je(e,t){return t.tipPercent===`custom`?t.customTip.trim()?Oe(t.customTip):{cents:0,success:!0}:{cents:Math.round(e*Number(t.tipPercent)/100),success:!0}}function Me(e,t,n,r){let i={};return n&&(i.email=n),e.widget.fields.serviceFee&&(i.includeServiceFee=t.includeServiceFee),e.widget.fields.promoCode&&t.promoCode.trim()&&(i.promoCode=t.promoCode.trim()),e.widget.fields.tipping&&(i.tipCents=r),i}function Ne(e,t,n){let r=e.widget.fields.tipping?je(n.subtotalCents,t):{cents:0,success:!0};if(!r.success)return{parsedTip:r,totalCents:null};let i=e.widget.fields.serviceFee&&t.includeServiceFee?n.serviceFeeCents||Math.round(n.subtotalCents*e.pricingPolicy.serviceFeeRateBasisPoints/1e4):0;return{parsedTip:r,totalCents:n.totalCents-n.serviceFeeCents-n.tipCents+i+r.cents}}function Pe(e,t){return{displayedTotalCents:e.totalCents,promoError:t&&e.appliedDiscount?.source!==`promo_code`?Ae:void 0}}function Fe(e,t){let n;return t||(n=e instanceof Error?e.message:`The order total could not be updated.`),{paymentError:n,promoError:t?Ae:void 0}}function Ie(e,t){if(!e?.complete)throw Error(`${t} address is required.`);return e.value}function Le(e,t,n,r){if(e.widget.fields.shipping)return t.shippingMatchesBilling?n:Ie(r.shipping,`Shipping`)}function Re({billingAddress:e,catalog:t,email:n,phone:r,shippingAddress:i}){let a={payment_method_data:{billing_details:t.widget.fields.phone?{address:e.address,email:n,name:e.name,phone:r}:{address:e.address,email:n,name:e.name}}};return i?{...a,shipping:{address:i.address,name:i.name,phone:t.widget.fields.phone?r:i.phone??null}}:a}function ze({catalog:e,checkoutItems:t,confirmationToken:n,email:r,fieldValues:i,metadata:a,phone:o,shippingAddress:s}){let c={customFieldAnswers:p(u(e,t),i.customFields),email:r};if(n&&(c.confirmationToken=n,c.paymentMethodConfiguration=`explicit`),a&&(c.metadata=a),e.widget.fields.memberId&&i.memberId.trim()&&(c.memberId=i.memberId.trim()),e.widget.fields.merchSize&&(c.merchSize=i.merchSize),e.widget.fields.phone&&(c.phone=o),s){let e={city:s.address.city??``,country:s.address.country,line1:s.address.line1??``,postal_code:s.address.postal_code??``,state:s.address.state??``};s.address.line2&&(e.line2=s.address.line2),c.shipping={address:e,name:s.name}}return c}function Be(e){if(!e())throw Error(`Payment component is no longer active.`)}function Ve(e,t){s(e,t)}function He(e,t,n,r){return e.kind===`failed`?{kind:`payment_failed`,message:r}:e.kind===`unresolved`?{kind:`payment_unresolved`,paymentReference:e.paymentReference,reason:e.reason,retryUrl:e.retryUrl}:{email:n,kind:`payment`,payment:e.payment,quote:t}}async function Ue({addresses:e,catalog:t,checkoutItems:n,client:r,elements:i,email:a,fieldValues:o,isAttemptActive:s,locallyPreviewedTotalCents:c,metadata:l,onPaymentRecoveryChange:u,phone:d,quote:f,stripe:p,stripeConnectedAccountId:m}){let h=a.trim().toLowerCase(),g=y(d),_=je(f.subtotalCents,o);if(!_.success)throw Error(_.message);let v=await r.calculateTotal({...Me(t,o,h,_.cents),catalog:t,items:n});if(Be(s),v.totalCents>0&&ye(f,v,c,m))return{kind:`quote_changed`,quote:v};let b,x;if(v.totalCents===0)t.widget.fields.shipping&&(b=Le(t,o,Ie(e.billing,`Billing`),e));else{if(!(i&&p))throw Error(`Payment form is still loading.`);await i.update({amount:v.totalCents}),Be(s);let n=await i.submit();if(Be(s),n.error)throw Error(n.error.message);let r=Ie(e.billing,`Billing`);b=Le(t,o,r,e);let a=await p.createConfirmationToken({elements:i,params:Re({billingAddress:r,catalog:t,email:h,phone:g,shippingAddress:b})});if(Be(s),a.error)throw Error(a.error.message);x=a.confirmationToken.id}Ve(u,{connectedAccountId:v.payment.connectedAccountId,paymentReference:v.paymentReference});let S=await Se(r,{checkout:v,submission:ze({catalog:t,checkoutItems:n,confirmationToken:x,email:h,fieldValues:o,metadata:l,phone:g,shippingAddress:b})},p);return Be(s),He(S,v,h,v.totalCents===0?`Order could not be completed. Review the details and try again.`:`Payment was declined. Check your payment details and try again.`)}function We(e,t){s(e,t)}function Ge(e,t){s(e,t)}function Ke(e,t){return{...e,...t}}function qe(e){let t={message:e.reason===`action_required`?`Payment needs your attention. Keep this checkout open.`:`Payment is not complete. Check its status before you try again.`,type:`unresolved`};return e.retryUrl&&(t.retryUrl=e.retryUrl),t}function Je(e,t,n){return e.kind===`unresolved`&&e.reason===`action_required`&&!e.retryUrl&&!t&&!n}function Ye(e){return e instanceof ie&&e.serverCode===`PAYMENT_WIDGET_SALES_LIMIT_REACHED`}function Xe({nextQuote:e,onQuoteChange:t,setDisplayedTotalCents:n,setPromoError:r,updateState:i,validatePromo:a}){let o=Pe(e,a);i({type:`quote_refresh_succeeded`}),n(o.displayedTotalCents),t(e),a&&r(o.promoError)}function Ze({error:e,setPromoError:t,updateState:n,validatePromo:r}){let i=Fe(e,r);r&&t(i.promoError),n(i.paymentError===void 0?{type:`quote_refresh_failed`}:{error:i.paymentError,type:`quote_refresh_failed`})}function Qe({onPaymentComplete:t,onPaymentRecoveryChange:n,onPaymentUncertain:r,onQuoteChange:i,result:a,setDisplayedTotalCents:o,dispatchState:c,unresolvedReferenceRef:l}){if(a.kind===`quote_changed`){let t=`The total changed to ${e(a.quote.totalCents)}. Review it and pay again.`;i(a.quote,t),o(a.quote.totalCents),c({type:`quote_changed`});return}if(a.kind===`payment_failed`){We(n,null),c({error:a.message,type:`retryable_failure`});return}if(a.kind===`payment_unresolved`){l.current=a.paymentReference,c(qe(a)),Ge(r,{paymentReference:a.paymentReference,reason:a.reason});return}i(a.quote),We(n,null),c({message:a.payment.paymentRequired?`Payment completed successfully.`:`Order confirmed. No payment was required.`,type:`succeeded`}),s(t,Ke(a.payment,{email:a.email,lineItems:a.quote.lineItems}))}function $e(e){let{catalog:t,checkoutItems:r,client:i,elements:a,email:o,fieldValues:c,metadata:l,onPaymentComplete:u,onResumePaymentFailed:d,onPaymentRecoveryChange:f,onPaymentUncertain:p,onQuoteChange:m,onStateChange:h,quote:g,resumePayment:v,stripe:y,stripeConnectedAccountId:b,stripeLoadFailed:C,paymentState:w,updateState:T}=e,[E,k]=O(g.totalCents),[A,j]=O(),M=D(!1),N=D(void 0),P=D(0),F=D(0),I=x(e=>T(e,!0),[T]),L=x(()=>{let e=F.current+1;return F.current=e,()=>F.current===e},[]);S(()=>()=>{F.current+=1,P.current+=1},[]);let{parsedTip:R,totalCents:z}=Ne(t,c,g);S(()=>{z!==null&&(k(z),z>0&&a?.update({amount:z}))},[t.pricingPolicy.serviceFeeRateBasisPoints,t.widget.fields.serviceFee,a,c.includeServiceFee,z,g.serviceFeeCents,g.tipCents,g.totalCents,g.subtotalCents]),S(()=>{let e=v?.paymentReference??N.current;if(!e||M.current||w.status!==`recovering`)return;M.current=!0;let t=L();return h(Z(w)),Ce(i,e,y).then(e=>{if(t()&&!Je(e,y,C)){if(e.kind===`failed`){We(f,null),d(),I({error:`The previous payment failed. Check your details and try again.`,type:`recovery_failed`});return}if(e.kind===`unresolved`){I(qe(e)),Ge(p,{paymentReference:e.paymentReference,reason:e.reason});return}We(f,null),I({message:e.payment.paymentRequired?`Payment completed successfully.`:`Order confirmed. No payment was required.`,type:`succeeded`}),s(u,Ke(e.payment,{email:null,lineItems:null}))}}),()=>{t()&&(F.current+=1),M.current=!1}},[i,u,d,f,p,h,v,y,C,L,I,w]);let ee=x((e=!1,t=!1)=>{t||(P.current+=1),e&&j(void 0),T({type:`field_changed`})},[T]);async function B(e=!1,n=!1){let a=o.trim().toLowerCase(),s=_({email:a,phone:``},!1);if(!(R.success&&(s.value||e)))return;P.current+=1;let l=P.current;T({type:`quote_refresh_started`});try{let e=await i.calculateTotal({...Me(t,c,s.value?.email??``,R.cents),catalog:t,items:r});if(l!==P.current)return;Xe({nextQuote:e,onQuoteChange:m,setDisplayedTotalCents:k,setPromoError:j,updateState:T,validatePromo:n})}catch(e){if(l!==P.current)return;if(Ye(e)){T({type:`sold_out`});return}Ze({error:e,setPromoError:j,updateState:T,validatePromo:n})}}async function te(){j(void 0),await B(!0,!0)}async function V({addresses:e,phone:s}){I({type:`submission_started`});let d=L();try{let n=await Ue({addresses:e,catalog:t,checkoutItems:r,client:i,elements:a,email:o,fieldValues:c,isAttemptActive:d,locallyPreviewedTotalCents:E,metadata:l,onPaymentRecoveryChange:f,phone:s,quote:g,stripe:y,stripeConnectedAccountId:b});if(!d())return;Qe({dispatchState:I,onPaymentComplete:u,onPaymentRecoveryChange:f,onPaymentUncertain:p,onQuoteChange:m,result:n,setDisplayedTotalCents:k,unresolvedReferenceRef:N})}catch(e){if(!d())return;if(We(f,null),Ye(e)){I({type:`sold_out`});return}let t=e instanceof ie?n(e.serverCode):void 0;if(t)return I({type:`submission_validation_failed`}),{phoneError:t};I({error:e instanceof Error?e.message:`Payment could not be completed.`,type:`retryable_failure`})}}let ne=w.status===`succeeded`||w.status===`unresolved`?w.message:void 0;return{commands:{applyPromo:te,checkPaymentStatus:()=>I({type:`recovery_started`}),fieldChanged:ee,refreshAuthoritativeTotal:B,reportValidationFailure:()=>I({type:`validation_failed`}),submit:V},state:{displayedTotalCents:E,isRecovering:w.status===`recovering`,isRefreshingQuote:w.status===`refreshing_quote`,isSubmitting:Q(w),isUnresolved:w.status===`unresolved`,parsedTip:R,paymentError:ge(w),promoError:A,retryUrl:w.retryUrl,terminalMessage:ne}}}const et=b;function tt(e){let{connectedAccountId:t,publishableKey:n}=e.payment;return et(n,t?{stripeAccount:t}:void 0)}function nt(e){return e===`monthly`?{interval:`month`,label:`Monthly`}:e===`annually`?{interval:`year`,label:`Annual`}:e===`every-six-months`?{interval:`6 months`,label:`Every 6 months`}:null}function rt(e,t,n){if(n){let{connectedAccountId:e}=n;return e}if(`payment`in t){let{connectedAccountId:e}=t.payment;return e}let{connectedAccountId:r}=e.payment;return r}function it({accentColor:e,catalog:t,checkoutItems:n,client:r,appearanceRoot:i,initialCustomFieldValues:a,paymentSummaryPosition:o,metadata:s,onPaymentComplete:c,onResumePaymentFailed:l,onPaymentRecoveryChange:u,onPaymentUncertain:d,onQuoteChange:f,quote:p,resumePayment:m,onStateChange:g,stripeLoader:_,theme:y,visualStyle:b}){let[C,w]=O(()=>Y(!!m)),E=D(C);E.current=C;let k=x((e,t=!1)=>{let n=he(E.current,e);n!==E.current&&(E.current=n,w(n),t&&g(Z(n)))},[g]),j=rt(t,p,m),M=D({connectedAccountId:j,paymentOption:p.paymentOption});C.status!==`submitting`&&C.status!==`recovering`&&(M.current={connectedAccountId:j,paymentOption:p.paymentOption});let{connectedAccountId:N,paymentOption:P}=M.current,F=T(()=>_(t.payment.publishableKey,N?{stripeAccount:N}:void 0).catch(()=>null),[t.payment.publishableKey,N,_]),[I,L]=O(!1);S(()=>{let e=!0;return L(!1),F.then(t=>{e&&t===null&&L(!0)}),()=>{e=!1}},[F]);let R=v(i,y,b,C.status===`submitting`||C.status===`recovering`,e);return R?A(K,{options:{amount:Math.max(p.totalCents,100),appearance:R,currency:t.payment.currency,mode:P===`one-time`?`payment`:`subscription`,paymentMethodTypes:t.community?.widgetAchEnabled?[`card`,`us_bank_account`]:[`card`],setupFutureUsage:`off_session`,syncAddressCheckbox:`none`},stripe:F,children:A(_t,{catalog:t,checkoutItems:n,client:r,initialCustomFieldValues:a,metadata:s,onPaymentComplete:c,onPaymentRecoveryChange:u,onPaymentUncertain:d,onQuoteChange:f,onResumePaymentFailed:l,onStateChange:g,paymentState:C,paymentSummaryPosition:o,quote:p,resumePayment:m,stripeConnectedAccountId:N,stripeLoadFailed:I,updateState:k})},`${t.payment.publishableKey}:${N??`platform`}:${P}`):A(h,{fieldCount:3,label:`Loading payment form`})}function at({label:e}){return j(`div`,{className:`lockerverse-payment__stripe-loader`,role:`status`,children:[A(`p`,{children:e}),j(`div`,{"aria-hidden":`true`,children:[A(`span`,{}),A(`span`,{}),A(`span`,{})]})]})}function ot({onError:e,onReady:t,ready:n}){return j(`div`,{className:`lockerverse-payment__stripe-element`,"data-ready":n,children:[n?null:A(at,{label:`Loading payment form...`}),A(`div`,{className:`lockerverse-payment__stripe-mount`,children:A(oe,{onLoadError:({error:t})=>e(t.message??`Payment form failed to load.`),onReady:t,options:{business:{name:`Lockerverse`},fields:{billingDetails:{address:`never`,email:`never`,name:`never`,phone:`never`}},layout:`tabs`,terms:{applePay:`auto`,card:`always`,googlePay:`auto`,usBankAccount:`auto`},wallets:{applePay:`auto`,googlePay:`auto`}}})})]})}function st({label:e,mode:t,onChange:n,onError:r,onReady:i,ready:a}){return j(`div`,{className:`lockerverse-payment__address`,children:[A(`h2`,{children:e}),j(`div`,{className:`lockerverse-payment__stripe-element lockerverse-payment__stripe-element--address`,"data-ready":a,children:[a?null:A(at,{label:`Loading ${e.toLowerCase()}...`}),A(`div`,{className:`lockerverse-payment__stripe-mount`,children:A(ae,{onChange:n,onLoadError:({error:t})=>r(t.message??`${e} failed to load.`),onReady:i,options:{autocomplete:{mode:`automatic`},mode:t}})})]})]})}function ct({message:e}){return e?A(`p`,{className:`lockerverse-payment__field-message`,role:`alert`,children:e}):null}function lt({catalog:e,displayedTotalCents:t,fieldValues:n,isBillingAddressReady:r,isPaymentReady:i,isShippingAddressReady:a,onAddressChange:o,onFieldValuesChange:s,onStripeLoadError:c,setIsBillingAddressReady:l,setIsPaymentReady:u,setIsShippingAddressReady:d}){let f=t>0;return j(k,{children:[f?A(ot,{onError:c,onReady:()=>u(!0),ready:i}):null,f||e.widget.fields.shipping?A(st,{label:f?`Billing address`:`Shipping address`,mode:`billing`,onChange:e=>o(`billing`,e),onError:c,onReady:()=>l(!0),ready:r}):null,e.widget.fields.shipping?j(`div`,{className:`lockerverse-payment__shipping`,children:[A(pe,{checked:n.shippingMatchesBilling,name:`shippingMatchesBilling`,onChange:e=>{s({...n,shippingMatchesBilling:e}),e?o(`shipping`,null):d(!1)},children:`Shipping is same as billing information`}),n.shippingMatchesBilling?null:A(st,{label:`Shipping address`,mode:`shipping`,onChange:e=>o(`shipping`,e),onError:c,onReady:()=>d(!0),ready:a})]}):null]})}function ut({catalog:t,displayedTotalCents:n,fieldValues:r,isBillingAddressReady:i,isPaymentReady:a,isRequiredShippingReady:o,isSubmitting:s,onFieldValuesChange:c,quote:l}){let u=n===0,d=u?!t.widget.fields.shipping||i&&o:a&&i&&o,f=nt(l.paymentOption),p=u?`Complete order`:`Pay ${e(n)}`;!u&&f&&(p=`Subscribe for ${e(n)}/${f.interval}`),s&&(p=u?`Completing…`:`Processing…`);let m=`Process payment for ${e(n)} total`;return u?m=`Complete order`:f&&(m=`Start ${f.label.toLowerCase()} subscription for ${e(n)}`),j(`div`,{className:`lockerverse-payment__actions`,children:[A(J,{amountCents:l.serviceFeeCents||Math.round(l.subtotalCents*t.pricingPolicy.serviceFeeRateBasisPoints/1e4),enabled:t.widget.fields.serviceFee,onChange:c,values:r}),A(`button`,{"aria-busy":s,"aria-label":m,disabled:s||!d,type:`submit`,children:p})]})}function dt(e,t){let n=e.elements.namedItem(t);if(n instanceof HTMLElement){n.focus();return}n instanceof RadioNodeList&&Array.from(n).find(e=>e instanceof HTMLElement)?.focus()}function ft({customFieldErrors:e,emailRef:t,form:n,parsedTipSuccess:r,phoneRef:i,validationErrors:a}){if(a.email){t.current?.focus();return}if(a.phone){i.current?.focus();return}if(!r){n.querySelector(`[name="tip"]`)?.focus();return}let[o]=Object.keys(e);o&&dt(n,`custom:${o}`)}function pt(t){let n=t.appliedDiscount;if(n?.source!==`email_list`)return;let r=n.percentageOff===void 0?e(t.discountCents):`${n.percentageOff}%`;return n.message??`Your email qualifies for ${r} off.`}function mt({email:e,emailDiscountMessage:n,emailErrorId:r,emailId:o,emailRef:s,errors:c,onEmailBlur:l,onEmailChange:u,onPhoneChange:d,phone:f,phoneCountry:p,phoneEnabled:m,phoneErrorId:h,phoneId:g,phoneRef:_}){return j(`div`,{className:`lockerverse-payment__contact`,children:[A(t,{error:c.email,errorId:r,id:o,label:`Email`,name:`email`,onBlur:l,onChange:e=>u(e.currentTarget.value),ref:s,required:!0,value:e}),n===void 0?null:A(`p`,{className:`lockerverse-payment__discount-message`,role:`status`,children:n}),m?A(i,{error:c.phone,errorId:h,id:g,label:`Phone`,children:A(a,{country:p,error:c.phone,errorId:h,id:g,inputRef:_,name:`phone`,onChange:d,required:!0,value:f})}):null]})}function ht({message:e}){return e?j(`div`,{className:`lockerverse-payment__actions`,children:[A(`p`,{className:`lockerverse-payment__field-message`,role:`alert`,children:e}),A(`button`,{className:`lockerverse-payment__status-check`,onClick:()=>window.location.reload(),type:`button`,children:`Reload checkout`})]}):null}function gt({paymentRequired:e,shippingRequired:t,isPaymentReady:n,isBillingAddressReady:r,isRequiredShippingReady:i,isSubmitting:a,scriptFailed:o,elementError:s,clearElementError:c}){let[l,u]=O(!1),d=e||t,f=(!e||n)&&(!d||r)&&i;if(S(()=>{if(u(!1),f&&c(void 0),!d||f||a)return;let e=window.setTimeout(()=>u(!0),3e4);return()=>window.clearTimeout(e)},[d,f,a,c]),!(!d||f||a)){if(o||s)return`The secure checkout fields could not load. Check your connection, then reload the checkout.`;if(l)return`The secure checkout fields are taking longer than expected. You can wait or reload the checkout.`}}function _t({catalog:e,checkoutItems:t,client:n,initialCustomFieldValues:i,paymentSummaryPosition:a,metadata:o,onPaymentComplete:s,onResumePaymentFailed:c,onPaymentRecoveryChange:l,onPaymentUncertain:f,onQuoteChange:p,onStateChange:h,quote:v,resumePayment:y,stripeConnectedAccountId:b,stripeLoadFailed:x,paymentState:w,updateState:T}){let E=u(e,t),[M,N]=O(``),[P,F]=O(``),[I,L]=O(`US`),[R,z]=O({}),[ee,B]=O({}),[te,V]=O(),[ne,re]=O(),[H,U]=O(!1),[W,ie]=O(!1),[G,ae]=O(!1),[K,oe]=O(()=>({customFields:d(E,i),customTip:``,includeServiceFee:e.widget.fields.serviceFee,memberId:``,merchSize:`M`,promoCode:``,shippingMatchesBilling:!0,tipPercent:`10`})),le=D({billing:null,shipping:null}),ue=D(null),de=D(null),q=D(null),pe=D(v.totalCents>0),J=$e({catalog:e,checkoutItems:t,client:n,elements:se(),email:M,fieldValues:K,metadata:o,onPaymentComplete:s,onPaymentRecoveryChange:l,onPaymentUncertain:f,onQuoteChange:p,onResumePaymentFailed:c,onStateChange:h,paymentState:w,quote:v,resumePayment:y,stripe:ce(),stripeConnectedAccountId:b,stripeLoadFailed:x,updateState:T}),{displayedTotalCents:Y,isRecovering:X,isUnresolved:he,isRefreshingQuote:ge,isSubmitting:Z,parsedTip:Q,paymentError:_e,promoError:ve,terminalMessage:ye,retryUrl:be}=J.state,xe=`lockerverse-${C()}`,Se=`${xe}-email`,Ce=`${Se}-error`,we=`${xe}-phone`,Te=`${we}-error`,Ee=`${xe}-tip-error`,De=(Q.success?Q.cents:null)??0,Oe=Y-De,ke=!e.widget.fields.shipping||K.shippingMatchesBilling||G,Ae=gt({clearElementError:re,elementError:ne,isBillingAddressReady:W,isPaymentReady:H,isRequiredShippingReady:ke,isSubmitting:Z,paymentRequired:Y>0,scriptFailed:x,shippingRequired:e.widget.fields.shipping});S(()=>{Z&&q.current?.focus({preventScroll:!0})},[Z]),S(()=>{Z||R.email||!R.phone||de.current?.focus()},[R.email,R.phone,Z]),S(()=>{let e=Y>0;e&&!pe.current&&(U(!1),ie(!1)),pe.current=e},[Y]);function je(e){J.commands.fieldChanged(!1,e!==`email`),z(t=>{let n={...t};return delete n[e],n})}function Me(e){let t=e.promoCode!==K.promoCode,n=e.includeServiceFee!==K.includeServiceFee;J.commands.fieldChanged(t,!(t||n)),oe(e),B({}),V(void 0)}async function Ne(t){t.preventDefault();let n=e.widget.fields.phone?r(P,I):``,i=_({email:M,phone:n},e.widget.fields.phone),a=m(E,K.customFields);if(!(i.value&&Q.success)||Object.keys(a).length>0){z(i.errors),B(a),V(Q.success?void 0:Q.message),J.commands.reportValidationFailure();let e=t.currentTarget;queueMicrotask(()=>{ft({customFieldErrors:a,emailRef:ue,form:e,parsedTipSuccess:Q.success,phoneRef:de,validationErrors:i.errors})});return}z({}),B({});let o=await J.commands.submit({addresses:le.current,phone:n});o?.phoneError&&z({phone:o.phoneError})}if(ye||X)return j(`div`,{className:`lockerverse-payment__actions`,children:[j(`p`,{className:`lockerverse-payment__payment-status`,ref:q,role:`status`,tabIndex:-1,children:[X?`Recovering payment…`:ye,be?j(k,{children:[` `,A(`a`,{href:be,rel:`noopener noreferrer`,target:`_blank`,children:`Complete payment`})]}):null]}),he||X?A(`button`,{"aria-busy":X,className:`lockerverse-payment__status-check`,disabled:X,onClick:J.commands.checkPaymentStatus,type:`button`,children:X?`Checking payment status…`:`Check payment status`}):null]});let Pe=A(g,{displayedBaseCents:Oe,displayedTipCents:De,displayedTotalCents:Y,quote:v}),Fe=A(fe,{enabled:e.widget.fields.tipping,error:te,errorId:Ee,onChange:Me,values:K}),Ie={bottom:{afterFields:j(k,{children:[Fe,Pe]}),beforeFields:null},hidden:{afterFields:Fe,beforeFields:null},top:{afterFields:null,beforeFields:j(k,{children:[Pe,Fe]})}}[a??`top`];return j(`form`,{"aria-busy":Z,className:`lockerverse-payment__form`,noValidate:!0,onSubmit:Ne,children:[A(`div`,{"data-lockerverse-input-region":``,inert:Z?!0:void 0,children:j(`fieldset`,{className:`lockerverse-payment__input-fieldset`,disabled:Z,children:[Ie.beforeFields,A(mt,{email:M,emailDiscountMessage:pt(v),emailErrorId:Ce,emailId:Se,emailRef:ue,errors:R,onEmailBlur:()=>J.commands.refreshAuthoritativeTotal(),onEmailChange:e=>{N(e),je(`email`)},onPhoneChange:({value:e,country:t})=>{F(e),L(t),je(`phone`)},phone:P,phoneCountry:I,phoneEnabled:e.widget.fields.phone,phoneErrorId:Te,phoneId:we,phoneRef:de}),A(ht,{message:Ae}),A(lt,{catalog:e,displayedTotalCents:Y,fieldValues:K,isBillingAddressReady:W,isPaymentReady:H,isShippingAddressReady:G,onAddressChange:(e,t)=>{le.current[e]=t},onFieldValuesChange:Me,onStripeLoadError:re,setIsBillingAddressReady:ie,setIsPaymentReady:U,setIsShippingAddressReady:ae}),A(me,{customFields:E,errors:ee,fields:e.widget.fields,idPrefix:xe,isPromoApplying:ge,memberIdLabel:e.community?.memberIdLabel,onApplyPromo:J.commands.applyPromo,onChange:Me,promoError:ve,values:K}),Ie.afterFields,A(ut,{catalog:e,displayedTotalCents:Y,fieldValues:K,isBillingAddressReady:W,isPaymentReady:H,isRequiredShippingReady:ke,isSubmitting:Z,onFieldValuesChange:Me,quote:v})]})}),Z?A(`p`,{className:`lockerverse-payment__sr-only`,ref:q,role:`status`,tabIndex:-1,children:Y===0?`Completing order…`:`Processing payment…`}):null,A(ct,{message:_e})]})}function vt(){return A(h,{fieldCount:2,label:`Loading payment…`,sectionCount:2,showCheckbox:!0})}function yt(e,t){switch(t.type){case`loading`:return{phase:`loading`,revision:e.revision};case`ready`:return St(t.displayedQuote,e.revision+1);case`error`:return{failure:t.failure,phase:`error`,revision:e.revision};case`checkout`:return e.phase===`ready`?{...e,displayedQuote:t.checkout,quoteFailure:void 0}:e;case`quote-error`:return e.phase===`ready`?{...e,quoteFailure:t.failure}:e;default:return e}}function $(e,t,n){return e?.catalog===t&&e.selectionKey===n}function bt({checkout:e}){return{displayedQuote:e,type:`ready`}}function xt(e){return e instanceof Error?e.message:`Lockerverse payment could not load.`}function St(e,t){return{checkoutItems:[...e.items],displayedQuote:e,phase:`ready`,quoteFailure:void 0,revision:t}}function Ct(e,t){let n=e.widget.fields.serviceFee;return G(e,{includeServiceFee:n,selection:t})}function wt(e,t){try{return St(Ct(e,t),1)}catch(e){return{failure:xt(e),phase:`error`,revision:0}}}function Tt({catalog:e,client:t,paymentState:n,selection:r}){let i=ke(r),a=i.success?JSON.stringify(i.value):`invalid-selection`,o=T(()=>i.success?i.value:[],[i.success,a]),[s,c]=E(yt,void 0,()=>i.success?wt(e,o):{phase:`loading`,revision:0}),l=D(void 0),u=D(0),d=D(s.phase===`ready`?{catalog:e,selectionKey:a}:void 0),f=D(s.phase===`error`?{catalog:e,selectionKey:a}:void 0),p=n===`submitting`||n===`success`||n===`unresolved`;S(()=>{if(!i.success||p||$(f.current,e,a)||$(l.current,e,a))return;let n=!0;l.current={catalog:e,selectionKey:a};let r=$(d.current,e,a);r||c({type:`loading`});function s(e){n&&c(e)}function m(){n&&(l.current=void 0,f.current={catalog:e,selectionKey:a})}let h;function g(t){if(!n||(l.current=void 0,f.current={catalog:e,selectionKey:a},r&&h!==void 0&&u.current!==h))return;let i=xt(t);if(i===`This option is sold out.`){c({failure:i,type:`error`});return}c(r?{failure:i,type:`quote-error`}:{failure:i,type:`error`})}async function _(){try{h=u.current;let n=e.widget.fields.serviceFee;if(!r){let t=Ct(e,o);r=!0,d.current={catalog:e,selectionKey:a},s(bt({checkout:t}))}let i=await t.calculateTotal({catalog:e,includeServiceFee:n,selection:o});m(),u.current===h&&s({checkout:i,type:`checkout`})}catch(e){g(e)}}return _(),()=>{n=!1,$(l.current,e,a)&&(l.current=void 0)}},[e,t,i.success,p,a,o]);let m=$(d.current,e,a)||$(f.current,e,a)||$(l.current,e,a),h=p||m?s:{phase:`loading`,revision:s.revision};return{selectionError:i.success?void 0:i.message,session:h,updateCheckout:e=>{u.current+=1,c({checkout:e,type:`checkout`})}}}const Et=z({recovery:z({connectedAccountId:L(H()),paymentReference:B(H(),U(),I())}),selectionFingerprint:H(),version:W([N(1),N(2)]),widgetId:ee(H())});function Dt(e){let t=ke(e);return t.success?JSON.stringify(t.value.map(e=>{let t=e.productSlug.trim();return`quantity`in e?[`quantity`,t,e.quantity]:`amountCents`in e?[`amount`,t,e.amountCents]:[`product`,t]})):null}const Ot=`A previous payment uses different checkout details. Return to its original checkout to check the payment before you pay again.`;function kt(e,t,n){let r;try{r=window.sessionStorage.getItem(e)}catch{return{recovery:null}}if(!r)return{recovery:null};try{let e=ne(Et,JSON.parse(r));if(!e.success)throw Error(`Invalid recovery record`);let i=e.output;return i.selectionFingerprint!==t||i.version===2&&i.widgetId!==n?{error:Ot,recovery:null}:{recovery:{connectedAccountId:i.recovery.connectedAccountId,paymentReference:i.recovery.paymentReference}}}catch{return{error:`The saved payment could not be read. Contact support to check it before you pay again.`,recovery:null}}}function At({selection:e,storageKey:t,widgetId:n}){let r=Dt(e),i=JSON.stringify([t,r,n]),[a,o]=O(null),s=D(null);S(()=>{if(!t)return;let e=s.current,a={recovery:null};e?.recovery?a=e.identity===i?{recovery:e.recovery}:{error:Ot,recovery:null}:r!==null&&(a=kt(t,r,n)),a.recovery&&(s.current={identity:i,recovery:a.recovery}),o({identity:i,...a})},[r,i,t,n]);let c=x(e=>{if(!(!t||r===null)){s.current=e?{identity:i,recovery:e}:null;try{e?window.sessionStorage.setItem(t,JSON.stringify({recovery:e,selectionFingerprint:r,version:2,widgetId:n})):window.sessionStorage.removeItem(t)}catch{}}},[r,i,t,n]);return{error:t&&a?.identity===i?a.error:void 0,ready:!t||a?.identity===i,recovery:t&&a?.identity===i?a.recovery:null,remember:c}}const jt={annually:`/year`,"every-six-months":` every 6 months`,monthly:`/month`,"one-time":``};function Mt({branding:e,catalog:t}){return j(`header`,{children:[t.widget.showCommunityBranding&&e?j(`div`,{className:`lockerverse-payment__branding`,children:[e.imageUrl?A(`img`,{alt:e.name,height:`48`,src:e.imageUrl,width:`48`}):null,A(`strong`,{children:e.name})]}):null,A(`h1`,{children:t.widget.title??t.widget.name}),t.widget.description?A(`p`,{children:t.widget.description}):null]})}function Nt({catalog:t,selection:n}){let r=n?.length?t.products.filter(e=>n.some(t=>t.productSlug===e.slug)):t.products.filter(e=>e.id!==t.widget.requiredShipping?.productId);return r.length===0?null:j(`div`,{className:`lockerverse-payment__payment-summary`,children:[A(`h2`,{children:`Products`}),A(`div`,{className:`lockerverse-payment__payment-summary-items`,children:r.map(t=>{let n=t.pricingMode===`fixed`?t.amountCents:t.minimumAmountCents,r=jt[t.paymentOption];return j(`div`,{className:`lockerverse-payment__payment-summary-row`,children:[A(`span`,{children:t.name}),A(`strong`,{children:n===null?`Choose amount`:`${t.pricingMode===`custom`?`From `:``}${e(n)}${r}`})]},t.id)})}),A(`p`,{children:`Base prices. Final total is checked at checkout.`})]})}function Pt(e,t){let n=c(e?.[`--lockerverse-accent`]??t?.accentColor??`#38d77a`),r=l(n),i={...e};return(e?.[`--lockerverse-accent`]!==void 0||t?.accentColor)&&(i[`--lockerverse-accent`]=n),r&&e?.[`--lockerverse-accent-contrast`]===void 0&&(i[`--lockerverse-accent-contrast`]=r),{accent:n,rootStyle:i}}function Ft({catalog:e,client:t,loadError:n,onRetry:r,...i}){let{branding:a,className:o,completionView:c,paymentSummaryPosition:l=`top`,recoveryStorageKey:u,initialCustomFieldValues:d,metadata:f,onPaymentComplete:p,onPaymentRecoveryChange:m,onPaymentUncertain:h,resumePayment:g,selection:_,style:v,stripeLoader:y=et,theme:b=`dark`,...C}=i,[T,E]=O(g),k=D(null),[M,N]=O(null),P=x(e=>{N(e),s(p,e)},[p]),[F,I]=O(),[L,R]=O(`idle`),z=D(void 0),{selectionError:ee,session:B,updateCheckout:te}=Tt({catalog:e,client:t,paymentState:L,selection:_}),V=B.phase===`ready`?B.revision:void 0,ne=x(e=>{V!==void 0&&(z.current=V),R(e)},[V]),re=x(e=>m?.(e),[m]),H=x(()=>{E(void 0)},[]);S(()=>{B.phase===`loading`&&I(void 0)},[B.phase]),w(()=>{B.phase===`ready`&&z.current!==B.revision&&R(e=>e===`success`||e===`unresolved`?e:`idle`)},[B.phase,B.revision]);let U=[`lockerverse-payment`,o].filter(Boolean).join(` `),W=a??e.community,{accent:ie,rootStyle:G}=Pt(v,W);return M&&c===`summary`?A(`section`,{...C,className:U,"data-lockerverse-theme":b,"data-payment-state":`success`,style:G,children:j(`div`,{className:`lockerverse-payment__completion`,role:`status`,children:[A(`span`,{"aria-hidden":`true`,className:`lockerverse-payment__completion-icon`,children:A(`svg`,{"aria-hidden":`true`,fill:`none`,height:`28`,stroke:`currentColor`,strokeWidth:`2`,viewBox:`0 0 24 24`,width:`28`,children:A(`path`,{d:`m5 12 4 4L19 6`})})}),A(`h1`,{children:M.paymentRequired?`Thank you`:`Order confirmed`}),A(`p`,{children:M.paymentRequired?`Your payment has been received.`:`Your order is confirmed. No payment was required.`})]})}):ee?A(`section`,{...C,className:U,"data-lockerverse-theme":b,role:`alert`,style:G,children:ee}):B.phase===`error`&&B.failure===`This option is sold out.`||L===`sold_out`?j(`section`,{...C,className:U,"data-lockerverse-theme":b,role:`alert`,style:G,children:[A(`h1`,{children:`Sold out`}),A(`p`,{children:`This option is sold out.`})]}):B.phase===`error`?A(`section`,{...C,className:U,"data-lockerverse-theme":b,style:G,children:A(`p`,{role:`alert`,children:B.failure})}):B.phase===`ready`?j(`section`,{...C,"aria-label":`Payment`,className:U,"data-lockerverse-theme":b,"data-payment-state":L,ref:k,style:G,children:[A(Mt,{branding:W,catalog:e}),n?j(`div`,{role:`alert`,children:[A(`p`,{children:n.message}),A(`button`,{onClick:r,type:`button`,children:`Retry`})]}):null,F?A(`p`,{className:`lockerverse-payment__payment-status`,role:`status`,children:F}):null,B.quoteFailure?j(`div`,{className:`lockerverse-payment__payment-status`,role:`alert`,children:[A(`span`,{children:B.quoteFailure}),A(`span`,{children:` The final total will be checked when you submit.`})]}):null,A(it,{accentColor:ie,appearanceRoot:k,catalog:e,checkoutItems:B.checkoutItems,client:t,initialCustomFieldValues:d,metadata:f,onPaymentComplete:P,onPaymentRecoveryChange:re,onPaymentUncertain:h,onQuoteChange:(e,t)=>{I(t),te(e)},onResumePaymentFailed:H,onStateChange:ne,paymentSummaryPosition:l,quote:B.displayedQuote,resumePayment:T,stripeLoader:y,theme:b,visualStyle:G},B.revision)]}):j(`section`,{...C,"aria-busy":`true`,"aria-label":`Payment`,className:U,"data-lockerverse-theme":b,style:G,children:[A(Mt,{branding:W,catalog:e}),n?j(`div`,{role:`alert`,children:[A(`p`,{children:n.message}),A(`button`,{onClick:r,type:`button`,children:`Retry`})]}):null,A(vt,{})]})}function It({children:e,loading:t=!1,viewProps:n}){let{branding:r,className:i,completionView:a,paymentSummaryPosition:o,recoveryStorageKey:s,initialCustomFieldValues:u,metadata:d,onPaymentComplete:f,onPaymentRecoveryChange:p,onPaymentUncertain:m,resumePayment:h,selection:g,stripeLoader:_,style:v,theme:y=`dark`,...b}=n,x=c(v?.[`--lockerverse-accent`]??r?.accentColor??`#38d77a`),S=l(x),C={...v};return(v?.[`--lockerverse-accent`]!==void 0||r?.accentColor)&&(C[`--lockerverse-accent`]=x),S&&v?.[`--lockerverse-accent-contrast`]===void 0&&(C[`--lockerverse-accent-contrast`]=S),A(`section`,{...b,...t?{"aria-busy":!0,"aria-label":`Payment`}:{},className:[`lockerverse-payment`,i].filter(Boolean).join(` `),"data-lockerverse-theme":y,style:C,children:e})}function Lt(e){let{catalog:t,client:n,loadError:r,onRetry:i,...a}=e,{onPaymentRecoveryChange:o,recoveryStorageKey:c,resumePayment:l,selection:u}=a,d=At({selection:u,storageKey:c,widgetId:t.widget.id}),f=x(e=>{d.remember(e),s(o,e)},[o,d.remember]);return!d.ready||d.error?A(It,{loading:!d.ready,viewProps:a,children:d.error?A(`p`,{role:`alert`,children:d.error}):A(vt,{})}):A(Ft,{...e,onPaymentRecoveryChange:f,resumePayment:l??d.recovery})}function Rt({widget:e,...t}){return e.error&&!e.catalog?j(It,{viewProps:t,children:[A(`p`,{role:`alert`,children:e.error.message}),A(`button`,{onClick:e.refresh,type:`button`,children:`Retry`})]}):e.loading?j(It,{loading:!0,viewProps:t,children:[e.catalog?j(k,{children:[A(Mt,{branding:t.branding??e.catalog.community,catalog:e.catalog}),(t.paymentSummaryPosition??`top`)===`top`?A(Nt,{catalog:e.catalog,selection:t.selection}):null]}):null,A(vt,{})]}):e.catalog?A(Lt,{catalog:e.catalog,client:e.client,loadError:e.error,onRetry:e.refresh,...t}):A(It,{loading:!0,viewProps:t,children:A(vt,{})})}export{tt as n,Rt as t};
1
+ import{t as e}from"./format-money.js";import{d as t,i as n,n as r,p as i,t as a,u as o}from"./phone-field.js";import{t as s}from"./host-callback.js";import{n as c,t as l}from"./accent-contrast.js";import{a as u,i as d,n as f,r as p,s as m}from"./custom-fields.js";import{t as h}from"./form-skeleton.js";import{t as g}from"./payment-summary.js";import{i as _,n as v,r as y,t as b}from"./stripe-loader.js";import{useCallback as x,useEffect as S,useId as C,useLayoutEffect as w,useMemo as T,useReducer as E,useRef as D,useState as O}from"react";import{Fragment as k,jsx as A,jsxs as j}from"react/jsx-runtime";import{array as M,literal as N,minLength as P,minValue as F,nonEmpty as I,nullable as L,number as R,object as z,optional as ee,pipe as B,regex as te,safeInteger as V,safeParse as ne,strictObject as re,string as H,trim as U,union as W}from"valibot";import{AddressElement as ie,Elements as G,PaymentElement as ae,useElements as oe,useStripe as se}from"@stripe/react-stripe-js";import{LockerverseSdkError as K,estimateLockerverseCheckout as ce}from"@lockerverse/sdk/checkout";function le({ariaDescribedBy:e,ariaLabel:t,ariaLabelledBy:n,className:r,id:i,invalid:a=!1,name:o,onValueChange:s,options:c,value:l}){return A(`select`,{"aria-describedby":e,"aria-invalid":a||void 0,"aria-label":t,"aria-labelledby":n,className:[`lockerverse-form__control`,`lockerverse-form__select`,r].filter(Boolean).join(` `),id:i,name:o,onChange:e=>s(e.currentTarget.value),value:l,children:c.map(e=>A(`option`,{value:e.value,children:e.label},e.value))})}const ue=[`XS`,`S`,`M`,`L`,`XL`,`XXL`,`XXXL`],de=[`15`,`12`,`10`,`5`],q=[...de,`custom`];function fe({enabled:e,error:t,errorId:n,onChange:r,values:i}){if(!e)return null;let a=e=>r({...i,...e}),o=(e,t)=>{let n=q.indexOf(t),r;switch(e.key){case`ArrowDown`:case`ArrowRight`:r=(n+1)%q.length;break;case`ArrowLeft`:case`ArrowUp`:r=(n-1+q.length)%q.length;break;case`Home`:r=0;break;case`End`:r=q.length-1;break;default:return}e.preventDefault();let i=q[r];i&&((e.currentTarget.closest(`[role="radiogroup"]`)?.querySelectorAll(`input[type="radio"]`))?.[r]?.focus(),a({tipPercent:i}))};return j(`div`,{className:`lockerverse-payment__tip-box`,children:[A(`p`,{children:`Add a tip to support the Lockerverse platform`}),j(`div`,{"aria-label":`Tip amount`,role:`radiogroup`,children:[de.map(e=>j(`label`,{className:`lockerverse-payment__tip-choice`,children:[A(`input`,{checked:i.tipPercent===e,name:`tipPercent`,onChange:()=>a({tipPercent:e}),onKeyDown:t=>o(t,e),tabIndex:i.tipPercent===e?0:-1,type:`radio`,value:e}),j(`span`,{children:[e,`%`]})]},e)),j(`label`,{className:`lockerverse-payment__tip-choice`,children:[A(`input`,{checked:i.tipPercent===`custom`,name:`tipPercent`,onChange:()=>a({tipPercent:`custom`}),onKeyDown:e=>o(e,`custom`),tabIndex:i.tipPercent===`custom`?0:-1,type:`radio`,value:`custom`}),A(`span`,{children:`Other`})]})]}),i.tipPercent===`custom`?j(`label`,{children:[A(`span`,{children:`Custom tip`}),j(`span`,{className:`lockerverse-payment__money-input`,children:[A(`span`,{"aria-hidden":`true`,children:`$`}),A(`input`,{"aria-describedby":t?n:void 0,"aria-invalid":t?`true`:void 0,inputMode:`decimal`,name:`tip`,onChange:e=>a({customTip:e.currentTarget.value}),placeholder:`0.00`,value:i.customTip})]}),t?A(`span`,{className:`lockerverse-payment__field-message`,id:n,children:t}):null]}):A(`input`,{name:`tip`,type:`hidden`,value:i.tipPercent})]})}function pe({checked:e,children:t,name:n,onChange:r}){let i=C();return j(`label`,{className:`lockerverse-payment__check-row`,htmlFor:i,children:[A(o,{checked:e,id:i,name:n,onChange:e=>r(e.currentTarget.checked)}),A(`span`,{children:t})]})}function me({customFields:e,errors:t,fields:n,idPrefix:r,isPromoApplying:i,memberIdLabel:a,onChange:o,onApplyPromo:s,promoError:c,values:l}){let u=e=>o({...l,...e});return j(`div`,{className:`lockerverse-payment__additional-fields`,children:[n.memberId?j(`label`,{children:[A(`span`,{children:a?.trim()||`Member ID`}),A(`input`,{name:`memberId`,onChange:e=>u({memberId:e.currentTarget.value}),placeholder:`Optional`,value:l.memberId})]}):null,n.merchSize?j(`div`,{className:`lockerverse-payment__field`,children:[A(`span`,{id:`${r}-merch-size-label`,children:`Size`}),A(le,{ariaLabelledBy:`${r}-merch-size-label`,name:`merchSize`,onValueChange:e=>{let t=ue.find(t=>t===e);t&&u({merchSize:t})},options:ue.map(e=>({label:e,value:e})),value:l.merchSize})]}):null,n.promoCode?j(`div`,{className:`lockerverse-payment__field`,children:[A(`span`,{id:`${r}-promo-code-label`,children:`Promo code`}),j(`div`,{className:`lockerverse-payment__promo-control`,children:[A(`input`,{"aria-describedby":c?`${r}-promo-code-error`:void 0,"aria-invalid":c?`true`:void 0,"aria-labelledby":`${r}-promo-code-label`,name:`promoCode`,onChange:e=>u({promoCode:e.currentTarget.value}),placeholder:`Optional`,value:l.promoCode}),A(`button`,{disabled:!l.promoCode.trim()||i,onClick:s,type:`button`,children:i?`Applying…`:`Apply`})]}),c?A(`p`,{className:`lockerverse-payment__field-message`,id:`${r}-promo-code-error`,role:`alert`,children:c}):null]}):null,A(f,{choiceClassName:`lockerverse-payment__check-row`,errorClassName:`lockerverse-payment__field-message`,errors:t,fields:e,idPrefix:r,onChange:e=>u({customFields:e}),values:l.customFields})]})}function J({amountCents:t,enabled:n,onChange:r,values:i}){return n?j(pe,{checked:i.includeServiceFee,name:`includeServiceFee`,onChange:e=>r({...i,includeServiceFee:e}),children:[`Add `,e(t),` to help cover processing fees`]}):null}function Y(e){return{error:void 0,message:void 0,status:e?`recovering`:`editing`}}function X(e,t,n){return t.includes(e.status)?{...e,...n}:e}function he(e,t){if(t.type===`recovery_started`&&e.status===`unresolved`)return{...e,message:void 0,status:`recovering`};if(e.status===`sold_out`||e.status===`succeeded`||e.status===`unresolved`)return e;switch(t.type){case`field_changed`:return X(e,[`editing`,`invalid`,`refreshing_quote`],{error:void 0,status:`editing`});case`validation_failed`:return X(e,[`editing`],{status:`invalid`});case`quote_refresh_started`:return X(e,[`editing`,`invalid`],{status:`refreshing_quote`});case`quote_refresh_succeeded`:return X(e,[`refreshing_quote`],{error:void 0,status:`editing`});case`quote_refresh_failed`:return X(e,[`refreshing_quote`],{error:t.error??e.error,status:`editing`});case`submission_started`:return X(e,[`editing`,`invalid`,`refreshing_quote`],{error:void 0,status:`submitting`});case`submission_validation_failed`:return X(e,[`submitting`],{error:void 0,status:`invalid`});case`quote_changed`:return X(e,[`submitting`],{status:`editing`});case`retryable_failure`:return X(e,[`editing`,`invalid`,`submitting`],{error:t.error,status:`editing`});case`recovery_failed`:return X(e,[`recovering`],{error:t.error,retryUrl:void 0,status:`editing`});case`sold_out`:return{error:void 0,message:void 0,status:`sold_out`};case`succeeded`:return X(e,[`recovering`,`submitting`],{message:t.message,retryUrl:void 0,status:`succeeded`});case`unresolved`:return X(e,[`recovering`,`submitting`],{message:t.message,retryUrl:t.retryUrl,status:`unresolved`});default:return e}}function ge(e){return e.status===`editing`||e.status===`invalid`||e.status===`refreshing_quote`?e.error:void 0}function Z(e){return e.status===`sold_out`?`sold_out`:e.status===`succeeded`?`success`:e.status===`unresolved`?`unresolved`:e.status===`submitting`||e.status===`recovering`?`submitting`:e.status===`invalid`?`invalid`:ge(e)?`error`:`idle`}function Q(e){return e.status===`submitting`}const _e=[`amountCents`,`discountableSubtotalCents`,`discountCents`,`serviceFeeCents`,`subtotalCents`,`tipCents`,`totalCents`],ve=[`discountableSubtotalCents`,`discountCents`,`subtotalCents`];function ye(e,t,n,r){return(n===t.totalCents?ve:_e).some(n=>e[n]!==t[n])||r!==t.payment.connectedAccountId||e.authoritative&&(e.payment.connectedAccountId!==r||e.payment.currency!==t.payment.currency)||JSON.stringify(e.appliedDiscount)!==JSON.stringify(t.appliedDiscount)||JSON.stringify(e.lineItems)!==JSON.stringify(t.lineItems)}function be(e){if(e.checkoutStatus===`success`)return{kind:`success`,payment:e};if(e.checkoutStatus===`failed`)return{kind:`failed`,payment:e};let t={kind:`unresolved`,paymentReference:e.paymentReference,reason:e.checkoutStatus===`action_required`?`action_required`:`pending`};return e.retryUrl&&(t.retryUrl=e.retryUrl),t}async function xe(e,t,n){if(t.checkoutStatus!==`action_required`||!t.requiresAction)return be(t);if(!n)return{kind:`unresolved`,paymentReference:t.paymentReference,reason:`action_required`};if(t.clientSecret)try{await n.handleNextAction({clientSecret:t.clientSecret})}catch{}try{return be(await e.getPaymentStatus(t.paymentReference))}catch{return{kind:`unresolved`,paymentReference:t.paymentReference,reason:`action_required`}}}async function Se(e,t,n){let r;try{r=await e.submitPayment(t)}catch(n){if(!(n instanceof K&&n.recoveryRecommended))throw n;try{r=await e.getPaymentStatus(t.checkout.paymentReference)}catch{return{kind:`unresolved`,paymentReference:t.checkout.paymentReference,reason:`recovery_failed`}}}return xe(e,r,n)}async function Ce(e,t,n){try{return xe(e,await e.getPaymentStatus(t),n)}catch{return{kind:`unresolved`,paymentReference:t,reason:`recovery_failed`}}}const we=B(H(),U(),I()),Te=B(R(),V(),F(1)),Ee=B(M(W([re({amountCents:Te,productSlug:we}),re({productSlug:we,quantity:Te}),re({productSlug:we})])),P(1)),De=B(H(),U(),te(/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/,`Enter a valid tip amount.`));function Oe(e){let t=ne(De,e);if(!t.success)return{message:t.issues[0]?.message??`Enter a valid tip amount.`,success:!1};let[n=`0`,r=``]=t.output.split(`.`),i=BigInt(n)*100n+BigInt(r.padEnd(2,`0`));return i>BigInt(2**53-1)?{message:`Enter a valid tip amount.`,success:!1}:{cents:Number(i),success:!0}}function ke(e){let t=ne(Ee,e);return t.success?{success:!0,value:t.output}:{message:`Lockerverse payment configuration is invalid.`,success:!1}}const Ae=`This promo code is invalid or cannot be applied.`;function je(e,t){return t.tipPercent===`custom`?t.customTip.trim()?Oe(t.customTip):{cents:0,success:!0}:{cents:Math.round(e*Number(t.tipPercent)/100),success:!0}}function Me(e,t,n,r){let i={};return n&&(i.email=n),e.widget.fields.serviceFee&&(i.includeServiceFee=t.includeServiceFee),e.widget.fields.promoCode&&t.promoCode.trim()&&(i.promoCode=t.promoCode.trim()),e.widget.fields.tipping&&(i.tipCents=r),i}function Ne(e,t,n){let r=e.widget.fields.tipping?je(n.subtotalCents,t):{cents:0,success:!0};if(!r.success)return{parsedTip:r,totalCents:null};let i=e.widget.fields.serviceFee&&t.includeServiceFee?n.serviceFeeCents||Math.round(n.subtotalCents*e.pricingPolicy.serviceFeeRateBasisPoints/1e4):0;return{parsedTip:r,totalCents:n.totalCents-n.serviceFeeCents-n.tipCents+i+r.cents}}function Pe(e,t){return{displayedTotalCents:e.totalCents,promoError:t&&e.appliedDiscount?.source!==`promo_code`?Ae:void 0}}function Fe(e,t){let n;return t||(n=e instanceof Error?e.message:`The order total could not be updated.`),{paymentError:n,promoError:t?Ae:void 0}}function Ie(e,t){if(!e?.complete)throw Error(`${t} address is required.`);return e.value}function Le(e,t,n,r){if(e.widget.fields.shipping)return t.shippingMatchesBilling?n:Ie(r.shipping,`Shipping`)}function Re({billingAddress:e,catalog:t,email:n,phone:r,shippingAddress:i}){let a={payment_method_data:{billing_details:t.widget.fields.phone?{address:e.address,email:n,name:e.name,phone:r}:{address:e.address,email:n,name:e.name}}};return i?{...a,shipping:{address:i.address,name:i.name,phone:t.widget.fields.phone?r:i.phone??null}}:a}function ze({catalog:e,checkoutItems:t,confirmationToken:n,email:r,fieldValues:i,metadata:a,phone:o,shippingAddress:s}){let c={customFieldAnswers:p(u(e,t),i.customFields),email:r};if(n&&(c.confirmationToken=n,c.paymentMethodConfiguration=`explicit`),a&&(c.metadata=a),e.widget.fields.memberId&&i.memberId.trim()&&(c.memberId=i.memberId.trim()),e.widget.fields.merchSize&&(c.merchSize=i.merchSize),e.widget.fields.phone&&(c.phone=o),s){let e={city:s.address.city??``,country:s.address.country,line1:s.address.line1??``,postal_code:s.address.postal_code??``,state:s.address.state??``};s.address.line2&&(e.line2=s.address.line2),c.shipping={address:e,name:s.name}}return c}function Be(e){if(!e())throw Error(`Payment component is no longer active.`)}function Ve(e,t){s(e,t)}function He(e,t,n,r){return e.kind===`failed`?{kind:`payment_failed`,message:r}:e.kind===`unresolved`?{kind:`payment_unresolved`,paymentReference:e.paymentReference,reason:e.reason,retryUrl:e.retryUrl}:{email:n,kind:`payment`,payment:e.payment,quote:t}}async function Ue({addresses:e,catalog:t,checkoutItems:n,client:r,elements:i,email:a,fieldValues:o,isAttemptActive:s,locallyPreviewedTotalCents:c,metadata:l,onPaymentRecoveryChange:u,phone:d,quote:f,stripe:p,stripeConnectedAccountId:m}){let h=a.trim().toLowerCase(),g=y(d),_=je(f.subtotalCents,o);if(!_.success)throw Error(_.message);let v=await r.calculateTotal({...Me(t,o,h,_.cents),catalog:t,items:n});if(Be(s),v.totalCents>0&&ye(f,v,c,m))return{kind:`quote_changed`,quote:v};let b,x;if(v.totalCents===0)t.widget.fields.shipping&&(b=Le(t,o,Ie(e.billing,`Billing`),e));else{if(!(i&&p))throw Error(`Payment form is still loading.`);await i.update({amount:v.totalCents}),Be(s);let n=await i.submit();if(Be(s),n.error)throw Error(n.error.message);let r=Ie(e.billing,`Billing`);b=Le(t,o,r,e);let a=await p.createConfirmationToken({elements:i,params:Re({billingAddress:r,catalog:t,email:h,phone:g,shippingAddress:b})});if(Be(s),a.error)throw Error(a.error.message);x=a.confirmationToken.id}Ve(u,{connectedAccountId:v.payment.connectedAccountId,paymentReference:v.paymentReference});let S=await Se(r,{checkout:v,submission:ze({catalog:t,checkoutItems:n,confirmationToken:x,email:h,fieldValues:o,metadata:l,phone:g,shippingAddress:b})},p);return Be(s),He(S,v,h,v.totalCents===0?`Order could not be completed. Review the details and try again.`:`Payment was declined. Check your payment details and try again.`)}function We(e,t){s(e,t)}function Ge(e,t){s(e,t)}function Ke(e,t){return{...e,...t}}function qe(e){let t={message:e.reason===`action_required`?`Payment needs your attention. Keep this checkout open.`:`Payment is not complete. Check its status before you try again.`,type:`unresolved`};return e.retryUrl&&(t.retryUrl=e.retryUrl),t}function Je(e,t,n){return e.kind===`unresolved`&&e.reason===`action_required`&&!e.retryUrl&&!t&&!n}function Ye(e){return e instanceof K&&e.serverCode===`PAYMENT_WIDGET_SALES_LIMIT_REACHED`}function Xe({nextQuote:e,onQuoteChange:t,setDisplayedTotalCents:n,setPromoError:r,updateState:i,validatePromo:a}){let o=Pe(e,a);i({type:`quote_refresh_succeeded`}),n(o.displayedTotalCents),t(e),a&&r(o.promoError)}function Ze({error:e,setPromoError:t,updateState:n,validatePromo:r}){let i=Fe(e,r);r&&t(i.promoError),n(i.paymentError===void 0?{type:`quote_refresh_failed`}:{error:i.paymentError,type:`quote_refresh_failed`})}function Qe({onPaymentComplete:t,onPaymentRecoveryChange:n,onPaymentUncertain:r,onQuoteChange:i,result:a,setDisplayedTotalCents:o,dispatchState:c,unresolvedReferenceRef:l}){if(a.kind===`quote_changed`){let t=`The total changed to ${e(a.quote.totalCents)}. Review it and pay again.`;i(a.quote,t),o(a.quote.totalCents),c({type:`quote_changed`});return}if(a.kind===`payment_failed`){We(n,null),c({error:a.message,type:`retryable_failure`});return}if(a.kind===`payment_unresolved`){l.current=a.paymentReference,c(qe(a)),Ge(r,{paymentReference:a.paymentReference,reason:a.reason});return}i(a.quote),We(n,null),c({message:a.payment.paymentRequired?`Payment completed successfully.`:`Order confirmed. No payment was required.`,type:`succeeded`}),s(t,Ke(a.payment,{email:a.email,lineItems:a.quote.lineItems}))}function $e(e){let{catalog:t,checkoutItems:r,client:i,elements:a,email:o,fieldValues:c,metadata:l,onPaymentComplete:u,onResumePaymentFailed:d,onPaymentRecoveryChange:f,onPaymentUncertain:p,onQuoteChange:m,onStateChange:h,quote:g,resumePayment:v,stripe:y,stripeConnectedAccountId:b,stripeLoadFailed:C,paymentState:w,updateState:T}=e,[E,k]=O(g.totalCents),[A,j]=O(),M=D(!1),N=D(void 0),P=D(0),F=D(0),I=x(e=>T(e,!0),[T]),L=x(()=>{let e=F.current+1;return F.current=e,()=>F.current===e},[]);S(()=>()=>{F.current+=1,P.current+=1},[]);let{parsedTip:R,totalCents:z}=Ne(t,c,g);S(()=>{z!==null&&(k(z),z>0&&a?.update({amount:z}))},[t.pricingPolicy.serviceFeeRateBasisPoints,t.widget.fields.serviceFee,a,c.includeServiceFee,z,g.serviceFeeCents,g.tipCents,g.totalCents,g.subtotalCents]),S(()=>{let e=v?.paymentReference??N.current;if(!e||M.current||w.status!==`recovering`)return;M.current=!0;let t=L();return h(Z(w)),Ce(i,e,y).then(e=>{if(t()&&!Je(e,y,C)){if(e.kind===`failed`){We(f,null),d(),I({error:`The previous payment failed. Check your details and try again.`,type:`recovery_failed`});return}if(e.kind===`unresolved`){I(qe(e)),Ge(p,{paymentReference:e.paymentReference,reason:e.reason});return}We(f,null),I({message:e.payment.paymentRequired?`Payment completed successfully.`:`Order confirmed. No payment was required.`,type:`succeeded`}),s(u,Ke(e.payment,{email:null,lineItems:null}))}}),()=>{t()&&(F.current+=1),M.current=!1}},[i,u,d,f,p,h,v,y,C,L,I,w]);let ee=x((e=!1,t=!1)=>{t||(P.current+=1),e&&j(void 0),T({type:`field_changed`})},[T]);async function B(e=!1,n=!1){let a=o.trim().toLowerCase(),s=_({email:a,phone:``},!1);if(!(R.success&&(s.value||e)))return;P.current+=1;let l=P.current;T({type:`quote_refresh_started`});try{let e=await i.calculateTotal({...Me(t,c,s.value?.email??``,R.cents),catalog:t,items:r});if(l!==P.current)return;Xe({nextQuote:e,onQuoteChange:m,setDisplayedTotalCents:k,setPromoError:j,updateState:T,validatePromo:n})}catch(e){if(l!==P.current)return;if(Ye(e)){T({type:`sold_out`});return}Ze({error:e,setPromoError:j,updateState:T,validatePromo:n})}}async function te(){j(void 0),await B(!0,!0)}async function V({addresses:e,phone:s}){I({type:`submission_started`});let d=L();try{let n=await Ue({addresses:e,catalog:t,checkoutItems:r,client:i,elements:a,email:o,fieldValues:c,isAttemptActive:d,locallyPreviewedTotalCents:E,metadata:l,onPaymentRecoveryChange:f,phone:s,quote:g,stripe:y,stripeConnectedAccountId:b});if(!d())return;Qe({dispatchState:I,onPaymentComplete:u,onPaymentRecoveryChange:f,onPaymentUncertain:p,onQuoteChange:m,result:n,setDisplayedTotalCents:k,unresolvedReferenceRef:N})}catch(e){if(!d())return;if(We(f,null),Ye(e)){I({type:`sold_out`});return}let t=e instanceof K?n(e.serverCode):void 0;if(t)return I({type:`submission_validation_failed`}),{phoneError:t};I({error:e instanceof Error?e.message:`Payment could not be completed.`,type:`retryable_failure`})}}let ne=w.status===`succeeded`||w.status===`unresolved`?w.message:void 0;return{commands:{applyPromo:te,checkPaymentStatus:()=>I({type:`recovery_started`}),fieldChanged:ee,refreshAuthoritativeTotal:B,reportValidationFailure:()=>I({type:`validation_failed`}),submit:V},state:{displayedTotalCents:E,isRecovering:w.status===`recovering`,isRefreshingQuote:w.status===`refreshing_quote`,isSubmitting:Q(w),isUnresolved:w.status===`unresolved`,parsedTip:R,paymentError:ge(w),promoError:A,retryUrl:w.retryUrl,terminalMessage:ne}}}const et=b;function tt(e){let{connectedAccountId:t,publishableKey:n}=e.payment;return et(n,t?{stripeAccount:t}:void 0)}function nt(e){return e===`monthly`?{interval:`month`,label:`Monthly`}:e===`annually`?{interval:`year`,label:`Annual`}:e===`every-six-months`?{interval:`6 months`,label:`Every 6 months`}:null}function rt(e,t,n){if(n){let{connectedAccountId:e}=n;return e}if(`payment`in t){let{connectedAccountId:e}=t.payment;return e}let{connectedAccountId:r}=e.payment;return r}function it({accentColor:e,catalog:t,checkoutItems:n,client:r,appearanceRoot:i,initialCustomFieldValues:a,paymentSummaryPosition:o,metadata:s,onPaymentComplete:c,onResumePaymentFailed:l,onPaymentRecoveryChange:u,onPaymentUncertain:d,onQuoteChange:f,quote:p,resumePayment:m,onStateChange:g,stripeLoader:_,theme:y,visualStyle:b}){let[C,w]=O(()=>Y(!!m)),E=D(C);E.current=C;let k=x((e,t=!1)=>{let n=he(E.current,e);n!==E.current&&(E.current=n,w(n),t&&g(Z(n)))},[g]),j=rt(t,p,m),M=D({connectedAccountId:j,paymentOption:p.paymentOption});C.status!==`submitting`&&C.status!==`recovering`&&(M.current={connectedAccountId:j,paymentOption:p.paymentOption});let{connectedAccountId:N,paymentOption:P}=M.current,F=T(()=>_(t.payment.publishableKey,N?{stripeAccount:N}:void 0).catch(()=>null),[t.payment.publishableKey,N,_]),[I,L]=O(!1);S(()=>{let e=!0;return L(!1),F.then(t=>{e&&t===null&&L(!0)}),()=>{e=!1}},[F]);let R=v(i,y,b,C.status===`submitting`||C.status===`recovering`,e);return R?A(G,{options:{amount:Math.max(p.totalCents,100),appearance:R,currency:t.payment.currency,mode:P===`one-time`?`payment`:`subscription`,paymentMethodTypes:t.community?.widgetAchEnabled?[`card`,`us_bank_account`]:[`card`],setupFutureUsage:`off_session`,syncAddressCheckbox:`none`},stripe:F,children:A(_t,{catalog:t,checkoutItems:n,client:r,initialCustomFieldValues:a,metadata:s,onPaymentComplete:c,onPaymentRecoveryChange:u,onPaymentUncertain:d,onQuoteChange:f,onResumePaymentFailed:l,onStateChange:g,paymentState:C,paymentSummaryPosition:o,quote:p,resumePayment:m,stripeConnectedAccountId:N,stripeLoadFailed:I,updateState:k})},`${t.payment.publishableKey}:${N??`platform`}:${P}`):A(h,{fieldCount:3,label:`Loading payment form`})}function at({label:e}){return j(`div`,{className:`lockerverse-payment__stripe-loader`,role:`status`,children:[A(`p`,{children:e}),j(`div`,{"aria-hidden":`true`,children:[A(`span`,{}),A(`span`,{}),A(`span`,{})]})]})}function ot({onError:e,onReady:t,ready:n}){return j(`div`,{className:`lockerverse-payment__stripe-element`,"data-ready":n,children:[n?null:A(at,{label:`Loading payment form...`}),A(`div`,{className:`lockerverse-payment__stripe-mount`,children:A(ae,{onLoadError:({error:t})=>e(t.message??`Payment form failed to load.`),onReady:t,options:{business:{name:`Lockerverse`},fields:{billingDetails:{address:`never`,email:`never`,name:`never`,phone:`never`}},layout:`tabs`,terms:{applePay:`auto`,card:`always`,googlePay:`auto`,usBankAccount:`auto`},wallets:{applePay:`auto`,googlePay:`auto`}}})})]})}function st({label:e,mode:t,onChange:n,onError:r,onReady:i,ready:a}){return j(`div`,{className:`lockerverse-payment__address`,children:[A(`h2`,{children:e}),j(`div`,{className:`lockerverse-payment__stripe-element lockerverse-payment__stripe-element--address`,"data-ready":a,children:[a?null:A(at,{label:`Loading ${e.toLowerCase()}...`}),A(`div`,{className:`lockerverse-payment__stripe-mount`,children:A(ie,{onChange:n,onLoadError:({error:t})=>r(t.message??`${e} failed to load.`),onReady:i,options:{autocomplete:{mode:`automatic`},mode:t}})})]})]})}function ct({message:e}){return e?A(`p`,{className:`lockerverse-payment__field-message`,role:`alert`,children:e}):null}function lt({catalog:e,displayedTotalCents:t,fieldValues:n,isBillingAddressReady:r,isPaymentReady:i,isShippingAddressReady:a,onAddressChange:o,onFieldValuesChange:s,onStripeLoadError:c,setIsBillingAddressReady:l,setIsPaymentReady:u,setIsShippingAddressReady:d}){let f=t>0;return j(k,{children:[f?A(ot,{onError:c,onReady:()=>u(!0),ready:i}):null,f||e.widget.fields.shipping?A(st,{label:f?`Billing address`:`Shipping address`,mode:`billing`,onChange:e=>o(`billing`,e),onError:c,onReady:()=>l(!0),ready:r}):null,e.widget.fields.shipping?j(`div`,{className:`lockerverse-payment__shipping`,children:[A(pe,{checked:n.shippingMatchesBilling,name:`shippingMatchesBilling`,onChange:e=>{s({...n,shippingMatchesBilling:e}),e?o(`shipping`,null):d(!1)},children:`Shipping is same as billing information`}),n.shippingMatchesBilling?null:A(st,{label:`Shipping address`,mode:`shipping`,onChange:e=>o(`shipping`,e),onError:c,onReady:()=>d(!0),ready:a})]}):null]})}function ut({catalog:t,displayedTotalCents:n,fieldValues:r,isBillingAddressReady:i,isPaymentReady:a,isRequiredShippingReady:o,isSubmitting:s,onFieldValuesChange:c,quote:l}){let u=n===0,d=u?!t.widget.fields.shipping||i&&o:a&&i&&o,f=nt(l.paymentOption),p=u?`Complete order`:`Pay ${e(n)}`;!u&&f&&(p=`Subscribe for ${e(n)}/${f.interval}`),s&&(p=u?`Completing…`:`Processing…`);let m=`Process payment for ${e(n)} total`;return u?m=`Complete order`:f&&(m=`Start ${f.label.toLowerCase()} subscription for ${e(n)}`),j(`div`,{className:`lockerverse-payment__actions`,children:[A(J,{amountCents:l.serviceFeeCents||Math.round(l.subtotalCents*t.pricingPolicy.serviceFeeRateBasisPoints/1e4),enabled:t.widget.fields.serviceFee,onChange:c,values:r}),A(`button`,{"aria-busy":s,"aria-label":m,disabled:s||!d,type:`submit`,children:p})]})}function dt(e,t){let n=e.elements.namedItem(t);if(n instanceof HTMLElement){n.focus();return}n instanceof RadioNodeList&&Array.from(n).find(e=>e instanceof HTMLElement)?.focus()}function ft({customFieldErrors:e,emailRef:t,form:n,parsedTipSuccess:r,phoneRef:i,validationErrors:a}){if(a.email){t.current?.focus();return}if(a.phone){i.current?.focus();return}if(!r){n.querySelector(`[name="tip"]`)?.focus();return}let[o]=Object.keys(e);o&&dt(n,`custom:${o}`)}function pt(t){let n=t.appliedDiscount;if(n?.source!==`email_list`)return;let r=n.percentageOff===void 0?e(t.discountCents):`${n.percentageOff}%`;return n.message??`Your email qualifies for ${r} off.`}function mt({email:e,emailDiscountMessage:n,emailErrorId:r,emailId:o,emailRef:s,errors:c,onEmailBlur:l,onEmailChange:u,onPhoneChange:d,phone:f,phoneCountry:p,phoneEnabled:m,phoneErrorId:h,phoneId:g,phoneRef:_}){return j(`div`,{className:`lockerverse-payment__contact`,children:[A(t,{error:c.email,errorId:r,id:o,label:`Email`,name:`email`,onBlur:l,onChange:e=>u(e.currentTarget.value),ref:s,required:!0,value:e}),n===void 0?null:A(`p`,{className:`lockerverse-payment__discount-message`,role:`status`,children:n}),m?A(i,{error:c.phone,errorId:h,id:g,label:`Phone`,children:A(a,{country:p,error:c.phone,errorId:h,id:g,inputRef:_,name:`phone`,onChange:d,required:!0,value:f})}):null]})}function ht({message:e}){return e?j(`div`,{className:`lockerverse-payment__actions`,children:[A(`p`,{className:`lockerverse-payment__field-message`,role:`alert`,children:e}),A(`button`,{className:`lockerverse-payment__status-check`,onClick:()=>window.location.reload(),type:`button`,children:`Reload checkout`})]}):null}function gt({paymentRequired:e,shippingRequired:t,isPaymentReady:n,isBillingAddressReady:r,isRequiredShippingReady:i,isSubmitting:a,scriptFailed:o,elementError:s,clearElementError:c}){let[l,u]=O(!1),d=e||t,f=(!e||n)&&(!d||r)&&i;if(S(()=>{if(u(!1),f&&c(void 0),!d||f||a)return;let e=window.setTimeout(()=>u(!0),3e4);return()=>window.clearTimeout(e)},[d,f,a,c]),!(!d||f||a)){if(o||s)return`The secure checkout fields could not load. Check your connection, then reload the checkout.`;if(l)return`The secure checkout fields are taking longer than expected. You can wait or reload the checkout.`}}function _t({catalog:e,checkoutItems:t,client:n,initialCustomFieldValues:i,paymentSummaryPosition:a,metadata:o,onPaymentComplete:s,onResumePaymentFailed:c,onPaymentRecoveryChange:l,onPaymentUncertain:f,onQuoteChange:p,onStateChange:h,quote:v,resumePayment:y,stripeConnectedAccountId:b,stripeLoadFailed:x,paymentState:w,updateState:T}){let E=u(e,t),[M,N]=O(``),[P,F]=O(``),[I,L]=O(`US`),[R,z]=O({}),[ee,B]=O({}),[te,V]=O(),[ne,re]=O(),[H,U]=O(!1),[W,ie]=O(!1),[G,ae]=O(!1),[K,ce]=O(()=>({customFields:d(E,i),customTip:``,includeServiceFee:e.widget.fields.serviceFee,memberId:``,merchSize:`M`,promoCode:``,shippingMatchesBilling:!0,tipPercent:`10`})),le=D({billing:null,shipping:null}),ue=D(null),de=D(null),q=D(null),pe=D(v.totalCents>0),J=$e({catalog:e,checkoutItems:t,client:n,elements:oe(),email:M,fieldValues:K,metadata:o,onPaymentComplete:s,onPaymentRecoveryChange:l,onPaymentUncertain:f,onQuoteChange:p,onResumePaymentFailed:c,onStateChange:h,paymentState:w,quote:v,resumePayment:y,stripe:se(),stripeConnectedAccountId:b,stripeLoadFailed:x,updateState:T}),{displayedTotalCents:Y,isRecovering:X,isUnresolved:he,isRefreshingQuote:ge,isSubmitting:Z,parsedTip:Q,paymentError:_e,promoError:ve,terminalMessage:ye,retryUrl:be}=J.state,xe=`lockerverse-${C()}`,Se=`${xe}-email`,Ce=`${Se}-error`,we=`${xe}-phone`,Te=`${we}-error`,Ee=`${xe}-tip-error`,De=(Q.success?Q.cents:null)??0,Oe=Y-De,ke=!e.widget.fields.shipping||K.shippingMatchesBilling||G,Ae=gt({clearElementError:re,elementError:ne,isBillingAddressReady:W,isPaymentReady:H,isRequiredShippingReady:ke,isSubmitting:Z,paymentRequired:Y>0,scriptFailed:x,shippingRequired:e.widget.fields.shipping});S(()=>{Z&&q.current?.focus({preventScroll:!0})},[Z]),S(()=>{Z||R.email||!R.phone||de.current?.focus()},[R.email,R.phone,Z]),S(()=>{let e=Y>0;e&&!pe.current&&(U(!1),ie(!1)),pe.current=e},[Y]);function je(e){J.commands.fieldChanged(!1,e!==`email`),z(t=>{let n={...t};return delete n[e],n})}function Me(e){let t=e.promoCode!==K.promoCode,n=e.includeServiceFee!==K.includeServiceFee;J.commands.fieldChanged(t,!(t||n)),ce(e),B({}),V(void 0)}async function Ne(t){t.preventDefault();let n=e.widget.fields.phone?r(P,I):``,i=_({email:M,phone:n},e.widget.fields.phone),a=m(E,K.customFields);if(!(i.value&&Q.success)||Object.keys(a).length>0){z(i.errors),B(a),V(Q.success?void 0:Q.message),J.commands.reportValidationFailure();let e=t.currentTarget;queueMicrotask(()=>{ft({customFieldErrors:a,emailRef:ue,form:e,parsedTipSuccess:Q.success,phoneRef:de,validationErrors:i.errors})});return}z({}),B({});let o=await J.commands.submit({addresses:le.current,phone:n});o?.phoneError&&z({phone:o.phoneError})}if(ye||X)return j(`div`,{className:`lockerverse-payment__actions`,children:[j(`p`,{className:`lockerverse-payment__payment-status`,ref:q,role:`status`,tabIndex:-1,children:[X?`Recovering payment…`:ye,be?j(k,{children:[` `,A(`a`,{href:be,rel:`noopener noreferrer`,target:`_blank`,children:`Complete payment`})]}):null]}),he||X?A(`button`,{"aria-busy":X,className:`lockerverse-payment__status-check`,disabled:X,onClick:J.commands.checkPaymentStatus,type:`button`,children:X?`Checking payment status…`:`Check payment status`}):null]});let Pe=A(g,{displayedBaseCents:Oe,displayedTipCents:De,displayedTotalCents:Y,quote:v}),Fe=A(fe,{enabled:e.widget.fields.tipping,error:te,errorId:Ee,onChange:Me,values:K}),Ie={bottom:{afterFields:j(k,{children:[Fe,Pe]}),beforeFields:null},hidden:{afterFields:Fe,beforeFields:null},top:{afterFields:null,beforeFields:j(k,{children:[Pe,Fe]})}}[a??`top`];return j(`form`,{"aria-busy":Z,className:`lockerverse-payment__form`,noValidate:!0,onSubmit:Ne,children:[A(`div`,{"data-lockerverse-input-region":``,inert:Z?!0:void 0,children:j(`fieldset`,{className:`lockerverse-payment__input-fieldset`,disabled:Z,children:[Ie.beforeFields,A(mt,{email:M,emailDiscountMessage:pt(v),emailErrorId:Ce,emailId:Se,emailRef:ue,errors:R,onEmailBlur:()=>J.commands.refreshAuthoritativeTotal(),onEmailChange:e=>{N(e),je(`email`)},onPhoneChange:({value:e,country:t})=>{F(e),L(t),je(`phone`)},phone:P,phoneCountry:I,phoneEnabled:e.widget.fields.phone,phoneErrorId:Te,phoneId:we,phoneRef:de}),A(ht,{message:Ae}),A(lt,{catalog:e,displayedTotalCents:Y,fieldValues:K,isBillingAddressReady:W,isPaymentReady:H,isShippingAddressReady:G,onAddressChange:(e,t)=>{le.current[e]=t},onFieldValuesChange:Me,onStripeLoadError:re,setIsBillingAddressReady:ie,setIsPaymentReady:U,setIsShippingAddressReady:ae}),A(me,{customFields:E,errors:ee,fields:e.widget.fields,idPrefix:xe,isPromoApplying:ge,memberIdLabel:e.community?.memberIdLabel,onApplyPromo:J.commands.applyPromo,onChange:Me,promoError:ve,values:K}),Ie.afterFields,A(ut,{catalog:e,displayedTotalCents:Y,fieldValues:K,isBillingAddressReady:W,isPaymentReady:H,isRequiredShippingReady:ke,isSubmitting:Z,onFieldValuesChange:Me,quote:v})]})}),Z?A(`p`,{className:`lockerverse-payment__sr-only`,ref:q,role:`status`,tabIndex:-1,children:Y===0?`Completing order…`:`Processing payment…`}):null,A(ct,{message:_e})]})}function vt(){return A(h,{fieldCount:2,label:`Loading payment…`,sectionCount:2,showCheckbox:!0})}function yt(e,t){switch(t.type){case`loading`:return{phase:`loading`,revision:e.revision};case`ready`:return St(t.displayedQuote,e.revision+1);case`error`:return{failure:t.failure,phase:`error`,revision:e.revision};case`checkout`:return e.phase===`ready`?{...e,displayedQuote:t.checkout,quoteFailure:void 0}:e;case`quote-error`:return e.phase===`ready`?{...e,quoteFailure:t.failure}:e;default:return e}}function $(e,t,n){return e?.catalog===t&&e.selectionKey===n}function bt({checkout:e}){return{displayedQuote:e,type:`ready`}}function xt(e){return e instanceof Error?e.message:`Lockerverse payment could not load.`}function St(e,t){return{checkoutItems:[...e.items],displayedQuote:e,phase:`ready`,quoteFailure:void 0,revision:t}}function Ct(e,t){let n=e.widget.fields.serviceFee;return ce(e,{includeServiceFee:n,selection:t})}function wt(e,t){try{return St(Ct(e,t),1)}catch(e){return{failure:xt(e),phase:`error`,revision:0}}}function Tt({catalog:e,client:t,paymentState:n,selection:r}){let i=ke(r),a=i.success?JSON.stringify(i.value):`invalid-selection`,o=T(()=>i.success?i.value:[],[i.success,a]),[s,c]=E(yt,void 0,()=>i.success?wt(e,o):{phase:`loading`,revision:0}),l=D(void 0),u=D(0),d=D(s.phase===`ready`?{catalog:e,selectionKey:a}:void 0),f=D(s.phase===`error`?{catalog:e,selectionKey:a}:void 0),p=n===`submitting`||n===`success`||n===`unresolved`;S(()=>{if(!i.success||p||$(f.current,e,a)||$(l.current,e,a))return;let n=!0;l.current={catalog:e,selectionKey:a};let r=$(d.current,e,a);r||c({type:`loading`});function s(e){n&&c(e)}function m(){n&&(l.current=void 0,f.current={catalog:e,selectionKey:a})}let h;function g(t){if(!n||(l.current=void 0,f.current={catalog:e,selectionKey:a},r&&h!==void 0&&u.current!==h))return;let i=xt(t);if(i===`This option is sold out.`){c({failure:i,type:`error`});return}c(r?{failure:i,type:`quote-error`}:{failure:i,type:`error`})}async function _(){try{h=u.current;let n=e.widget.fields.serviceFee;if(!r){let t=Ct(e,o);r=!0,d.current={catalog:e,selectionKey:a},s(bt({checkout:t}))}let i=await t.calculateTotal({catalog:e,includeServiceFee:n,selection:o});m(),u.current===h&&s({checkout:i,type:`checkout`})}catch(e){g(e)}}return _(),()=>{n=!1,$(l.current,e,a)&&(l.current=void 0)}},[e,t,i.success,p,a,o]);let m=$(d.current,e,a)||$(f.current,e,a)||$(l.current,e,a),h=p||m?s:{phase:`loading`,revision:s.revision};return{selectionError:i.success?void 0:i.message,session:h,updateCheckout:e=>{u.current+=1,c({checkout:e,type:`checkout`})}}}const Et=z({recovery:z({connectedAccountId:L(H()),paymentReference:B(H(),U(),I())}),selectionFingerprint:H(),version:W([N(1),N(2)]),widgetId:ee(H())});function Dt(e){let t=ke(e);return t.success?JSON.stringify(t.value.map(e=>{let t=e.productSlug.trim();return`quantity`in e?[`quantity`,t,e.quantity]:`amountCents`in e?[`amount`,t,e.amountCents]:[`product`,t]})):null}const Ot=`A previous payment uses different checkout details. Return to its original checkout to check the payment before you pay again.`;function kt(e,t,n){let r;try{r=window.sessionStorage.getItem(e)}catch{return{recovery:null}}if(!r)return{recovery:null};try{let e=ne(Et,JSON.parse(r));if(!e.success)throw Error(`Invalid recovery record`);let i=e.output;return i.selectionFingerprint!==t||i.version===2&&i.widgetId!==n?{error:Ot,recovery:null}:{recovery:{connectedAccountId:i.recovery.connectedAccountId,paymentReference:i.recovery.paymentReference}}}catch{return{error:`The saved payment could not be read. Contact support to check it before you pay again.`,recovery:null}}}function At({selection:e,storageKey:t,widgetId:n}){let r=Dt(e),i=JSON.stringify([t,r,n]),[a,o]=O(null),s=D(null);S(()=>{if(!t)return;let e=s.current,a={recovery:null};e?.recovery?a=e.identity===i?{recovery:e.recovery}:{error:Ot,recovery:null}:r!==null&&(a=kt(t,r,n)),a.recovery&&(s.current={identity:i,recovery:a.recovery}),o({identity:i,...a})},[r,i,t,n]);let c=x(e=>{if(!(!t||r===null)){s.current=e?{identity:i,recovery:e}:null;try{e?window.sessionStorage.setItem(t,JSON.stringify({recovery:e,selectionFingerprint:r,version:2,widgetId:n})):window.sessionStorage.removeItem(t)}catch{}}},[r,i,t,n]);return{error:t&&a?.identity===i?a.error:void 0,ready:!t||a?.identity===i,recovery:t&&a?.identity===i?a.recovery:null,remember:c}}const jt={annually:`/year`,"every-six-months":` every 6 months`,monthly:`/month`,"one-time":``};function Mt({branding:e,catalog:t}){return j(`header`,{children:[t.widget.showCommunityBranding&&e?j(`div`,{className:`lockerverse-payment__branding`,children:[e.imageUrl?A(`img`,{alt:e.name,height:`48`,src:e.imageUrl,width:`48`}):null,A(`strong`,{children:e.name})]}):null,A(`h1`,{children:t.widget.title??t.widget.name}),t.widget.description?A(`p`,{children:t.widget.description}):null]})}function Nt({catalog:t,selection:n}){let r=n?.length?t.products.filter(e=>n.some(t=>t.productSlug===e.slug)):t.products.filter(e=>e.id!==t.widget.requiredShipping?.productId);return r.length===0?null:j(`div`,{className:`lockerverse-payment__payment-summary`,children:[A(`h2`,{children:`Products`}),A(`div`,{className:`lockerverse-payment__payment-summary-items`,children:r.map(t=>{let n=t.pricingMode===`fixed`?t.amountCents:t.minimumAmountCents,r=jt[t.paymentOption];return j(`div`,{className:`lockerverse-payment__payment-summary-row`,children:[A(`span`,{children:t.name}),A(`strong`,{children:n===null?`Choose amount`:`${t.pricingMode===`custom`?`From `:``}${e(n)}${r}`})]},t.id)})}),A(`p`,{children:`Base prices. Final total is checked at checkout.`})]})}function Pt(e,t){let n=c(e?.[`--lockerverse-accent`]??t?.accentColor??`#38d77a`),r=l(n),i={...e};return(e?.[`--lockerverse-accent`]!==void 0||t?.accentColor)&&(i[`--lockerverse-accent`]=n),r&&e?.[`--lockerverse-accent-contrast`]===void 0&&(i[`--lockerverse-accent-contrast`]=r),{accent:n,rootStyle:i}}function Ft({catalog:e,client:t,loadError:n,onRetry:r,...i}){let{branding:a,className:o,completionView:c,paymentSummaryPosition:l=`top`,recoveryStorageKey:u,initialCustomFieldValues:d,metadata:f,onPaymentComplete:p,onPaymentRecoveryChange:m,onPaymentUncertain:h,resumePayment:g,selection:_,style:v,stripeLoader:y=et,theme:b=`dark`,...C}=i,[T,E]=O(g),k=D(null),[M,N]=O(null),P=x(e=>{N(e),s(p,e)},[p]),[F,I]=O(),[L,R]=O(`idle`),z=D(void 0),{selectionError:ee,session:B,updateCheckout:te}=Tt({catalog:e,client:t,paymentState:L,selection:_}),V=B.phase===`ready`?B.revision:void 0,ne=x(e=>{V!==void 0&&(z.current=V),R(e)},[V]),re=x(e=>m?.(e),[m]),H=x(()=>{E(void 0)},[]);S(()=>{B.phase===`loading`&&I(void 0)},[B.phase]),w(()=>{B.phase===`ready`&&z.current!==B.revision&&R(e=>e===`success`||e===`unresolved`?e:`idle`)},[B.phase,B.revision]);let U=[`lockerverse-payment`,o].filter(Boolean).join(` `),W=a??e.community,{accent:ie,rootStyle:G}=Pt(v,W);return M&&c===`summary`?A(`section`,{...C,className:U,"data-lockerverse-theme":b,"data-payment-state":`success`,style:G,children:j(`div`,{className:`lockerverse-payment__completion`,role:`status`,children:[A(`span`,{"aria-hidden":`true`,className:`lockerverse-payment__completion-icon`,children:A(`svg`,{"aria-hidden":`true`,fill:`none`,height:`28`,stroke:`currentColor`,strokeWidth:`2`,viewBox:`0 0 24 24`,width:`28`,children:A(`path`,{d:`m5 12 4 4L19 6`})})}),A(`h1`,{children:M.paymentRequired?`Thank you`:`Order confirmed`}),A(`p`,{children:M.paymentRequired?`Your payment has been received.`:`Your order is confirmed. No payment was required.`})]})}):ee?A(`section`,{...C,className:U,"data-lockerverse-theme":b,role:`alert`,style:G,children:ee}):B.phase===`error`&&B.failure===`This option is sold out.`||L===`sold_out`?j(`section`,{...C,className:U,"data-lockerverse-theme":b,role:`alert`,style:G,children:[A(`h1`,{children:`Sold out`}),A(`p`,{children:`This option is sold out.`})]}):B.phase===`error`?A(`section`,{...C,className:U,"data-lockerverse-theme":b,style:G,children:A(`p`,{role:`alert`,children:B.failure})}):B.phase===`ready`?j(`section`,{...C,"aria-label":`Payment`,className:U,"data-lockerverse-theme":b,"data-payment-state":L,ref:k,style:G,children:[A(Mt,{branding:W,catalog:e}),n?j(`div`,{role:`alert`,children:[A(`p`,{children:n.message}),A(`button`,{onClick:r,type:`button`,children:`Retry`})]}):null,F?A(`p`,{className:`lockerverse-payment__payment-status`,role:`status`,children:F}):null,B.quoteFailure?j(`div`,{className:`lockerverse-payment__payment-status`,role:`alert`,children:[A(`span`,{children:B.quoteFailure}),A(`span`,{children:` The final total will be checked when you submit.`})]}):null,A(it,{accentColor:ie,appearanceRoot:k,catalog:e,checkoutItems:B.checkoutItems,client:t,initialCustomFieldValues:d,metadata:f,onPaymentComplete:P,onPaymentRecoveryChange:re,onPaymentUncertain:h,onQuoteChange:(e,t)=>{I(t),te(e)},onResumePaymentFailed:H,onStateChange:ne,paymentSummaryPosition:l,quote:B.displayedQuote,resumePayment:T,stripeLoader:y,theme:b,visualStyle:G},B.revision)]}):j(`section`,{...C,"aria-busy":`true`,"aria-label":`Payment`,className:U,"data-lockerverse-theme":b,style:G,children:[A(Mt,{branding:W,catalog:e}),n?j(`div`,{role:`alert`,children:[A(`p`,{children:n.message}),A(`button`,{onClick:r,type:`button`,children:`Retry`})]}):null,A(vt,{})]})}function It({children:e,loading:t=!1,viewProps:n}){let{branding:r,className:i,completionView:a,paymentSummaryPosition:o,recoveryStorageKey:s,initialCustomFieldValues:u,metadata:d,onPaymentComplete:f,onPaymentRecoveryChange:p,onPaymentUncertain:m,resumePayment:h,selection:g,stripeLoader:_,style:v,theme:y=`dark`,...b}=n,x=c(v?.[`--lockerverse-accent`]??r?.accentColor??`#38d77a`),S=l(x),C={...v};return(v?.[`--lockerverse-accent`]!==void 0||r?.accentColor)&&(C[`--lockerverse-accent`]=x),S&&v?.[`--lockerverse-accent-contrast`]===void 0&&(C[`--lockerverse-accent-contrast`]=S),A(`section`,{...b,...t?{"aria-busy":!0,"aria-label":`Payment`}:{},className:[`lockerverse-payment`,i].filter(Boolean).join(` `),"data-lockerverse-theme":y,style:C,children:e})}function Lt(e){let{catalog:t,client:n,loadError:r,onRetry:i,...a}=e,{onPaymentRecoveryChange:o,recoveryStorageKey:c,resumePayment:l,selection:u}=a,d=At({selection:u,storageKey:c,widgetId:t.widget.id}),f=x(e=>{d.remember(e),s(o,e)},[o,d.remember]);return!d.ready||d.error?A(It,{loading:!d.ready,viewProps:a,children:d.error?A(`p`,{role:`alert`,children:d.error}):A(vt,{})}):A(Ft,{...e,onPaymentRecoveryChange:f,resumePayment:l??d.recovery})}function Rt({widget:e,...t}){return e.error&&!e.catalog?j(It,{viewProps:t,children:[A(`p`,{role:`alert`,children:e.error.message}),A(`button`,{onClick:e.refresh,type:`button`,children:`Retry`})]}):e.loading?j(It,{loading:!0,viewProps:t,children:[e.catalog?j(k,{children:[A(Mt,{branding:t.branding??e.catalog.community,catalog:e.catalog}),(t.paymentSummaryPosition??`top`)===`top`?A(Nt,{catalog:e.catalog,selection:t.selection}):null]}):null,A(vt,{})]}):e.catalog?A(Lt,{catalog:e.catalog,client:e.client,loadError:e.error,onRetry:e.refresh,...t}):A(It,{loading:!0,viewProps:t,children:A(vt,{})})}export{tt as n,Rt as t};
2
2
  //# sourceMappingURL=lockerverse-payment.js.map