import{r as t,h as i,g as n,c as r,H as e}from"./p-b891c2f1.js";import{_ as s}from"./p-684c85b4.js";import"./p-aafd8ea4.js";import{a as o,g as a}from"./p-6fd3642a.js";import{p as d}from"./p-8fc67a82.js";import{e as l,f as h,c as u}from"./p-9a3745a6.js";import{a as c,g as v,s as f}from"./p-60f049de.js";import{g as p,b as m,a as y}from"./p-1c2e2695.js";import"./p-112455b1.js";function g(t){const i=t.indexOf("?");if(-1===i)return t;const n=p(t),r=t.substr(0,i);for(var e=arguments.length,s=new Array(e>1?e-1:0),o=1;o<e;o++)s[o-1]=arguments[o];s.forEach((t=>delete n[t]));const a=m(n);return a?r+"?"+a:r}const w=class{constructor(i){t(this,i)}handleOrderChange(){var t,i;this.disabled||("address_invalid"===(null===(t=null==this?void 0:this.order)||void 0===t?void 0:t.tax_status)||(null===(i=null==this?void 0:this.order)||void 0===i?void 0:i.shipping_enabled))&&this.addAddressField()}componentWillLoad(){var t,i;this.hasAddress=!!this.el.querySelector("sc-order-shipping-address"),this.hasTaxIDField=!!this.el.querySelector("sc-order-tax-id-input"),(null===(t=this.taxProtocol)||void 0===t?void 0:t.tax_enabled)&&(this.addAddressField(),(null===(i=this.taxProtocol)||void 0===i?void 0:i.eu_vat_required)&&this.addTaxIDField()),this.handleOrderChange()}addAddressField(){if(this.hasAddress)return;const t=this.el.querySelector("sc-payment"),i=document.createElement("sc-order-shipping-address");i.label=s("Address","surecart"),t.parentNode.insertBefore(i,t),this.hasAddress=!0}addTaxIDField(){if(this.hasTaxIDField)return;const t=this.el.querySelector("sc-payment"),i=document.createElement("sc-order-tax-id-input");t.parentNode.insertBefore(i,t),this.hasTaxIDField=!0}render(){return i("slot",null)}get el(){return n(this)}static get watchers(){return{order:["handleOrderChange"]}}},E=class{constructor(i){t(this,i),this.scUpdateError=r(this,"scUpdateError",7),this.scSetState=r(this,"scSetState",7)}handleErrorUpdate(t){this.scUpdateError.emit(t)}handleOrderChange(){this.error=null}handleErrorEvent(t){this.error=t.detail,Object.keys((null==t?void 0:t.detail)||{}).length&&this.scSetState.emit("REJECT")}handlePayError(t){var i;this.error=(null===(i=t.detail)||void 0===i?void 0:i.message)||{code:"",message:"Something went wrong with your payment."}}getErrorMessage(t){return"order.line_items.price.blank"===t.code?s("This product is no longer purchasable.","surecart"):null==t?void 0:t.message}errorMessage(){var t,i,n,r,e,s;return(null===(n=null===(i=null===(t=this.error)||void 0===t?void 0:t.additional_errors)||void 0===i?void 0:i[0])||void 0===n?void 0:n.message)?this.getErrorMessage(null===(e=null===(r=this.error)||void 0===r?void 0:r.additional_errors)||void 0===e?void 0:e[0]):(null===(s=null==this?void 0:this.error)||void 0===s?void 0:s.message)?this.getErrorMessage(null==this?void 0:this.error):""}render(){return i(e,null,!!this.errorMessage()&&i("sc-alert",{type:"danger",scrollOnOpen:!0,open:!!this.errorMessage()},i("span",{slot:"title"},this.errorMessage())),i("slot",null))}static get watchers(){return{error:["handleErrorUpdate"],order:["handleOrderChange"]}}};
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function _(t,i){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,e,s=n.call(t),o=[];try{for(;(void 0===i||i-- >0)&&!(r=s.next()).done;)o.push(r.value)}catch(t){e={error:t}}finally{try{r&&!r.done&&(n=s.return)&&n.call(s)}finally{if(e)throw e.error}}return o}var S;!function(t){t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped"}(S||(S={}));var C={type:"xstate.init"};function P(t){return void 0===t?[]:[].concat(t)}function b(t,i){return"string"==typeof(t="string"==typeof t&&i&&i[t]?i[t]:t)?{type:t}:"function"==typeof t?{type:t.name,exec:t}:t}function R(t){return function(i){return t===i}}function x(t){return"string"==typeof t?{type:t}:t}function O(t,i){return{value:t,context:i,actions:[],changed:!1,matches:R(t)}}function I(t,i,n){var r=i,e=!1;return[t.filter((function(t){if("xstate.assign"===t.type){e=!0;var i=Object.assign({},r);return"function"==typeof t.assignment?i=t.assignment(r,n):Object.keys(t.assignment).forEach((function(e){i[e]="function"==typeof t.assignment[e]?t.assignment[e](r,n):t.assignment[e]})),r=i,!1}return!0})),r,e]}var T=function(t,i){return t.actions.forEach((function(n){var r=n.exec;return r&&r(t.context,i)}))};const j=function(t,i){void 0===i&&(i={});var n=_(I(P(t.states[t.initial].entry).map((function(t){return b(t,i.actions)})),t.context,C),2),r={config:t,_options:i,initialState:{value:t.initial,actions:n[0],context:n[1],matches:R(t.initial)},transition:function(i,n){var e,s,o="string"==typeof i?{value:i,context:t.context}:i,a=o.value,d=o.context,l=x(n),h=t.states[a];if(h.on){var u=P(h.on[l.type]);try{for(var c=function(t){var i="function"==typeof Symbol&&Symbol.iterator,n=i&&t[i],r=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(i?"Object is not iterable.":"Symbol.iterator is not defined.")}(u),v=c.next();!v.done;v=c.next()){var f=v.value;if(void 0===f)return O(a,d);var p="string"==typeof f?{target:f}:f,m=p.target,y=p.actions,g=void 0===y?[]:y,w=p.cond,E=void 0===m,S=t.states[null!=m?m:a];if((void 0===w?function(){return!0}:w)(d,l)){var C=_(I((E?P(g):[].concat(h.exit,g,S.entry).filter((function(t){return t}))).map((function(t){return b(t,r._options.actions)})),d,l),3),T=C[0],j=null!=m?m:a;return{value:j,context:C[1],actions:T,changed:m!==a||T.length>0||C[2],matches:R(j)}}}}catch(t){e={error:t}}finally{try{v&&!v.done&&(s=c.return)&&s.call(c)}finally{if(e)throw e.error}}}return O(a,d)}};return r}({id:"fetch",initial:"idle",context:{retries:3},states:{idle:{on:{FETCH:"loading"}},loading:{on:{RESOLVE:"draft",REJECT:"failure",EXPIRE:"expired",PAID:"paid"}},draft:{on:{FINALIZE:"finalizing",FETCH:"updating",REJECT:"draft"}},updating:{on:{RESOLVE:"draft",EXPIRE:"expired",REJECT:"draft"}},finalizing:{on:{PAID:"paid",REJECT:"draft"}},paid:{on:{CONFIRMED:"confirmed",REJECT:"draft"}},expired:{},confirmed:{},failure:{on:{RETRY:{target:"loading",actions:{type:"xstate.assign",assignment:{retries:t=>t.retries+1}}}}}}}),F=class{constructor(i){t(this,i),this.scSetCheckoutFormState=r(this,"scSetCheckoutFormState",7),this._stateService=function(t){var i=t.initialState,n=S.NotStarted,r=new Set,e={_machine:t,send:function(e){n===S.Running&&(i=t.transition(i,e),T(i,x(e)),r.forEach((function(t){return t(i)})))},subscribe:function(t){return r.add(t),t(i),{unsubscribe:function(){return r.delete(t)}}},start:function(r){if(r){var s="object"==typeof r?r:{context:t.config.context,value:r};i={value:s.value,actions:[],context:s.context,matches:R(s.value)}}return n=S.Running,T(i,C),e},stop:function(){return n=S.Stopped,r.clear(),e},get state(){return i},get status(){return n}};return e}(j),this.checkoutState=j.initialState}setState(t){const{send:i}=this._stateService;return i(t)}handleCheckoutStateChange(t){this.scSetCheckoutFormState.emit(t.value)}componentWillLoad(){this._stateService.subscribe((t=>this.checkoutState=t)),this._stateService.start()}disconnectedCallback(){this._stateService.stop()}handleSetStateEvent(t){this.setState(t.detail)}async handlePaid(){this.setState("PAID")}async handleConfirmed(){this.setState("CONFIRMED")}render(){return"expired"===this.checkoutState.value?i("sc-block-ui",null,i("div",null,s("Please refresh the page.","surecart"))):i("slot",null)}static get watchers(){return{checkoutState:["handleCheckoutStateChange"]}}},A=class{constructor(i){t(this,i),this.scConfirmed=r(this,"scConfirmed",7),this.scOrderPaid=r(this,"scOrderPaid",7),this.scError=r(this,"scError",7),this.mode="live"}handlePaidEvent(){this.confirmOrder()}async confirmOrder(){var t,i;const n=await this.el.querySelector("sc-form").getFormJson();let r=d(n);try{const n=await o({method:"PATCH",path:y(`surecart/v1/checkouts/${null===(t=this.order)||void 0===t?void 0:t.id}/confirm`,[l]),data:r});this.scConfirmed.emit(),this.scOrderPaid.emit(n)}catch(t){console.error(t),this.scError.emit(t)}finally{const t=null===(i=this.order)||void 0===i?void 0:i.id;c(this.formId,this.mode),window.location.assign(y(this.successUrl,{order:t}))}}render(){return i("slot",null)}get el(){return n(this)}},D=(t,i,n)=>{if(null==i?void 0:i.id)return i.id;const r=a(window.location.href,"order");if(r)return r;const e=localStorage.getItem(`${t}-modified`);return e?n&&e===n?window.localStorage.getItem(t):"":window.localStorage.getItem(t)},J=class{constructor(i){t(this,i),this.scUpdateOrderState=r(this,"scUpdateOrderState",7),this.scUpdateDraftState=r(this,"scUpdateDraftState",7),this.scPaid=r(this,"scPaid",7),this.scError=r(this,"scError",7),this.scSetState=r(this,"scSetState",7),this.mode="live",this.prices=[],this.currencyCode="usd",this.processor="stripe"}handleUpdateSession(t){const{data:i,options:n}=t.detail;(null==n?void 0:n.silent)?this.update({...this.defaultFormData(),...i}):this.loadUpdate(i)}handlePricesChange(){let t=this.addInitialPrices()||[];if(t=this.addPriceChoices(t),null==t?void 0:t.length)return this.loadUpdate({line_items:t})}async finalize(){return await this.handleFormSubmit()}order(){return v(null==this?void 0:this.formId,this.mode)}getProcessor(){switch(this.processor){case"paypal":case"paypal-card":return"paypal";default:return"stripe"}}getPaymentIntent(){var t;const i=this.getProcessor();return null===(t=this.paymentIntents)||void 0===t?void 0:t[i]}async handleFormSubmit(){var t,i,n,r,e,s,o,a,l;this.scError.emit({});const u=this.getPaymentIntent();this.scSetState.emit("FINALIZE");const c=await this.el.querySelector("sc-form").getFormJson();let v=d(c);try{await this.update({...this.defaultFormData(),...v})}catch(t){console.error(t),this.scSetState.emit("REJECT"),this.handleErrorResponse(t)}if((null===(t=this.order())||void 0===t?void 0:t.total_amount)>0&&!u&&"stripe"===this.getProcessor()&&this.stripePaymentElement)return this.scError.emit({message:"Something went wrong. Please try again."}),console.error("No payment intent found."),this.scSetState.emit("REJECT");try{const t=await h({id:null===(i=this.order())||void 0===i?void 0:i.id,data:v,query:{...this.defaultFormQuery(),...(null==u?void 0:u.id)?{payment_intent_id:null==u?void 0:u.id}:{}},processor:this.getProcessor()});return(null===(n=this.order())||void 0===n?void 0:n.total_amount)>0&&(null==u?void 0:u.id)&&(null===(r=null==t?void 0:t.payment_intent)||void 0===r?void 0:r.id)!==(null==u?void 0:u.id)?(console.error("Payment intent mismatch",null==u?void 0:u.id,null===(e=null==t?void 0:t.payment_intent)||void 0===e?void 0:e.id),this.scError.emit({message:"Something went wrong. Please try again."}),this.scSetState.emit("REJECT")):("paid"===(null==t?void 0:t.status)&&this.scPaid.emit(),f(t,this.formId),this.order())}catch(t){if("order.line_items.old_price_versions"===(null===(o=null===(s=null==t?void 0:t.additional_errors)||void 0===s?void 0:s[0])||void 0===o?void 0:o.code))return void await this.loadUpdate({id:null===(a=this.order())||void 0===a?void 0:a.id,data:{status:"draft",refresh_price_versions:!0}});if(["order.invalid_status_transition"].includes(null==t?void 0:t.code))return await this.loadUpdate({id:null===(l=this.order())||void 0===l?void 0:l.id,data:{status:"draft"}}),void this.handleFormSubmit();this.handleErrorResponse(t)}}async handlePaid(){this.scSetState.emit("PAID")}async handlePayError(){this.scSetState.emit("REJECT")}async handleCouponApply(t){const i=t.detail;this.scError.emit({}),this.loadUpdate({discount:{...i?{promotion_code:i}:{}}})}handleErrorResponse(t){if("rest_cookie_invalid_nonce"!==(null==t?void 0:t.code)){if("readonly"===(null==t?void 0:t.code))return window.localStorage.removeItem(this.groupId),void window.location.assign(g(window.location.href,"order"));(null==t?void 0:t.message)&&this.scError.emit(t),"http_request_failed"===(null==t?void 0:t.code)&&this.scError.emit({message:"Something went wrong. Please reload the page and try again."}),this.scSetState.emit("REJECT")}else this.scSetState.emit("EXPIRE")}defaultFormData(){var t;return{return_url:window.top.location.href,currency:(null===(t=this.order())||void 0===t?void 0:t.currency)||this.currencyCode,live_mode:"test"!==this.mode,group_key:this.groupId}}defaultFormQuery(){return{form_id:this.formId}}componentDidLoad(){this.findOrCreateOrder()}findOrCreateOrder(){var t,i,n;const r=this.getInitialDataFromUrl();return(null===(t=null==r?void 0:r.discount)||void 0===t?void 0:t.promotion_code)&&window.history.replaceState({},document.title,g(window.location.href,"coupon")),(null===(i=null==r?void 0:r.line_items)||void 0===i?void 0:i.length)&&window.history.replaceState({},document.title,g(window.location.href,"line_items")),(null===(n=null==r?void 0:r.line_items)||void 0===n?void 0:n.length)?(c(this.formId,this.mode),this.fetch(r)):D(this.groupId,this.order,this.modified)&&this.persist?this.fetch(r):this.initialize(r)}getInitialDataFromUrl(){let t={};const i=(a(window.location.href,"coupon")||"").toUpperCase();t={...t,...i?{discount:{promotion_code:i}}:{}};const n=a(window.location.href,"line_items");return t={...t,...n&&(null==n?void 0:n.length)?{line_items:n}:{}},t}async initialize(t={}){let i=this.addInitialPrices()||[];return i=this.addPriceChoices(i),this.loadUpdate((null==i?void 0:i.length)?{line_items:i,...t}:{...t})}addInitialPrices(){var t;return(null===(t=null==this?void 0:this.prices)||void 0===t?void 0:t.length)?this.prices.some((t=>!(null==t?void 0:t.id)))?void 0:this.prices.map((t=>({price_id:t.id,quantity:t.quantity}))):[]}addPriceChoices(t=[]){return this.el.querySelectorAll("[price-id]").forEach((i=>{i.checked&&t.push({quantity:i.quantity||1,price_id:i.priceId,...i.defaultAmount?{ad_hoc_amount:i.defaultAmount}:{}}),i.defaultAmount&&t.push({quantity:i.quantity||1,price_id:i.priceId,ad_hoc_amount:i.defaultAmount})})),t}getSessionId(){var t,i;if(null===(t=this.order())||void 0===t?void 0:t.id)return null===(i=this.order())||void 0===i?void 0:i.id;const n=D(this.groupId,this.order,this.modified);return this.persist?n:void 0}async fetch(t={}){this.loadUpdate({status:"draft",...t})}async update(t={},i={}){try{const n=await u({id:this.getSessionId(),data:{...this.defaultFormData(),...t},query:{...this.defaultFormQuery(),...i}});f(n,this.formId)}catch(t){if(["order.not_found"].includes(null==t?void 0:t.code))return c(this.formId,this.mode),this.initialize();throw console.error(t),t}}async loadUpdate(t={}){try{this.scSetState.emit("FETCH"),await this.update({...this.defaultFormData(),...t}),this.scSetState.emit("RESOLVE")}catch(t){this.handleErrorResponse(t)}}render(){return i("sc-line-items-provider",{order:this.order(),onScUpdateLineItems:t=>this.loadUpdate({line_items:t.detail})},i("slot",null))}get el(){return n(this)}static get watchers(){return{prices:["handlePricesChange"]}}};export{w as sc_form_components_validator,E as sc_form_error_provider,F as sc_form_state_provider,A as sc_order_confirm_provider,J as sc_session_provider}