PageSourceSearch

https://obermeyer.com/cdn/shopifycloud/checkout-web/assets/c1/d08a6c7d.B8v-AHSc.js

js obermeyer.com collected 2026-10-02 11:36:14 UTC 69,846 bytes, 1 lines download raw bytes

1import{U as e,V as t,T as a,s as o,t as n,y as r,m as i}from"./2c1ab0fe.GMbxnz74.js";import{E as s,dF as l,gO as p,gN as d,gV as c,aK as u,aF as y,dv as h,b4 as m,S as v,T as _,W as A,aa as g,a9 as P,gQ as E,fz as f,hE as b,hF as S,hG as C,hc as T,bp as N,dl as w,hH as I,dt as R,du as M,hI as D,gR as L,C as O,b3 as B,hJ as Y,hK as x,hL as U,hM as k,go as F,hN as V,ab as H,aN as q,w as z,hO as G,hP as j,hQ as Q,hR as W,hS as Z}from"./4c290a1e.C6TDJ9Fn.js";import{d as $,b as K,c as J,e as X,f as ee,u as te,W as ae,a as oe}from"./ed9f2238.D-8_6d2f.js";import{e as ne,I as re,W as ie,f as se}from"./app.CepNJbvh.js";import{i as le}from"./0a7dffce.DfUtZWCu.js";import{f as pe,g as de,s as ce,r as ue,B as ye,P as he,U as me,a as ve,w as _e,x as Ae,i as ge,N as Pe,E as Ee,h as fe,y as be,z as Se,A as Ce,C as Te,F as Ne,G as we,l as Ie,H as Re,J as Me,K as De,L as Le,M as Oe,j as Be,T as Ye,O as xe,Q as Ue,D as ke,V as Fe,I as Ve,R as He,u as qe,m as ze,n as Ge,o as je,W as Qe,p as We,q as Ze,t as $e,v as Ke}from"./13b13169.Db0IGzkq.js";import{a as Je,g as Xe,i as et}from"./21cc90a2.DAzJmttM.js";import{fT as tt,gT as at,gU as ot,gV as nt,cb as rt,gW as it,c6 as st,i as lt,e as pt,fW as dt,go as ct,fU as ut,gA as yt,gX as ht,gn as mt,dB as vt,fF as _t,cm as At,fX as gt}from"./164ad2e3.BbIvMjRY.js";import{u as Pt,a as Et,g as ft}from"./33464469.6IaCgV4U.js";import{d as bt}from"./b8733b27.B0VmlfYu.js";import{d as St}from"./7fc410e0.B54X0yKF.js";import{u as Ct}from"./ec391382.3QXLMag7.js";import"./53bbdad9.CGJC_1cv.js";import"./9f047e05.CCJUgz_L.js";import"./5fda1420.KYpufQ--.js";import"./60a453ce.CkhHeRBc.js";import"./bb728e1c.iawBHR84.js";const Tt={id:"1501fe0af4559751b078e255872e602b9742658e6ef2d8b73091b38649adb321",type:"query",name:"ApplePayPaymentSession",source:""};class Nt{constructor(e){this.reason=e}}class wt extends Error{constructor(){super(...arguments),this.name="ApplePaySessionCreationResponseError"}}const It=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(Tt,{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 wt("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 ne("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 ie(`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 se(`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 re("ApplePaySession Query error: reached maximum amount of polls");if(m<=5)break;await t(r.pollDelay);break;default:e(r)}}}catch(_){if(_ instanceof wt||_ instanceof ie)return l.counter({name:"apple_pay_session_query_error",value:1,attributes:{reason:_.name}}),new Nt(`${_.name}: ${_.message}`);throw _}},Rt={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:p,deliveryMethodTitlePrefixes:u,formattedRecurringTotals:y,formattedRecurringTotalTooltip:m,merchandiseLines:v}){const _=[];v?.lines&&v.lines.forEach(e=>{_.push({label:de(e),amount:pe(e.totalPrice.amount)})});const A=void 0===e?[]:[{label:l.subtotal,amount:e?pe(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:pe(e.amount)})):h(e).map(({line:e,method:o},n,r)=>({label:Dt(e,o,1===r.length,t,a),amount:pe(o.cost.amount)}))}({deliveryNext:o,deliveryOptionGroupTypeLabels:p,deliveryMethodTitlePrefixes:u}),P=t&&"available_total"===t?.status&&0!==t?.totalDuty.amount?[{label:l.duties,amount:pe(t.totalDuty.amount)}]:[],E=a&&"available_total"===a.status&&0!==a.totalTax.amount?[{label:l.taxes,amount:pe(a.totalTax.amount)}]:[],f=n&&n.lines.map(e=>{if(le(e)){const t=e.amount?.amount;if(t)return{label:e.title,amount:d(pe(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(pe(o))}]:[]})??[],T=r?.lines.filter(e=>"giftCard"===e.method.type).map(e=>e.cost?{label:l.giftCards,amount:d(pe(e.cost.amount))}:void 0).filter(e=>void 0!==e)||[],N=i&&i[0],w=N&&N.amount.amount>0?[{label:l.tip,amount:pe(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 Dt(e,t,a,o,n){const r=n[t.methodType];return a?r:`${r} (${o[e.type]})`}function Lt({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:pe(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,Xe(n).filter(e=>e.length>0));return r.map(a=>({label:Yt(a,e,t),amount:xt(a),detail:kt(a,t),identifier:ce(a)}))}const Ot=", ";function Bt(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+=`${Ot}${i}`,i=s;return t(r,i)}function Yt(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 Bt([...new Set([n,i])].filter(Boolean),a)}function xt(e){return pe(e.reduce((e,t)=>e+t.costAfterDiscounts.amount,0))}function Ut(e,t){return e.add(t),e}function kt(e,t){return Bt([...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(Ut,new Set)],t)}function Ft(e,t){return{label:e,amount:pe(t.amount)}}function Vt(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:Ht(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(Rt).includes(t)&&(a.zoneCode=e.locality||void 0,a.city=e.administrativeArea||e.subLocality||void 0),a.lastName||(a.lastName=a.firstName),a}function Ht(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 qt({embed:e,isCrossOriginIframeEnabled:t}){if(t&&"undefined"!=typeof window&&window.self!==window.top)return e?.client?.embedderHostname}const zt=new Set(["HUF","RSD"]);function Gt(e){return void 0!==e&&function(e){return zt.has(e)}(e)}function jt(e){const t=Number(e);return Number.isFinite(t)?Math.ceil(Number(t.toFixed(2))).toFixed(2):e}function Qt(e){return{...e,amount:jt(e.amount)}}function Wt(e){return{...e,amount:jt(e.amount)}}function Zt(e){const{newLineItems:t,newShippingMethods:a}=e;return{...e,newTotal:Qt(e.newTotal),...t&&{newLineItems:t.map(Qt)},...a&&{newShippingMethods:a.map(Wt)}}}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 Kt=({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 Xt(){const{observability:e}=v(),t=ee(K.ApplePay),{trackComplete:a}=Pt(K.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===X.Attempt)return;if(!r)return void f.remove("apple-pay-authorization");const i=o===X.Success?"success":"failed";f.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 ea(){const e=nt(),t=Xt(),{inMemoryApplePayParts:{asPaymentMethod:a}}=P();return o(()=>{const o=a.value?J.PaymentMethod:J.Express;e(),t({status:X.Failure,walletType:o})},[t,e,a])}function ta(){const e=$(K.ApplePay),t=ee(K.ApplePay),{trackComplete:a}=Pt(K.ApplePay),{checkout:{wallets:n},observability:r}=v(),{inMemoryApplePayParts:i}=P(),s=nt();return o(({session:o,isProcessing:l=!1,isMessagingHandledElsewhere:p=!1,error:d,isAborted:c})=>{if(d instanceof ne)return;f.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}),f.exists("apple-pay-authorization")?(t(X.Failure,u),a({result:"failed",durationMs:f.end("apple-pay-authorization"),walletType:u})):(e(X.Failure,u),r.counter({name:"wallet_sheet_failed",value:1,attributes:{instrument:K.ApplePay}})),l||p||(i.paymentSheetError.value={type:"session_terminated"});const{actionable:y}=bt(d);if(d instanceof re?r.leaveErrorBreadcrumb(`IgnoredApplePayAPIError: ${d.message}`):y?r.error(d,{severity:"error",errorClass:it.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 aa=["BR","KW","PA","PE","PH"];function oa(e){return e.hasFlagEnabled(C)}function na(e,t){if(!t)return{};const a={district:void 0,line2:void 0,subdistrict:void 0},o=e.countryCode?.toUpperCase();return o&&aa.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=[N.InvalidExtensionState,N.InvalidCaptcha,N.SubmittedForCompletion];class ia extends ye{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 he({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 se("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 he({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 se(`violation not handled: ${e.code}`,{groupingHash:`ApplePayAPIError::ViolationNotHandled::${e.code}`}),{severity:"error",errorClass:it.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:K.ApplePay,action:n?.action??"abort",asPaymentMethod:Boolean(a?.asPaymentMethod)}}),this.reportAddressRequirementMismatch({violationCode:r,wallet:K.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=>T.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:K.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(N.InvalidCaptcha)?"captcha_required":"exceptional_completion_status"}}]}},stale:()=>(this.observability.error(new se("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=Vt(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:[...w,"MERCHANDISE_NOT_APPLICABLE",...me,...I,...ve,_e,Ae],generateAction:()=>({action:"abort"})},{violations:ge,generateAction:()=>this.generateAbortAction("session_terminated")},{violations:Pe,generateAction:()=>this.generateAbortAction("shipping_options_changed")},{violations:Ee,generateAction:()=>la("emailAddress",this.translations.emailInvalidError)},{violations:["BUYER_IDENTITY_CONTACT_INFO_DOES_NOT_MATCH_CUSTOMER_PROFILE"],generateAction:()=>this.generateAbortAction("unhandled_completion_status")},{violations:fe,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:[...be],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:[...Se,"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:Ce,generateAction:()=>this.generateDecelerateAction()}]:[{violations:Te,generateAction:()=>sa("name",this.translations.nameContainsEmojisError)},{violations:Ne,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",...R],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:we,generateAction:()=>sa("name",this.translations.lastNameTooLongError)},{violations:["PAYMENTS_ADDRESS1_TOO_LONG","PAYMENTS_ADDRESS2_TOO_LONG"],generateAction:()=>sa("addressLines",this.translations.addressLineTooLongError)},{violations:[Ie],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:Re,generateAction:()=>sa("postalCode",this.translations.postalCodeEmojiError)},{violations:Me,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",...De,...Le],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}=Be(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",...M],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:Oe,generateAction:()=>la("name",this.translations.nameContainsEmojisError)},{violations:De,generateAction:()=>({action:"abort",effects:[()=>{this.inMemoryApplePayParts.paymentSheetError.value={type:"exceptional_completion_status"},this.inMemoryApplePayParts.requirePhoneOnNextAttempt.value=!0}]})}]}getCompletionDeceleratedViolationActions(e){return e?.options?.applePayRecoveryFlowEnabled?[{violations:Ye,generateAction:()=>this.generateDecelerateAction({paymentSheetError:{type:"new_tax_must_be_accepted",tone:"warning"}})},{violations:[...D,L,...xe,...Ue,...O,...ke,"DELIVERY_WRONG_NUMBER_OF_DELIVERY_LINES",...Fe,...Ve],generateAction:()=>this.generateDecelerateAction()}]:this.getCompletionAbortViolationActions()}getCompletionAbortViolationActions(){return[{violations:[...Ye,L,...xe,...O,"DELIVERY_COMPANY_REQUIRED"],generateAction:()=>({action:"abort"})},{violations:Ue,generateAction:()=>this.generateAbortAction("session_terminated")},{violations:ke,generateAction:()=>this.generateAbortAction("unusable_partial_address")},{violations:["DELIVERY_WRONG_NUMBER_OF_DELIVERY_LINES",...Fe],generateAction:()=>this.generateAbortAction("unhandled_completion_status")},{violations:Ve,generateAction:()=>this.generateAbortAction("ineligible_discount")}]}mapUnhandledCompletion(e){return this.observability.error(new se(`Intercepted completion returned unhandled status: ${e.status}`,{groupingHash:`ApplePayAPIError::InterceptedCompletionReturned::Unhandled::${e.status}`}),{severity:"error",errorClass:it.Api}),this.generateAbortAction("unhandled_completion_status")}getNegotiationViolationActions(e){return[{violations:["MERCHANDISE_CART_AND_CURRENCY_UPDATED_BASED_ON_COUNTRY","MERCHANDISE_CART_UPDATED_BASED_ON_COUNTRY",L,...w,...I,_e,Ae],generateAction:()=>({action:"abort"})},{violations:Pe,generateAction:()=>({action:"update",errors:[new ApplePayError("addressUnserviceable")]})},...this.getNegotiationShippingAddressViolationActions(e),{violations:[Ie],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:[...He,"DELIVERY_INVALID_POSTAL_CODE_FOR_COUNTRY","DELIVERY_INVALID_POSTAL_CODE_FOR_ZONE"],generateAction:()=>({action:"no-op"})}]:[{violations:He,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 se(`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 pa(){const{i18n:e,observability:t}=v(),{inMemoryApplePayParts:n,persistedApplePaySignal:r}=P(),i=qe(),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 da({canDecelerate:e,checkout:t}){return e.value&&B({checkout:t})}const ca=class extends F{};ca.type="wallet:address-replace";let ua=ca;function ya({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 ha({observability:o},{errorName:"InvalidAccessError",methodName:e});throw r}else ha({observability:o},{errorName:"SessionAlreadyTerminated",methodName:e})}function ha({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 ma(){const e=ta(),t=V(),{progress:a}=lt(),r=pt(),i=dt(),s=g(),l=at(),p=_().buyerIdentity.value?.customerProfile,d=H(),c=ct(),u=ut("APPLE_PAY"),{inMemoryApplePayParts:{asPaymentMethod:y,requirePhoneOnNextAttempt:h,requireBillingPhoneOnNextAttempt:m,paymentSheetError:b,expiresAt:C,preCompletionHandler:T,subscriptionReviewTransition:N},persistedApplePaySignal:w,walletUsedForSubmissionSignal:I}=P(),R=pa(),M=function(){const e=pa();return o((t,a)=>{const{completionResultMapper:o}=e();if(!o)throw new se("CompletionResultMapper not set up correctly",{groupingHash:"ApplePayAPIError::CompletionResultMapper"});return o.mapResultToPaymentSheetAction(t,a)},[e])}(),D=ea(),O=Xt(),{source:{checkoutSessionIdentifier:B},observability:F,checkout:{wallets:W,address:{countryDetails:Z},configuration:$},shop:ee,events:oe,client:ne}=v(),re=oa(ee),ie=$.addressSettings.nonBillingAddressSettings,le=$.layout.isOnePage,pe=te(K.ApplePay),{trackAttempt:de}=Pt(K.ApplePay),ce=yt(y),ue=_(),ye=ue.buyerIdentity.value?.purchasingCompany,he=ue.availableDeliveryAddresses?.value,me=ue.mustSelectProvidedAddress?.value,ve=E({availableDeliveryAddresses:he,mustSelectProvidedAddress:me}),{email:_e,shippingAddress:Ae,billingAddress:ge,paymentLines:Pe,deliveryLines:Ee}=A(),fe=ze(),be=ht({shouldPersist:!0}),Se=Et({flag:S,onAbort:be,onError:e=>{throw e}}),Ce=function({canDecelerate:e,asPaymentMethod:t}){const a=function({canDecelerate:e}){const t=Y(),{checkout:a,shop:o}=v();return n(()=>(o.hasFlagEnabled(x)||o.hasFlagEnabled(U))&&da({canDecelerate:e,checkout:a})&&t.value)}({canDecelerate:e}),{checkout:o}=v(),r=st();return n(()=>{const n=null!==r,i=da({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?k(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:ce,asPaymentMethod:y}),Te=function(){const{negotiate:e}=lt(),{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=R(),S=y.value,Y=ce.value,x=S?J.PaymentMethod:J.Express;function k(){try{ya({methodName:"completePayment",abortSignal:_,wallets:W,observability:F},()=>n.completePayment(ApplePaySession.STATUS_FAILURE)),F.leaveErrorBreadcrumb("[ApplePay] Completion flow - clearing activeSession (abort path)"),W.clearActiveSession({invokingWallet:"APPLE_PAY"}),F.log("apple_pay_authorization_aborted","Apple Pay authorization aborted during payment completion",{}),D()}catch(a){e({session:n,error:a})}finally{S||t()}}if(de({walletType:x}),f.start("apple-pay-authorization"),O({status:X.Attempt,walletType:x}),!_.aborted&&W.activeSession.value&&A?.())return F.leaveErrorBreadcrumb("ApplePay: authorization blocked by payment method reconciliation"),b.value={type:"session_terminated"},void k();
1function V(t,a){switch(a.effects?.forEach(e=>e()),a.action){case"submit":{const a=u.value,n=B&&a?.walletOrderTypeIdentifier&&a?.walletServiceUrl&&a?.walletAuthenticationToken?{status:ApplePaySession.STATUS_SUCCESS,orderDetails:{orderTypeIdentifier:a.walletOrderTypeIdentifier,orderIdentifier:B,webServiceURL:a.walletServiceUrl,authenticationToken:a.walletAuthenticationToken}}:ApplePaySession.STATUS_SUCCESS;let r=!1;try{ya({methodName:"completePayment",abortSignal:_,wallets:W,observability:F},()=>{t.completePayment(n),r=!0})}catch(o){e({session:t,error:o,isProcessing:!0})}finally{F.leaveErrorBreadcrumb("[ApplePay] payment completed successfully",{walletType:x}),W.clearActiveSession({invokingWallet:"APPLE_PAY"})}return r&&O({status:X.Success,walletType:x}),I.value="APPLE_PAY",r}case"show_error":{const n=Qe(a),r={status:ApplePaySession.STATUS_FAILURE,errors:n};F.log("apple_pay_authorization_has_errors","apple_pay_authorization_has_errors",{errors:n});try{ya({methodName:"completePayment",abortSignal:_,wallets:W,observability:F},()=>t.completePayment(r)),_.aborted||0===r.errors.length?(F.leaveErrorBreadcrumb("[ApplePay] payment failed with no errors or abort action, sheet will close"),W.clearActiveSession({invokingWallet:"APPLE_PAY"}),D()):(F.leaveErrorBreadcrumb("[ApplePay] payment failed with handled errors, sheet will remain open for retry"),D())}catch(o){return e({session:t,error:o}),!1}return!0}case"abort":return k(),!1;case"decelerate":{if(!Y)return k(),!1;const n=a.completePaymentStatus??ApplePaySession.STATUS_FAILURE;try{ya({methodName:"completePayment",abortSignal:_,wallets:W,observability:F},()=>t.completePayment(n)),W.clearActiveSession({invokingWallet:"APPLE_PAY"}),O({status:X.Failure,walletType:x,endsAuthorization:!1}),pe({event:ae.RecoveryFlowInitiated,walletType:x}),le.value&&(W.setEscalatedWallet("APPLE_PAY"),"review"===r.value.currentPage?.id&&i("payment-methods",{replace:!0})),w.value={...w.value,receiptIdForPaymentFailure:void 0,recoverySubmissionAttemptCount:0},le.value?oe.dispatchEvent(new ua):P=!0}catch(o){return e({session:t,error:o}),!1}return!0}default:return e({session:t,error:new se(`Missing handler for payment sheet action "${a.action}"`,{groupingHash:"ApplePayAPIError::MissingHandlerPaymentSheetAction"})}),!1}}const H=ie.value.isRequired("address2"),$=ie.value.isRequired("firstName"),{token:te,billingContact:ue,shippingContact:he}=o.payment,me=ie.value.isRequired("phone",{countryCode:Ht(he?.countryCode)}),be=E.validateBilling(o.payment);if(be.shouldPersist&&ue&&!ye){const e=!l.value&&me||m.value?he?.phoneNumber:void 0;m.value&&he?.phoneNumber&&F.counter({name:"apple_pay_billing_phone_provided_after_retry",value:1,attributes:{asPaymentMethod:S}});const t={...ue,phoneNumber:e};re&&await Z.fetch(Ht(t.countryCode)),va(ge,t,re)}if(be.paymentSheetAction)return void V(n,be.paymentSheetAction);if(F.log("wallets_shipping_address_update","onPaymentAuthorized: decision state before shipping address update",{asPaymentMethod:S,shippingContactDefined:Boolean(he),isShippingContactPostalCodePadded:q(he?.postalCode,Ht(he?.countryCode)),isCurrentProposedPostalCodePadded:q(Ae.value?.postalCode,Ae.value?.countryCode),shippingRequired:l.value}),!S&&!ve){const e=E.validateShipping(o.payment,l.value,H&&!Y,$,me&&!Y);if(e.shouldPersist&&he){c({postalCode:he.postalCode,countryCode:Ht(he.countryCode),city:he.locality,zoneCode:he.administrativeArea||he.subLocality},"APPLE_PAY"),re&&await Z.fetch(Ht(he.countryCode));const e={...Vt(he),...na(he,re)};F.log("wallets_shipping_address_update","onPaymentAuthorized: update with complete shipping address from shippingContact",{isPostalCodePadded:q(e.postalCode,e.countryCode),countryCode:e.countryCode}),va(Ae,he,re)}if(e.paymentSheetAction)return void V(n,e.paymentSheetAction)}if(!S){const e=p?.email??he?.emailAddress;e&&(_e.value=e)}he?.phoneNumber&&Ee.value.forEach(e=>{e.value={...e.value,deliveryMethodOptions:{...e.value.deliveryMethodOptions,phone:he.phoneNumber}}}),h.value&&he?.phoneNumber&&F.counter({name:"apple_pay_phone_provided_after_retry",value:1,attributes:{asPaymentMethod:S}}),S?fe({phone:he?.phoneNumber,email:he?.emailAddress,firstName:ue?.givenName}):fe();const Ne=s.current.fields.paymentDue.value;if(Ne&&Ne.amount>0||d.value){const e=Pe.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}}(te.paymentMethod.displayName);Pe.value=z(e,{method:{type:"wallet",name:"APPLE_PAY",walletContent:{...te.paymentData,lastDigits:a,cardNetworkBrand:t,paymentMethodIdentifier:u.value?.paymentMethodIdentifier,...Y&&{expiresAt:C.value}}}})}const we=Ce.value,Ie=d.value,Re=Ie?G(ne.unstable_getSerialization("experiments")):null,Me=void 0!==g&&g===Q(Re),De=W.activeSession.value,Le=we.isCaliforniaDeceleration&&we.hasSubscription&&!S&&!_.aborted&&"APPLE_PAY"===De?.wallet&&!De.asPaymentMethod&&we.isABTestActive&&Me,Oe={...we,shouldDecelerate:we.shouldDecelerate&&!Le};if(Ie){const e=null!==Re,t=function(e){return e.shouldDecelerate?e.isCaliforniaDeceleration?"california":"decelerated":"none"}(Oe);F.counter({name:"apple_pay_subscriptions_deceleration_variant",value:1,attributes:{variant:Re??j.Control,complete_payment_status:"success",is_ab_test_active:ee.hasFlagEnabled(U),is_california_excluded:Oe.isCaliforniaDeceleration,has_caution_banner:!1,deceleration_scope:t,is_enrolled:e,as_payment_method:S}})}if(Oe.shouldDecelerate){if(le.value&&!(await Te(_,k)))return;if(W.setEscalatedWallet("APPLE_PAY"),W.setIsDecelerating(!0),!V(n,{action:"decelerate",completePaymentStatus:ApplePaySession.STATUS_SUCCESS,effects:[]}))return W.setEscalatedWallet(null),W.setIsDecelerating(!1),W.setHasActiveApplePaySubscriptionReview(!1),void(N.value=void 0);if(N.value="in_app_deceleration",W.setHasActiveApplePaySubscriptionReview(!0),P)try{await Se({wallet:"APPLE_PAY",reason:"subscriptions",asPaymentMethod:S})}catch(Ve){N.value=void 0,Ve instanceof Error&&e({session:n,error:Ve})}return}const Be=T?.value;if(Be&&!(await Be()))return F.leaveErrorBreadcrumb("ApplePay: Pre-completion handler failed",{asPaymentMethod:S}),void k();v.value=!0;let Ye=0,xe="",Ue="unexpected error",ke=[];const Fe=Ge(s.current.fields.deliveryNext?.value);try{F.leaveErrorBreadcrumb("ApplePay: Payment authorized negotiation",{retryCount:Ye});const e=Ae.value;for(;;){let t=!1;if(_.aborted)break;if(await a("apple-pay-payment-authorized",a=>{const o=a;"rejected"===o.status&&(ke=o.violations.map(e=>e.code),o.violations.some(e=>"BUYER_IDENTITY_MISSING_CONTACT_METHOD"===e.code)&&F.log("apple_pay_on_payment_authorized","Apple Pay is missing contact method",{asPaymentMethod:y.value,proposedEmail:_e.value||"",customerProfileEmail:p?.email||"",shippingContactEmail:he?.emailAddress||"",hasShippingContact:Boolean(he),shippingContactPhone:he?.phoneNumber||"",allViolationCodes:o.violations.map(e=>e.code).join(","),isPhoneRequired:me}));const r="rejected"===o.status&&o.violations.some(e=>e.code===L),{shouldRetry:i,retryReason:l,updatedDeliveryMethodHandles:d}=_a(o,{retryCount:Ye,negotiated:s,originalSelectedDeliveryMethods:Fe});if(i&&!r)return d&&(mt(Ee,d),x===J.Express&&(F.log("wallets_shipping_address_update","onPaymentAuthorized: restoring address snapshot on retry",{isSnapshotPostalCodePadded:q(e?.postalCode,e?.countryCode),countryCode:e?.countryCode,retryCount:Ye}),ve||(Ae.value=e))),F.leaveErrorBreadcrumb(`ApplePay: retrying due to ${l}`,{retryCount:Ye}),Ye++,xe=l,void(t=!_.aborted);F.leaveErrorBreadcrumb("ApplePay: completed negotiation",{action:"paymentAuthorized",status:a.status,retryCount:Ye,retryReason:xe});const c=M(o,{shippingCountryCode:Ht(he?.countryCode),billingCountryCode:Ht(ue?.countryCode),...Y&&{options:{applePayRecoveryFlowEnabled:Y,asPaymentMethod:y.value}}});V(n,c),Ue=a.status},{skipToCompletion:!0,customizeCompletion:x===J.Express?je:void 0}),!t)break}P&&await Se({wallet:"APPLE_PAY",reason:"submitForCompletion",asPaymentMethod:S})}catch(Ve){Ve instanceof Error&&e({session:n,error:Ve})}finally{v.value=!1,Ye>0&&(F.counter({name:"wallet_submit_for_completion_retry",value:1,attributes:{retry_reason:xe||"unknown",retry_count:Ye,status:Ue,instrument:K.ApplePay}}),F.log("wallet_submit_for_completion_retry_details","[ApplePay] SubmitForCompletion retry details",{retryReason:xe,retryCount:Ye,status:Ue,instrument:K.ApplePay,asPaymentMethod:S,lastRejectionViolationCodes:ke}))}},[y,ie,R,h,m,b,s,d,u,B,I,e,de,O,D,t,ye,ge,l,p?.email,c,Ae,_e,Ee,Pe,a,Te,M,fe,W,F,w,ce,Se,le,oe,C,T,N,pe,ve,Ce,Z,re,ne,ee,r,i])}function va(e,t,a){const o=na(t,a),n=e.fields.line2;e.value={...Vt(t),...o},n&&"line2"in o&&(n.value=o.line2)}function _a(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=We(e,a.current.fields.deliveryNext?.peek(),o);return r?{shouldRetry:!0,retryReason:"delivery_option_mismatch",updatedDeliveryMethodHandles:r}:n}function Aa(){const e=pa();return o((t,a)=>{const{negotiationResultMapper:o}=e();if(!o)throw new se("NegotiationResultMapper not set up correctly",{groupingHash:"ApplePayAPIError::NegotiationResultMapper"});return o.mapResultToPaymentSheetAction(t,a)},[e])}function ga(){const e=ea(),t=v(),{checkout:{wallets:a},observability:n}=t;return o(({session:t,paymentSheetAction:o,onProceed:r,abortSignal:i})=>{switch(o.action){case"abort":ya({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 se(`Missing handler for payment sheet action "${o.action}"`,{groupingHash:"ApplePayAPIError::MissingHandlerPaymentSheetAction"})}},[e,a,n])}function Pa(){const e=ta(),t=g(),a=$(K.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=qt({embed:c,isCrossOriginIframeEnabled:l.hasFlagEnabled(W)}),m=function(){const{checkout:e,observability:t}=v(),a=e.configuration.addressSettings.nonBillingAddressSettings.value,n=tt(),r=_(),i=a.isRequired("phone",{countryCode:Ht(r.buyerIdentity.value?.countryCode)}),s=at(),{value:l}=r.deliveryNext,p=A(),d=g(),c=ot(),{paymentDue:u,recurringTotals:y,...h}=ue(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:Kt({asPaymentMethod:o,phoneRequired:i,shouldRequestPhoneOnRetry:r,shopPayOptInExists:d}),emailRequired:Jt({asPaymentMethod:o,emailRequired:n.value,shopPayOptInExists:d,proposedEmailExists:v}),shippingRequired:!A&&s.value}),I=Ft(m.lineItemsLabels.total,u),R=Mt({...h,formattedRecurringTotals:c(y),...m}),M=A?[]:Lt({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 Gt(u.currencyCode)?function(e){const{lineItems:t,shippingMethods:a}=e;return{...e,total:Qt(e.total),...t&&{lineItems:t.map(Qt)},...a&&{shippingMethods:a.map(Wt)}}}(D):D},[T,N,w,b,f,l,n,S,c,m,C,h,u,i,y,s,t,p])}(),C=function(){const e="apple-pay-gateway.apple.com/paymentservices/startSession";return"CN"===At().geolocation.country.code?`https://cn-${e}`:`https://${e}`}(),T=function(){const e=$(K.ApplePay),{trackComplete:t}=Pt(K.ApplePay),a=nt(),{inMemoryApplePayParts:n}=P(),{checkout:r,observability:i,shop:s}=v(),l=rt();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;f.remove("apple-pay-sheet-load"),f.exists("apple-pay-authorization")&&t({result:"failed",durationMs:f.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:K.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=b(s),h=s.hasFlagEnabled(S),m=void 0!==n.subscriptionReviewTransition.value&&et({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(X.Cancelled)},[a,n.asPaymentMethod,n.paymentSheetError,n.subscriptionReviewTransition,n.requirePhoneOnNextAttempt,n.prefetchPaymentSession,t,e,i,s,r,l])}(),N=function(){const e=$(K.ApplePay),t=ta(),{shop:a,source:{sourceId:n},observability:r,checkout:{wallets:i},embed:s,graphql:{coreGraphql:l}}=v(),p=qt({embed:s,isCrossOriginIframeEnabled:a.hasFlagEnabled(W)}),{inMemoryApplePayParts:{prefetchPaymentSession:d}}=P(),c=_t(K.ApplePay);return o((a,o,s,u)=>{const y=u===d.value?.prefetchUrl;r.histogram({name:"apple_pay_prefetch_session",value:f.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 ne)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}),It({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 Nt)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 re(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 re("Apple Pay session query returned no data after session was cancelled"):new se("session query returned no data");return void t({session:a,error:l,isAborted:e})}e(X.Success,o?J.PaymentMethod:J.Express),o||c(),ya({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,d,i,p])}(),w=function(){const{observability:e,checkout:{wallets:t,address:{countryDetails:a,extendedAddressMode:n}},checkout:r,shop:i}=v(),s=oa(i),l=ta(),p=ea(),d=Aa(),c=ot(),u=g(),y=te(K.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(Ht(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:St(t,n)}}))}}}(e,{...Vt(t),...na(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:Ht(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}),ya({methodName:"abort",abortSignal:v,wallets:t,observability:e},()=>i.abort()),t.clearActiveSession({invokingWallet:"APPLE_PAY"}),p())}},walletName:K.ApplePay,logPrefix:"ApplePay::useOnPaymentMethodSelected"})}catch(b){b instanceof Error&&l({session:i,error:b})}}if(i&&t.activeSession.value){if(g&&!(await async function(a){let o=!1;try{o=await a(v)}catch(b){return b instanceof Error&&l({session:i,error:b}),!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 se("Payment method selection reconciliation timed out",{groupingHash:"ApplePayAPIError::PaymentMethodSelectionReconciliationTimeout"})})),o)}(g)))return;!function(){const{paymentDue:a,recurringTotals:o,...n}=ue(u);if(null==a)return l({session:i,error:new se("Missing negotiated payment due",{groupingHash:"ApplePayAPIError::MissingNegotiatedPaymentDue"})});const r=Gt(a.currencyCode);try{ya({methodName:"completePaymentMethodSelection",abortSignal:v,wallets:t,observability:e},()=>{const e={newTotal:Ft(_.total,a),newLineItems:Mt({...n,formattedRecurringTotals:c(o),formattedRecurringTotalTooltip:m,lineItemsLabels:_,deliveryOptionGroupTypeLabels:A,deliveryMethodTitlePrefixes:P})};i.completePaymentMethodSelection(r?Zt(e):e)})}catch(b){b instanceof Error&&l({error:b,session:i})}}()}r.isShippingRequired.value||f.endAndRun("apple-pay-sheet-load",t=>{y({event:ae.SheetLoaded,ttl:t}),e.histogram({name:"wallet_sheet_loaded",value:t,attributes:{instrument:K.ApplePay}})})},[t,p,P,A,c,m,d,_,u,r.isShippingRequired,e,l,y,h,n,a,s])}(),I=function(){const e=ta(),t=ot(),a=Aa(),n=g(),r=vt(),{observability:i,checkout:{wallets:s,address:{countryDetails:l,extendedAddressMode:p}},shop:d}=v(),c=oa(d),{inMemoryApplePayParts:{initialDeliveryIdentifier:u}}=P(),{deliveryLines:y,shippingAddress:h}=A(),m=te(K.ApplePay),b=Ze(),S=_(),C=S.availableDeliveryAddresses?.value,T=S.mustSelectProvidedAddress?.value,N=S.deliveryNext?.value,w=E({availableDeliveryAddresses:C,mustSelectProvidedAddress:T}),{formattedRecurringTotalTooltip:I,lineItemsLabels:R,deliveryOptionGroupTypeLabels:M,deliveryMethodTitlePrefixes:D}=$t(),L=ga();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 Ke(t)}catch(a){return e({session:d,error:new se("Invalid shipping method identifier",{groupingHash:"ApplePayAPIError::InvalidShippingMethodIdentifier",cause:a,metadata:{identifier:t}})}),null}};if(A){const e=g(_);
1if(null==e)return;return mt(y,e),void S(d)}const P=h.value,E=g(o.shippingMethod.identifier);if(null!=E){mt(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 b({abortSignal:v,fieldsToResolve:["deliveryNext","duties","taxes"],customizeNegotiation:e=>$e(e,P,{interfaceFlow:"APPLE_PAY",isPickupSelected:r.value,isConstrainedAddress:w,availableDeliveryAddresses:C,negotiatedDelivery:N,deliveryAddressOptions:{extendedAddressMode:p}}),observability:i,walletName:K.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}),L({session:d,paymentSheetAction:e,onProceed:()=>S(d),abortSignal:v})}catch(o){o instanceof Error&&e({error:o,session:d})}}},logPrefix:"ApplePay::useOnShippingMethodSelected"})}catch(T){e({session:d,error:T})}}function S(a){const{paymentDue:o,recurringTotals:r,...l}=ue(n);if(null==o)return e({session:a,error:new se("Missing negotiated payment due",{groupingHash:"ApplePayAPIError::MissingNegotiatedPaymentDue"})});const p=Gt(o.currencyCode);try{ya({methodName:"completeShippingMethodSelection",abortSignal:v,wallets:s,observability:i},()=>{const e={newTotal:Ft(R.total,o),newLineItems:Mt({...l,formattedRecurringTotals:t(r),formattedRecurringTotalTooltip:I,lineItemsLabels:R,deliveryOptionGroupTypeLabels:M,deliveryMethodTitlePrefixes:D})};a.completeShippingMethodSelection(p?Zt(e):e)}),f.endAndRun("apple-pay-sheet-load",e=>{m({event:ae.SheetLoaded,ttl:e}),i.histogram({name:"wallet_sheet_loaded",value:e,attributes:{instrument:K.ApplePay}})})}catch(T){T instanceof Error&&e({error:T,session:a})}}},[s,D,M,t,I,a,L,r,R,n,y,h,e,i,m,u,b,w,C,N,l,c,p])}(),R=function(){const e=ta(),t=ot(),a=Aa(),n=g(),r=vt(),{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=oa(f.shop),{formattedRecurringTotalTooltip:I,lineItemsLabels:R,deliveryOptionGroupTypeLabels:M,deliveryMethodTitlePrefixes:D,connectTwoShippingTitles:L}=$t(),O=ga(),{shouldGateCrossBorder:B,crossBorderGate:Y}=oe(),x=yt(s);return o(async(o,s,c)=>{const y={...Vt(o.shippingContact),...na(o.shippingContact,w)};C.log("wallets_shipping_address_update","onShippingContactSelected: update with partial shipping address",{countryCode:y.countryCode,isPostalCodePadded:q(y.postalCode,y.countryCode)});const v=o.shippingContact.countryCode?Ht(o.shippingContact.countryCode):void 0;if(mt(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 re("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:q(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:K.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:Ht(o.shippingContact.countryCode),...t&&{options:{applePayRecoveryFlowEnabled:t}}});
1n.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}=ue(n);if(null==r)return e({session:a,error:new se("Missing negotiated payment due",{groupingHash:"ApplePayAPIError::MissingNegotiatedPaymentDue"})});const d=Gt(r.currencyCode);try{const e={newTotal:Ft(R.total,r),newLineItems:Mt({...p,formattedRecurringTotals:t(s),formattedRecurringTotalTooltip:I,lineItemsLabels:R,deliveryOptionGroupTypeLabels:M,deliveryMethodTitlePrefixes:D})},n=Lt({deliveryMethodTitlePrefixes:D,connectTwoShippingTitles:L,deliveryNext:l}),u={...e,newShippingMethods:n};ya({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])}(),M=ma();return o(({asPaymentMethod:o=!1,supportedNetworks:l,waitForTotalsToSettle:c,isPaymentAuthorizationBlocked:v,subscriptionConsent:_})=>{f.start("apple-pay-session-begin"),i.value=void 0,n.value=o;const A=r(!1),g=new AbortController,{paymentDue:P}=ue(t);if(!P)return a(X.Failure,o?J.PaymentMethod:J.Express),i.value={type:"session_terminated"},d.error(new se("Missing paymentDue",{groupingHash:"ApplePayAPIError::MissingPaymentDue"}),{severity:"error",errorClass:it.Api}),{session:void 0,error:"no_payment_due"};let E;s.value||(s.value={prefetchPromise:(async()=>(await Promise.resolve(),It({graphql:u,sourceId:p,validationUrl:C,asPaymentMethod:o,signal:g.signal,observability:d,isPrefetch:!0,domain:h})))(),prefetchUrl:C});const b=m(l,y);try{E=new ApplePaySession(Z,b)}catch(S){return S instanceof Error&&e({error:S}),{session:void 0,error:"session_creation_failed"}}return E.oncancel=()=>T(g,A),E.onvalidatemerchant=e=>N(E,o,g.signal,e.validationURL),E.onpaymentmethodselected=e=>w(e,E,g.signal,c),E.onshippingmethodselected=e=>I(e,E,g.signal),E.onshippingcontactselected=e=>R(e,E,g.signal),E.onpaymentauthorized=e=>M(e,E,A,g.signal,v,_),{session:E,error:void 0}},[n,m,t,i,T,M,w,R,I,N,y,e,a,s,C,u,d,p,h])}function Ea(){const{inMemoryApplePayParts:{asPaymentMethod:e,expiresAt:t}}=P(),{observability:a,checkout:{wallets:n}}=v(),r=yt(e);return o(o=>{if(o){f.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:K.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 fa=new Set(D);function ba(){const{applePaySessionHandler:e,inMemoryApplePayParts:t}=P(),a=gt(function(){const{negotiate:e}=lt(),t=pt(),{observability:a,shopPay:o,checkout:{wallets:n,identity:r,proposal:i}}=v(),s="shopPay"===r.current.value,{inMemoryApplePayParts:{isLoadingPaymentSheet:l,paymentSheetError:p}}=P(),d=s?K.ShopPayApplePay:K.ApplePay,c=Pa(),u=$(d),y=Ct(),h=rt(),{shopOfferReconciliationPending:m}=o,A=Ea(),g=_().paymentMethods?.value,E=g?.find(e=>"wallet"===e.type&&"APPLE_PAY"===e.name),f=E?.supportedNetworks,b=e=>{if(!m.value)return Promise.resolve(!0);a.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)}(m,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:d})=>{if(!o){u(X.Clicked,J.PaymentMethod);try{const o=c({asPaymentMethod:!0,supportedNetworks:f||[],waitForTotalsToSettle:b,isPaymentAuthorizationBlocked:()=>m.value}),u=await(async o=>{l.value=!0;try{if(s){if(!o||!o())return!1;y()}const n=await new Promise((a,o)=>{e({legacyFiltering:{include:["deliveryNext"]},runListenersOnError:!0,negotiationStage:"completion",silenceViolations:ft({journey:t.value,negotiated:i.negotiated.value,fieldsToValidate:["deliveryNext"]}),onComplete:a}).catch(o)}),r=h.value&&"error"===n.status&&n.violations.length>0&&n.violations.every(({code:e})=>fa.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{l.value=!1}})(d),v=!r||r.current;u&&!n.activeSession.value&&v&&A(o.session)}catch(v){a.leaveErrorBreadcrumb("Failed to create Apple Pay session",{error:v,shopPay:s}),p.value={type:"failed_to_create_session"},"APPLE_PAY"===n.activeSession.value?.wallet&&n.clearActiveSession({invokingWallet:"APPLE_PAY"})}}}}()),o=gt(Pa()),n=gt(Ea());return i(()=>
1{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{ba 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.