PageSourceSearch

https://paopao-essentials.de/cdn/shopifycloud/checkout-web/assets/c1/d08a6c7d.MCuREdbu.js

js paopao-essentials.de collected 2026-10-05 20:47:27 UTC 71,238 bytes, 1 lines download raw bytes

1import{a4 as e,a5 as t,T as a,q as o,k as n,y as r,h as i}from"./2c1ab0fe.RaLGJvq2.js";import{i as s,g4 as l,g3 as d,gb as p,ar as c,ao as u,d7 as y,aK as h,a as m,_ as v,g5 as _,bW as A,g_ as g,g$ as P,h0 as f,gu as E,a$ as b,c_ as S,h1 as C,d5 as T,d6 as N,h2 as w,g6 as I,g7 as M,aJ as R,h3 as D,h4 as L,fJ as O,fr as B,h5 as Y,a3 as x,au as k,cq as U,h6 as F,h7 as V,h8 as H,h9 as q,ha as z,hb as j,hc as G}from"./f67abd2c.BTHhdhoM.js";import{a as Q,b as $,c as Z,W}from"./78ab3dd0.DVuP3OIA.js";import{u as J,i as K}from"./app.CPIYcwpp.js";import{a as X,I as ee,W as te,b as ae}from"./d4ea2faa.CUbB3413.js";import{f as oe,g as ne,s as re,r as ie,B as se,P as le,U as de,a as pe,w as ce,x as ue,i as ye,N as he,E as me,h as ve,y as _e,z as Ae,A as ge,C as Pe,F as fe,G as Ee,l as be,H as Se,J as Ce,K as Te,L as Ne,M as we,j as Ie,T as Me,O as Re,Q as De,D as Le,V as Oe,I as Be,R as Ye,u as xe,m as ke,n as Ue,o as Fe,W as Ve,p as He,q as qe,t as ze,v as je}from"./13b13169.DRhAkbty.js";import{a as Ge,g as Qe,i as $e}from"./e12db40c.CeuzD2R-.js";import{fC as Ze,gx as We,gy as Je,gz as Ke,bx as Xe,gA as et,ch as tt,r as at,j as ot,fF as nt,g4 as rt,fD as it,gf as st,gB as lt,g3 as dt,dG as pt,fq as ct,ct as ut,g as yt}from"./164ad2e3.bPUx3Fg0.js";import{b as ht}from"./2b94e6ef.DMADjiM6.js";import{b as mt,c as vt,u as _t,a as At}from"./ed9f2238.LhdxRD0S.js";import{u as gt,a as Pt,g as ft}from"./33464469.D4VYuHzY.js";import{d as Et}from"./b8733b27.DyQMMnlU.js";import{d as bt}from"./7fc410e0.DLP-84MU.js";import{u as St}from"./ec391382.Djhp_AZL.js";import"./22345fd4.BOPeNj8v.js";import"./cdfd59e6.D3c62CGi.js";import"./d0bb51ec.BIqtCEEY.js";import"./60a453ce.BHWO3gHr.js";import"./9dba8418.DCzpk36x.js";import"./24773686.DFsBOEme.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:s,isPrefetch:l,domain:d})=>{const p=(({sourceId:e,isPrefetch:t})=>t?`${e}-prefetch-${J()}`:`${e}-${J()}`)({sourceId:o,isPrefetch:l}),c=async e=>{const{data:t,error:o}=await a.staticQuery(Ct,{cache:!1,variables:e?{pendingTask:{taskId:e}}:{applePaySessionCreate:{resourceId:p,validationUrl:n,domain:d,walletInstrumentation:{expressWalletInCheckout:!r}}}});if(o)throw s.leaveErrorBreadcrumb("[ApplePay] session creation query returned GraphQL error",{error:o}),new Nt("session creation query returned GraphQL error");return t||(s.counter({name:"apple_pay_session_query_error",value:1,attributes:{reason:"no_data"}}),s.log("apple_pay_api_query","ApplePaySession: No data returned"),void s.leaveErrorBreadcrumb("[ApplePay] session creation query returned no data"))};function u({result:e,pollingCount:t}){s.histogram({name:"apple_pay_session_creation",value:performance.now()-m,attributes:{result:e,pollingCount:t,isPrefetch:l}})}let y="",h=0;const m=performance.now();try{for(;;){if(i.aborted)throw new X("Apple pay signal aborted",{groupingHash:"AbortedSessionError::createPaymentSession::SignalAborted"});const a=performance.now(),n=await c(y);if(!n)return;const r=n.applePaySession;switch(r.__typename){case"ApplePaySessionCreationSuccess":return u({result:"success",pollingCount:h}),r;case"ApplePaySessionCreationFailed":if(u({result:"failed",pollingCount:h}),s.log("apple_pay_api_session_cancelled","Apply Pay session creation failed",{pollingCount:h,error:r?.code,resourceId:p}),"FAILURE_RESPONSE_FROM_WALLET_PROVIDER"===r.code)throw new te(`ApplePaySession Query error: fail to create apple pay session with ${r.code}`);if("NO_PENDING_TASK"===r.code)return s.counter({name:"apple_pay_no_pending_task_error",value:1,attributes:{pollingCount:h,sourceId:o,isPrefetch:l}}),s.log("apple_pay_api_session_cancelled","Apply Pay session has no pending task",{pollingCount:h,sourceId:o,isPrefetch:l}),void s.leaveErrorBreadcrumb("[ApplePay] session creation failed with NO_PENDING_TASK",{pollingCount:h,sourceId:o,isPrefetch:l});if(l)return;throw new ae(`ApplePaySession Query error: fail to create apple pay session with ${r.code}`,{groupingHash:"ApplePayAPIError::QueryError::FailToCreateSession"});case"PendingTask":if(!y){const e=600-(performance.now()-a);e>0&&await t(e)}if(y=r.taskId,h++,h>=9)throw s.log("apple_pay_api_session_cancelled","Apple Pay polling session reached maximum amount of polls",{pollingCount:h,flightDelay:performance.now()-a}),new ee("ApplePaySession Query error: reached maximum amount of polls");if(h<=5)break;await t(r.pollDelay);break;default:e(r)}}}catch(v){if(v instanceof Nt||v instanceof te)return s.counter({name:"apple_pay_session_query_error",value:1,attributes:{reason:v.name}}),new Tt(`${v.name}: ${v.message}`);throw v}},It={EG:"EG",AE:"AE"};
1function Mt({subtotal:e,duties:t,taxes:a,deliveryNext:o,discountLines:n,paymentLines:r,tipLines:i,shopPromotion:s,lineItemsLabels:l,deliveryOptionGroupTypeLabels:c,deliveryMethodTitlePrefixes:u,formattedRecurringTotals:h,formattedRecurringTotalTooltip:m,merchandiseLines:v}){const _=[];v?.lines&&v.lines.forEach(e=>{_.push({label:ne(e),amount:oe(e.totalPrice.amount)})});const A=void 0===e?[]:[{label:l.subtotal,amount:e?oe(e.amount):void 0}],g=function({deliveryNext:e,deliveryOptionGroupTypeLabels:t,deliveryMethodTitlePrefixes:a}){const o=p(e);return o?o.map(({totalCost:e})=>({label:a.SHIPPING,amount:oe(e.amount)})):y(e).map(({line:e,method:o},n,r)=>({label:Rt(e,o,1===r.length,t,a),amount:oe(o.cost.amount)}))}({deliveryNext:o,deliveryOptionGroupTypeLabels:c,deliveryMethodTitlePrefixes:u}),P=t&&"available_total"===t?.status&&0!==t?.totalDuty.amount?[{label:l.duties,amount:oe(t.totalDuty.amount)}]:[],f=a&&"available_total"===a.status&&0!==a.totalTax.amount?[{label:l.taxes,amount:oe(a.totalTax.amount)}]:[],E=n&&n.lines.map(e=>{if(K(e)){const t=e.amount?.amount;if(t)return{label:e.title,amount:d(oe(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(oe(o))}]:[]})??[],T=r?.lines.filter(e=>"giftCard"===e.method.type).map(e=>e.cost?{label:l.giftCards,amount:d(oe(e.cost.amount))}:void 0).filter(e=>void 0!==e)||[],N=i&&i[0],w=N&&N.amount.amount>0?[{label:l.tip,amount:oe(N.amount.amount)}]:[],I=h?h.map(e=>({label:e,amount:"0.00",type:"pending"})):[],M=I.length>0&&m?[{label:m,amount:"0.00",type:"pending"}]:[];return[..._,...A,...g,...P,...f,...E,...C,...T,...w,...I,...M]}function Rt(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=p(a);if(o)return o.map(({totalTitle:e,totalCostAfterDiscounts:t,deliveryMethodHandles:a,deliveryPromisePresentmentTitle:o})=>({label:e,amount:oe(t.amount),detail:o?.short??"",identifier:JSON.stringify(a)}));const n=c(a).filter(u).map(Ge),r=function(e,t){if(!e||"filled"!==e.status||!h(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,Qe(n).filter(e=>e.length>0));return r.map(a=>({label:Bt(a,e,t),amount:Yt(a),detail:kt(a,t),identifier:re(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 oe(e.reduce((e,t)=>e+t.costAfterDiscounts.amount,0))}function xt(e,t){return e.add(t),e}function kt(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 Ut(e,t){return{label:e,amount:oe(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&&l.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(s(t))return t;return{UK:"GB",JA:"JP"}[t]||(l.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 jt(e){const t=Number(e);return Number.isFinite(t)?Math.ceil(Number(t.toFixed(2))).toFixed(2):e}function Gt(e){return{...e,amount:jt(e.amount)}}function Qt(e){return{...e,amount:jt(e.amount)}}function $t(e){const{newLineItems:t,newShippingMethods:a}=e;return{...e,newTotal:Gt(e.newTotal),...t&&{newLineItems:t.map(Gt)},...a&&{newShippingMethods:a.map(Qt)}}}function Zt(){const{i18n:e,shop:t}=m(),{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}=m(),t=vt(Q.ApplePay),{trackComplete:a}=gt(Q.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===Z.Attempt)return;if(!r)return void ht.remove("apple-pay-authorization");const i=o===Z.Success?"success":"failed";ht.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=Ke(),t=Kt(),{inMemoryApplePayParts:{asPaymentMethod:a}}=v();return o(()=>{const o=a.value?$.PaymentMethod:$.Express;e(),t({status:Z.Failure,walletType:o})},[t,e,a])}function ea(){const e=mt(Q.ApplePay),t=vt(Q.ApplePay),{trackComplete:a}=gt(Q.ApplePay),{checkout:{wallets:n},observability:r}=m(),{inMemoryApplePayParts:i}=v(),s=Ke();return o(({session:o,isProcessing:l=!1,isMessagingHandledElsewhere:d=!1,error:p,isAborted:c})=>{if(p instanceof X)return;ht.remove("apple-pay-sheet-load");const u=i.asPaymentMethod.value?$.PaymentMethod:$.Express;r.counter({name:"apple_pay_session_terminated",value:1,attributes:{error_type:p.name,wallet_type:u}}),r.log("apple_pay_terminate_session_session","Apple Pay session terminated",{wallet_type:u,error_type:p.name,error_message:p.message,error_cause:p.cause,error_stack:p.stack}),ht.exists("apple-pay-authorization")?(t(Z.Failure,u),a({result:"failed",durationMs:ht.end("apple-pay-authorization"),walletType:u})):(e(Z.Failure,u),r.counter({name:"wallet_sheet_failed",value:1,attributes:{instrument:Q.ApplePay}})),l||d||(i.paymentSheetError.value={type:"session_terminated"});const{actionable:y}=Et(p);if(p instanceof ee?r.leaveErrorBreadcrumb(`IgnoredApplePayAPIError: ${p.message}`):y?r.error(p,{severity:"error",errorClass:et.Api}):r.leaveErrorBreadcrumb("[ApplePay] Unactionable error",{error:p}),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(g)}function oa(e,t){return e.hasFlagEnabled(P)&&f.has(t)}function na(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 ra=[b.InvalidExtensionState,b.InvalidCaptcha,b.SubmittedForCompletion];class ia extends se{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 le({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 ae("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 le({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 ae(`violation not handled: ${e.code}`,{groupingHash:`ApplePayAPIError::ViolationNotHandled::${e.code}`}),{severity:"error",errorClass:et.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:Q.ApplePay,action:n?.action??"abort",asPaymentMethod:Boolean(a?.asPaymentMethod)}}),this.reportAddressRequirementMismatch({violationCode:r,wallet:Q.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),layout:a?.layout,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=>E.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:Q.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),layout:t?.layout,violationCode:a,violations:e.reasons.join(",")}),this.generateDecelerateAction()}return{action:o,effects:[()=>{this.inMemoryApplePayParts.paymentSheetError.value={type:e.reasons.includes(b.InvalidCaptcha)?"captcha_required":"exceptional_completion_status"}}]}},stale:()=>(this.observability.error(new ae("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:[...S,"MERCHANDISE_NOT_APPLICABLE",...de,...C,...pe,ce,ue],generateAction:()=>({action:"abort"})},{violations:ye,generateAction:()=>this.generateAbortAction("session_terminated")},{violations:he,generateAction:()=>this.generateAbortAction("shipping_options_changed")},{violations:me,generateAction:()=>la("emailAddress",this.translations.emailInvalidError)},{violations:["BUYER_IDENTITY_CONTACT_INFO_DOES_NOT_MATCH_CUSTOMER_PROFILE"],generateAction:()=>this.generateAbortAction("unhandled_completion_status")},{violations:ve,generateAction:()=>la("phoneNumber",this.translations.phoneInvalidError)},{violations:["BUYER_IDENTITY_MISSING_CONTACT_METHOD","BUYER_IDENTITY_EMAIL_REQUIRED"],generateAction:()=>la("emailAddress",this.translations.contactInfoBlank)},...this.getCompletionDeceleratedViolationActions(e),{violations:[..._e],generateAction:()=>la("phoneNumber",this.translations.phoneInvalidError)},{violations:["PAYMENTS_PHONE_NUMBER_DOES_NOT_MATCH_EXPECTED_PATTERN"],generateAction:()=>sa("phoneNumber",this.translations.phoneInvalidError)},...this.getCompletionShippingAddressViolationActions(e,t),{violations:[...Ae,"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:ge,generateAction:()=>this.generateDecelerateAction()}]:[{violations:Pe,generateAction:()=>sa("name",this.translations.nameContainsEmojisError)},{violations:fe,generateAction:()=>sa("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",...T],generateAction:()=>sa("addressLines",this.translations.invalidBillingAddressError)},{violations:["PAYMENTS_LAST_NAME_CONTAINS_HTML_TAGS","PAYMENTS_LAST_NAME_CONTAINS_URL"],generateAction:()=>sa("name",this.translations.invalidBillingAddressError)},{violations:Ee,generateAction:()=>sa("name",this.translations.lastNameTooLongError)},{violations:["PAYMENTS_ADDRESS1_TOO_LONG","PAYMENTS_ADDRESS2_TOO_LONG"],generateAction:()=>sa("addressLines",this.translations.addressLineTooLongError)},{violations:[be],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:()=>sa("postalCode",this.translations.postalCodeInvalidError)},{violations:Se,generateAction:()=>sa("postalCode",this.translations.postalCodeEmojiError)},{violations:Ce,generateAction:()=>sa("postalCode",this.translations.postalCodeNotSupportedError)},{violations:["PAYMENTS_FIRST_NAME_REQUIRED"],generateAction:()=>sa("name",this.translations.firstNameBlank)},{violations:["PAYMENTS_LAST_NAME_REQUIRED"],generateAction:()=>sa("name",this.translations.lastNameBlank)},{violations:["PAYMENTS_ADDRESS1_REQUIRED"],generateAction:()=>sa("addressLines",this.translations.addressLine1Blank)},{violations:["PAYMENTS_CITY_REQUIRED"],generateAction:()=>sa("locality",this.translations.cityBlank)},{violations:["PAYMENTS_CITY_TOO_LONG","PAYMENTS_CITY_CONTAINS_MATHEMATICAL_SYMBOLS","PAYMENTS_CITY_CONTAINS_EMOJIS","PAYMENTS_CITY_CONTAINS_HTML_TAGS"],generateAction:()=>sa("locality",this.translations.invalidBillingAddressError)},{violations:["PAYMENTS_POSTAL_CODE_REQUIRED"],generateAction:()=>sa("postalCode",this.translations.postalCodeBlank)},{violations:["PAYMENTS_COUNTRY_REQUIRED"],generateAction:()=>sa("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:()=>sa("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",...Te,...Ne],generateAction:()=>this.generateDecelerateAction()}]:[{violations:["DELIVERY_FIRST_NAME_REQUIRED"],generateAction:()=>la("name",this.translations.firstNameBlank)},{violations:["DELIVERY_LAST_NAME_REQUIRED"],generateAction:()=>la("name",this.translations.lastNameBlank)},{violations:["DELIVERY_ADDRESS1_REQUIRED"],generateAction:()=>la("addressLines",this.translations.addressLine1Blank)},{violations:["DELIVERY_ADDRESS2_REQUIRED"],generateAction:()=>la("addressLines",this.translations.addressLine2Blank)},{violations:["DELIVERY_CITY_REQUIRED"],generateAction:()=>la("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:()=>la("country",this.translations.countryBlank)},{violations:["DELIVERY_POSTAL_CODE_REQUIRED"],generateAction:()=>la("postalCode",this.translations.postalCodeBlank)},{violations:["DELIVERY_ZONE_NOT_FOUND"],generateAction:()=>{const{shippingZone:a,shippingCountry:o}=Ie(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:()=>la("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:()=>la("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",...N],generateAction:()=>la("addressLines",this.translations.invalidShippingAddressError)},{violations:["DELIVERY_CITY_CONTAINS_HTML_TAGS"],generateAction:()=>la("locality",this.translations.invalidShippingAddressError)},{violations:["DELIVERY_ADDRESS1_TOO_LONG"],generateAction:()=>la("addressLines",this.translations.addressLineTooLongError)},{violations:["DELIVERY_FIRST_NAME_TOO_LONG"],generateAction:()=>la("name",this.translations.firstNameTooLongError)},{violations:["DELIVERY_LAST_NAME_TOO_LONG"],generateAction:()=>la("name",this.translations.lastNameTooLongError)},{violations:we,generateAction:()=>la("name",this.translations.nameContainsEmojisError)},{violations:Te,generateAction:()=>({action:"abort",effects:[()=>{this.inMemoryApplePayParts.paymentSheetError.value={type:"exceptional_completion_status"},this.inMemoryApplePayParts.requirePhoneOnNextAttempt.value=!0}]})}]}getCompletionDeceleratedViolationActions(e){return e?.options?.applePayRecoveryFlowEnabled?[{violations:Me,generateAction:()=>this.generateDecelerateAction({paymentSheetError:{type:"new_tax_must_be_accepted",tone:"warning"}})},{violations:[...w,I,...Re,...De,...M,...Le,"DELIVERY_WRONG_NUMBER_OF_DELIVERY_LINES",...Oe,...Be],generateAction:()=>this.generateDecelerateAction()}]:this.getCompletionAbortViolationActions()}getCompletionAbortViolationActions(){return[{violations:[...Me,I,...Re,...M,"DELIVERY_COMPANY_REQUIRED"],generateAction:()=>({action:"abort"})},{violations:De,generateAction:()=>this.generateAbortAction("session_terminated")},{violations:Le,generateAction:()=>this.generateAbortAction("unusable_partial_address")},{violations:["DELIVERY_WRONG_NUMBER_OF_DELIVERY_LINES",...Oe],generateAction:()=>this.generateAbortAction("unhandled_completion_status")},{violations:Be,generateAction:()=>this.generateAbortAction("ineligible_discount")}]}mapUnhandledCompletion(e){return this.observability.error(new ae(`Intercepted completion returned unhandled status: ${e.status}`,{groupingHash:`ApplePayAPIError::InterceptedCompletionReturned::Unhandled::${e.status}`}),{severity:"error",errorClass:et.Api}),this.generateAbortAction("unhandled_completion_status")}getNegotiationViolationActions(e){return[{violations:["MERCHANDISE_CART_AND_CURRENCY_UPDATED_BASED_ON_COUNTRY","MERCHANDISE_CART_UPDATED_BASED_ON_COUNTRY",I,...S,...C,ce,ue],generateAction:()=>({action:"abort"})},{violations:he,generateAction:()=>({action:"update",errors:[new ApplePayError("addressUnserviceable")]})},...this.getNegotiationShippingAddressViolationActions(e),{violations:[be],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:[...Ye,"DELIVERY_INVALID_POSTAL_CODE_FOR_COUNTRY","DELIVERY_INVALID_POSTAL_CODE_FOR_ZONE"],generateAction:()=>({action:"no-op"})}]:[{violations:Ye,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)=>(ra.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 ae(`Intercepted ${t} returned invalid: ${r}`,{groupingHash:`ApplePayAPIError::InterceptedNegotiationReturned::Invalid::${r}`}),{severity:"error"})}}function sa(e,t){return{action:"show_error",errors:[new ApplePayError("billingContactInvalid",e,t)]}}function la(e,t){return{action:"show_error",errors:[new ApplePayError("shippingContactInvalid",e,t)]}}function da(){const{i18n:e,observability:t}=m(),{inMemoryApplePayParts:n,persistedApplePaySignal:r}=v(),i=xe(),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 ia(t,s,n,r,i),[s,n,r,t,i])}function pa({canDecelerate:e,checkout:t}){return e.value&&R({checkout:t})}const ca=class extends O{};ca.type="wallet:address-replace";let ua=ca;function ya(e,t){const{streetName:a,streetNumber:o,...n}=e.extendedFields??{};if(null==a&&null==o)return e;const r=Object.values(n).some(e=>null!=e);return{...e,address1:t,extendedFields:r?n:void 0}}function ha({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 ma({observability:o},{errorName:"InvalidAccessError",methodName:e});throw r}else ma({observability:o},{errorName:"SessionAlreadyTerminated",methodName:e})}function ma({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 va(){const e=ea(),t=Y(),{progress:a}=at(),r=ot(),i=nt(),s=We(),l=x(),d=rt(),p=it("APPLE_PAY"),{inMemoryApplePayParts:{asPaymentMethod:c,requirePhoneOnNextAttempt:u,requireBillingPhoneOnNextAttempt:y,paymentSheetError:h,expiresAt:g,preCompletionHandler:P,subscriptionReviewTransition:f},persistedApplePaySignal:E,walletUsedForSubmissionSignal:b}=v(),S=da(),C=function(){const e=da();return o((t,a)=>{const{completionResultMapper:o}=e();if(!o)throw new ae("CompletionResultMapper not set up correctly",{groupingHash:"ApplePayAPIError::CompletionResultMapper"});return o.mapResultToPaymentSheetAction(t,a)},[e])}(),T=Xt(),N=Kt(),{source:{checkoutSessionIdentifier:w},observability:M,checkout:{wallets:R,address:{countryDetails:O},configuration:j,negotiator:G},shop:J,events:K,client:X}=m(),ee=G.current.fields.buyerIdentity.value?.customerProfile,te=aa(J),oe=j.addressSettings.nonBillingAddressSettings,ne=j.layout.isOnePage,re=j.layout.baseName,ie=_t(Q.ApplePay),{trackAttempt:se}=gt(Q.ApplePay),le=st(c),de=G.current.fields,pe=de.buyerIdentity.value?.purchasingCompany,ce=de.availableDeliveryAddresses?.value,ue=de.mustSelectProvidedAddress?.value,ye=_({availableDeliveryAddresses:ce,mustSelectProvidedAddress:ue}),{email:he,shippingAddress:me,billingAddress:ve,paymentLines:_e,deliveryLines:Ae}=G.parts,ge=ke(),Pe=lt({shouldPersist:!0}),fe=Pt({flag:A,onAbort:Pe,onError:e=>{throw e}}),Ee=function({canDecelerate:e,asPaymentMethod:t}){const a=function({canDecelerate:e}){const t=D(),{checkout:a}=m();return n(()=>pa({canDecelerate:e,checkout:a})&&t.value)}({canDecelerate:e}),{checkout:o}=m(),r=tt();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?L(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:le,asPaymentMethod:c}),be=function(){const{negotiate:e}=at(),{checkout:{wallets:t},observability:a}=m();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 d="rejected";l?d="session_ended":r&&(d="unsettled_status");const p={result:"failed",reason:d,status:r??"none"};return a.counter({name:"apple_pay_pre_deceleration_negotiation_attempt",value:1,attributes:p}),a.log("apple_pay_pre_deceleration_negotiation_attempt","[ApplePay] Pre-deceleration negotiation aborted",{...p,error:String(i)}),n(),!1},[e,t,a])}();return o(async(o,n,m,v,_,A)=>{let D=!1;const L=S(),Y=c.value,x=le.value,j=Y?$.PaymentMethod:$.Express,de={};function ce(){try{ha({methodName:"completePayment",abortSignal:v,wallets:R,observability:M},()=>n.completePayment(ApplePaySession.STATUS_FAILURE)),M.leaveErrorBreadcrumb("[ApplePay] Completion flow - clearing activeSession (abort path)"),R.clearActiveSession({invokingWallet:"APPLE_PAY"}),M.log("apple_pay_authorization_aborted","Apple Pay authorization aborted during payment completion",{}),T()}catch(a){e({session:n,error:a})}finally{Y||t()}}if(se({walletType:j}),ht.start("apple-pay-authorization"),N({status:Z.Attempt,walletType:j}),!v.aborted&&R.activeSession.value&&_?.())return M.leaveErrorBreadcrumb("ApplePay: authorization blocked by payment method reconciliation"),h.value={type:"session_terminated"},void ce();
1function ue(t,a){switch(a.effects?.forEach(e=>e()),a.action){case"submit":{const a=p.value,n=w&&a?.walletOrderTypeIdentifier&&a?.walletServiceUrl&&a?.walletAuthenticationToken?{status:ApplePaySession.STATUS_SUCCESS,orderDetails:{orderTypeIdentifier:a.walletOrderTypeIdentifier,orderIdentifier:w,webServiceURL:a.walletServiceUrl,authenticationToken:a.walletAuthenticationToken}}:ApplePaySession.STATUS_SUCCESS;let r=!1;try{ha({methodName:"completePayment",abortSignal:v,wallets:R,observability:M},()=>{t.completePayment(n),r=!0})}catch(o){e({session:t,error:o,isProcessing:!0})}finally{M.leaveErrorBreadcrumb("[ApplePay] payment completed successfully",{walletType:j}),R.clearActiveSession({invokingWallet:"APPLE_PAY"})}return r&&N({status:Z.Success,walletType:j}),b.value="APPLE_PAY",r}case"show_error":{const n=Ve(a),r={status:ApplePaySession.STATUS_FAILURE,errors:n};M.log("apple_pay_authorization_has_errors","apple_pay_authorization_has_errors",{errors:n});try{ha({methodName:"completePayment",abortSignal:v,wallets:R,observability:M},()=>t.completePayment(r)),v.aborted||0===r.errors.length?(M.leaveErrorBreadcrumb("[ApplePay] payment failed with no errors or abort action, sheet will close"),R.clearActiveSession({invokingWallet:"APPLE_PAY"}),T()):(M.leaveErrorBreadcrumb("[ApplePay] payment failed with handled errors, sheet will remain open for retry"),T())}catch(o){return e({session:t,error:o}),!1}return!0}case"abort":return ce(),!1;case"decelerate":{if(!x)return ce(),!1;const n=a.completePaymentStatus??ApplePaySession.STATUS_FAILURE;try{ha({methodName:"completePayment",abortSignal:v,wallets:R,observability:M},()=>t.completePayment(n)),R.clearActiveSession({invokingWallet:"APPLE_PAY"}),N({status:Z.Failure,walletType:j,endsAuthorization:!1}),ie({event:W.RecoveryFlowInitiated,walletType:j}),ne.value&&(R.setEscalatedWallet("APPLE_PAY"),"review"===r.value.currentPage?.id&&i("payment-methods",{replace:!0})),E.value={...E.value,receiptIdForPaymentFailure:void 0,recoverySubmissionAttemptCount:0},ne.value?K.dispatchEvent(new ua):D=!0}catch(o){return e({session:t,error:o}),!1}return!0}default:return e({session:t,error:new ae(`Missing handler for payment sheet action "${a.action}"`,{groupingHash:"ApplePayAPIError::MissingHandlerPaymentSheetAction"})}),!1}}
1const Pe=oe.value.isRequired("address2"),Se=oe.value.isRequired("firstName"),{token:Ce,billingContact:Te,shippingContact:Ne}=o.payment,we=oe.value.isRequired("phone",{countryCode:Vt(Ne?.countryCode)}),Ie=L.validateBilling(o.payment);if(Ie.shouldPersist&&Te&&!pe){const e=!s.value&&we||y.value?Ne?.phoneNumber:void 0;y.value&&Ne?.phoneNumber&&M.counter({name:"apple_pay_billing_phone_provided_after_retry",value:1,attributes:{asPaymentMethod:Y}});const t={...Te,phoneNumber:e};te&&await O.fetch(Vt(t.countryCode)),_a(ve,t,te),oa(J,Vt(t.countryCode))&&(de.billing=t.addressLines?.[0])}if(Ie.paymentSheetAction)return void ue(n,Ie.paymentSheetAction);if(M.log("wallets_shipping_address_update","onPaymentAuthorized: decision state before shipping address update",{asPaymentMethod:Y,shippingContactDefined:Boolean(Ne),isShippingContactPostalCodePadded:k(Ne?.postalCode,Vt(Ne?.countryCode)),isCurrentProposedPostalCodePadded:k(me.value?.postalCode,me.value?.countryCode),shippingRequired:s.value}),!Y&&!ye){const e=L.validateShipping(o.payment,s.value,Pe&&!x,Se,we&&!x);if(e.shouldPersist&&Ne){d({postalCode:Ne.postalCode,countryCode:Vt(Ne.countryCode),city:Ne.locality,zoneCode:Ne.administrativeArea||Ne.subLocality},"APPLE_PAY"),te&&await O.fetch(Vt(Ne.countryCode));const e={...Ft(Ne),...na(Ne,te)};M.log("wallets_shipping_address_update","onPaymentAuthorized: update with complete shipping address from shippingContact",{isPostalCodePadded:k(e.postalCode,e.countryCode),countryCode:e.countryCode}),_a(me,Ne,te),oa(J,Vt(Ne.countryCode))&&(de.shipping=Ne.addressLines?.[0])}if(e.paymentSheetAction)return void ue(n,e.paymentSheetAction)}if(!Y){const e=ee?.email??Ne?.emailAddress;e&&(he.value=e)}Ne?.phoneNumber&&Ae.value.forEach(e=>{e.value={...e.value,deliveryMethodOptions:{...e.value.deliveryMethodOptions,phone:Ne.phoneNumber}}}),u.value&&Ne?.phoneNumber&&M.counter({name:"apple_pay_phone_provided_after_retry",value:1,attributes:{asPaymentMethod:Y}}),Y?ge({phone:Ne?.phoneNumber,email:Ne?.emailAddress,firstName:Te?.givenName}):ge();const Me=G.current.fields.paymentDue.value;if(Me&&Me.amount>0||l.value){const e=_e.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}}(Ce.paymentMethod.displayName);_e.value=U(e,{method:{type:"wallet",name:"APPLE_PAY",walletContent:{...Ce.paymentData,lastDigits:a,cardNetworkBrand:t,paymentMethodIdentifier:p.value?.paymentMethodIdentifier,...x&&{expiresAt:g.value}}}})}const Re=Ee.value,De=l.value,Le=De?F(X.unstable_getSerialization("experiments")):null,Oe=void 0!==A&&A===z(Le),Be=R.activeSession.value,Ye=Re.isCaliforniaDeceleration&&Re.hasSubscription&&!Y&&!v.aborted&&"APPLE_PAY"===Be?.wallet&&!Be.asPaymentMethod&&Re.isABTestActive&&Oe,xe={...Re,shouldDecelerate:Re.shouldDecelerate&&!Ye};if(De){const e=null!==Le,t=function(e){return e.shouldDecelerate?e.isCaliforniaDeceleration?"california":"decelerated":"none"}(xe);M.counter({name:"apple_pay_subscriptions_deceleration_variant",value:1,attributes:{variant:Le??V.Control,complete_payment_status:"success",is_ab_test_active:J.hasFlagEnabled(H),is_california_excluded:xe.isCaliforniaDeceleration,has_caution_banner:!1,deceleration_scope:t,is_enrolled:e,as_payment_method:Y}})}if(xe.shouldDecelerate){if(ne.value&&!(await be(v,ce)))return;if(R.setEscalatedWallet("APPLE_PAY"),R.setIsDecelerating(!0),!ue(n,{action:"decelerate",completePaymentStatus:ApplePaySession.STATUS_SUCCESS,effects:[]}))return R.setEscalatedWallet(null),R.setIsDecelerating(!1),R.setHasActiveApplePaySubscriptionReview(!1),void(f.value=void 0);if(f.value="in_app_deceleration",R.setHasActiveApplePaySubscriptionReview(!0),D)try{await fe({wallet:"APPLE_PAY",reason:"subscriptions",asPaymentMethod:Y})}catch(Ze){f.value=void 0,Ze instanceof Error&&e({session:n,error:Ze})}return}const ke=P?.value;if(ke&&!(await ke()))return M.leaveErrorBreadcrumb("ApplePay: Pre-completion handler failed",{asPaymentMethod:Y}),void ce();m.value=!0;let He=0,qe="",ze="unexpected error",je=[];const Ge=Ue(G.current.fields.deliveryNext?.value),Qe=j===$.Express?Fe:void 0,$e=!J.hasFlagEnabled(q)||void 0===de.shipping&&void 0===de.billing?Qe:e=>function(e,t){const{delivery:a,payment:o}=e,{shipping:n,billing:r}=t,i=o?.billingAddress?.streetAddress;return{...e,...a&&void 0!==n&&{delivery:{...a,deliveryLines:a.deliveryLines.map(e=>{const t=e.destination?.streetAddress,a=e.deliveryMethodTypes.some(B);return t&&!a?{...e,destination:{...e.destination,streetAddress:ya(t,n)}}:e})}},...o&&i&&void 0!==r&&{payment:{...o,billingAddress:{...o.billingAddress,streetAddress:ya(i,r)}}}}}(Qe?Qe(e):e,de);try{M.leaveErrorBreadcrumb("ApplePay: Payment authorized negotiation",{retryCount:He});const e=me.value;for(;;){let t=!1;if(v.aborted)break;if(await a("apple-pay-payment-authorized",a=>{const o=a;"rejected"===o.status&&(je=o.violations.map(e=>e.code),o.violations.some(e=>"BUYER_IDENTITY_MISSING_CONTACT_METHOD"===e.code)&&M.log("apple_pay_on_payment_authorized","Apple Pay is missing contact method",{asPaymentMethod:c.value,proposedEmail:he.value||"",customerProfileEmail:ee?.email||"",shippingContactEmail:Ne?.emailAddress||"",hasShippingContact:Boolean(Ne),shippingContactPhone:Ne?.phoneNumber||"",allViolationCodes:o.violations.map(e=>e.code).join(","),isPhoneRequired:we}));const r="rejected"===o.status&&o.violations.some(e=>e.code===I),{shouldRetry:i,retryReason:s,updatedDeliveryMethodHandles:l}=Aa(o,{retryCount:He,negotiated:G,originalSelectedDeliveryMethods:Ge});if(i&&!r)return l&&(dt(Ae,l),j===$.Express&&(M.log("wallets_shipping_address_update","onPaymentAuthorized: restoring address snapshot on retry",{isSnapshotPostalCodePadded:k(e?.postalCode,e?.countryCode),countryCode:e?.countryCode,retryCount:He}),ye||(me.value=e))),M.leaveErrorBreadcrumb(`ApplePay: retrying due to ${s}`,{retryCount:He}),He++,qe=s,void(t=!v.aborted);M.leaveErrorBreadcrumb("ApplePay: completed negotiation",{action:"paymentAuthorized",status:a.status,retryCount:He,retryReason:qe});const d=C(o,{shippingCountryCode:Vt(Ne?.countryCode),billingCountryCode:Vt(Te?.countryCode),...x&&{options:{applePayRecoveryFlowEnabled:x,asPaymentMethod:c.value,layout:re}}});ue(n,d),ze=a.status},{skipToCompletion:!0,customizeCompletion:$e}),!t)break}D&&await fe({wallet:"APPLE_PAY",reason:"submitForCompletion",asPaymentMethod:Y})}catch(Ze){Ze instanceof Error&&e({session:n,error:Ze})}finally{m.value=!1,He>0&&(M.counter({name:"wallet_submit_for_completion_retry",value:1,attributes:{retry_reason:qe||"unknown",retry_count:He,status:ze,instrument:Q.ApplePay}}),M.log("wallet_submit_for_completion_retry_details","[ApplePay] SubmitForCompletion retry details",{retryReason:qe,retryCount:He,status:ze,instrument:Q.ApplePay,asPaymentMethod:Y,lastRejectionViolationCodes:je}))}},[c,oe,S,u,y,h,G,l,p,w,b,e,se,N,T,t,pe,ve,s,ee?.email,d,me,he,Ae,_e,a,be,C,ge,R,M,E,le,fe,ne,re,K,g,P,f,ie,ye,Ee,O,te,X,J,r,i])}function _a(e,t,a){const o=na(t,a),n=e.fields.line2;e.value={...Ft(t),...o},n&&"line2"in o&&(n.value=o.line2)}function Aa(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=He(e,a.current.fields.deliveryNext?.peek(),o);return r?{shouldRetry:!0,retryReason:"delivery_option_mismatch",updatedDeliveryMethodHandles:r}:n}function ga(){const e=da();return o((t,a)=>{const{negotiationResultMapper:o}=e();if(!o)throw new ae("NegotiationResultMapper not set up correctly",{groupingHash:"ApplePayAPIError::NegotiationResultMapper"});return o.mapResultToPaymentSheetAction(t,a)},[e])}function Pa(){const e=Xt(),t=m(),{checkout:{wallets:a},observability:n}=t;return o(({session:t,paymentSheetAction:o,onProceed:r,abortSignal:i})=>{switch(o.action){case"abort":ha({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 ae(`Missing handler for payment sheet action "${o.action}"`,{groupingHash:"ApplePayAPIError::MissingHandlerPaymentSheetAction"})}},[e,a,n])}function fa(){const e=ea(),t=mt(Q.ApplePay),{inMemoryApplePayParts:{asPaymentMethod:a,paymentSheetError:n,prefetchPaymentSession:i}}=v(),{shop:s,source:{sourceId:l},observability:d,embed:p,graphql:{coreGraphql:c},checkout:{negotiator:u}}=m(),{countryCode:y}=s,h=Ht({embed:p,isCrossOriginIframeEnabled:s.hasFlagEnabled(j)}),g=function(){const{checkout:e,observability:t}=m(),a=e.configuration.addressSettings.nonBillingAddressSettings.value,n=Ze(),r=a.isRequired("phone",{countryCode:Vt(e.negotiator.current.fields.buyerIdentity.value?.countryCode)}
1),i=We(),{value:s}=e.negotiator.current.fields.deliveryNext,l=e.negotiator,d=Je(),{paymentDue:p,recurringTotals:c,...u}=ie(l),y=Zt(),{deliveryMethodTitlePrefixes:h,connectTwoShippingTitles:A}=y,g=e.negotiator.current.fields.availableDeliveryAddresses?.value,P=e.negotiator.current.fields.mustSelectProvidedAddress?.value,{inMemoryApplePayParts:{asPaymentMethod:f,requirePhoneOnNextAttempt:E,requireBillingPhoneOnNextAttempt:b}}=v();return o((a,o)=>{const l=f.value,m=E.value||b.value,v=Boolean(e.negotiator.parts.shopPayArtifact.value?.optIn),S=Boolean(e.negotiator.parts.email.value);m&&t.counter({name:"apple_pay_phone_retry_requested",value:1,attributes:{addressSettingsPhoneRequired:r,asPaymentMethod:l}});const C=_({availableDeliveryAddresses:g,mustSelectProvidedAddress:P}),T=l||C,{requiredShippingContactFields:N,requiredBillingContactFields:w}=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:l,phoneRequired:r,shouldRequestPhoneOnRetry:m,shopPayOptInExists:v}),emailRequired:Jt({asPaymentMethod:l,emailRequired:n.value,shopPayOptInExists:v,proposedEmailExists:S}),shippingRequired:!T&&i.value}),I=Ut(y.lineItemsLabels.total,p),M=Mt({...u,formattedRecurringTotals:d(c),...y}),R=T?[]:Dt({deliveryMethodTitlePrefixes:h,connectTwoShippingTitles:A,deliveryNext:s}),D={total:I,currencyCode:p.currencyCode,countryCode:o,lineItems:M,shippingMethods:R,shippingType:"shipping",merchantCapabilities:["supports3DS"],supportedNetworks:a,requiredShippingContactFields:N,requiredBillingContactFields:w};return zt(p.currencyCode)?function(e){const{lineItems:t,shippingMethods:a}=e;return{...e,total:Gt(e.total),...t&&{lineItems:t.map(Gt)},...a&&{shippingMethods:a.map(Qt)}}}(D):D},[f,E,b,A,h,s,n,g,d,y,P,u,p,r,c,i,t,e.negotiator.parts])}(),P=function(){const e="apple-pay-gateway.apple.com/paymentservices/startSession";return"CN"===ut().geolocation.country.code?`https://cn-${e}`:`https://${e}`}(),f=function(){const e=mt(Q.ApplePay),{trackComplete:t}=gt(Q.ApplePay),a=Ke(),{inMemoryApplePayParts:n}=v(),{checkout:r,observability:i,shop:s}=m(),l=Xe();return o((o,d)=>{o.abort(),n.prefetchPaymentSession.value=void 0;const p=d.value,c=n.asPaymentMethod.value,u=c?$.PaymentMethod:$.Express;ht.remove("apple-pay-sheet-load"),ht.exists("apple-pay-authorization")&&t({result:"failed",durationMs:ht.end("apple-pay-authorization"),walletType:u}),i.counter({name:"apple_pay_on_cancel",value:1,attributes:{completion_in_progress:p.toString(),wallet_type:u}}),i.counter({name:"wallet_sheet_cancelled",value:1,attributes:{instrument:Q.ApplePay}}),i.log("apple_pay_use_on_cancel_sheet_cancelled","Apple Pay sheet cancelled",{completionInProgress:p,walletType:u}),n.requirePhoneOnNextAttempt.value&&i.counter({name:"apple_pay_cancelled_after_phone_retry",value:1,attributes:{asPaymentMethod:c}});const y=s.hasFlagEnabled(A),h=void 0!==n.subscriptionReviewTransition.value&&$e({applePayThreePageVaultedReviewEnabled:y,isOnePageCheckout:r.configuration.layout.isOnePage.value}),m=l.value||h;if(p)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:m}),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:m}),"APPLE_PAY"===r.wallets.activeSession.value?.wallet&&r.wallets.clearActiveSession({invokingWallet:"APPLE_PAY"}),m)return;a()}e(Z.Cancelled)},[a,n.asPaymentMethod,n.paymentSheetError,n.subscriptionReviewTransition,n.requirePhoneOnNextAttempt,n.prefetchPaymentSession,t,e,i,s,r,l])}(),E=function(){const e=mt(Q.ApplePay),t=ea(),{shop:a,source:{sourceId:n},observability:r,checkout:{wallets:i},embed:s,graphql:{coreGraphql:l}}=m(),d=Ht({embed:s,isCrossOriginIframeEnabled:a.hasFlagEnabled(j)}),{inMemoryApplePayParts:{prefetchPaymentSession:p}}=v(),c=ct(Q.ApplePay);return o((a,o,s,u)=>{const y=u===p.value?.prefetchUrl;r.histogram({name:"apple_pay_prefetch_session",value:ht.end("apple-pay-session-begin"),attributes:{prefetch:y?"success":"retried"}}),async function(){if(p.value)try{const e=await p.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:p.value?.prefetchUrl}):y||r.leaveErrorBreadcrumb("[ApplePay] session query prefetch URL mismatch - starting new validation query",{validationUrl:u,prefetchUrl:p.value?.prefetchUrl})}catch(e){if(e instanceof X)return;r.log("apple_pay_on_validate_merchant","Apple Pay prefetch session error",{error:e,prefetchValidationUrl:p.value?.prefetchUrl,validationUrl:u})}return r.leaveErrorBreadcrumb("[ApplePay] starting new session query",{hadPrefetch:Boolean(p.value),validationUrl:u}),wt({graphql:l,sourceId:n,validationUrl:u,asPaymentMethod:o,signal:s,observability:r,isPrefetch:!1,domain:d})}().then(n=>{if(p.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 ee(n.reason)});if(!n){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 ee("Apple Pay session query returned no data after session was cancelled"):new ae("session query returned no data");return void t({session:a,error:l,isAborted:e})}e(Z.Success,o?$.PaymentMethod:$.Express),o||c(),ha({methodName:"completeMerchantValidation",abortSignal:s,wallets:i,observability:r},()=>a.completeMerchantValidation(JSON.parse(n.body)))}).catch(e=>{t({error:e,session:a,isAborted:s.aborted})})},[l,n,r,e,c,t,p,i,d])}(),b=function(){const{observability:e,checkout:{wallets:t,address:{countryDetails:a,extendedAddressMode:n},negotiator:r},checkout:i,shop:s}=m(),l=aa(s),d=ea(),p=Xt(),c=ga(),u=Je(),y=_t(Q.ApplePay),h=qe(),{formattedRecurringTotalTooltip:v,lineItemsLabels:_,deliveryOptionGroupTypeLabels:A,deliveryMethodTitlePrefixes:g}=Zt();return o(async(o,s,m,P)=>{const{billingContact:f}=o.paymentMethod;if(!i.isShippingRequired.value&&f){e.leaveErrorBreadcrumb("ApplePay: Payment method selected negotiation");try{l&&await a.fetch(Vt(f.countryCode)),await h({abortSignal:m,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),...na(t,o)},{interfaceFlow:"APPLE_PAY",deliveryAddressOptions:a}))(e,f,{deliveryAddressOptions:{extendedAddressMode:n},extendedAddressFieldsEnabled:l}),observability:e,onComplete:function(a){if(t.activeSession.value&&!m.aborted&&(e.leaveErrorBreadcrumb("ApplePay: completed negotiation",{action:"paymentMethodSelected",status:a.status}),f)){const o=c(a,{billingCountryCode:Vt(f.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:s}),ha({methodName:"abort",abortSignal:m,wallets:t,observability:e},()=>s.abort()),t.clearActiveSession({invokingWallet:"APPLE_PAY"}),p())}},walletName:Q.ApplePay,logPrefix:"ApplePay::useOnPaymentMethodSelected"})}catch(E){E instanceof Error&&d({session:s,error:E})}}if(s&&t.activeSession.value){if(P&&!(await async function(a){let o=!1;try{o=await a(m)}catch(E){return E instanceof Error&&d({session:s,error:E}),!1}return m.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"),d({session:s,error:new ae("Payment method selection reconciliation timed out",{groupingHash:"ApplePayAPIError::PaymentMethodSelectionReconciliationTimeout"})})),o)}(P)))return;!function(){const{paymentDue:a,recurringTotals:o,...n}=ie(r);if(null==a)return d({session:s,error:new ae("Missing negotiated payment due",{groupingHash:"ApplePayAPIError::MissingNegotiatedPaymentDue"})});const i=zt(a.currencyCode);try{ha({methodName:"completePaymentMethodSelection",abortSignal:m,wallets:t,observability:e},()=>{const e={newTotal:Ut(_.total,a),newLineItems:Mt({...n,formattedRecurringTotals:u(o),formattedRecurringTotalTooltip:v,lineItemsLabels:_,deliveryOptionGroupTypeLabels:A,deliveryMethodTitlePrefixes:g})};s.completePaymentMethodSelection(i?$t(e):e)})}catch(E){E instanceof Error&&d({error:E,session:s})}}()}i.isShippingRequired.value||ht.endAndRun("apple-pay-sheet-load",t=>{y({event:W.SheetLoaded,ttl:t}),e.histogram({name:"wallet_sheet_loaded",value:t,attributes:{instrument:Q.ApplePay}})})},[t,p,g,A,u,v,c,_,r,i.isShippingRequired,e,d,y,h,n,a,l])}(),S=function(){const e=ea(),t=Je(),a=ga(),n=pt(),{observability:r,checkout:{wallets:i,address:{countryDetails:s,extendedAddressMode:l},negotiator:d},shop:p}=m(),c=aa(p),{inMemoryApplePayParts:{initialDeliveryIdentifier:u}}=v(),{deliveryLines:y,shippingAddress:h}=d.parts,A=_t(Q.ApplePay),g=qe(),P=d.current.fields,f=P.availableDeliveryAddresses?.value,E=P.mustSelectProvidedAddress?.value,b=P.deliveryNext?.value,S=_({availableDeliveryAddresses:f,mustSelectProvidedAddress:E}),{formattedRecurringTotalTooltip:C,lineItemsLabels:T,deliveryOptionGroupTypeLabels:N,deliveryMethodTitlePrefixes:w}=Zt(),I=Pa();return o(async(o,p,m)=>{const v=u.value;u.value=void 0;const _=o.shippingMethod.identifier===v;r.counter({name:"apple_pay_skip_initial_delivery_negotiation",value:1,attributes:{skippedNegotiation:_}}),!_&&v&&r.log("apple_pay_on_shipping_method_selected","Apple Pay failed to skip initial delivery negotiation",{expectedHandle:v,actualHandle:o.shippingMethod.identifier});const P=t=>{try{return je(t)}catch(a){return e({session:p,error:new ae("Invalid shipping method identifier",{groupingHash:"ApplePayAPIError::InvalidShippingMethodIdentifier",cause:a,metadata:{identifier:t}})}),null}};if(_){const e=P(v);
1if(null==e)return;return dt(y,e),void R(p)}const E=h.value,M=P(o.shippingMethod.identifier);if(null!=M){dt(y,M),r.leaveErrorBreadcrumb("ApplePay: Shipping method selected negotiation",{handles:JSON.stringify(M),identifier:o.shippingMethod.identifier});try{c&&await s.fetch(E.countryCode),await g({abortSignal:m,fieldsToResolve:["deliveryNext","duties","taxes"],customizeNegotiation:e=>ze(e,E,{interfaceFlow:"APPLE_PAY",isPickupSelected:n.value,isConstrainedAddress:S,availableDeliveryAddresses:f,negotiatedDelivery:b,deliveryAddressOptions:{extendedAddressMode:l}}),observability:r,walletName:Q.ApplePay,onComplete:function(t){if(i.activeSession.value&&!m.aborted){r.leaveErrorBreadcrumb("ApplePay: completed negotiation",{action:"shippingMethodSelected",status:t.status});try{const e=a(t,{shippingCountryCode:E.countryCode});e.effects?.forEach(e=>e()),r.leaveErrorBreadcrumb("ApplePay: Payment sheet action",{action:"shippingMethodSelected",paymentSheetAction:e.action}),I({session:p,paymentSheetAction:e,onProceed:()=>R(p),abortSignal:m})}catch(o){o instanceof Error&&e({error:o,session:p})}}},logPrefix:"ApplePay::useOnShippingMethodSelected"})}catch(D){e({session:p,error:D})}}function R(a){const{paymentDue:o,recurringTotals:n,...s}=ie(d);if(null==o)return e({session:a,error:new ae("Missing negotiated payment due",{groupingHash:"ApplePayAPIError::MissingNegotiatedPaymentDue"})});const l=zt(o.currencyCode);try{ha({methodName:"completeShippingMethodSelection",abortSignal:m,wallets:i,observability:r},()=>{const e={newTotal:Ut(T.total,o),newLineItems:Mt({...s,formattedRecurringTotals:t(n),formattedRecurringTotalTooltip:C,lineItemsLabels:T,deliveryOptionGroupTypeLabels:N,deliveryMethodTitlePrefixes:w})};a.completeShippingMethodSelection(l?$t(e):e)}),ht.endAndRun("apple-pay-sheet-load",e=>{A({event:W.SheetLoaded,ttl:e}),r.histogram({name:"wallet_sheet_loaded",value:e,attributes:{instrument:Q.ApplePay}})})}catch(D){D instanceof Error&&e({error:D,session:a})}}},[i,w,N,t,C,a,I,n,T,d,y,h,e,r,A,u,g,S,f,b,s,c,l])}(),C=function(){const e=ea(),t=Je(),a=ga(),n=pt(),{inMemoryApplePayParts:{initialDeliveryIdentifier:r,asPaymentMethod:i}}=v(),s=m(),{deliveryLines:l,shippingAddress:d}=s.checkout.negotiator.parts,p=qe(),c=s.checkout.negotiator.current.fields.availableDeliveryAddresses?.value,u=s.checkout.negotiator.current.fields.mustSelectProvidedAddress?.value,y=s.checkout.negotiator.current.fields.deliveryNext?.value,h=_({availableDeliveryAddresses:c,mustSelectProvidedAddress:u}),A=s.checkout.negotiator,{checkout:{wallets:g,address:P},observability:f}=s,{countryDetails:E,extendedAddressMode:b}=P,S=aa(s.shop),{formattedRecurringTotalTooltip:C,lineItemsLabels:T,deliveryOptionGroupTypeLabels:N,deliveryMethodTitlePrefixes:w,connectTwoShippingTitles:I}=Zt(),M=Pa(),{shouldGateCrossBorder:R,crossBorderGate:D}=At(),L=st(i);return o(async(o,i,s)=>{const u={...Ft(o.shippingContact),...na(o.shippingContact,S)};f.log("wallets_shipping_address_update","onShippingContactSelected: update with partial shipping address",{countryCode:u.countryCode,isPostalCodePadded:k(u.postalCode,u.countryCode)});const m=o.shippingContact.countryCode?Vt(o.shippingContact.countryCode):void 0;if(dt(l,void 0),r.value=void 0,R(m)){f.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:m});try{e({session:i,isMessagingHandledElsewhere:!0,error:new ee("Session terminated due to cross-border shipping country change")})}catch(_){f.leaveErrorBreadcrumb("ApplePay: failed to abort session for cross-border gate",{errorName:_ instanceof Error?_.name:"Unknown",errorMessage:_ instanceof Error?_.message:String(_)})}D(()=>{d.fields.zoneCode.value=void 0,d.fields.coordinates.value=void 0,d.fields.countryCode.value=m})}else if(h)v(i);else{d.value=u,f.leaveErrorBreadcrumb("ApplePay: Shipping contact selected negotiation",{countryCode:u.countryCode,isPostalCodePadded:k(u.postalCode,u.countryCode)});try{S&&await E.fetch(u.countryCode),await p({abortSignal:s,fieldsToResolve:["deliveryNext","duties","taxes"],customizeNegotiation:e=>ze(e,u,{interfaceFlow:"APPLE_PAY",isPickupSelected:n.value,isConstrainedAddress:h,availableDeliveryAddresses:c,negotiatedDelivery:y,deliveryAddressOptions:{extendedAddressMode:b}}),observability:f,walletName:Q.ApplePay,onComplete:function(e){const t=L.value;if(!g.activeSession.value)return;if(s.aborted)return;f.leaveErrorBreadcrumb("ApplePay: completed negotiation",{action:"shippingContactSelected",status:e.status});const n=a(e,{shippingCountryCode:Vt(o.shippingContact.countryCode),...t&&{options:{applePayRecoveryFlowEnabled:t}}});
1n.effects?.forEach(e=>e()),f.leaveErrorBreadcrumb("ApplePay: Payment sheet action",{action:"shippingContactSelected",paymentSheetAction:n.action}),M({session:i,paymentSheetAction:n,onProceed:e=>v(i,e),abortSignal:s})},logPrefix:"ApplePay::useOnShippingContactSelected"})}catch(_){_ instanceof Error&&e({session:i,error:_})}}function v(a,o){const{paymentDue:n,recurringTotals:i,deliveryNext:l,...d}=ie(A);if(null==n)return e({session:a,error:new ae("Missing negotiated payment due",{groupingHash:"ApplePayAPIError::MissingNegotiatedPaymentDue"})});const p=zt(n.currencyCode);try{const e={newTotal:Ut(T.total,n),newLineItems:Mt({...d,formattedRecurringTotals:t(i),formattedRecurringTotalTooltip:C,lineItemsLabels:T,deliveryOptionGroupTypeLabels:N,deliveryMethodTitlePrefixes:w})},c=Dt({deliveryMethodTitlePrefixes:w,connectTwoShippingTitles:I,deliveryNext:l}),u={...e,newShippingMethods:c};ha({methodName:"completeShippingContactSelection",abortSignal:s,wallets:g,observability:f},()=>a.completeShippingContactSelection({errors:o,...p?$t(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=c.find(t=>e.every(e=>t.identifier.includes(e)))?.identifier;t&&(r.value=t)}catch(_){f.error(_)}}catch(_){_ instanceof Error&&e({error:_,session:a})}}},[l,d,n,a,M,A,e,T,t,C,N,w,I,r,p,g,f,L,h,c,y,R,D,S,E,b])}(),T=va();return o(({asPaymentMethod:o=!1,supportedNetworks:s,waitForTotalsToSettle:p,isPaymentAuthorizationBlocked:m,subscriptionConsent:v})=>{ht.start("apple-pay-session-begin"),n.value=void 0,a.value=o;const _=r(!1),A=new AbortController,{paymentDue:N}=ie(u);if(!N)return t(Z.Failure,o?$.PaymentMethod:$.Express),n.value={type:"session_terminated"},d.error(new ae("Missing paymentDue",{groupingHash:"ApplePayAPIError::MissingPaymentDue"}),{severity:"error",errorClass:et.Api}),{session:void 0,error:"no_payment_due"};let w;i.value||(i.value={prefetchPromise:(async()=>(await Promise.resolve(),wt({graphql:c,sourceId:l,validationUrl:P,asPaymentMethod:o,signal:A.signal,observability:d,isPrefetch:!0,domain:h})))(),prefetchUrl:P});const I=g(s,y);try{w=new ApplePaySession(G,I)}catch(M){return M instanceof Error&&e({error:M}),{session:void 0,error:"session_creation_failed"}}return w.oncancel=()=>f(A,_),w.onvalidatemerchant=e=>E(w,o,A.signal,e.validationURL),w.onpaymentmethodselected=e=>b(e,w,A.signal,p),w.onshippingmethodselected=e=>S(e,w,A.signal),w.onshippingcontactselected=e=>C(e,w,A.signal),w.onpaymentauthorized=e=>T(e,w,_,A.signal,m,v),{session:w,error:void 0}},[a,g,u,n,f,T,b,C,S,E,y,e,t,i,P,c,d,l,h])}function Ea(){const{inMemoryApplePayParts:{asPaymentMethod:e,expiresAt:t}}=v(),{observability:a,checkout:{wallets:n}}=m(),r=st(e);return o(o=>{if(o){ht.start("apple-pay-sheet-load"),a.counter({name:"apple_pay_button_click",value:1,attributes:{wallet_type:e.value?$.PaymentMethod:$.Express}}),a.counter({name:"wallet_sheet_clicked",value:1,attributes:{instrument:Q.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 ba=new Set(w);function Sa(){const{applePaySessionHandler:e,inMemoryApplePayParts:t}=v(),a=yt(function(){const{negotiate:e}=at(),t=ot(),{observability:a,shopPay:o,checkout:{wallets:n,identity:r,negotiator:i,proposal:s}}=m(),l="shopPay"===r.current.value,{inMemoryApplePayParts:{isLoadingPaymentSheet:d,paymentSheetError:p}}=v(),c=l?Q.ShopPayApplePay:Q.ApplePay,u=fa(),y=mt(c),h=St(),_=Xe(),{shopOfferReconciliationPending:A}=o,g=Ea(),P=i.current.fields.paymentMethods?.value,f=P?.find(e=>"wallet"===e.type&&"APPLE_PAY"===e.name),E=f?.supportedNetworks,b=e=>{if(!A.value)return Promise.resolve(!0);
1a.counter({name:"apple_pay_shop_offer_reconciliation_wait",value:1});const t=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)}(A,e).then(e=>(a.histogram({name:"apple_pay_shop_offer_reconciliation_wait_duration",value:Date.now()-t,attributes:{reconciled:e}}),e))};return async({disabled:o=!1,isMountedRef:r,validateButtonPress:i})=>{if(!o){y(Z.Clicked,$.PaymentMethod);try{const o=u({asPaymentMethod:!0,supportedNetworks:E||[],waitForTotalsToSettle:b,isPaymentAuthorizationBlocked:()=>A.value}),c=await(async o=>{d.value=!0;try{if(l){if(!o||!o())return!1;h()}const n=await new Promise((a,o)=>{e({legacyFiltering:{include:["deliveryNext"]},runListenersOnError:!0,negotiationStage:"completion",silenceViolations:ft({journey:t.value,negotiated:s.negotiated.value,fieldsToValidate:["deliveryNext"]}),onComplete:a}).catch(o)}),r=_.value&&"error"===n.status&&n.violations.length>0&&n.violations.every(({code:e})=>ba.has(e));return r&&(a.counter({name:"apple_pay_silenced_violations_requiring_new_token",value:1}),a.log("apple_pay_silenced_violations","PayWithApplePayButton: silenced violations",{violations:n.violations})),"success"===n.status||r}catch{return p.value={type:"failed_to_create_session"},!1}finally{d.value=!1}})(i),y=!r||r.current;c&&!n.activeSession.value&&y&&g(o.session)}catch(c){a.leaveErrorBreadcrumb("Failed to create Apple Pay session",{error:c,shopPay:l}),p.value={type:"failed_to_create_session"},"APPLE_PAY"===n.activeSession.value?.wallet&&n.clearActiveSession({invokingWallet:"APPLE_PAY"})}}}}()),o=yt(fa()),n=yt(Ea());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{Sa 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.