1import{U as e,V as t,T as a,q as o,f as n,y as r,h as i}from"./2c1ab0fe.D_oO1jU7.js";import{A as s,dl as l,gB as p,gA as d,gI as c,aE as u,aB as y,dh as h,a_ as m,O as v,P as _,Q as A,a7 as g,a6 as P,gD as E,hp as f,hq as b,hr as S,hc as C,bi as T,cR as N,hs as w,df as I,dg as R,ht as M,gE as D,C as L,aZ as O,hu as B,hv as Y,hw as x,hx as U,gd as k,hy as F,a8 as V,aH as H,u as q,hz as z,hA as G,hB as j,hC as Q,hD as Z}from"./4c290a1e.D9lE9kmU.js";import{d as $,b as W,c as J,e as K,f as X,u as ee,W as te,a as ae}from"./ed9f2238.C-XxbQrN.js";import{f as oe,I as ne,W as re,g as ie}from"./app.bDJ3v-8C.js";import{i as se}from"./65f3d4da.8ZfwXSRH.js";import{f as le,g as pe,s as de,r as ce,B as ue,P as ye,U as he,a as me,w as ve,x as _e,i as Ae,N as ge,E as Pe,h as Ee,y as fe,z as be,A as Se,C as Ce,F as Te,G as Ne,l as we,H as Ie,J as Re,K as Me,L as De,M as Le,j as Oe,T as Be,O as Ye,Q as xe,D as Ue,V as ke,I as Fe,R as Ve,u as He,m as qe,n as ze,o as Ge,W as je,p as Qe,q as Ze,t as $e,v as We}from"./13b13169.ClpNblxR.js";import{a as Je,g as Ke,i as Xe}from"./0a7dffce.BMM606kb.js";import{fO as et,gR as tt,gS as at,gT as ot,c7 as nt,gU as rt,c2 as it,h as st,e as lt,fR as pt,gk as dt,fP as ct,gJ as ut,gV as yt,gj as ht,di as mt,fA as vt,ci as _t,fS as At}from"./164ad2e3.DgUUtBtV.js";import{f as gt}from"./cb8fcd45.gqoNFKgG.js";import{u as Pt,a as Et}from"./bea9843a.Ccz9HjeB.js";import{d as ft}from"./b8733b27.CelQ77Wt.js";import{d as bt}from"./f78726c8.K7FaLIh2.js";import{u as St}from"./ec391382.Cpl2aZVN.js";import"./53bbdad9.Bipg1_Lt.js";import"./60a453ce.BIyixFcg.js";import"./bb728e1c.BObJOhlA.js";const Ct={id:"1501fe0af4559751b078e255872e602b9742658e6ef2d8b73091b38649adb321",type:"query",name:"ApplePayPaymentSession",source:""};class Tt{constructor(e){this.reason=e}}class Nt extends Error{constructor(){super(...arguments),this.name="ApplePaySessionCreationResponseError"}}const wt=async({graphql:a,sourceId:o,validationUrl:n,asPaymentMethod:r,signal:i,observability:l,isPrefetch:p,domain:d})=>{const c=(({sourceId:e,isPrefetch:t})=>t?`${e}-prefetch-${s()}`:`${e}-${s()}`)({sourceId:o,isPrefetch:p}),u=async e=>{const{data:t,error:o}=await a.staticQuery(Ct,{cache:!1,variables:e?{pendingTask:{taskId:e}}:{applePaySessionCreate:{resourceId:c,validationUrl:n,domain:d,walletInstrumentation:{expressWalletInCheckout:!r}}}});if(o)throw l.leaveErrorBreadcrumb("[ApplePay] session creation query returned GraphQL error",{error:o}),new Nt("session creation query returned GraphQL error");return t||(l.counter({name:"apple_pay_session_query_error",value:1,attributes:{reason:"no_data"}}),l.log("apple_pay_api_query","ApplePaySession: No data returned"),void l.leaveErrorBreadcrumb("[ApplePay] session creation query returned no data"))};function y({result:e,pollingCount:t}){l.histogram({name:"apple_pay_session_creation",value:performance.now()-v,attributes:{result:e,pollingCount:t,isPrefetch:p}})}let h="",m=0;const v=performance.now();try{for(;;){if(i.aborted)throw new oe("Apple pay signal aborted",{groupingHash:"AbortedSessionError::createPaymentSession::SignalAborted"});const a=performance.now(),n=await u(h);if(!n)return;const r=n.applePaySession;switch(r.__typename){case"ApplePaySessionCreationSuccess":return y({result:"success",pollingCount:m}),r;case"ApplePaySessionCreationFailed":if(y({result:"failed",pollingCount:m}),l.log("apple_pay_api_session_cancelled","Apply Pay session creation failed",{pollingCount:m,error:r?.code,resourceId:c}),"FAILURE_RESPONSE_FROM_WALLET_PROVIDER"===r.code)throw new re(`ApplePaySession Query error: fail to create apple pay session with ${r.code}`);if("NO_PENDING_TASK"===r.code)return l.counter({name:"apple_pay_no_pending_task_error",value:1,attributes:{pollingCount:m,sourceId:o,isPrefetch:p}}),l.log("apple_pay_api_session_cancelled","Apply Pay session has no pending task",{pollingCount:m,sourceId:o,isPrefetch:p}),void l.leaveErrorBreadcrumb("[ApplePay] session creation failed with NO_PENDING_TASK",{pollingCount:m,sourceId:o,isPrefetch:p});if(p)return;throw new ie(`ApplePaySession Query error: fail to create apple pay session with ${r.code}`,{groupingHash:"ApplePayAPIError::QueryError::FailToCreateSession"});case"PendingTask":if(!h){const e=600-(performance.now()-a);e>0&&await t(e)}if(h=r.taskId,m++,m>=9)throw l.log("apple_pay_api_session_cancelled","Apple Pay polling session reached maximum amount of polls",{pollingCount:m,flightDelay:performance.now()-a}),new ne("ApplePaySession Query error: reached maximum amount of polls");if(m<=5)break;await t(r.pollDelay);break;default:e(r)}}}catch(_){if(_ instanceof Nt||_ instanceof re)return l.counter({name:"apple_pay_session_query_error",value:1,attributes:{reason:_.name}}),new Tt(`${_.name}: ${_.message}`);throw _}},It={EG:"EG",AE:"AE"};
1function Rt({subtotal:e,duties:t,taxes:a,deliveryNext:o,discountLines:n,paymentLines:r,tipLines:i,shopPromotion:s,lineItemsLabels:l,deliveryOptionGroupTypeLabels:p,deliveryMethodTitlePrefixes:u,formattedRecurringTotals:y,formattedRecurringTotalTooltip:m,merchandiseLines:v}){const _=[];v?.lines&&v.lines.forEach((e=>{_.push({label:pe(e),amount:le(e.totalPrice.amount)})}));const A=void 0===e?[]:[{label:l.subtotal,amount:e?le(e.amount):void 0}],g=function({deliveryNext:e,deliveryOptionGroupTypeLabels:t,deliveryMethodTitlePrefixes:a}){const o=c(e);return o?o.map((({totalCost:e})=>({label:a.SHIPPING,amount:le(e.amount)}))):h(e).map((({line:e,method:o},n,r)=>({label:Mt(e,o,1===r.length,t,a),amount:le(o.cost.amount)})))}({deliveryNext:o,deliveryOptionGroupTypeLabels:p,deliveryMethodTitlePrefixes:u}),P=t&&"available_total"===t?.status&&0!==t?.totalDuty.amount?[{label:l.duties,amount:le(t.totalDuty.amount)}]:[],E=a&&"available_total"===a.status&&0!==a.totalTax.amount?[{label:l.taxes,amount:le(a.totalTax.amount)}]:[],f=n&&n.lines.map((e=>{if(se(e)){const t=e.amount?.amount;if(t)return{label:e.title,amount:d(le(t))}}})).filter((e=>void 0!==e))||[],b={SHOP_DISCOUNT_OFFER:l.shopDiscountOffer,SHOP_CASH_BALANCE:l.shopCashBalance,SHOP_PROMOTION:l.shopPromotion},S=new Map("filled"===s?.status?s.promotions.map((({promotionId:e,type:t})=>[e,t])):[]),C=r?.lines.filter((e=>"redeemable"===e.method.type&&"SHOP_CASH"===e.method.redemptionSource)).flatMap((e=>e.method.redemptionContent?.details??[])).flatMap((e=>{const t=e.promotionType??(null==e.redemptionId?void 0:S.get(e.redemptionId)),a="SHOP_PROMOTION"===e.redemptionType&&"DOORBUSTER"===t?l.flashDeal:b[e.redemptionType],o=Number(e.destinationAmount.amount);return a&&0!==o?[{label:a,amount:d(le(o))}]:[]}))??[],T=r?.lines.filter((e=>"giftCard"===e.method.type)).map((e=>e.cost?{label:l.giftCards,amount:d(le(e.cost.amount))}:void 0)).filter((e=>void 0!==e))||[],N=i&&i[0],w=N&&N.amount.amount>0?[{label:l.tip,amount:le(N.amount.amount)}]:[],I=y?y.map((e=>({label:e,amount:"0.00",type:"pending"}))):[],R=I.length>0&&m?[{label:m,amount:"0.00",type:"pending"}]:[];return[..._,...A,...g,...P,...E,...f,...C,...T,...w,...I,...R]}function Mt(e,t,a,o,n){const r=n[t.methodType];return a?r:`${r} (${o[e.type]})`}function Dt({deliveryMethodTitlePrefixes:e,connectTwoShippingTitles:t,deliveryNext:a}){const o=c(a);if(o)return o.map((({totalTitle:e,totalCostAfterDiscounts:t,deliveryMethodHandles:a,deliveryPromisePresentmentTitle:o})=>({label:e,amount:le(t.amount),detail:o?.short??"",identifier:JSON.stringify(a)})));const n=u(a).filter(y).map(Je),r=function(e,t){if(!e||"filled"!==e.status||!m(e))return t;const a=new Set(e.lines.reduce(((e,t)=>("available"===t.status&&t.selectedDeliveryMethodHandle&&e.add(t.selectedDeliveryMethodHandle),e)),new Set)),o=t.find((e=>e.every((e=>a.has(e.handle)))));return o?[o,...t.filter((e=>e!==o))]:t}(a,Ke(n).filter((e=>e.length>0)));return r.map((a=>({label:Bt(a,e,t),amount:Yt(a),detail:Ut(a,t),identifier:de(a)})))}const Lt=", ";function Ot(e,t){const a=e.values(),o=a.next();if(o.done)return"";const n=a.next();if(n.done)return o.value;let r=o.value,i=n.value;for(const s of a)r+=`${Lt}${i}`,i=s;return t(r,i)}function Bt(e,t,a){const o=e.find((e=>"ONE_TIME_PURCHASE"===e.deliveryLine.type));let n="";o&&(n="PICK_UP"===o.methodType?t[o.methodType]:o.title);const r=e.find((e=>"SUBSCRIPTION"===e.deliveryLine.type));let i="";if(r){if("PICK_UP"===r.methodType||"LOCAL"===r.methodType)return r.title;i=r.title,n=o?.title??""}return Ot([...new Set([n,i])].filter(Boolean),a)}function Yt(e){return le(e.reduce(((e,t)=>e+t.costAfterDiscounts.amount),0))}function xt(e,t){return e.add(t),e}function Ut(e,t){return Ot([...e.map((e=>{const{methodType:t,pickupLocation:a,deliveryPromisePresentmentTitle:o,description:n}=e;return"PICK_UP"===t||"PICKUP_POINT"===t?function(e){if(e){const{address1:t="",address2:a="",city:o="",company:n="",zoneCode:r="",countryCode:i=""}=e;return[n,[t,a].filter(Boolean).join(" "),o,r,i].filter(Boolean).join(", ")}}(a?.address)??"":o?o.short:n||""})).reduce(xt,new Set)],t)}function kt(e,t){return{label:e,amount:le(t.amount)}}function Ft(e){const t=e.countryCode?.toUpperCase(),a={firstName:e.givenName||void 0,lastName:e.familyName||void 0,address1:e?.addressLines?.[0],address2:e?.addressLines?.[1]||void 0,city:e.locality||void 0,postalCode:e.postalCode||void 0,zoneCode:e.administrativeArea||e.subLocality||void 0,countryCode:Vt(e.countryCode),phone:e.phoneNumber||void 0};return"HK"===a.countryCode&&(a.postalCode=void 0,a.zoneCode=e.postalCode),a.countryCode&&p.includes(a.countryCode)&&(a.zoneCode=a.countryCode,a.countryCode="US"),t&&Object.keys(It).includes(t)&&(a.zoneCode=e.locality||void 0,a.city=e.administrativeArea||e.subLocality||void 0),a.lastName||(a.lastName=a.firstName),a}function Vt(e){if(!e)return"ZZ";const t=e.toUpperCase();if(l(t))return t;return{UK:"GB",JA:"JP"}[t]||(p.includes(t)?t:"ZZ")}function Ht({embed:e,isCrossOriginIframeEnabled:t}){if(t&&"undefined"!=typeof window&&window.self!==window.top)return e?.client?.embedderHostname}const qt=new Set(["HUF","RSD"]);function zt(e){return void 0!==e&&function(e){return qt.has(e)}(e)}function Gt(e){const t=Number(e);return Number.isFinite(t)?Math.ceil(Number(t.toFixed(2))).toFixed(2):e}function jt(e){return{...e,amount:Gt(e.amount)}}function Qt(e){return{...e,amount:Gt(e.amount)}}function Zt(e){const{newLineItems:t,newShippingMethods:a}=e;return{...e,newTotal:jt(e.newTotal),...t&&{newLineItems:t.map(jt)},...a&&{newShippingMethods:a.map(Qt)}}}function $t(){const{i18n:e,shop:t}=v(),{name:o}=t,n=e.translate("order_summary.recurring_total_tooltip"),r=a((()=>({total:o,subtotal:e.translate("order_summary.subtotal_label"),duties:e.translate("order_summary.duties_label"),taxes:e.translate("order_summary.estimated_taxes_label"),shopDiscountOffer:e.translate("order_summary.exclusive_deal"),shopCashBalance:e.translate("order_summary.shop_cash_title"),shopPromotion:e.translate("order_summary.shop_promotion"),flashDeal:e.translate("order_summary.flash_deal"),giftCards:e.translate("order_summary.gift_card_label"),tip:e.translate("order_summary.tip_label")})),[o,e]),i=a((()=>({ONE_TIME_PURCHASE:e.translate("shipping.shipping_method_one_time_purchase_group_title"),SUBSCRIPTION:e.translate("shipping.shipping_method_subscription_group_title")})),[e]),s=a((()=>({SHIPPING:e.translate("wallets.shipping_line_label"),LOCAL:e.translate("shipping.local_delivery"),PICK_UP:e.translate("delivery_options.pick_up"),PICKUP_POINT:e.translate("delivery_options.pickup_point_method_definition"),RETAIL:e.translate("delivery_options.retail_method_definition"),NONE:e.translate("delivery_options.none_method_definition")})),[e]),l=a((()=>(t,a)=>e.translate("wallets.connect_shipping_methods",{method1:t,method2:a})),[e]);return a((()=>({formattedRecurringTotalTooltip:n,lineItemsLabels:r,deliveryOptionGroupTypeLabels:i,deliveryMethodTitlePrefixes:s,connectTwoShippingTitles:l})),[n,r,i,s,l])}const Wt=({asPaymentMethod:e,phoneRequired:t,shouldRequestPhoneOnRetry:a,shopPayOptInExists:o})=>e?o:t||a,Jt=({asPaymentMethod:e,emailRequired:t,shopPayOptInExists:a,proposedEmailExists:o})=>e?!o&&a:t;function Kt(){const{observability:e}=v(),t=X(W.ApplePay),{trackComplete:a}=Pt(W.ApplePay);return o((({status:o,walletType:n,endsAuthorization:r=!0})=>{if(e.counter({name:"apple_pay_payment_status",value:1,attributes:{status:o,wallet_type:n}}),t(o,n),o===K.Attempt)return;if(!r)return void gt.remove("apple-pay-authorization");const i=o===K.Success?"success":"failed";gt.endAndRun("apple-pay-authorization",(t=>{a({result:i,durationMs:t,walletType:n,attributes:{walletType:n}}),e.log("apple_pay_payment_status_updated","Apple Pay payment authorization status update received",{result:i,status:o,walletType:n})}))}),[e,t,a])}function Xt(){const e=ot(),t=Kt(),{inMemoryApplePayParts:{asPaymentMethod:a}}=P();return o((()=>{const o=a.value?J.PaymentMethod:J.Express;e(),t({status:K.Failure,walletType:o})}),[t,e,a])}function ea(){const e=$(W.ApplePay),t=X(W.ApplePay),{trackComplete:a}=Pt(W.ApplePay),{checkout:{wallets:n},observability:r}=v(),{inMemoryApplePayParts:i}=P(),s=ot();return o((({session:o,isProcessing:l=!1,isMessagingHandledElsewhere:p=!1,error:d,isAborted:c})=>{if(d instanceof oe)return;gt.remove("apple-pay-sheet-load");const u=i.asPaymentMethod.value?J.PaymentMethod:J.Express;r.counter({name:"apple_pay_session_terminated",value:1,attributes:{error_type:d.name,wallet_type:u}}),r.log("apple_pay_terminate_session_session","Apple Pay session terminated",{wallet_type:u,error_type:d.name,error_message:d.message,error_cause:d.cause,error_stack:d.stack}),gt.exists("apple-pay-authorization")?(t(K.Failure,u),a({result:"failed",durationMs:gt.end("apple-pay-authorization"),walletType:u})):(e(K.Failure,u),r.counter({name:"wallet_sheet_failed",value:1,attributes:{instrument:W.ApplePay}})),l||p||(i.paymentSheetError.value={type:"session_terminated"});const{actionable:y}=ft(d);if(d instanceof ne?r.leaveErrorBreadcrumb(`IgnoredApplePayAPIError: ${d.message}`):y?r.error(d,{severity:"error",errorClass:rt.Api}):r.leaveErrorBreadcrumb("[ApplePay] Unactionable error",{error:d}),n.setHasActiveApplePaySubscriptionReview(!1),c||"APPLE_PAY"!==n.activeSession.value?.wallet?r.leaveErrorBreadcrumb("[ApplePay] clearActiveSession skipped",{activeSession:n.activeSession.value?.wallet,isAborted:c}):n.clearActiveSession({invokingWallet:"APPLE_PAY"}),o)try{o.abort()}catch{}finally{s()}}),[i.asPaymentMethod,i.paymentSheetError,s,r,t,a,e,n])}const ta=["BR","KW","PA","PE","PH"];function aa(e){return e.hasFlagEnabled(S)}function oa(e,t){if(!t)return{};const a={district:void 0,line2:void 0,subdistrict:void 0},o=e.countryCode?.toUpperCase();return o&&ta.includes(o)?(e.subLocality&&(a.district=e.subLocality),e.addressLines?.[1]&&(a.line2=e.addressLines[1]),e.subAdministrativeArea&&(a.subdistrict=e.subAdministrativeArea),a):a}const na=[T.InvalidExtensionState,T.InvalidCaptcha,T.SubmittedForCompletion];class ra extends ue{constructor(e,t,a,o,n){super(),this.observability=e,this.translations=t,this.inMemoryApplePayParts=a,this.persistedApplePaySignal=o,this.reportAddressRequirementMismatch=n}get negotiationResultMapper(){return new ye({success:({result:e,violationActions:t,defaultMapper:a})=>{if(!("errors"in e))return a();const{firstPaymentSheetAction:o}=this.getMergedPaymentSheetAction({resultViolations:e.errors,violationActions:t});return o||a()},invalid:({result:e})=>
1(this.notifyInvalidResult(e,"negotiation"),this.generateAbortAction("exceptional_negotiation_status")),stale:()=>(this.observability.error(new ie("Intercepted negotiation returned stale",{groupingHash:"ApplePayAPIError::InterceptedNegotiationReturned::Stale"}),{severity:"error"}),this.generateAbortAction("exceptional_negotiation_status")),denied:()=>({action:"abort"}),throttled:()=>({action:"abort"}),tooManyRequests:()=>({action:"abort"})},(()=>this.mapUnhandledNegotiation()),(e=>this.getNegotiationViolationActions(e)))}get completionResultMapper(){return new ye({success:({result:e,defaultMapper:t})=>"receipt"in e?{action:"submit"}:t(),failed:({result:e})=>(this.observability.log("apple_pay_payment_sheet_action_generator_failed","Apple Pay completion failed",{reason:e.reason}),this.generateAbortAction("exceptional_completion_status")),rejected:({result:e,violationActions:t,options:a})=>{this.getUnhandledErrors(e.violations,t).forEach((e=>{this.observability.error(new ie(`violation not handled: ${e.code}`,{groupingHash:`ApplePayAPIError::ViolationNotHandled::${e.code}`}),{severity:"error",errorClass:rt.Api})}));const{generatePrioritizedPaymentSheetAction:o}=this.getMergedPaymentSheetAction({resultViolations:e.violations,violationActions:t}),{action:n,violationCode:r}=o();return r&&this.observability.counter({name:"wallet_action_generator_handled_error",value:1,attributes:{violationCode:r,WalletName:W.ApplePay,action:n?.action??"abort",asPaymentMethod:Boolean(a?.asPaymentMethod)}}),this.reportAddressRequirementMismatch({violationCode:r,wallet:W.ApplePay,asPaymentMethod:this.inMemoryApplePayParts.asPaymentMethod.value,outcome:n?.action??"abort"}),n?("decelerate"===n.action&&(this.persistedApplePaySignal.value={...this.persistedApplePaySignal.value,recoveryViolation:r},this.observability.log("apple_pay_authorization_decelerated","Apple Pay authorization decelerated during payment completion",{asPaymentMethod:Boolean(a?.asPaymentMethod),violationCode:r,violations:e.violations.map((e=>e.code)).join(",")})),n):{action:"abort"}},invalid:({result:e,options:t})=>{const a=Boolean(t?.applePayRecoveryFlowEnabled)&&e.reasons.length>0&&e.reasons.every((e=>C.includes(e))),o=a?"decelerate":"abort";if(this.notifyInvalidResult(e,"completion",o),a){const a=e.reasons.at(0)??"unknown";return this.persistedApplePaySignal.value={...this.persistedApplePaySignal.value,recoveryViolation:a},this.observability.counter({name:"wallet_action_generator_handled_error",value:1,attributes:{violationCode:a,WalletName:W.ApplePay,action:"decelerate",asPaymentMethod:Boolean(t?.asPaymentMethod)}}),this.observability.log("apple_pay_authorization_decelerated","Apple Pay authorization decelerated during payment completion",{asPaymentMethod:Boolean(t?.asPaymentMethod),violationCode:a,violations:e.reasons.join(",")}),this.generateDecelerateAction()}return{action:o,effects:[()=>{this.inMemoryApplePayParts.paymentSheetError.value={type:e.reasons.includes(T.InvalidCaptcha)?"captcha_required":"exceptional_completion_status"}}]}},stale:()=>(this.observability.error(new ie("Intercepted negotiation returned stale",{groupingHash:"ApplePayAPIError::InterceptedNegotiationReturned::Stale"}),{severity:"error"}),this.generateAbortAction("exceptional_completion_status")),fetch_failed:()=>this.generateAbortAction("exceptional_completion_status"),alreadyCompleted:()=>({action:"abort"}),denied:()=>({action:"abort"}),throttled:()=>({action:"abort"}),tooManyRequests:()=>({action:"abort"})},(e=>this.mapUnhandledCompletion(e)),((e,t)=>this.getCompletionViolationActions(e,t)))}validateBilling(e){const{billingContact:t}=e;return t?{shouldPersist:!0}:{shouldPersist:!1,paymentSheetAction:{action:"abort"}}}validateShipping(e,t,a,o,n){const{shippingContact:r}=e;if(!t)return{shouldPersist:!1};if(!r)return{shouldPersist:!1,paymentSheetAction:{action:"abort"}};const i=Ft(r),s=[];return a&&!i.address2&&s.push(new ApplePayError("shippingContactInvalid","addressLines",this.translations.addressLine2Blank)),o&&!i.firstName&&s.push(new ApplePayError("shippingContactInvalid","name",this.translations.firstNameBlank)),n&&!i.phone&&s.push(new ApplePayError("shippingContactInvalid","phoneNumber",this.translations.phoneBlank)),s.length>0?{shouldPersist:!1,paymentSheetAction:{action:"show_error",errors:s}}:{shouldPersist:!0}}getCompletionViolationActions(e,t){return[{violations:[...N,"MERCHANDISE_NOT_APPLICABLE",...he,...w,...me,ve,_e],generateAction:()=>({action:"abort"})},{violations:Ae,generateAction:()=>this.generateAbortAction("session_terminated")},{violations:ge,generateAction:()=>this.generateAbortAction("shipping_options_changed")},{violations:Pe,generateAction:()=>sa("emailAddress",this.translations.emailInvalidError)},{violations:["BUYER_IDENTITY_CONTACT_INFO_DOES_NOT_MATCH_CUSTOMER_PROFILE"],generateAction:()=>this.generateAbortAction("unhandled_completion_status")},{violations:Ee,generateAction:()=>sa("phoneNumber",this.translations.phoneInvalidError)},{violations:["BUYER_IDENTITY_MISSING_CONTACT_METHOD","BUYER_IDENTITY_EMAIL_REQUIRED"],generateAction:()=>sa("emailAddress",this.translations.contactInfoBlank)},...this.getCompletionDeceleratedViolationActions(e),{violations:[...fe],generateAction:()=>sa("phoneNumber",this.translations.phoneInvalidError)},{violations:["PAYMENTS_PHONE_NUMBER_DOES_NOT_MATCH_EXPECTED_PATTERN"],generateAction:()=>ia("phoneNumber",this.translations.phoneInvalidError)},...this.getCompletionShippingAddressViolationActions(e,t),{violations:[...be,"PAYMENTS_METHOD_REQUIRED"],generateAction:()=>({action:"show_error",errors:[new ApplePayError("unknown",void 0,void 0)]})},...this.getCompletionBillingAddressViolationActions(e)]}getCompletionBillingAddressViolationActions(e){return Boolean(e?.options?.applePayRecoveryFlowEnabled)?[{violations:Se,generateAction:()=>this.generateDecelerateAction()}]:[{violations:Ce,generateAction:()=>ia("name",this.translations.nameContainsEmojisError)},{violations:Te,generateAction:()=>ia("name",this.translations.firstNameTooLongError)},{violations:["PAYMENTS_ADDRESS1_CONTAINS_HTML_TAGS","PAYMENTS_ADDRESS1_CONTAINS_EMOJIS","PAYMENTS_ADDRESS1_CONTAINS_MATHEMATICAL_SYMBOLS","PAYMENTS_ADDRESS2_CONTAINS_EMOJIS","PAYMENTS_ADDRESS2_CONTAINS_MATHEMATICAL_SYMBOLS","PAYMENTS_COMPANY_CONTAINS_EMOJIS",...I],generateAction:()=>ia("addressLines",this.translations.invalidBillingAddressError)},{violations:["PAYMENTS_LAST_NAME_CONTAINS_HTML_TAGS","PAYMENTS_LAST_NAME_CONTAINS_URL"],generateAction:()=>ia("name",this.translations.invalidBillingAddressError)},{violations:Ne,generateAction:()=>ia("name",this.translations.lastNameTooLongError)},{violations:["PAYMENTS_ADDRESS1_TOO_LONG","PAYMENTS_ADDRESS2_TOO_LONG"],generateAction:()=>ia("addressLines",this.translations.addressLineTooLongError)},{violations:[we],generateAction:()=>({action:"show_error",errors:[this.createApplePayZoneError(this.translations.zoneNotFoundError,"billingContactInvalid",e?.billingCountryCode)]})},{violations:["PAYMENTS_INVALID_POSTAL_CODE_FOR_COUNTRY","PAYMENTS_INVALID_POSTAL_CODE_FOR_ZONE"],generateAction:()=>ia("postalCode",this.translations.postalCodeInvalidError)},{violations:Ie,generateAction:()=>ia("postalCode",this.translations.postalCodeEmojiError)},{violations:Re,generateAction:()=>ia("postalCode",this.translations.postalCodeNotSupportedError)},{violations:["PAYMENTS_FIRST_NAME_REQUIRED"],generateAction:()=>ia("name",this.translations.firstNameBlank)},{violations:["PAYMENTS_LAST_NAME_REQUIRED"],generateAction:()=>ia("name",this.translations.lastNameBlank)},{violations:["PAYMENTS_ADDRESS1_REQUIRED"],generateAction:()=>ia("addressLines",this.translations.addressLine1Blank)},{violations:["PAYMENTS_CITY_REQUIRED"],generateAction:()=>ia("locality",this.translations.cityBlank)},{violations:["PAYMENTS_CITY_TOO_LONG","PAYMENTS_CITY_CONTAINS_MATHEMATICAL_SYMBOLS","PAYMENTS_CITY_CONTAINS_EMOJIS","PAYMENTS_CITY_CONTAINS_HTML_TAGS"],generateAction:()=>ia("locality",this.translations.invalidBillingAddressError)},{violations:["PAYMENTS_POSTAL_CODE_REQUIRED"],generateAction:()=>ia("postalCode",this.translations.postalCodeBlank)},{violations:["PAYMENTS_COUNTRY_REQUIRED"],generateAction:()=>ia("country",this.translations.countryBlank)},{violations:["PAYMENTS_ZONE_REQUIRED_FOR_COUNTRY"],generateAction:()=>({action:"show_error",errors:[this.createApplePayZoneError(this.translations.deliveryZoneBlank,"billingContactInvalid",e?.billingCountryCode)]})},{violations:["PAYMENTS_SHIPPING_MUST_MATCH_BILLING"],generateAction:()=>ia("postalAddress",this.translations.billingMustMatchShipping)},{violations:["PAYMENTS_PHONE_NUMBER_REQUIRED"],generateAction:()=>({action:"abort",effects:[()=>{this.inMemoryApplePayParts.paymentSheetError.value={type:"exceptional_completion_status"},this.inMemoryApplePayParts.requireBillingPhoneOnNextAttempt.value=!0}]})}]}getCompletionShippingAddressViolationActions(e,t){return Boolean(e?.options?.applePayRecoveryFlowEnabled)?[{violations:["DELIVERY_ZONE_NOT_FOUND","DELIVERY_COMPANY_REQUIRED",...Me,...De],generateAction:()=>this.generateDecelerateAction()}]:[{violations:["DELIVERY_FIRST_NAME_REQUIRED"],generateAction:()=>sa("name",this.translations.firstNameBlank)},{violations:["DELIVERY_LAST_NAME_REQUIRED"],generateAction:()=>sa("name",this.translations.lastNameBlank)},{violations:["DELIVERY_ADDRESS1_REQUIRED"],generateAction:()=>sa("addressLines",this.translations.addressLine1Blank)},{violations:["DELIVERY_ADDRESS2_REQUIRED"],generateAction:()=>sa("addressLines",this.translations.addressLine2Blank)},{violations:["DELIVERY_CITY_REQUIRED"],generateAction:()=>sa("locality",this.translations.cityBlank)},{violations:["DELIVERY_ZONE_REQUIRED_FOR_COUNTRY"],generateAction:()=>({action:"show_error",errors:[this.createApplePayZoneError(this.translations.deliveryZoneBlank,"shippingContactInvalid",e?.shippingCountryCode)]})},{violations:["DELIVERY_COUNTRY_REQUIRED"],generateAction:()=>sa("country",this.translations.countryBlank)},{violations:["DELIVERY_POSTAL_CODE_REQUIRED"],generateAction:()=>sa("postalCode",this.translations.postalCodeBlank)},{violations:["DELIVERY_ZONE_NOT_FOUND"],generateAction:()=>{const{shippingZone:a,shippingCountry:o}=Oe(t);return{action:"show_error",errors:[this.createApplePayZoneError(this.translations.zoneNotFoundError,"shippingContactInvalid",e?.shippingCountryCode)],effects:[()=>{this.observability.log("apple_pay_payment_completion_failed","Delivery zone issue",{reason:"DELIVERY_ZONE_NOT_FOUND",shippingZone:a,shippingCountry:o})}]}}},{violations:["DELIVERY_INVALID_POSTAL_CODE_FOR_COUNTRY","DELIVERY_INVALID_POSTAL_CODE_FOR_ZONE","DELIVERY_POSTAL_CODE_NOT_SUPPORTED"],generateAction:()=>sa("postalCode",this.translations.postalCodeInvalidError)},{violations:["DELIVERY_LAST_NAME_CONTAINS_HTML_TAGS","DELIVERY_FIRST_NAME_CONTAINS_HTML_TAGS","DELIVERY_LAST_NAME_CONTAINS_URL","DELIVERY_FIRST_NAME_CONTAINS_URL"],generateAction:()=>sa("name",this.translations.invalidShippingAddressError)},{violations:["DELIVERY_ADDRESS1_CONTAINS_HTML_TAGS","DELIVERY_ADDRESS2_CONTAINS_HTML_TAGS","DELIVERY_ADDRESS1_CONTAINS_EMOJIS","DELIVERY_ADDRESS2_CONTAINS_EMOJIS","DELIVERY_ADDRESS2_CONTAINS_MATHEMATICAL_SYMBOLS",...R],generateAction:()=>sa("addressLines",this.translations.invalidShippingAddressError)},{violations:["DELIVERY_CITY_CONTAINS_HTML_TAGS"],generateAction:()=>sa("locality",this.translations.invalidShippingAddressError)},{violations:["DELIVERY_ADDRESS1_TOO_LONG"],generateAction:()=>sa("addressLines",this.translations.addressLineTooLongError)},{violations:["DELIVERY_FIRST_NAME_TOO_LONG"],generateAction:()=>sa("name",this.translations.firstNameTooLongError)},{violations:["DELIVERY_LAST_NAME_TOO_LONG"],generateAction:()=>sa("name",this.translations.lastNameTooLongError)},{violations:Le,generateAction:()=>sa("name",this.translations.nameContainsEmojisError)},{violations:Me,generateAction:()=>({action:"abort",effects:[()=>{this.inMemoryApplePayParts.paymentSheetError.value={type:"exceptional_completion_status"},this.inMemoryApplePayParts.requirePhoneOnNextAttempt.value=!0}]})}]}getCompletionDeceleratedViolationActions(e){return e?.options?.applePayRecoveryFlowEnabled?[{violations:Be,generateAction:()=>this.generateDecelerateAction({paymentSheetError:{type:"new_tax_must_be_accepted",tone:"warning"}})},{violations:[...M,D,...Ye,...xe,...L,...Ue,"DELIVERY_WRONG_NUMBER_OF_DELIVERY_LINES",...ke,...Fe],generateAction:()=>this.generateDecelerateAction()}]:this.getCompletionAbortViolationActions()}getCompletionAbortViolationActions(){return[{violations:[...Be,D,...Ye,...L,"DELIVERY_COMPANY_REQUIRED"],generateAction:()=>({action:"abort"})},{violations:xe,generateAction:()=>this.generateAbortAction("session_terminated")},{violations:Ue,generateAction:()=>this.generateAbortAction("unusable_partial_address")},{violations:["DELIVERY_WRONG_NUMBER_OF_DELIVERY_LINES",...ke],generateAction:()=>this.generateAbortAction("unhandled_completion_status")},{violations:Fe,generateAction:()=>this.generateAbortAction("ineligible_discount")}]}mapUnhandledCompletion(e){return this.observability.error(new ie(`Intercepted completion returned unhandled status: ${e.status}`,{groupingHash:`ApplePayAPIError::InterceptedCompletionReturned::Unhandled::${e.status}`}),{severity:"error",errorClass:rt.Api}),this.generateAbortAction("unhandled_completion_status")}getNegotiationViolationActions(e){return[{violations:["MERCHANDISE_CART_AND_CURRENCY_UPDATED_BASED_ON_COUNTRY","MERCHANDISE_CART_UPDATED_BASED_ON_COUNTRY",D,...N,...w,ve,_e],generateAction:()=>({action:"abort"})},{violations:ge,generateAction:()=>({action:"update",errors:[new ApplePayError("addressUnserviceable")]})},...this.getNegotiationShippingAddressViolationActions(e),{violations:[we],generateAction:()=>({action:"update",errors:[this.createApplePayZoneError(this.translations.zoneNotFoundError,"billingContactInvalid",e?.billingCountryCode)]})},{violations:["PAYMENTS_INVALID_POSTAL_CODE_FOR_COUNTRY","PAYMENTS_INVALID_POSTAL_CODE_FOR_ZONE"],generateAction:()=>({action:"update",errors:[new ApplePayError("billingContactInvalid","postalCode",this.translations.postalCodeInvalidError)]})}]}getNegotiationShippingAddressViolationActions(e){return Boolean(e?.options?.applePayRecoveryFlowEnabled)?[{violations:[...Ve,"DELIVERY_INVALID_POSTAL_CODE_FOR_COUNTRY","DELIVERY_INVALID_POSTAL_CODE_FOR_ZONE"],generateAction:()=>({action:"no-op"})}]:[{violations:Ve,generateAction:()=>({action:"update",errors:[this.createApplePayZoneError(this.translations.zoneNotFoundError,"shippingContactInvalid",e?.shippingCountryCode)]})},{violations:["DELIVERY_INVALID_POSTAL_CODE_FOR_COUNTRY"],generateAction:()=>this.createInvalidPostalCodeViolationAction(e?.shippingCountryCode)},{violations:["DELIVERY_INVALID_POSTAL_CODE_FOR_ZONE"],generateAction:()=>({action:"update",errors:[new ApplePayError("shippingContactInvalid","postalCode",this.translations.postalCodeInvalidError)]})}]}createInvalidPostalCodeViolationAction(e){return"CA"===e||"GB"===e?{action:"no-op"}:{action:"update",errors:[new ApplePayError("shippingContactInvalid","postalCode",this.translations.postalCodeInvalidError)]}}mapUnhandledNegotiation(){return{action:"update",errors:[]}}createApplePayZoneError(e,t,a){return new ApplePayError(t,"AE"===a?"subLocality":"administrativeArea","AE"===a&&e===this.translations.zoneNotFoundError?this.translations.emirateNotFoundError:e)}generateAbortAction(e){return{action:"abort",effects:[()=>{this.inMemoryApplePayParts.paymentSheetError.value={type:e}}]}}generateDecelerateAction({paymentSheetError:e={type:"recovery_notice"}}={}){return{action:"decelerate",effects:[()=>{this.inMemoryApplePayParts.paymentSheetError.value=e}]}}
1notifyInvalidResult(e,t,a){const{expectedReasons:o,unexpectedReasons:n}=[...new Set(e.reasons)].reduce(((e,t)=>(na.includes(t)?e.expectedReasons.push(t):e.unexpectedReasons.push(t),e)),{expectedReasons:[],unexpectedReasons:[]});o.length>0&&(this.observability.log("apple_pay_payment_sheet_action_generator_negotiation_rejected","wallet_rejected_negotiation",{wallet:"apple_pay",reason:"invalid",stage:t,expectedReasons:o.sort(),unexpectedReasons:n.sort(),action:a}),this.observability.counter({name:"wallet_rejected_negotiation",value:1,attributes:{wallet:"apple_pay",reason:"invalid",stage:t,expectedReasons:o.sort().join(","),hasUnexpectedReasons:Boolean(n.length),action:a}}));for(const r of n.sort())this.observability.error(new ie(`Intercepted ${t} returned invalid: ${r}`,{groupingHash:`ApplePayAPIError::InterceptedNegotiationReturned::Invalid::${r}`}),{severity:"error"})}}function ia(e,t){return{action:"show_error",errors:[new ApplePayError("billingContactInvalid",e,t)]}}function sa(e,t){return{action:"show_error",errors:[new ApplePayError("shippingContactInvalid",e,t)]}}function la(){const{i18n:e,observability:t}=v(),{inMemoryApplePayParts:n,persistedApplePaySignal:r}=P(),i=He(),s=a((()=>({postalCodeNotSupportedError:e.translate("wallets.errors.unsupported.postal_code"),billingMustMatchShipping:e.translate("wallets.errors.invalid.billing_must_match_shipping"),invalidShippingAddressError:e.translate("wallets.errors.invalid.shipping_address"),invalidBillingAddressError:e.translate("wallets.errors.invalid.billing_address"),firstNameTooLongError:e.translate("wallets.errors.formatting.first_name_too_long"),lastNameTooLongError:e.translate("wallets.errors.formatting.last_name_too_long"),nameContainsEmojisError:e.translate("wallets.errors.formatting.name_contains_emojis"),addressLineTooLongError:e.translate("wallets.errors.formatting.address_too_long"),postalCodeInvalidError:e.translate("wallets.errors.invalid.postal_code"),postalCodeEmojiError:e.translate("wallets.errors.formatting.postal_code_contains_emoji"),zoneNotFoundError:e.translate("wallets.errors.invalid.zone"),emirateNotFoundError:e.translate("wallets.errors.invalid.emirate"),emailInvalidError:e.translate("wallets.errors.invalid.email"),phoneInvalidError:e.translate("wallets.errors.invalid.phone"),firstNameBlank:e.translate("wallets.errors.missing.first_name"),lastNameBlank:e.translate("wallets.errors.missing.last_name"),addressLine1Blank:e.translate("wallets.errors.missing.address1"),addressLine2Blank:e.translate("wallets.errors.missing.address2"),cityBlank:e.translate("wallets.errors.missing.city"),postalCodeBlank:e.translate("wallets.errors.missing.zip"),countryBlank:e.translate("wallets.errors.missing.country"),deliveryZoneBlank:e.translate("wallets.errors.missing.province"),phoneBlank:e.translate("wallets.errors.missing.phone"),contactInfoBlank:e.translate("wallets.errors.missing.contact_info")})),[e]);return o((()=>new ra(t,s,n,r,i)),[s,n,r,t,i])}function pa({canDecelerate:e,checkout:t}){return e.value&&O({checkout:t})}const da=class extends k{};da.type="wallet:address-replace";let ca=da;function ua({methodName:e,abortSignal:t,wallets:a,observability:o},n){if(!t?.aborted&&a.activeSession.value)try{n()}catch(r){if(r instanceof Error&&"InvalidAccessError"===r.name)return void ya({observability:o},{errorName:"InvalidAccessError",methodName:e});throw r}else ya({observability:o},{errorName:"SessionAlreadyTerminated",methodName:e})}function ya({observability:e},t){e.counter({name:"apple_pay_session_error",value:1,attributes:t}),e.log("apple_pay_with_active_session","Apple Pay active session error",t),e.leaveErrorBreadcrumb("[Apple Pay] Error while calling ApplePaySession method",t,"error")}function ha(){const e=ea(),t=F(),{progress:a}=st(),r=lt(),i=pt(),s=g(),l=tt(),p=_().buyerIdentity.value?.customerProfile,d=V(),c=dt(),u=ct("APPLE_PAY"),{inMemoryApplePayParts:{asPaymentMethod:y,requirePhoneOnNextAttempt:h,requireBillingPhoneOnNextAttempt:m,paymentSheetError:f,expiresAt:S,preCompletionHandler:C,subscriptionReviewTransition:T},persistedApplePaySignal:N,walletUsedForSubmissionSignal:w}
1=P(),I=la(),R=function(){const e=la();return o(((t,a)=>{const{completionResultMapper:o}=e();if(!o)throw new ie("CompletionResultMapper not set up correctly",{groupingHash:"ApplePayAPIError::CompletionResultMapper"});return o.mapResultToPaymentSheetAction(t,a)}),[e])}(),M=Xt(),L=Kt(),{source:{checkoutSessionIdentifier:O},observability:k,checkout:{wallets:Q,address:{countryDetails:Z},configuration:$},shop:X,events:ae,client:oe}=v(),ne=aa(X),re=$.addressSettings.nonBillingAddressSettings,se=$.layout.isOnePage,le=ee(W.ApplePay),{trackAttempt:pe}=Pt(W.ApplePay),de=ut(y),ce=_(),ue=ce.buyerIdentity.value?.purchasingCompany,ye=ce.availableDeliveryAddresses?.value,he=ce.mustSelectProvidedAddress?.value,me=E({availableDeliveryAddresses:ye,mustSelectProvidedAddress:he}),{email:ve,shippingAddress:_e,billingAddress:Ae,paymentLines:ge,deliveryLines:Pe}=A(),Ee=qe(),fe=yt({shouldPersist:!0}),be=Et({flag:b,onAbort:fe,onError:e=>{throw e}}),Se=function({canDecelerate:e,asPaymentMethod:t}){const a=function({canDecelerate:e}){const t=B(),{checkout:a,shop:o}=v();return n((()=>(o.hasFlagEnabled(Y)||o.hasFlagEnabled(x))&&pa({canDecelerate:e,checkout:a})&&t.value))}({canDecelerate:e}),{checkout:o}=v(),r=it();return n((()=>{const n=null!==r,i=pa({canDecelerate:e,checkout:o});return t.value?{shouldDecelerate:!1,isABTestActive:n,isCaliforniaDeceleration:!1,hasSubscription:i}:a.value?{shouldDecelerate:!0,isABTestActive:n,isCaliforniaDeceleration:!0,hasSubscription:i}:n?U(r)?{shouldDecelerate:i,isABTestActive:!0,isCaliforniaDeceleration:!1,hasSubscription:i}:{shouldDecelerate:!1,isABTestActive:!0,isCaliforniaDeceleration:!1,hasSubscription:i}:{shouldDecelerate:!1,isABTestActive:!1,isCaliforniaDeceleration:!1,hasSubscription:i}}))}({canDecelerate:de,asPaymentMethod:y}),Ce=function(){const{negotiate:e}=st(),{checkout:{wallets:t},observability:a}=v();return o((async(o,n)=>{let r,i,s=!1;try{await e({runListenersOnError:!0,fieldsToResolve:["deliveryNext"],onComplete:e=>{"success"!==e.status&&"error"!==e.status&&"invalid"!==e.status?r=e.status:s=!0}})}catch(c){s||(i=c)}const l=o.aborted||!t.activeSession.value;if(s&&!l)return!0;let p="rejected";l?p="session_ended":r&&(p="unsettled_status");const d={result:"failed",reason:p,status:r??"none"};return a.counter({name:"apple_pay_pre_deceleration_negotiation_attempt",value:1,attributes:d}),a.log("apple_pay_pre_deceleration_negotiation_attempt","[ApplePay] Pre-deceleration negotiation aborted",{...d,error:String(i)}),n(),!1}),[e,t,a])}();return o((async(o,n,v,_,A,g)=>{let P=!1;const E=I(),b=y.value,B=de.value,Y=b?J.PaymentMethod:J.Express;function U(){try{ua({methodName:"completePayment",abortSignal:_,wallets:Q,observability:k},(()=>n.completePayment(ApplePaySession.STATUS_FAILURE))),k.leaveErrorBreadcrumb("[ApplePay] Completion flow - clearing activeSession (abort path)"),Q.clearActiveSession({invokingWallet:"APPLE_PAY"}),k.log("apple_pay_authorization_aborted","Apple Pay authorization aborted during payment completion",{}),M()}catch(a){e({session:n,error:a})}finally{b||t()}}if(pe({walletType:Y}),gt.start("apple-pay-authorization"),L({status:K.Attempt,walletType:Y}),!_.aborted&&Q.activeSession.value&&A?.())return k.leaveErrorBreadcrumb("ApplePay: authorization blocked by payment method reconciliation"),f.value={type:"session_terminated"},void U();function F(t,a){switch(a.effects?.forEach((e=>e())),a.action){case"submit":{const a=u.value,n=O&&a?.walletOrderTypeIdentifier&&a?.walletServiceUrl&&a?.walletAuthenticationToken?{status:ApplePaySession.STATUS_SUCCESS,orderDetails:{orderTypeIdentifier:a.walletOrderTypeIdentifier,orderIdentifier:O,webServiceURL:a.walletServiceUrl,authenticationToken:a.walletAuthenticationToken}}:ApplePaySession.STATUS_SUCCESS;let r=!1;try{ua({methodName:"completePayment",abortSignal:_,wallets:Q,observability:k},(()=>{t.completePayment(n),r=!0}))}catch(o){e({session:t,error:o,isProcessing:!0})}finally{k.leaveErrorBreadcrumb("[ApplePay] payment completed successfully",{walletType:Y}),Q.clearActiveSession({invokingWallet:"APPLE_PAY"})}return r&&L({status:K.Success,walletType:Y}),w.value="APPLE_PAY",r}case"show_error":{const n=je(a),r={status:ApplePaySession.STATUS_FAILURE,errors:n};k.log("apple_pay_authorization_has_errors","apple_pay_authorization_has_errors",{errors:n});try{ua({methodName:"completePayment",abortSignal:_,wallets:Q,observability:k},(()=>t.completePayment(r))),_.aborted||0===r.errors.length?(k.leaveErrorBreadcrumb("[ApplePay] payment failed with no errors or abort action, sheet will close"),Q.clearActiveSession({invokingWallet:"APPLE_PAY"}),M()):(k.leaveErrorBreadcrumb("[ApplePay] payment failed with handled errors, sheet will remain open for retry"),M())}catch(o){return e({session:t,error:o}),!1}return!0}case"abort":return U(),!1;case"decelerate":{if(!B)return U(),!1;const n=a.completePaymentStatus??ApplePaySession.STATUS_FAILURE;try{ua({methodName:"completePayment",abortSignal:_,wallets:Q,observability:k},(()=>t.completePayment(n))),Q.clearActiveSession({invokingWallet:"APPLE_PAY"}),L({status:K.Failure,walletType:Y,endsAuthorization:!1}),le({event:te.RecoveryFlowInitiated,walletType:Y}),se.value&&(Q.setEscalatedWallet("APPLE_PAY"),"review"===r.value.currentPage?.id&&i("payment-methods",{replace:!0})),N.value={...N.value,receiptIdForPaymentFailure:void 0,recoverySubmissionAttemptCount:0},se.value?ae.dispatchEvent(new ca):P=!0}catch(o){return e({session:t,error:o}),!1}return!0}default:return e({session:t,error:new ie(`Missing handler for payment sheet action "${a.action}"`,{groupingHash:"ApplePayAPIError::MissingHandlerPaymentSheetAction"})}),!1}}const V=re.value.isRequired("address2"),$=re.value.isRequired("firstName"),{token:ee,billingContact:ce,shippingContact:ye}=o.payment,he=re.value.isRequired("phone",{countryCode:Vt(ye?.countryCode)}
1),fe=E.validateBilling(o.payment);if(fe.shouldPersist&&ce&&!ue){const e=!l.value&&he||m.value?ye?.phoneNumber:void 0;m.value&&ye?.phoneNumber&&k.counter({name:"apple_pay_billing_phone_provided_after_retry",value:1,attributes:{asPaymentMethod:b}});const t={...ce,phoneNumber:e};ne&&await Z.fetch(Vt(t.countryCode)),ma(Ae,t,ne)}if(fe.paymentSheetAction)return void F(n,fe.paymentSheetAction);if(k.log("wallets_shipping_address_update","onPaymentAuthorized: decision state before shipping address update",{asPaymentMethod:b,shippingContactDefined:Boolean(ye),isShippingContactPostalCodePadded:H(ye?.postalCode,Vt(ye?.countryCode)),isCurrentProposedPostalCodePadded:H(_e.value?.postalCode,_e.value?.countryCode),shippingRequired:l.value}),!b&&!me){const e=E.validateShipping(o.payment,l.value,V&&!B,$,he&&!B);if(e.shouldPersist&&ye){c({postalCode:ye.postalCode,countryCode:Vt(ye.countryCode),city:ye.locality,zoneCode:ye.administrativeArea||ye.subLocality},"APPLE_PAY"),ne&&await Z.fetch(Vt(ye.countryCode));const e={...Ft(ye),...oa(ye,ne)};k.log("wallets_shipping_address_update","onPaymentAuthorized: update with complete shipping address from shippingContact",{isPostalCodePadded:H(e.postalCode,e.countryCode),countryCode:e.countryCode}),ma(_e,ye,ne)}if(e.paymentSheetAction)return void F(n,e.paymentSheetAction)}if(!b){const e=p?.email??ye?.emailAddress;e&&(ve.value=e)}ye?.phoneNumber&&Pe.value.forEach((e=>{e.value={...e.value,deliveryMethodOptions:{...e.value.deliveryMethodOptions,phone:ye.phoneNumber}}})),h.value&&ye?.phoneNumber&&k.counter({name:"apple_pay_phone_provided_after_retry",value:1,attributes:{asPaymentMethod:b}}),b?Ee({phone:ye?.phoneNumber,email:ye?.emailAddress,firstName:ce?.givenName}):Ee();const Te=s.current.fields.paymentDue.value;if(Te&&Te.amount>0||d.value){const e=ge.value,{brand:t,lastFourDigits:a}=function(e){const t={brand:"",lastFourDigits:""};if(!e)return t;const a=e.split(" ");if(2!==a.length)return t;const[o,n]=a;if(void 0===o||void 0===n)return t;for(const r of o.toLowerCase())if(r<"a"||r>"z")return t;return Number.isNaN(Number(n))?t:{brand:o,lastFourDigits:n}}(ee.paymentMethod.displayName);ge.value=q(e,{method:{type:"wallet",name:"APPLE_PAY",walletContent:{...ee.paymentData,lastDigits:a,cardNetworkBrand:t,paymentMethodIdentifier:u.value?.paymentMethodIdentifier,...B&&{expiresAt:S.value}}}})}const Ne=Se.value,we=d.value,Ie=we?z(oe.unstable_getSerialization("experiments")):null,Re=void 0!==g&&g===j(Ie),Me=Q.activeSession.value,De=Ne.isCaliforniaDeceleration&&Ne.hasSubscription&&!b&&!_.aborted&&"APPLE_PAY"===Me?.wallet&&!Me.asPaymentMethod&&Ne.isABTestActive&&Re,Le={...Ne,shouldDecelerate:Ne.shouldDecelerate&&!De};if(we){const e=null!==Ie,t=function(e){return e.shouldDecelerate?e.isCaliforniaDeceleration?"california":"decelerated":"none"}(Le);k.counter({name:"apple_pay_subscriptions_deceleration_variant",value:1,attributes:{variant:Ie??G.Control,complete_payment_status:"success",is_ab_test_active:X.hasFlagEnabled(x),is_california_excluded:Le.isCaliforniaDeceleration,has_caution_banner:!1,deceleration_scope:t,is_enrolled:e,as_payment_method:b}})}if(Le.shouldDecelerate){if(se.value&&!(await Ce(_,U)))return;if(Q.setEscalatedWallet("APPLE_PAY"),Q.setIsDecelerating(!0),!F(n,{action:"decelerate",completePaymentStatus:ApplePaySession.STATUS_SUCCESS,effects:[]}))return Q.setEscalatedWallet(null),Q.setIsDecelerating(!1),Q.setHasActiveApplePaySubscriptionReview(!1),void(T.value=void 0);if(T.value="in_app_deceleration",Q.setHasActiveApplePaySubscriptionReview(!0),P)try{await be({wallet:"APPLE_PAY",reason:"subscriptions",asPaymentMethod:b})}catch(Fe){T.value=void 0,Fe instanceof Error&&e({session:n,error:Fe})}return}const Oe=C?.value;if(Oe&&!(await Oe()))return k.leaveErrorBreadcrumb("ApplePay: Pre-completion handler failed",{asPaymentMethod:b}),void U();v.value=!0;let Be=0,Ye="",xe="unexpected error",Ue=[];const ke=ze(s.current.fields.deliveryNext?.value);try{k.leaveErrorBreadcrumb("ApplePay: Payment authorized negotiation",{retryCount:Be});const e=_e.value;for(;;){let t=!1;if(_.aborted)break;if(await a("apple-pay-payment-authorized",(a=>{const o=a;"rejected"===o.status&&(Ue=o.violations.map((e=>e.code)),o.violations.some((e=>"BUYER_IDENTITY_MISSING_CONTACT_METHOD"===e.code))&&k.log("apple_pay_on_payment_authorized","Apple Pay is missing contact method",{asPaymentMethod:y.value,proposedEmail:ve.value||"",customerProfileEmail:p?.email||"",shippingContactEmail:ye?.emailAddress||"",hasShippingContact:Boolean(ye),shippingContactPhone:ye?.phoneNumber||"",allViolationCodes:o.violations.map((e=>e.code)).join(","),isPhoneRequired:he}));const r="rejected"===o.status&&o.violations.some((e=>e.code===D)),{shouldRetry:i,retryReason:l,updatedDeliveryMethodHandles:d}=va(o,{retryCount:Be,negotiated:s,originalSelectedDeliveryMethods:ke});if(i&&!r)return d&&(ht(Pe,d),Y===J.Express&&(k.log("wallets_shipping_address_update","onPaymentAuthorized: restoring address snapshot on retry",{isSnapshotPostalCodePadded:H(e?.postalCode,e?.countryCode),countryCode:e?.countryCode,retryCount:Be}),me||(_e.value=e))),k.leaveErrorBreadcrumb(`ApplePay: retrying due to ${l}`,{retryCount:Be}),Be++,Ye=l,void(t=!_.aborted);k.leaveErrorBreadcrumb("ApplePay: completed negotiation",{action:"paymentAuthorized",status:a.status,retryCount:Be,retryReason:Ye});const c=R(o,{shippingCountryCode:Vt(ye?.countryCode),billingCountryCode:Vt(ce?.countryCode),...B&&{options:{applePayRecoveryFlowEnabled:B,asPaymentMethod:y.value}}});F(n,c),xe=a.status}),{skipToCompletion:!0,customizeCompletion:Y===J.Express?Ge:void 0}),!t)break}P&&await be({wallet:"APPLE_PAY",reason:"submitForCompletion",asPaymentMethod:b})}catch(Fe){Fe instanceof Error&&e({session:n,error:Fe})}finally{v.value=!1,Be>0&&(k.counter({name:"wallet_submit_for_completion_retry",value:1,attributes:{retry_reason:Ye||"unknown",retry_count:Be,status:xe,instrument:W.ApplePay}}),k.log("wallet_submit_for_completion_retry_details","[ApplePay] SubmitForCompletion retry details",{retryReason:Ye,retryCount:Be,status:xe,instrument:W.ApplePay,asPaymentMethod:b,lastRejectionViolationCodes:Ue}))}}),[y,re,I,h,m,f,s,d,u,O,w,e,pe,L,M,t,ue,Ae,l,p?.email,c,_e,ve,Pe,ge,a,Ce,R,Ee,Q,k,N,de,be,se,ae,S,C,T,le,me,Se,Z,ne,oe,X,r,i])}function ma(e,t,a){const o=oa(t,a),n=e.fields.line2;e.value={...Ft(t),...o},n&&"line2"in o&&(n.value=o.line2)}function va(e,{retryCount:t,negotiated:a,originalSelectedDeliveryMethods:o}){const n={shouldRetry:!1,retryReason:"",updatedDeliveryMethodHandles:void 0};if("rejected"!==e.status||t>=1)return n;const r=Qe(e,a.current.fields.deliveryNext?.peek(),o);return r?{shouldRetry:!0,retryReason:"delivery_option_mismatch",updatedDeliveryMethodHandles:r}:n}function _a(){const e=la();return o(((t,a)=>{const{negotiationResultMapper:o}=e();if(!o)throw new ie("NegotiationResultMapper not set up correctly",{groupingHash:"ApplePayAPIError::NegotiationResultMapper"});return o.mapResultToPaymentSheetAction(t,a)}),[e])}function Aa(){const e=Xt(),t=v(),{checkout:{wallets:a},observability:n}=t;return o((({session:t,paymentSheetAction:o,onProceed:r,abortSignal:i})=>{switch(o.action){case"abort":ua({methodName:"abort",abortSignal:i,wallets:a,observability:n},(()=>t.abort())),a.clearActiveSession({invokingWallet:"APPLE_PAY"}),e();break;case"update":r(o.errors);break;case"no-op":r();break;default:throw new ie(`Missing handler for payment sheet action "${o.action}"`,{groupingHash:"ApplePayAPIError::MissingHandlerPaymentSheetAction"})}}),[e,a,n])}function ga(){const e=ea(),t=g(),a=$(W.ApplePay),{inMemoryApplePayParts:{asPaymentMethod:n,paymentSheetError:i,prefetchPaymentSession:s}}=P(),{shop:l,source:{sourceId:p},observability:d,embed:c,graphql:{coreGraphql:u}}
1=v(),{countryCode:y}=l,h=Ht({embed:c,isCrossOriginIframeEnabled:l.hasFlagEnabled(Q)}),m=function(){const{checkout:e,observability:t}=v(),a=e.configuration.addressSettings.nonBillingAddressSettings.value,n=et(),r=_(),i=a.isRequired("phone",{countryCode:Vt(r.buyerIdentity.value?.countryCode)}),s=tt(),{value:l}=r.deliveryNext,p=A(),d=g(),c=at(),{paymentDue:u,recurringTotals:y,...h}=ce(d),m=$t(),{deliveryMethodTitlePrefixes:f,connectTwoShippingTitles:b}=m,S=r.availableDeliveryAddresses?.value,C=r.mustSelectProvidedAddress?.value,{inMemoryApplePayParts:{asPaymentMethod:T,requirePhoneOnNextAttempt:N,requireBillingPhoneOnNextAttempt:w}}=P();return o(((e,a)=>{const o=T.value,r=N.value||w.value,d=Boolean(p.shopPayArtifact.value?.optIn),v=Boolean(p.email.value);r&&t.counter({name:"apple_pay_phone_retry_requested",value:1,attributes:{addressSettingsPhoneRequired:i,asPaymentMethod:o}});const _=E({availableDeliveryAddresses:S,mustSelectProvidedAddress:C}),A=o||_,{requiredShippingContactFields:g,requiredBillingContactFields:P}=function({phoneRequired:e,emailRequired:t,shippingRequired:a}){const o=["name","postalAddress"],n=[...e?["phone"]:[],...t?["email"]:[]];return{requiredShippingContactFields:a?[...o,...n]:n,requiredBillingContactFields:o}}({phoneRequired:Wt({asPaymentMethod:o,phoneRequired:i,shouldRequestPhoneOnRetry:r,shopPayOptInExists:d}),emailRequired:Jt({asPaymentMethod:o,emailRequired:n.value,shopPayOptInExists:d,proposedEmailExists:v}),shippingRequired:!A&&s.value}),I=kt(m.lineItemsLabels.total,u),R=Rt({...h,formattedRecurringTotals:c(y),...m}),M=A?[]:Dt({deliveryMethodTitlePrefixes:f,connectTwoShippingTitles:b,deliveryNext:l}),D={total:I,currencyCode:u.currencyCode,countryCode:a,lineItems:R,shippingMethods:M,shippingType:"shipping",merchantCapabilities:["supports3DS"],supportedNetworks:e,requiredShippingContactFields:g,requiredBillingContactFields:P};return zt(u.currencyCode)?function(e){const{lineItems:t,shippingMethods:a}=e;return{...e,total:jt(e.total),...t&&{lineItems:t.map(jt)},...a&&{shippingMethods:a.map(Qt)}}}(D):D}),[T,N,w,b,f,l,n,S,c,m,C,h,u,i,y,s,t,p])}(),S=function(){const e="apple-pay-gateway.apple.com/paymentservices/startSession";return"CN"===_t().geolocation.country.code?`https://cn-${e}`:`https://${e}`}(),C=function(){const e=$(W.ApplePay),{trackComplete:t}=Pt(W.ApplePay),a=ot(),{inMemoryApplePayParts:n}=P(),{checkout:r,observability:i,shop:s}=v(),l=nt();return o(((o,p)=>{o.abort(),n.prefetchPaymentSession.value=void 0;const d=p.value,c=n.asPaymentMethod.value,u=c?J.PaymentMethod:J.Express;gt.remove("apple-pay-sheet-load"),gt.exists("apple-pay-authorization")&&t({result:"failed",durationMs:gt.end("apple-pay-authorization"),walletType:u}),i.counter({name:"apple_pay_on_cancel",value:1,attributes:{completion_in_progress:d.toString(),wallet_type:u}}),i.counter({name:"wallet_sheet_cancelled",value:1,attributes:{instrument:W.ApplePay}}),i.log("apple_pay_use_on_cancel_sheet_cancelled","Apple Pay sheet cancelled",{completionInProgress:d,walletType:u}),n.requirePhoneOnNextAttempt.value&&i.counter({name:"apple_pay_cancelled_after_phone_retry",value:1,attributes:{asPaymentMethod:c}});const y=f(s),h=s.hasFlagEnabled(b),m=void 0!==n.subscriptionReviewTransition.value&&Xe({applePaySubscriptionsDecelerationActive:y,applePayThreePageVaultedReviewEnabled:h,isOnePageCheckout:r.configuration.layout.isOnePage.value}),v=l.value||m;if(d)i.log("apple_pay_on_cancel_completion_in_progress","Apple Pay cancelled during completion - activeSession NOT cleared, expecting completion flow to handle cleanup",{asPaymentMethod:c,inRecoveryFlow:v}),n.paymentSheetError.value={type:"payment_cancelled_while_processing"};else{if(i.log("apple_pay_on_cancel_normal_path","Apple Pay cancelled - clearing activeSession",{asPaymentMethod:c,inRecoveryFlow:v}),"APPLE_PAY"===r.wallets.activeSession.value?.wallet&&r.wallets.clearActiveSession({invokingWallet:"APPLE_PAY"}),v)return;a()}e(K.Cancelled)}),[a,n.asPaymentMethod,n.paymentSheetError,n.subscriptionReviewTransition,n.requirePhoneOnNextAttempt,n.prefetchPaymentSession,t,e,i,s,r,l])}(),T=function(){const e=$(W.ApplePay),t=ea(),{shop:a,source:{sourceId:n},observability:r,checkout:{wallets:i},embed:s,graphql:{coreGraphql:l}}=v(),p=Ht({embed:s,isCrossOriginIframeEnabled:a.hasFlagEnabled(Q)}),{inMemoryApplePayParts:{prefetchPaymentSession:d}}=P(),c=vt(W.ApplePay);return o(((a,o,s,u)=>{const y=u===d.value?.prefetchUrl;r.histogram({name:"apple_pay_prefetch_session",value:gt.end("apple-pay-session-begin"),attributes:{prefetch:y?"success":"retried"}}),async function(){if(d.value)try{const e=await d.value.prefetchPromise;if(y&&e)return e;
1y&&!e?r.leaveErrorBreadcrumb("[ApplePay] session query prefetch returned no data - starting new validation query",{validationUrl:u,prefetchUrl:d.value?.prefetchUrl}):y||r.leaveErrorBreadcrumb("[ApplePay] session query prefetch URL mismatch - starting new validation query",{validationUrl:u,prefetchUrl:d.value?.prefetchUrl})}catch(e){if(e instanceof oe)return;r.log("apple_pay_on_validate_merchant","Apple Pay prefetch session error",{error:e,prefetchValidationUrl:d.value?.prefetchUrl,validationUrl:u})}return r.leaveErrorBreadcrumb("[ApplePay] starting new session query",{hadPrefetch:Boolean(d.value),validationUrl:u}),wt({graphql:l,sourceId:n,validationUrl:u,asPaymentMethod:o,signal:s,observability:r,isPrefetch:!1,domain:p})}().then((n=>{if(d.value=void 0,n instanceof Tt)return r.leaveErrorBreadcrumb("[ApplePay] Validation query returned failed response",{reason:n.reason}),r.log("apple_pay_on_validate_merchant","Apple Pay session creation failed",{reason:n.reason}),void t({session:a,error:new ne(n.reason)});if(n)e(K.Success,o?J.PaymentMethod:J.Express),o||c(),ua({methodName:"completeMerchantValidation",abortSignal:s,wallets:i,observability:r},(()=>a.completeMerchantValidation(JSON.parse(n.body))));else{const e=s.aborted,n="APPLE_PAY"===i.activeSession.value?.wallet;r.leaveErrorBreadcrumb("[ApplePay] Validation query returned no data",{asPaymentMethod:o,isAborted:e,isActiveApplePaySession:n});const l=e||!n?new ne("Apple Pay session query returned no data after session was cancelled"):new ie("session query returned no data");t({session:a,error:l,isAborted:e})}})).catch((e=>{t({error:e,session:a,isAborted:s.aborted})}))}),[l,n,r,e,c,t,d,i,p])}(),N=function(){const{observability:e,checkout:{wallets:t,address:{countryDetails:a,extendedAddressMode:n}},checkout:r,shop:i}=v(),s=aa(i),l=ea(),p=Xt(),d=_a(),c=at(),u=g(),y=ee(W.ApplePay),h=Ze(),{formattedRecurringTotalTooltip:m,lineItemsLabels:_,deliveryOptionGroupTypeLabels:A,deliveryMethodTitlePrefixes:P}=$t();return o((async(o,i,v,g)=>{const{billingContact:E}=o.paymentMethod;if(!r.isShippingRequired.value&&E){e.leaveErrorBreadcrumb("ApplePay: Payment method selected negotiation");try{s&&await a.fetch(Vt(E.countryCode)),await h({abortSignal:v,fieldsToResolve:["duties","taxes"],customizeNegotiation:e=>((e,t,{deliveryAddressOptions:a,extendedAddressFieldsEnabled:o=!1}={})=>function(e,t,{interfaceFlow:a,isConstrainedAddress:o=!1,deliveryAddressOptions:n}={}){return o?e:{...e,delivery:{...e.delivery,interfaceFlow:a,useProgressiveRates:!1,deliveryLines:(e.delivery?.deliveryLines??[]).map((e=>({...e,destination:{partialStreetAddress:bt(t,n)}})))}}}(e,{...Ft(t),...oa(t,o)},{interfaceFlow:"APPLE_PAY",deliveryAddressOptions:a}))(e,E,{deliveryAddressOptions:{extendedAddressMode:n},extendedAddressFieldsEnabled:s}),observability:e,onComplete:function(a){if(t.activeSession.value&&!v.aborted&&(e.leaveErrorBreadcrumb("ApplePay: completed negotiation",{action:"paymentMethodSelected",status:a.status}),E)){const o=d(a,{billingCountryCode:Vt(E.countryCode)});o.effects?.forEach((e=>e())),"abort"===o.action&&(e.log("apple_pay_on_payment_method_selected","[ApplePayButton.session.onpaymentmethodselected] session aborted due to blocking error",{errors:o.errors,session:i}),ua({methodName:"abort",abortSignal:v,wallets:t,observability:e},(()=>i.abort())),t.clearActiveSession({invokingWallet:"APPLE_PAY"}),p())}},walletName:W.ApplePay,logPrefix:"ApplePay::useOnPaymentMethodSelected"})}catch(f){f instanceof Error&&l({session:i,error:f})}}if(i&&t.activeSession.value){if(g&&!(await async function(a){let o=!1;try{o=await a(v)}catch(f){return f instanceof Error&&l({session:i,error:f}),!1}return v.aborted||!t.activeSession.value?(e.leaveErrorBreadcrumb("ApplePay: session ended while waiting for totals to settle"),!1):(o||(e.leaveErrorBreadcrumb("ApplePay: totals did not settle before payment method selection"),l({session:i,error:new ie("Payment method selection reconciliation timed out",{groupingHash:"ApplePayAPIError::PaymentMethodSelectionReconciliationTimeout"})})),o)}(g)))return;!function(){const{paymentDue:a,recurringTotals:o,...n}=ce(u);
1if(null==a)return l({session:i,error:new ie("Missing negotiated payment due",{groupingHash:"ApplePayAPIError::MissingNegotiatedPaymentDue"})});const r=zt(a.currencyCode);try{ua({methodName:"completePaymentMethodSelection",abortSignal:v,wallets:t,observability:e},(()=>{const e={newTotal:kt(_.total,a),newLineItems:Rt({...n,formattedRecurringTotals:c(o),formattedRecurringTotalTooltip:m,lineItemsLabels:_,deliveryOptionGroupTypeLabels:A,deliveryMethodTitlePrefixes:P})};i.completePaymentMethodSelection(r?Zt(e):e)}))}catch(f){f instanceof Error&&l({error:f,session:i})}}()}r.isShippingRequired.value||gt.endAndRun("apple-pay-sheet-load",(t=>{y({event:te.SheetLoaded,ttl:t}),e.histogram({name:"wallet_sheet_loaded",value:t,attributes:{instrument:W.ApplePay}})}))}),[t,p,P,A,c,m,d,_,u,r.isShippingRequired,e,l,y,h,n,a,s])}(),w=function(){const e=ea(),t=at(),a=_a(),n=g(),r=mt(),{observability:i,checkout:{wallets:s,address:{countryDetails:l,extendedAddressMode:p}},shop:d}=v(),c=aa(d),{inMemoryApplePayParts:{initialDeliveryIdentifier:u}}=P(),{deliveryLines:y,shippingAddress:h}=A(),m=ee(W.ApplePay),f=Ze(),b=_(),S=b.availableDeliveryAddresses?.value,C=b.mustSelectProvidedAddress?.value,T=b.deliveryNext?.value,N=E({availableDeliveryAddresses:S,mustSelectProvidedAddress:C}),{formattedRecurringTotalTooltip:w,lineItemsLabels:I,deliveryOptionGroupTypeLabels:R,deliveryMethodTitlePrefixes:M}=$t(),D=Aa();return o((async(o,d,v)=>{const _=u.value;u.value=void 0;const A=o.shippingMethod.identifier===_;i.counter({name:"apple_pay_skip_initial_delivery_negotiation",value:1,attributes:{skippedNegotiation:A}}),!A&&_&&i.log("apple_pay_on_shipping_method_selected","Apple Pay failed to skip initial delivery negotiation",{expectedHandle:_,actualHandle:o.shippingMethod.identifier});const g=t=>{try{return We(t)}catch(a){return e({session:d,error:new ie("Invalid shipping method identifier",{groupingHash:"ApplePayAPIError::InvalidShippingMethodIdentifier",cause:a,metadata:{identifier:t}})}),null}};if(A){const e=g(_);if(null==e)return;return ht(y,e),void b(d)}const P=h.value,E=g(o.shippingMethod.identifier);if(null!=E){ht(y,E),i.leaveErrorBreadcrumb("ApplePay: Shipping method selected negotiation",{handles:JSON.stringify(E),identifier:o.shippingMethod.identifier});try{c&&await l.fetch(P.countryCode),await f({abortSignal:v,fieldsToResolve:["deliveryNext","duties","taxes"],customizeNegotiation:e=>$e(e,P,{interfaceFlow:"APPLE_PAY",isPickupSelected:r.value,isConstrainedAddress:N,availableDeliveryAddresses:S,negotiatedDelivery:T,deliveryAddressOptions:{extendedAddressMode:p}}),observability:i,walletName:W.ApplePay,onComplete:function(t){if(s.activeSession.value&&!v.aborted){i.leaveErrorBreadcrumb("ApplePay: completed negotiation",{action:"shippingMethodSelected",status:t.status});try{const e=a(t,{shippingCountryCode:P.countryCode});e.effects?.forEach((e=>e())),i.leaveErrorBreadcrumb("ApplePay: Payment sheet action",{action:"shippingMethodSelected",paymentSheetAction:e.action}),D({session:d,paymentSheetAction:e,onProceed:()=>b(d),abortSignal:v})}catch(o){o instanceof Error&&e({error:o,session:d})}}},logPrefix:"ApplePay::useOnShippingMethodSelected"})}catch(C){e({session:d,error:C})}}function b(a){const{paymentDue:o,recurringTotals:r,...l}=ce(n);if(null==o)return e({session:a,error:new ie("Missing negotiated payment due",{groupingHash:"ApplePayAPIError::MissingNegotiatedPaymentDue"})});const p=zt(o.currencyCode);try{ua({methodName:"completeShippingMethodSelection",abortSignal:v,wallets:s,observability:i},(()=>{const e={newTotal:kt(I.total,o),newLineItems:Rt({...l,formattedRecurringTotals:t(r),formattedRecurringTotalTooltip:w,lineItemsLabels:I,deliveryOptionGroupTypeLabels:R,deliveryMethodTitlePrefixes:M})};a.completeShippingMethodSelection(p?Zt(e):e)})),gt.endAndRun("apple-pay-sheet-load",(e=>{m({event:te.SheetLoaded,ttl:e}),i.histogram({name:"wallet_sheet_loaded",value:e,attributes:{instrument:W.ApplePay}})}))}catch(C){C instanceof Error&&e({error:C,session:a})}}}),[s,M,R,t,w,a,D,r,I,n,y,h,e,i,m,u,f,N,S,T,l,c,p])}(),I=function(){const e=ea(),t=at(),a=_a(),n=g(),r=mt(),{inMemoryApplePayParts:{initialDeliveryIdentifier:i,asPaymentMethod:s}}=P(),{deliveryLines:l,shippingAddress:p}=A(),d=Ze(),c=_(),u=c.availableDeliveryAddresses?.value,y=c.mustSelectProvidedAddress?.value,h=c.deliveryNext?.value,m=E({availableDeliveryAddresses:u,mustSelectProvidedAddress:y}),f=v(),{checkout:{wallets:b,address:S},observability:C}=f,{countryDetails:T,extendedAddressMode:N}=S,w=aa(f.shop),{formattedRecurringTotalTooltip:I,lineItemsLabels:R,deliveryOptionGroupTypeLabels:M,deliveryMethodTitlePrefixes:D,connectTwoShippingTitles:L}=$t(),O=Aa(),{shouldGateCrossBorder:B,crossBorderGate:Y}=ae(),x=ut(s);return o((async(o,s,c)=>{const y={...Ft(o.shippingContact),...oa(o.shippingContact,w)};C.log("wallets_shipping_address_update","onShippingContactSelected: update with partial shipping address",{countryCode:y.countryCode,isPostalCodePadded:H(y.postalCode,y.countryCode)}
1);const v=o.shippingContact.countryCode?Vt(o.shippingContact.countryCode):void 0;if(ht(l,void 0),i.value=void 0,B(v)){C.log("apple_pay_cross_border_gate","Apple Pay shipping country creates a cross-border split. Closing the payment sheet and opening the consolidation modal.",{shippingCountryCode:v});try{e({session:s,isMessagingHandledElsewhere:!0,error:new ne("Session terminated due to cross-border shipping country change")})}catch(A){C.leaveErrorBreadcrumb("ApplePay: failed to abort session for cross-border gate",{errorName:A instanceof Error?A.name:"Unknown",errorMessage:A instanceof Error?A.message:String(A)})}Y((()=>{p.fields.zoneCode.value=void 0,p.fields.coordinates.value=void 0,p.fields.countryCode.value=v}))}else if(m)_(s);else{p.value=y,C.leaveErrorBreadcrumb("ApplePay: Shipping contact selected negotiation",{countryCode:y.countryCode,isPostalCodePadded:H(y.postalCode,y.countryCode)});try{w&&await T.fetch(y.countryCode),await d({abortSignal:c,fieldsToResolve:["deliveryNext","duties","taxes"],customizeNegotiation:e=>$e(e,y,{interfaceFlow:"APPLE_PAY",isPickupSelected:r.value,isConstrainedAddress:m,availableDeliveryAddresses:u,negotiatedDelivery:h,deliveryAddressOptions:{extendedAddressMode:N}}),observability:C,walletName:W.ApplePay,onComplete:function(e){const t=x.value;if(!b.activeSession.value)return;if(c.aborted)return;C.leaveErrorBreadcrumb("ApplePay: completed negotiation",{action:"shippingContactSelected",status:e.status});const n=a(e,{shippingCountryCode:Vt(o.shippingContact.countryCode),...t&&{options:{applePayRecoveryFlowEnabled:t}}});n.effects?.forEach((e=>e())),C.leaveErrorBreadcrumb("ApplePay: Payment sheet action",{action:"shippingContactSelected",paymentSheetAction:n.action}),O({session:s,paymentSheetAction:n,onProceed:e=>_(s,e),abortSignal:c})},logPrefix:"ApplePay::useOnShippingContactSelected"})}catch(A){A instanceof Error&&e({session:s,error:A})}}function _(a,o){const{paymentDue:r,recurringTotals:s,deliveryNext:l,...p}=ce(n);if(null==r)return e({session:a,error:new ie("Missing negotiated payment due",{groupingHash:"ApplePayAPIError::MissingNegotiatedPaymentDue"})});const d=zt(r.currencyCode);try{const e={newTotal:kt(R.total,r),newLineItems:Rt({...p,formattedRecurringTotals:t(s),formattedRecurringTotalTooltip:I,lineItemsLabels:R,deliveryOptionGroupTypeLabels:M,deliveryMethodTitlePrefixes:D})},n=Dt({deliveryMethodTitlePrefixes:D,connectTwoShippingTitles:L,deliveryNext:l}),u={...e,newShippingMethods:n};ua({methodName:"completeShippingContactSelection",abortSignal:c,wallets:b,observability:C},(()=>a.completeShippingContactSelection({errors:o,...d?Zt(u):u})));try{const e=function(e,t){if(t?.length||!e)return;if("filled"!==e.status||!e.lines?.length)return;const a=e.lines.reduce(((e,t)=>("available"===t.status&&t.selectedDeliveryMethodHandle&&e.push(t.selectedDeliveryMethodHandle),e)),[]);return a.length<e.lines.length?void 0:a}(l,o);if(!e)return;const t=n.find((t=>e.every((e=>t.identifier.includes(e)))))?.identifier;t&&(i.value=t)}catch(A){C.error(A)}}catch(A){A instanceof Error&&e({error:A,session:a})}}}),[l,p,r,a,O,n,e,R,t,I,M,D,L,i,d,b,C,x,m,u,h,B,Y,w,T,N])}(),R=ha();return o((({asPaymentMethod:o=!1,supportedNetworks:l,waitForTotalsToSettle:c,isPaymentAuthorizationBlocked:v,subscriptionConsent:_})=>{gt.start("apple-pay-session-begin"),i.value=void 0,n.value=o;const A=r(!1),g=new AbortController,{paymentDue:P}=ce(t);if(!P)return a(K.Failure,o?J.PaymentMethod:J.Express),i.value={type:"session_terminated"},d.error(new ie("Missing paymentDue",{groupingHash:"ApplePayAPIError::MissingPaymentDue"}),{severity:"error",errorClass:rt.Api}),{session:void 0,error:"no_payment_due"};let E;s.value||(s.value={prefetchPromise:(async()=>(await Promise.resolve(),wt({graphql:u,sourceId:p,validationUrl:S,asPaymentMethod:o,signal:g.signal,observability:d,isPrefetch:!0,domain:h})))(),prefetchUrl:S});const f=m(l,y);try{E=new ApplePaySession(Z,f)}catch(b){return b instanceof Error&&e({error:b}),{session:void 0,error:"session_creation_failed"}}return E.oncancel=()=>C(g,A),E.onvalidatemerchant=e=>T(E,o,g.signal,e.validationURL),E.onpaymentmethodselected=e=>N(e,E,g.signal,c),E.onshippingmethodselected=e=>w(e,E,g.signal),E.onshippingcontactselected=e=>I(e,E,g.signal),E.onpaymentauthorized=e=>R(e,E,A,g.signal,v,_),{session:E,error:void 0}}),[n,m,t,i,C,R,N,I,w,T,y,e,a,s,S,u,d,p,h])}function Pa(){const{inMemoryApplePayParts:{asPaymentMethod:e,expiresAt:t}}=P(),{observability:a,checkout:{wallets:n}}=v(),r=ut(e);return o((o=>
1{if(o){gt.start("apple-pay-sheet-load"),a.counter({name:"apple_pay_button_click",value:1,attributes:{wallet_type:e.value?J.PaymentMethod:J.Express}}),a.counter({name:"wallet_sheet_clicked",value:1,attributes:{instrument:W.ApplePay}});try{o.begin()}catch(i){if(i instanceof Error&&"InvalidAccessError"===i.name)return void a.log("apple_pay_session_begin_error","Apple Pay session.begin() failed from insecure context",{errorName:"InvalidAccessError"});throw i}r.value&&(t.value=new Date(Date.now()+3e5).toISOString()),n.setActiveSession({newValue:"APPLE_PAY",asPaymentMethod:e.value})}}),[e,a,n,r,t])}const Ea=new Set(M);function fa(){const{applePaySessionHandler:e,inMemoryApplePayParts:t}=P(),a=At(function(){const{negotiate:e}=st(),{observability:t,shopPay:a,checkout:{wallets:o,identity:n}}=v(),r="shopPay"===n.current.value,{inMemoryApplePayParts:{isLoadingPaymentSheet:i,paymentSheetError:s}}=P(),l=r?W.ShopPayApplePay:W.ApplePay,p=ga(),d=$(l),c=St(),u=nt(),{shopOfferReconciliationPending:y}=a,h=Pa(),m=_().paymentMethods?.value,A=m?.find((e=>"wallet"===e.type&&"APPLE_PAY"===e.name)),g=A?.supportedNetworks,E=e=>{if(!y.value)return Promise.resolve(!0);t.counter({name:"apple_pay_shop_offer_reconciliation_wait",value:1});const a=Date.now();return function(e,t){return t.aborted?Promise.resolve(!1):e.value?new Promise((a=>{let o=!1,n=()=>{};const r=e=>{o||(o=!0,n(),t.removeEventListener("abort",i),clearTimeout(s),a(e))},i=()=>r(!1);t.addEventListener("abort",i,{once:!0});const s=setTimeout(i,5e3);n=e.subscribe((e=>{e||r(!0)})),o&&n(),t.aborted&&i()})):Promise.resolve(!0)}(y,e).then((e=>(t.histogram({name:"apple_pay_shop_offer_reconciliation_wait_duration",value:Date.now()-a,attributes:{reconciled:e}}),e)))};return async({disabled:a=!1,isMountedRef:n,validateButtonPress:l})=>{if(!a){d(K.Clicked,J.PaymentMethod);try{const a=p({asPaymentMethod:!0,supportedNetworks:g||[],waitForTotalsToSettle:E,isPaymentAuthorizationBlocked:()=>y.value}),d=await(async a=>{i.value=!0;try{if(r){if(!a||!a())return!1;c()}const o=await new Promise(((t,a)=>{e({runListenersOnError:!0,negotiationStage:"completion",include:["deliveryNext"],onComplete:t}).catch(a)})),n=u.value&&"error"===o.status&&o.violations.length>0&&o.violations.every((({code:e})=>Ea.has(e)));return n&&(t.counter({name:"apple_pay_silenced_violations_requiring_new_token",value:1}),t.log("apple_pay_silenced_violations","PayWithApplePayButton: silenced violations",{violations:o.violations})),"success"===o.status||n}catch{return s.value={type:"failed_to_create_session"},!1}finally{i.value=!1}})(l),m=!n||n.current;d&&!o.activeSession.value&&m&&h(a.session)}catch(m){t.leaveErrorBreadcrumb("Failed to create Apple Pay session",{error:m,shopPay:r}),s.value={type:"failed_to_create_session"},"APPLE_PAY"===o.activeSession.value?.wallet&&o.clearActiveSession({invokingWallet:"APPLE_PAY"})}}}}()),o=At(ga()),n=At(Pa());return i((()=>{if(t.sessionLoadFailed.value)return;const r={onClickHandler:(...e)=>a.current(...e),createSession:(...e)=>o.current(...e),showApplePayPaymentSheet:(...e)=>n.current(...e)};return e.value=r,()=>{e.value=void 0}}),[e,a,o,n,t]),null}export{fa as ApplePaySessionLoader};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.