1import{hQ as e,hR as t,ar as n,gs as o,hS as i,fI as a,cj as r,hG as s,bg as l,hT as d,hK as u,K as c,P as p,a8 as m,hU as y,N as h,be as g,dk as b,cK as f,cz as v,g3 as S,e9 as P,dj as A,aR as M,hV as C,hg as T,a as _,Q as I,hW as k,hX as x,J as E,a7 as D,by as w,gm as R,p as L,as as N,hY as F,hZ as B,hk as O,v as q,h_ as U,h$ as V,i0 as H,i1 as j,i2 as z,i3 as G,i4 as Y,i5 as W,ep as $,i6 as K,i7 as Q,i8 as J,eq as X,i9 as Z,ck as ee,e8 as te,ia as ne,ib as oe,ic as ie,id as ae,ag as re,ie as se,ig as le,ih as de,ii as ue,ij as ce,ik as pe,M as me,il as ye,b3 as he,im as ge,io as be,ip as fe,iq as ve,ir as Se,is as Pe,it as Ae,dQ as Me,S as Ce,iu as Te,iv as _e,iw as Ie,ix as ke,iy as xe,iz as Ee}from"./9dba8418.DInoCEzY.js";import{p as De,t as we,b as Re,d as Le,m as Ne,c as Fe,e as Be,f as Oe,g as qe,j as Ue,k as Ve,l as He,n as je,o as ze,q as Ge,r as Ye,u as We,v as $e,w as Ke,x as Qe,y as Je,z as Xe,A as Ze,B as et,C as tt,D as nt}from"./6a2fc6d6.CktMoRVE.js";import{p as ot,a as it}from"./1d34c07e.h4dJAaCz.js";import{ah as at,G as rt,a5 as st,j as lt,am as dt,M as ut,R as ct,Q as pt}from"./2c1ab0fe.Bywc2Brn.js";import{s as mt,g as yt,a as ht,d as gt,b as bt}from"./7fc410e0.DLvYSOnD.js";import{g as ft,a as vt}from"./413b21e2.IQKCsTEl.js";import{g as St,a as Pt,d as At,t as Mt,p as Ct,b as Tt,f as _t,r as It,s as kt,i as xt,j as Et,k as Dt,l as wt,o as Rt}from"./2255f8fa.8KqxH4Pm.js";import{a as Lt,b as Nt}from"./e477f96c.Bzke7wRl.js";import{S as Ft,s as Bt}from"./app.D2wFhSFv.js";import{d as Ot}from"./b8733b27.DhvkBeeV.js";import{g as qt}from"./ac5a19ff.By75ODwH.js";import{r as Ut}from"./2bac2c53.gEGJwgcc.js";import{D as Vt,r as Ht,w as jt,s as zt,f as Gt}from"./d0bb51ec.DwFzQH6k.js";import"./2495faa4.Tu9qVTlu.js";import"./cf29e63b.Cl-tFGZz.js";import"./cb38e5c2.BxvsOkWl.js";import"./d25d1b95.DsyU8-pY.js";import"./f67abd2c.CxgiarJo.js";import"./e39bc11c.gbgXD8RN.js";import"./08a3b809.5tqP2mr3.js";function Yt(e=[]){return new Set([...(e??[]).map(({stableId:e})=>e),...(e??[]).flatMap(({lineComponents:e})=>e.map(({stableId:e})=>e))])}class Wt extends Error{constructor(){super(...arguments),this.name="UnknownMerchandiseTypeError"}}function $t(t){switch(t.typename){case"ContextualizedProductVariantMerchandise":case"ProductVariantMerchandise":return{productVariantReference:{id:t.id,variantId:t.variantId,properties:Kt(t.properties),sellingPlanId:t.sellingPlan?.id??null,sellingPlanDigest:t.sellingPlan?.digest??null}};case"SourceProvidedMerchandise":if(!e(t))throw new Wt("Source-provided merchandise is missing the fields only the server can supply");return{sourceProvidedMerchandise:{title:t.title,subtitle:t.subtitle??void 0,price:{value:{amount:t.itemPrice.amount.toFixed(2),currencyCode:t.itemPrice.currencyCode}},giftCard:t.giftCard,productType:t.productType,sku:t.sku,variantId:t.variantId??void 0,productIdV2:t.productId??void 0,properties:Kt(t.properties),requiresShipping:t.requiresShipping,vendor:t.vendor??void 0,taxCode:t.taxCode??void 0,taxable:t.taxable??!0,taxesIncluded:t.taxesIncluded,optionalIdentifier:t.optionalIdentifier??void 0,weight:t.weight?{value:t.weight.value,unit:t.weight.unit}:void 0}};default:throw new Wt(`Unrecognized merchandise type: ${t.typename}`)}}function Kt(e){return e.map(e=>{switch(e.sourceType){case"MerchandisePropertyValueNull":return{name:e.name,value:e.value};case"MerchandisePropertyValueString":return{name:e.name,value:{string:e.value}};case"MerchandisePropertyValueInt":return{name:e.name,value:{integer:e.value}};case"MerchandisePropertyValueFloat":return{name:e.name,value:{float:e.value}};case"MerchandisePropertyValueBoolean":return{name:e.name,value:{boolean:e.value}};case"MerchandisePropertyValueJson":return{name:e.name,value:{json:JSON.parse(e.value)}};default:rt(e)}})}function Qt(e){if(!e)return{any:!0};const{currencyCode:t}=e;return{value:{amount:e.amount.toFixed(at(t)),currencyCode:t}}}function Jt(e,t){const n={stableId:e.stableId,merchandise:$t(e),quantity:{items:{value:e.quantity}},expectedTotalPrice:Qt(e.totalPrice)};if("parentRelationship"in e&&e.parentRelationship?.parent){const o=t().get(e.parentRelationship.parent.stableId);o&&(n.parent=Jt(o,t))}return n}function Xt(e){if(e)return{total:{amount:e.total.amount.toString(),currencyCode:e.total.currencyCode}}}function Zt(e){if(e&&0!==e.length)return{availableRedeemables:e.map(ft)}}function en(e){if(e)return{provider:e.provider,challenge:e.challenge,token:e.token}}function tn({shippingAddress:e,proposedDeliveryLines:a,externalDeliveryIds:r,destinationChanged:s,isSubmitForCompletion:l,isPointOfSale:d,isPointOfSaleShipToHome:u,negotiatedDelivery:c,filteredMerchandiseStableIds:p,locationAddress:m,geolocationCoordinates:y,retailLocationId:h,isShippingRequired:g,availableDeliveryAddresses:b,isConstrainedAddress:f,extendedAddressMode:v,marketDrivenShippingEnabled:S,stableIdToShopId:P,remoteShopsConfigMap:A}){const M="filled"===c?.status?c.lines.map(({type:e})=>e):[],C=a.sort((e,t)=>
1{const n=e.peek().type,o=t.peek().type;return M.indexOf(n)-M.indexOf(o)}),T=function(e){const t=e.find(e=>"ONE_TIME_PURCHASE"===e.peek().type);if(t)return t.peek().deliveryMethodOptions}(C),_="filled"===c?.status&&c.sourceIsBuyerProposal,I=C.map(e=>{const t=e.peek(),n="filled"===c?.status&&c?.lines.find(({type:e,id:n})=>e===t.type&&(!n||n===t.id))||void 0;return{proposedDeliveryLine:t,negotiatedDeliveryLine:n}}),k=I.map(({proposedDeliveryLine:e,negotiatedDeliveryLine:t})=>{const o=function({proposedDeliveryLine:e,filteredMerchandiseStableIds:t,marketDrivenShippingEnabled:n,stableIdToShopId:o,remoteShopsConfigMap:i}){const a=nn(e.targetMerchandiseLines,t)[0]?.stableId,r=a?o?.get(a):void 0;if(r){const e=i?.get(r);return{shopId:r,enabled:e?.marketDrivenShippingEnabled??!1,remoteConfigMissing:!e}}return{shopId:"local",enabled:n,remoteConfigMissing:!1}}({proposedDeliveryLine:e,filteredMerchandiseStableIds:p,marketDrivenShippingEnabled:S,stableIdToShopId:P,remoteShopsConfigMap:A}),i=function(e,t){const o=e.deliveryMethodHandle;if(!t||"not_required"===t.status||!o)return;const i=t.methods.find(({handle:e})=>e===o);return i?.cost?{amount:i.cost.amount,token:n(i)}:void 0}(e,t);return{...o,enabled:o.enabled||o.remoteConfigMissing&&Boolean(i?.token),rate:i}}),x=k.some(({enabled:e})=>e)?t(k,({rate:e})=>e?.amount??0,({enabled:e,shopId:t,rate:n})=>e&&n?.token?`${t}:${n.token}`:void 0):new Set;return I.map(({proposedDeliveryLine:t,negotiatedDeliveryLine:n},a)=>function({shippingAddress:e,proposedDeliveryLine:t,externalDeliveryIds:n,destinationChanged:a,negotiatedDeliveryLine:r,filteredMerchandiseStableIds:s,locationAddress:l,geolocationCoordinates:d,proposedAlternateOptions:u,isSubmitForCompletion:c,isPointOfSale:p,isPointOfSaleShipToHome:m,retailLocationId:y,isShippingRequired:h,availableDeliveryAddresses:g,isConstrainedAddress:b=!1,negotiatedSourceIsBuyerProposal:f=!1,extendedAddressMode:v,foldExpectedTotalPriceToZero:S=!1}){const P=t.targetMerchandiseLines.filter(({stableId:e})=>s.has(e)),A=P.length?P.some(({requiresShipping:e})=>e):void 0,M=r?.targetMerchandiseLines?.some(({requiresShipping:e})=>e),C=A??h??M??!0,{deliveryMethodHandle:T,deliveryMethodTypes:_,deliveryMethodOptions:I,targetMerchandiseLines:k,isCustomRate:x,customDeliveryStrategy:E}=t,D=function({proposedHandle:e,negotiatedHandle:t,canOverwriteNullishProposedHandle:n}){return n?e??t:e}({proposedHandle:T,negotiatedHandle:"available"===r?.status?r?.selectedDeliveryMethodHandle:void 0,canOverwriteNullishProposedHandle:f||b});let w;if("available"===r?.status){const e=r.methods.find(({handle:e})=>e===(T??D));w=e?.isCustomRate??x}else w=x;const R=mt({deliveryMethodHandle:D,deliveryMethodOptions:{instructions:I.instructions??u?.instructions,phone:I.phone??u?.phone},isCustomRate:w,isPointOfSale:p,retailLocationId:y,isPointOfSaleShipToHome:m,customDeliveryStrategy:E});!function(e,t){t?.externalCheckoutSessionId&&(e.externalCheckoutSessionId=t.externalCheckoutSessionId),t?.externalCustomerId&&(e.externalCustomerId=t.externalCustomerId),t?.externalPromiseId&&(e.externalPromiseId=t.externalPromiseId)}(R,n);const L=function({proposedTargetMerchandiseLines:e,filteredMerchandiseStableIds:t,hasMatchingNegotiatedDeliveryLine:n,isShippingRequired:o}){const i=nn(e,t);return i.length?{lines:i}:o?o&&!n?{any:!0}:{lines:[]}:{any:!0}}({proposedTargetMerchandiseLines:k,filteredMerchandiseStableIds:s,hasMatchingNegotiatedDeliveryLine:Boolean(r),isShippingRequired:h});let N;N=p&&!m?["RETAIL"]:C?_:["NONE"];const F=N.length>0&&N.every(e=>"PICK_UP"===e),B=N.includes("PICKUP_POINT"),O=C&&!F;let q;const U=g?.find(t=>o(t.address,e,["phone","zoneCode"])),V=g?.find(t=>o(t.address,e,["phone","zoneCode"])&&i(t.address,e));O?q=B&&l?yt(l,{extendedAddressMode:v}):b?{deliveryAddressReference:ht(g[0].address)}:V?{deliveryAddressReference:ht(V.address)}:c?{streetAddress:gt(e,{extendedAddressMode:v})}:{partialStreetAddress:gt(e,{extendedAddressMode:v})}:F&&(U?q={deliveryAddressReference:ht(U.address)}:l?.coordinates||l?.postalCode?q=yt(l,{extendedAddressMode:v}):d&&l?.countryCode&&(q=yt({countryCode:l.countryCode,coordinates:d},{extendedAddressMode:v})));const H=function(e,t,n=!1){const o={any:!0};if(!e||"not_required"===e.status||!t)return o;const{methods:i}=e,a=i.find(({handle:e})=>e===t)?.cost;if(!a)return o;const r=at(a.currencyCode);return{value:{amount:(n?0:a.amount).toFixed(r),currencyCode:a.currencyCode}}}(r,T,S);return{destination:q,selectedDeliveryStrategy:R,targetMerchandiseLines:L,deliveryMethodTypes:N,expectedTotalPrice:H,destinationChanged:a}}({shippingAddress:e,proposedDeliveryLine:t,externalDeliveryIds:r,destinationChanged:s,negotiatedDeliveryLine:n,filteredMerchandiseStableIds:p,locationAddress:m,geolocationCoordinates:y,proposedAlternateOptions:T,isSubmitForCompletion:l,isPointOfSale:d,isPointOfSaleShipToHome:u,retailLocationId:h,isShippingRequired:g,availableDeliveryAddresses:b,isConstrainedAddress:f,negotiatedSourceIsBuyerProposal:_,extendedAddressMode:v,foldExpectedTotalPriceToZero:x.has(a)}))}function nn(e,t){return e.reduce((e,{stableId:n})=>n&&t.has(n)?[...e,{stableId:n}]:e,[])}function on(e,t){if(e.anyAllocation)return{anyAllocation:e.anyAllocation};const n=Yt(t);return{allocated:{allocations:e.allocations.reduce((e,t)=>
1{const{target:{type:o,amount:i,stableId:a}}=t;if("MERCHANDISELINE"===o){if(a){if(!n.has(a))return e;e.push({amount:{value:{amount:i.amount.toString(),currencyCode:i.currencyCode}},target:{merchandiseLineTarget:{stableId:a}}})}}else e.push(function(e){const{target:{index:t,amount:{currencyCode:n,amount:o}}}=e;return{amount:{value:{amount:o.toString(),currencyCode:n}},target:{deliveryLineTarget:{atIndex:t}}}}(t));return e},[])}}}function an(e){switch(e.value?.typename){case"FixedAmountValue":{const{fixedAmount:{amount:t,currencyCode:n},appliesOnEachItem:o}=e.value;return{fixedAmountValue:{value:{amount:t.toString(),currencyCode:n},appliesOnEachItem:o}}}case"PercentageValue":{const{percentage:t}=e.value;return{percentageValue:{percentage:t.toString()}}}default:return{}}}function rn(e){const{signature:t="",signatureUuid:n=""}=e;return t.length&&n.length?{value:t,uuid:n}:null}function sn(e,t,n){return e.lines.reduce((e,o)=>{let i=null;return a(o)?i=function(e){return{allocationSet:{anyAllocation:{totalAmount:{any:!0}}},discount:{discountWithCode:e.title},required:!0}}(o):"code"===o.discount.type?i=function(e,t,n){const o=on(e,t);return o.anyAllocation||o.allocated.allocations.length||n?.leaveErrorBreadcrumb("discount.codeDiscountLineForGraphQL.no_allocation",{discountType:e.discount.type,discountTitle:e.discount.title,discountValue:e.discount.value}),{allocationSet:o,discount:{discountWithCode:e.discount.title},required:!0}}(o,t,n):"custom"===o.discount.type&&(i=function(e,t,n){const o=e.discount,i=on(e,t);return i.anyAllocation||i.allocated.allocations.length?{allocationSet:i,discount:{customDiscount:{targetEntireCart:"CART"===o.presentationLevel,title:o.title,description:o.description??null,value:an(o),signature:rn(o),type:o.discountType}},required:!0}:(n?.leaveErrorBreadcrumb("discount.customDiscountLineForGraphQL.no_allocation",{discountType:o.discountType,discountTitle:o.title,discountValue:an(o)}),null)}(o,t,n)),null!=i&&e.push(i),e},[])}
1function ln(e,t,n){return{message:t??e.note??null,customAttributes:n?.map(({...e})=>e)??e.customAttributes?.map(e=>({key:e.key,value:e.value}))??[]}}const dn={any:!0};class un extends Error{constructor(){super(...arguments),this.name="MalformedDateStringError"}}class cn extends Error{constructor(){super(...arguments),this.name="BankPaymentLineDroppedError"}}function pn(e,t,n){switch(e.name){case"PAYPAL_EXPRESS":{const o=e.walletContent,i=o?.payerApprovedAmount;return{name:"PAYPAL_EXPRESS",walletContent:{paypalWalletContent:{...o?.authAssertionContext&&{authAssertionContext:o.authAssertionContext},email:o?.email??"",payerId:o?.payerId??"",token:o?.token??"",expiresAt:o?.expiresAt??null,merchantId:o?.merchantId??null,currencyCode:o?.currencyCode??null,isVenmo:o?.isVenmo??null,...o?.isVaultWithPurchaseOrder&&{isVaultWithPurchaseOrder:!0},paymentMethodIdentifier:o?.paymentMethodIdentifier??"",...n&&{acceptedSubscriptionTerms:n},...t&&{vaultingAgreement:t},...i&&{payerApprovedAmount:{amount:i.amount,currencyCode:i.currencyCode}}}}}}case"SHOP_PAY":{const t=e.walletContent;if(null==t)return null;const n=t.creditCardInstallments?{installmentsCount:t.creditCardInstallments,intervalType:"MONTH"}:void 0;return{name:"SHOP_PAY",walletContent:{shopPayWalletContent:{sessionToken:t.sessionToken??"",billingAddress:{streetAddress:t.billingAddress},paymentAttributes:t.paymentAttributes,paymentMethod:t.paymentMethod,paymentMethodIdentifier:t.paymentMethodIdentifier??"",addressId:t.addressId,...null!=t.hsaRequested&&{hsaRequested:t.hsaRequested},...n&&{creditCardInstallmentPlan:n},...t.msiEligibleCard&&{msiEligibleCard:t.msiEligibleCard}}}}}case"APPLE_PAY":{const t=e.walletContent;return null==t?null:{name:"APPLE_PAY",walletContent:{applePayWalletContent:{paymentMethodIdentifier:t?.paymentMethodIdentifier,version:t?.version??"",data:t?.data??"",signature:t?.signature??"",lastDigits:t?.lastDigits,cardNetworkBrand:t?.cardNetworkBrand,header:{ephemeralPublicKey:t?.header?.ephemeralPublicKey??"",publicKeyHash:t?.header?.publicKeyHash??"",transactionId:t?.header?.transactionId??"",applicationData:t?.header?.applicationData},...t?.billingAddress&&{billingAddress:t.billingAddress},expiresAt:t?.expiresAt??null}}}}case"GOOGLE_PAY":{const t=e.walletContent;return null==t?null:{name:"GOOGLE_PAY",walletContent:t?{googlePayWalletContent:{protocolVersion:t.protocolVersion,signature:t.signature,signedMessage:t.signedMessage,sessionId:t.sessionId??void 0,...t.paymentMethodIdentifier&&{paymentMethodIdentifier:t.paymentMethodIdentifier},...t.billingAddress&&{billingAddress:{streetAddress:t.billingAddress}}}}:void 0}}case"SHOPIFY_INSTALLMENTS":{const t=e.walletContent;return null==t?null:{name:"SHOPIFY_INSTALLMENTS",walletContent:{shopifyInstallmentsWalletContent:{...t,billingAddress:{streetAddress:t.billingAddress},paymentMethodIdentifier:t.paymentMethodIdentifier}}}}default:throw new p(`Unable to handle wallet ${e.name}`)}}function mn(e,t){return{paymentMethodIdentifier:e.paymentMethodIdentifier,name:e.name,billingAddress:{streetAddress:t}}}function yn(e,t,n,{isCompleting:o=!1,hasSellingPlan:i,hasFixedSellingPlan:a,acceptPaymentVaulting:p,hasPayableDeposit:m,useIntervalForTaxAndPayment:y,fixSubscriptionRedeemablePaymentAmount:h=!1,backendRedeemableCompletionAllocation:g=!1,negotiationRedeemableRecompute:b=!1,observability:f}){const{runningTotal:v,paymentDue:S,deferredTotal:P,checkoutTotal:A,orderDeposit:M,paymentTermsTemplateType:C}=e,T=(e,t)=>e&&t?{value:{amount:e.amount.toString(),currencyCode:e.currencyCode}}:dn,_=t.lines.filter(e=>{const{method:{type:t},cost:n}=e;if("other"===t||"noop"===t)return!1;const r=n&&n.amount>0;return"giftCard"===t?(!o||r||i)&&!a:"redeemable"===t||!(null!=S&&!i&&o&&S.amount<=0)}),I=_.some(e=>"deferred"!==e.method.type),k=u({hasSellingPlan:i,hasFixedSellingPlan:a,paymentTermsTemplateType:C}),x=()=>null!=C||m||null!=M||Boolean(P&&P.amount.amount>0)||_.some(e=>null!=e.due||"deferred"===e.method.type),E=A?.currencyCode,D=h&&g&&k&&o&&null!=E&&!x()&&_.some(e=>!e.due&&l(e)&&null!=e.cost&&e.cost.amount>0&&e.cost.currencyCode===E)&&1===_.filter(e=>!e.due&&!l(e)).length&&_.some(e=>!e.due&&d(e));
1h&&g&&k&&o&&f?.counter({name:"subscription_redeemable_completion_deferral",value:1,attributes:{deferred:String(D)},exportImmediately:!0});const w=A&&h&&!D?function({hasRegularSubscriptionPaymentTerms:e,isCompleting:t,allowAtNegotiation:n=!1,runningTotal:o,paymentDue:i,checkoutTotal:a,lines:l}){if(!e||!t&&!n||null!=i&&i.currencyCode!==a.currencyCode)return;const d=function({runningTotal:e,paymentDue:t,checkoutTotal:n}){const o=[t,e].filter(e=>null!=e&&e.currencyCode===n.currencyCode);if(0!==o.length)return o.reduce((e,t)=>t.amount<e.amount?t:e)}({runningTotal:o,paymentDue:i,checkoutTotal:a}),u=Math.max(0,r(a.amount-(d?.amount??a.amount))),c=function({checkoutTotal:e,reflectedRedeemableAmount:t,lines:n}){const{hasPaymentMethodAmount:o,allocatedPaymentMethodAmount:i,allocatedRedeemableAmount:a}=n.reduce((t,n)=>n.due||null==n.cost||n.cost.currencyCode!==e.currencyCode?t:"giftCard"===n.method.type||"redeemable"===n.method.type?{...t,allocatedRedeemableAmount:r(t.allocatedRedeemableAmount+Math.max(0,n.cost.amount))}:{...t,hasPaymentMethodAmount:!0,allocatedPaymentMethodAmount:r(t.allocatedPaymentMethodAmount+Math.max(0,n.cost.amount))},{hasPaymentMethodAmount:!1,allocatedPaymentMethodAmount:0,allocatedRedeemableAmount:0});return o?{amount:Math.min(e.amount,r(i+a+t)),currencyCode:e.currencyCode,hasPaymentMethodAmount:o,inferredFromConcreteRedeemables:!1}:t>0||a>0?{...e,hasPaymentMethodAmount:o,inferredFromConcreteRedeemables:!0}:{...e,hasPaymentMethodAmount:o,inferredFromConcreteRedeemables:!1}}({checkoutTotal:a,reflectedRedeemableAmount:u,lines:l}),p=c.hasPaymentMethodAmount||c.inferredFromConcreteRedeemables;let m=c.amount,y=0,h=Math.min(u,c.amount);const g=new Map,b=new Set;let f=!1;return l.forEach(e=>{if(e.due||"giftCard"!==e.method.type&&"redeemable"!==e.method.type)return;if(!t&&(null==e.cost||e.cost.amount<=0))return f=!0,void b.add(e);if(!p){if(s(e)){const t=Math.max(0,r(m));return 0===t?(f=!0,void b.add(e)):(m=Math.max(0,r(m-t)),y=r(y+t),void g.set(e,{amount:t,currencyCode:a.currencyCode}))}return f=!0,void b.add(e)}if(null==e.cost){const t=h<=0,n=Math.max(0,r(s(e)&&t?m:Math.min(h,m)));return 0===n?(f=!0,void b.add(e)):(m=Math.max(0,r(m-n)),h=Math.max(0,r(h-n)),y=r(y+n),void g.set(e,{amount:n,currencyCode:a.currencyCode}))}if(e.cost.amount<=0)return f=!0,void b.add(e);if(e.cost.currencyCode!==a.currencyCode)return;const n=Math.max(0,r(Math.min(e.cost.amount,m)));if(0===n)return f=!0,void b.add(e);m=Math.max(0,r(m-n)),h=Math.max(0,r(h-n)),y=r(y+n),g.set(e,{amount:n,currencyCode:a.currencyCode})}),0!==g.size||0!==b.size?{paymentMethodAmount:{amount:{amount:Math.max(0,r(c.amount-y)),currencyCode:a.currencyCode},fillAmount:!f},redeemableAmounts:g,unconstrainedRedeemableLines:b}:void 0}({hasRegularSubscriptionPaymentTerms:k,isCompleting:o,allowAtNegotiation:b&&!x(),runningTotal:v,paymentDue:S,checkoutTotal:A,lines:_}):void 0;if(b&&k&&!o){const e=w?.redeemableAmounts.size??0,t=e>0;f?.counter({name:"subscription_redeemable_negotiation_recompute",value:1,attributes:{engaged:String(t),fixEnabled:String(h)}}),f?.log("subscription_redeemable_negotiation_recompute","[Payment] Negotiation-time subscription redeemable recompute",{engaged:t,fixEnabled:h,concreteRedeemableLines:e,hasCheckoutTotal:null!=A,deferredComponent:x()})}return _.map(t=>{const{method:{type:r},cost:s}=t,l=function(e,t,n,o,i,a,r,s){const l=e.method.type,d="wallet"===l&&"SHOP_PAY"===e.method.name&&e.method.walletContent?.shopPayAsPaymentMethodOptIn,u="direct"===l?e.method:void 0,p=!d&&u?.creditCardInstallments?{installmentsCount:u.creditCardInstallments,intervalType:"MONTH"}:void 0;return{directPaymentMethod:"direct"===l&&e.method.sessionId||d?{paymentMethodIdentifier:d?e.method.walletContent?.paymentMethodIdentifier:e.method.paymentMethodIdentifier,sessionId:d?e.method.walletContent?.sessionId||"":e.method.sessionId||"",billingAddress:{streetAddress:t},...i&&{acceptedSubscriptionTerms:!0},cardSource:d?null:e.method.cardSource||null,...o&&{vaultingAgreement:o},paymentAttributes:d?null:e.method.paymentAttributes,installmentPlan:p}:null,giftCardPaymentMethod:"giftCard"===l&&"code"in e.method?{code:e.method.code,billingAddress:n?{streetAddress:t}:null}:null,ownedGiftCardPaymentMethod:"giftCard"!==l||"code"in e.method?null:{
1id:e.method.id},redeemablePaymentMethod:"redeemable"===l&&e.method.redemptionContent?vt(e.method,t):null,walletPaymentMethod:"wallet"!==l||d?null:pn(e.method,o,i),walletsPlatformPaymentMethod:"walletsPlatformPaymentMethod"===l?{name:e.method.name,walletParams:e.method.walletParams}:null,..."shopWallet"===l&&{shopWallet:(m=e.method,m.shopPayApprovalId?{approvalId:m.shopPayApprovalId}:{token:m.token})},localPaymentMethod:"local"===l?mn(e.method,t):null,paymentOnDeliveryMethod:null,paymentOnDeliveryMethod2:"paymentOnDelivery"===l?{billingAddress:{streetAddress:t},paymentMethodIdentifier:e.method.paymentMethodIdentifier}:null,manualPaymentMethod:"manualPayment"===l?{id:e.method.id,billingAddress:{streetAddress:t},paymentMethodIdentifier:e.method.paymentMethodIdentifier}:null,customPaymentMethod:"customManualPayment"===l?{id:e.method.id,billingAddress:{streetAddress:t},paymentMethodIdentifier:e.method.paymentMethodIdentifier}:null,offsitePaymentMethod:"offsite"===l?{name:e.method.name,paymentMethodIdentifier:e.method.paymentMethodIdentifier,billingAddress:{streetAddress:t}}:null,customOnsitePaymentMethod:"customOnsite"===l?{name:e.method.name,paymentMethodIdentifier:e.method.paymentMethodIdentifier,billingAddress:{streetAddress:t},paymentAttributes:e.method.paymentAttributes??""}:null,deferredPaymentMethod:"deferred"===l&&(a&&r||!a)?{deferredPayment:!0}:null,customerCreditCardPaymentMethod:l===c.CreditCard?{token:e.method.token,paymentMethodIdentifier:e.method.paymentMethodIdentifier,...i&&{acceptedSubscriptionTerms:!0},cvvSessionId:e.method.cvvSessionId,...e.method.creditCardInstallments&&{installmentPlan:{installmentsCount:e.method.creditCardInstallments,intervalType:"MONTH"}}}:null,paypalBillingAgreementPaymentMethod:l===c.PayPal?{token:e.method.token,paymentMethodIdentifier:e.method.paymentMethodIdentifier,...i&&{acceptedSubscriptionTerms:!0}}:null,remotePaymentInstrument:"bank"===l&&e.method.selectedType&&e.method.selectedToken?(n&&s?.counter({name:"bank_payment_submit_result",value:1,attributes:{hasSelectedToken:"true"},exportImmediately:!0}),{paymentMethodIdentifier:e.method.paymentMethodIdentifier,billingAddress:{streetAddress:t},...o&&{vaultingAgreement:o},paymentCredentials:[{token:e.method.selectedToken,tokenType:e.method.selectedType}]}):("bank"===l&&n&&(s?.counter({name:"bank_payment_submit_result",value:1,attributes:{hasSelectedToken:"false"},exportImmediately:!0}),s?.error(new cn(`Bank remotePaymentInstrument set to null in getPaymentMethod: selectedToken=${e.method.selectedToken?"present":"missing"}, selectedType=${e.method.selectedType?"present":"missing"}`))),null)};var m}(t,n,o,p,i,m,I,f),d=Boolean(s&&s.amount>0);if("giftCard"===r){const e=w?.unconstrainedRedeemableLines.has(t)??!1,n=w?.redeemableAmounts.get(t);return{amount:T(e?void 0:n??s,!e&&(null!=n||d&&o)),paymentMethod:l}}if("redeemable"===r){const e=w?.unconstrainedRedeemableLines.has(t)??!1,n=w?.redeemableAmounts.get(t),i=e?void 0:n??s,a=l.redeemablePaymentMethod?.redemptionSource;return{amount:T(i,!e&&("STORE_CREDIT"===a||"CUSTOM"===a?null!=n||d&&o:d)),paymentMethod:l}}const u=A&&function({fixSubscriptionRedeemablePaymentAmount:e,hasRegularSubscriptionPaymentTerms:t,line:n,isCompleting:o,paymentDue:i,
1completionAmount:a,cost:r,coreAllocatesImmediateAmount:s}){if(!e||!t||n.due)return;if(o&&s){const e=i??r;if(null==e)return;return{amount:e,fillAmount:!1}}const l=o?a?.amount??r??i:i;return null!=l?{amount:l,fillAmount:!!o&&(a?.fillAmount??!0)}:void 0}({fixSubscriptionRedeemablePaymentAmount:h,hasRegularSubscriptionPaymentTerms:k,line:t,isCompleting:o,paymentDue:S,completionAmount:w?.paymentMethodAmount,cost:s,coreAllocatesImmediateAmount:D});if(u)return gn({line:t,paymentMethod:l,amount:u.amount,fillAmount:u.fillAmount,totalTaxRange:e.totalTaxRange,useIntervalForTaxAndPayment:!P&&y});if(null==S)return{amount:dn,paymentMethod:l};const g=i||m||o&&S.amount>0;if(P&&A){const n=Boolean(t.due);if(h&&(k||Boolean(M&&A.amount<=0))){const i=o&&0===A.amount,r=i||Boolean(a||M)&&g&&A.amount>0;return i&&!n&&f?.counter({name:"zero_due_immediate_line_concretized",value:1,exportImmediately:!0}),gn({line:t,paymentMethod:l,amount:n?P.amount:A,fillAmount:n?g:r,totalTaxRange:e.totalTaxRange,useIntervalForTaxAndPayment:!1})}return gn({line:t,paymentMethod:l,amount:n?P.amount:A,fillAmount:g,totalTaxRange:e.totalTaxRange,useIntervalForTaxAndPayment:!1})}return gn({line:t,paymentMethod:l,amount:S,fillAmount:g,totalTaxRange:e.totalTaxRange,useIntervalForTaxAndPayment:y})}).filter((e,t)=>{const n=e&&Object.values(e.paymentMethod).some(Boolean);return o&&!n&&e&&"bank"===_[t]?.method.type&&f?.error(new cn("Bank payment line dropped: all paymentMethod fields are null/falsy in paymentLinesForGraphQL")),Boolean(n)})}function hn(e,t){if(!t)return e.amount.toString();const n=t.interval.upperBound.amount-t.interval.lowerBound.amount;return r(e.amount+n).toString()}function gn({line:e,paymentMethod:t,amount:n,fillAmount:o,totalTaxRange:i,useIntervalForTaxAndPayment:a}){const r={paymentMethod:t,due:bn(e)};return o?a?{...r,amount:{interval:{upperBound:{amount:hn(n,i),currencyCode:n.currencyCode}}}}:{...r,amount:{value:{amount:n.amount.toString(),currencyCode:n.currencyCode}}}:{...r,amount:{any:!0}}}function bn(e){return e.due&&"time"in e.due?{time:fn(e.due.time)}:e.due}function fn(e){const t="string"==typeof e?new Date(e):e;if(!(t instanceof Date))return null;try{return t.toISOString()}catch{throw new un("Error converting date to ISO string")}}const vn={any:!0};function Sn(e,t,n){if("available_total_included"===e?.status&&"available_total"===t?.status)return{proposedMixedStateTotalAmount:{proposedTotalAmount:{value:{amount:t.totalDuty.amount.toString(),currencyCode:t.totalDuty.currencyCode}},proposedTotalIncludedAmount:{value:{amount:e.totalIncludedInTarget.amount.toString(),currencyCode:e.totalIncludedInTarget.currencyCode}}},proposedTotalAmount:null,proposedTotalIncludedAmount:null};switch(e?.status){case"available_total_included":return{proposedTotalAmount:null,proposedTotalIncludedAmount:{value:{amount:e.totalIncludedInTarget.amount.toString(),currencyCode:e.totalIncludedInTarget.currencyCode}},proposedMixedStateTotalAmount:null};case"available_total":return{proposedTotalAmount:function({totalCost:e,totalTaxRange:t,useIntervalForTaxAndPayment:n}){if(!n)return{value:{amount:e.amount.toString(),currencyCode:e.currencyCode}};const o=t?.interval.upperBound??e;return{interval:{upperBound:{amount:o.amount.toString(),currencyCode:o.currencyCode}}}}({useIntervalForTaxAndPayment:n?.useIntervalForTaxAndPayment??!1,totalCost:e.totalCost,totalTaxRange:e.totalTaxRange}),proposedTotalIncludedAmount:null,proposedMixedStateTotalAmount:null};default:return{proposedTotalAmount:vn,proposedTotalIncludedAmount:null,proposedMixedStateTotalAmount:null}}}class Pn extends Error{constructor(){super(...arguments),this.name="MissingRemoteSessionTokenError"}}const An={any:!0},Mn={get:()=>"dedicated"};function Cn({deliveryInput:e,merchandiseDetails:t,paymentDetailsByShop:n,perShopSessionToken:a,perShopTaxes:r,isCompleting:s,primaryPaymentMethod:l,observability:d,perShopQueueToken:u,extendedAddressMode:c}){const{stableIdToShopId:p,merchandiseLines:y}=t;if(null==p||0===p.size||null==a||0===a.size)return{delivery:e.deliveryTermsInput,merchandiseLines:y};const{localMerchandise:h,remoteMerchandiseByShop:g}=function(e,t){const n=[],o=new Map;
1return e.forEach(e=>{const i=null==e.stableId?void 0:t.get(e.stableId);if(i){const t=o.get(i)||[];o.set(i,[...t,e])}else n.push(e)}),{localMerchandise:n,remoteMerchandiseByShop:o}}(y,p),{deliveryTermsInputByShop:b,delivery:f}=function(e,t){const{deliveryLines:n,...o}=e,i={},a=[];return new Set(t.values()).forEach(e=>{i[e]={...o,deliveryLines:[]}}),n.forEach(e=>{const n=e.targetMerchandiseLines.lines?.[0],o=n?t.get(n.stableId??""):void 0,r=o?i[o]:void 0;r?r.deliveryLines.push(e):a.push(e)}),{deliveryTermsInputByShop:i,delivery:{deliveryLines:a,...o}}}(e.deliveryTermsInput,p),v=function({deliveryTermsInputByShop:e,merchandiseByShop:t,perShopSessionToken:n,perShopQueueToken:a,perShopTaxes:r,paymentDetailsByShop:s,isCompleting:l,shippingAddress:d,negotiatedMerchandiseLines:u,availableDeliveryAddresses:c,primaryPaymentMethod:p,observability:y,extendedAddressMode:h}){if(0!==t.size)return{remoteNegotiations:Array.from(t.entries()).map(([t,g])=>{const b=s?.get(t),f=u.filter(({stableId:e})=>g.some(t=>t.stableId===e)).some(e=>e.requiresShipping);return function({shopId:e,merchandiseLines:t,deliveryTermsInput:n,paymentDetails:a,sessionToken:r,queueToken:s,taxesInput:l,isCompleting:d=!1,shippingAddress:u,isShippingRequired:c,availableDeliveryAddresses:p,primaryPaymentMethod:y,observability:h,extendedAddressMode:g}){if(!r)throw new Pn(`No session token for remote shop: ${e}`);if(0===n.deliveryLines.length&&t.length>0){const e=p?.find(e=>o(e.address,u,["phone"])&&i(e.address,u));n.deliveryLines.push({destination:(()=>{if(c)return e?{deliveryAddressReference:ht(e.address)}:d?{streetAddress:gt(u,{extendedAddressMode:g})}:{partialStreetAddress:gt(u,{extendedAddressMode:g})}})(),selectedDeliveryStrategy:{deliveryStrategyMatchingConditions:{estimatedTimeInTransit:An,shipments:An},options:{}},targetMerchandiseLines:An,deliveryMethodTypes:[c?"SHIPPING":"NONE"],expectedTotalPrice:An,destinationChanged:!1})}const b=l??{proposedTotalAmount:An},{paymentDue:f,sessionId:v,paymentMethodIdentifier:S,billingAddress:P,cardSource:A,paymentAttributes:M,paymentFlexibilityTermsId:C,preserveBillingAddressExtendedFields:T}=a??{},_=T?Mn:g,I=[];if(f&&f.amount>0&&P&&v&&y){const e=function({primaryPaymentMethod:e,sessionId:t,billingAddress:n,cardSource:o,paymentAttributes:i,paymentMethodIdentifier:a,observability:r,extendedAddressMode:s}){if(function(e){return"direct"===e.type}(e))return{directPaymentMethod:{sessionId:t,paymentMethodIdentifier:a,cardSource:o,paymentAttributes:i,billingAddress:{streetAddress:m(n,{extendedAddressMode:s})}}};if(function(e){return"wallet"===e.type&&"SHOP_PAY"===e.name}(e)){const n=e.walletContent;return null==n?null:{walletPaymentMethod:{name:"SHOP_PAY",walletContent:{shopPayWalletContent:{sessionToken:t,billingAddress:{streetAddress:Tn(n.billingAddress,s)},paymentAttributes:n.paymentAttributes,paymentMethod:n.paymentMethod,paymentMethodIdentifier:a,addressId:n.addressId,...null!=n.hsaRequested&&{hsaRequested:n.hsaRequested},...n.creditCardInstallments&&{creditCardInstallmentPlan:{installmentsCount:n.creditCardInstallments,intervalType:"MONTH"}},...n.msiEligibleCard&&{msiEligibleCard:n.msiEligibleCard}}}}}}return r?.log("unexpected_remote_payment_method_type","Expected direct or Shop Pay wallet payment method for remote negotiation",{primaryPaymentMethodType:e.type}),null}({primaryPaymentMethod:y,sessionId:v,billingAddress:P,cardSource:A,paymentAttributes:M,paymentMethodIdentifier:S,observability:h,extendedAddressMode:_});e&&I.push({amount:d?{value:{amount:String(f.amount),currencyCode:f.currencyCode}}:An,paymentMethod:e})}return{shopId:e,delivery:n,merchandise:{merchandiseLines:t},payment:{totalAmount:An,paymentLines:I,...P&&{billingAddress:{streetAddress:m(P,{extendedAddressMode:_})}},...C&&{paymentFlexibilityTermsId:C}},sessionToken:r,queueToken:s,taxes:b}}({shopId:t,deliveryTermsInput:e[t]??{deliveryLines:[],noDeliveryRequired:[],useProgressiveRates:!1},merchandiseLines:g,paymentDetails:b,sessionToken:n?.get(t),queueToken:a?.get(t),taxesInput:r.get(t),isCompleting:l,shippingAddress:d,isShippingRequired:f,availableDeliveryAddresses:c,primaryPaymentMethod:p,observability:y,extendedAddressMode:h})})}}({deliveryTermsInputByShop:b,merchandiseByShop:g,perShopSessionToken:a,perShopQueueToken:u,perShopTaxes:r,paymentDetailsByShop:n,isCompleting:s,shippingAddress:e.shippingAddress,negotiatedMerchandiseLines:e.negotiatedMerchandiseLines,availableDeliveryAddresses:e.availableDeliveryAddresses,primaryPaymentMethod:l,observability:d,extendedAddressMode:c});return{delivery:f,merchandiseLines:h,remote:v}}function Tn(e,t){return m({address1:e.address1??void 0,address2:e.address2??void 0,city:e.city,company:e.company??void 0,countryCode:e.countryCode??void 0,firstName:e.firstName??void 0,lastName:e.lastName??void 0,postalCode:e.postalCode??void 0,zoneCode:e.zoneCode??void 0,phone:e.phone??void 0,district:e.extendedFields?.district??void 0,line2:e.extendedFields?.line2??void 0,streetName:e.extendedFields?.streetName??void 0,streetNumber:e.extendedFields?.streetNumber??void 0,subdistrict:e.extendedFields?.subdistrict??void 0},{extendedAddressMode:t})}const _n=["SHOP_PAY","SHOPIFY_INSTALLMENTS","GOOGLE_PAY"];function In(e){const t=e?.optIn;return Boolean(t&&!1===t.isAutoOptIn&&""===t.vaultPhone)}function kn(e,t,n,o,i){const a=In(n),r=function(e){if(void 0===e||void 0===e.optIn||!1===e.optIn)return e;const{isAutoOptIn:t,...n}=e.optIn;return{...e,optIn:n}}(n);if(!e)return r;if(o)return{optIn:{vaultPhone:a?"":i??"",vaultEmail:"",optInSource:"REMEMBER_ME"}};const s=r?.optIn;let l=s?s.vaultPhone:void 0;if(Boolean(r?.shopUser?.uuid)||(l=a?l??i:l||i),l=l??"",Boolean(r?.shopUser?.uuid)&&void 0===r?.optIn)return r;const d=void 0!==r&&!1!==r.optIn&&{...r.optIn,vaultPhone:l,vaultEmail:t?"":r.optIn?.vaultEmail};return{...r,optIn:d}}function xn({paymentLines:e,shopPayArtifact:t,shopPayRememberMeVisible:n,isManagedByMarketsPro:o,isApplePayInShopPayEnabled:i,isCompleting:a,wallets:r}){const s=Boolean(t?.shopUser?.uuid);if(!n&&!s)return!1;if(r?.escalatedWallet.value)return!1;if(o&&y(e))return!1;const l=i&&a;if(h(e,"APPLE_PAY")&&!l)return!1;const d=e[0]?.method,u=s&&"wallet"===d?.type&&"SHOPIFY_INSTALLMENTS"===d.name;if(!s||u){if("wallet"===d?.type&&_n.includes(d?.name))return!1;if("walletsPlatformPaymentMethod"===d?.type)return!1;const e=r?.activeSession.value;if(!1===e?.asPaymentMethod)return!1}
1return!(!Boolean(t?.optIn&&!s)&&!s)}class En extends Error{constructor(){super(...arguments),this.name="MissingSessionTokenError"}}class Dn extends Error{constructor(){super(...arguments),this.name="MissingShopPayAlternativePaymentMethodError"}}const wn={any:!0},Rn={get:()=>"dedicated"};function Ln(e){return e.find(e=>e.method.type===c.CreditCard||e.method.type===c.PayPal)}function Nn(e){return e.peek().token??null}function Fn(e){if(!e)return{type:"none"};if(e.any)return{type:"any"};if(e.interval){const t=e.interval.upperBound;return{type:"interval",amount:t?.amount,currencyCode:t?.currencyCode}}return e.value?{type:"value",amount:e.value.amount,currencyCode:e.value.currencyCode}:{type:"unknown"}}function Bn(e){if(null==e)return!0;const t=Number(e);return!Number.isFinite(t)||0===t}function On({proposedDeliveryLines:e,negotiatedDeliveryNext:t,shipPickupInOneOrderEnabled:n}){if(n){const t=e.filter(e=>!e.value.deliveryMethodTypes.includes("NONE"));return t.length>0&&t.every(e=>e.value.deliveryMethodTypes.includes("PICK_UP"))}const o=L(t,"ONE_TIME_PURCHASE"),i=N(o);return"PICK_UP"===i?.methodType}function qn(e){return e.localizationExtensions.peek().map(e=>{const{key:t,value:n}=e.peek();return{key:t,value:n||""}})}function Un(e){return e.deliveryExpectations&&"filled"===e.deliveryExpectations.status&&e.deliveryExpectations.deliveryExpectationLines.filter(e=>e.signedHandle).map(e=>({signedHandle:e.signedHandle}))||[]}class Vn extends Error{constructor(){super(...arguments),this.name="DirectPaymentLinesMismatchError"}}function Hn(e,{isCompleting:t=!1,customizeNegotiation:n,observability:o,paymentLinesObservability:i,wallets:a}={}){if(!e.sessionToken)throw new En("No session token");const{parts:r,throttleState:s,checkout:l}=e,{extendedAddressMode:d}=l.address,u=l.unstable_graphqlDataRequestInfo?.httpRequestInfo?.geolocation?.coordinates??void 0,c=e.shop.shipPickupInOneOrderEnabled,p=e.current.peek().deliveryNext,y=!(!c||("filled"===p?.status||"partial"===p?.status)&&!p.supportsSplitDeliveryMethod)||void 0,h=g(e.context.bankIdNumberSignal.peek()),{attributes:L,email:N,phoneNumber:O,acceptEmailMarketing:q,acceptSmsMarketing:U,smsMarketingPhone:V,purchaseOrderNumber:H,acceptPaymentVaulting:j,shopPayArtifact:z,shopPayRememberMeVisible:G,optionalDuties:Y,captcha:W,shippingAddress:$,billingAddress:K,availableRedeemables:Q,attribution:J,saleAttributions:X,reduction:Z,proposedDeliveryLines:ee,externalDeliveryIds:te,discountLines:ne,merchandiseLines:oe,locationAddress:ie,useProgressiveRates:ae,interfaceFlow:re,tipLines:se,note:le,rememberMe:de,setShippingAddressAsDefault:ue,cartMetafields:ce,memberships:pe,taxExemptions:me,useStoreCreditForSubscriptionRenewals:ye}=function(e){const t=e.email.peek().trim(),n=e.phone.peek().trim(),o=e.acceptEmailMarketing.peek(),i=e.acceptSmsMarketing.peek(),a=e.smsMarketingPhone.peek(),r=e.purchaseOrderNumber.peek(),s=e.acceptPaymentVaulting.peek(),l=e.shopPayArtifact.peek(),d=e.optionalDuties.peek(),u=e.captcha.peek(),c=e.shippingAddress.peek(),p=e.billingAddress.peek(),m=e.availableRedeemables.peek(),y=e.attribution.peek(),h=e.saleAttributions.peek(),g=e.reduction.peek(),b=e.deliveryLines.peek(),f=e.externalDeliveryIds.peek(),v=e.discountLines.peek(),S=e.merchandiseLines.peek(),P=e.locationAddress.peek(),A=e.useProgressiveRates.peek(),M=e.interfaceFlow.peek(),C=e.tipLines.peek(),T=e.note.peek(),_=e.attributes.peek(),I=e.cartMetafields.peek(),k=e.memberships.peek();return{attributes:_,email:t,phoneNumber:n,acceptEmailMarketing:o,acceptSmsMarketing:i,smsMarketingPhone:a,purchaseOrderNumber:r,acceptPaymentVaulting:s,shopPayArtifact:l,optionalDuties:d,captcha:u,shippingAddress:c,billingAddress:p,availableRedeemables:m,attribution:y,saleAttributions:h,reduction:g,proposedDeliveryLines:b,externalDeliveryIds:f,discountLines:v,merchandiseLines:S,locationAddress:P,useProgressiveRates:A,interfaceFlow:M,tipLines:C,note:T,rememberMe:e.rememberMe.peek(),setShippingAddressAsDefault:e.setShippingAddressAsDefault.peek(),shopPayRememberMeVisible:e.shopPayRememberMeVisible.peek(),cartMetafields:I,memberships:k,taxExemptions:e.taxExemptions.peek(),useStoreCreditForSubscriptionRenewals:e.useStoreCreditForSubscriptionRenewals.peek()}}(r);let he=r.paymentLines.peek();const ge=he[0]?.method,be=b(e.shop),fe=f({shop:e.shop,checkout:e.checkout,paymentMethods:e.current.peek().paymentMethods}),ve=function(e,t,n){const{parts:o,source:i,facts:a}=e,r=e.current.peek(),s=o.paymentLines.peek(),l=a.delivery?.[0]?.deliveryAddress,d=l??o.shippingAddress.peek(),u=o.billingAddress.peek(),c=!u.address1&&a.billingAddress?a.billingAddress:u,p=o.billingAddressOption.peek(),m=r.
1isShippingRequired,y=E(i)?a.requiresShipping:m,h=Ln(s);if(h)return n?.log("get_negotiation_input_vaulted_payment_billing_address_used","[getPaymentAddress] Using vaulted payment billing address"),h.method.billingAddress;const g=D(s),b="shipping"===p&&g,f=(()=>{const e=r.buyerIdentity?.purchasingCompany;if(e)return"billing"===p&&e.location.billingAddress?e.location.billingAddress:b?e.location.shippingAddress??d:void 0})();return f?(n?.log("get_negotiation_input_company_location_address_used","[getPaymentAddress] Using company location address"),f):"billing-fact"===p?(n?.log("get_negotiation_input_billing_fact_address_used","[getPaymentAddress] Using billing-fact address"),c):function(e,t){const{parts:n}=e,o=e.current.value,i=n.paymentLines.value,a=o.runningTotal&&o.runningTotal?.amount<=0,r=T(o.merchandiseLines?.lines).some(e=>Boolean(e.sellingPlan?.subscriptionDetails));if(a&&!r&&!o.deferredTotal?.amount.amount)return!1;const s=M(o.buyerIdentity?.customerProfile),l=i&&i[0];return!(!l||"wallet"!==l.method.type)&&(!s||"APPLE_PAY"!==l.method.name)&&(!!["GOOGLE_PAY","APPLE_PAY"].includes(l.method.name)||"PAYPAL_EXPRESS"===l.method.name&&t)}(e,t)?(n?.log("get_negotiation_input_wallet_billing_address_used","[getPaymentAddress] Using wallet billing address"),c):y&&b?(n?.log("get_negotiation_input_shipping_address_used","[getPaymentAddress] Using shipping address"),d):(n?.log("get_negotiation_input_default_billing_address_used","[getPaymentAddress] Using default billing address"),c)}(e,fe,o),Se=ve===function(e){return Ln(e.parts.paymentLines.peek())?.method.billingAddress}(e)?Rn:d,Pe={extendedAddressMode:Se};if(t&&z?.shopUser&&Lt(ge,e.current.fields.paymentMethods.peek(),e.shopPay.session.selectedPaymentMethod.value)){const t=Nt(ge)?ge:function(e,t){if("CUSTOM_ONSITE"===t?.paymentMethod&&"paymentBrands"in t){const n=t.paymentBrands??[],o=e.find(e=>w(e,n));if(o)return{type:"customOnsite",paymentMethodIdentifier:o.paymentMethodIdentifier,name:o.name,paymentBrands:n}}const n=e.find(e=>R(e));if(n)return{type:"customOnsite",paymentMethodIdentifier:n.paymentMethodIdentifier,name:"iDEAL",paymentBrands:["ideal"]}}(e.current.fields.paymentMethods.peek(),e.shopPay.session.selectedPaymentMethod.value);t?he=v(he,function({paymentMethod:e,billingAddress:t,extendedAddressMode:n}){return{method:{type:"wallet",name:"SHOP_PAY",walletContent:{paymentMethod:"CUSTOM_ONSITE",billingAddress:m(t,{extendedAddressMode:n}),paymentMethodIdentifier:e.paymentMethodIdentifier||"",paymentAttributes:e.paymentAttributes}}}}({paymentMethod:t,billingAddress:ve,extendedAddressMode:Se}),be):o?.error(new Dn("Failed to resolve Shop Pay alternative payment method from available payment methods"))}const Ae=function(e){return e.some(({method:e})=>"wallet"===e.type&&"SHOPIFY_INSTALLMENTS"===e.name)}(he)||e.shopPay.session.isInstallmentsSelected.value?[]:se,Me=e.current.peek(),Ce=S({availableDeliveryAddresses:Me.availableDeliveryAddresses,mustSelectProvidedAddress:Me.mustSelectProvidedAddress}),Te=Me.shippingAddress,_e=Me.contactInfo?.email,Ie=function(e,t){return null==t?e:e.filter(({totalPrice:e})=>null==e||e.currencyCode===t)}(oe,Me.merchandiseLines?.lines?.[0]?.totalPrice.currencyCode||Me.buyerIdentity?.presentmentCurrency),ke=Yt(Ie),xe=P(Me),Ee=Boolean(xe?.amount),Re=!Te||!A($,Te,["phone"]);Re&&Te?.oneTimeUse&&($.oneTimeUse=!1);const Le=t&&1===he.length?he[0]:void 0,Ne=void 0!==Le&&"wallet"===Le.method.type&&("APPLE_PAY"===Le.method.name||"GOOGLE_PAY"===Le.method.name)&&"APPLE_PAY"!==a?.escalatedWallet.value,{proposedTotalAmount:Fe,proposedTotalIncludedAmount:Be,proposedMixedStateTotalAmount:Oe}=Sn(Me.taxes,Me.duties,{useIntervalForTaxAndPayment:Ne}),qe=function({proposedTotalAmount:e,proposedTotalIncludedAmount:t,proposedMixedStateTotalAmount:n}){return{amount:Fn(e),includedAmount:Fn(t),mixedState:n?{amount:Fn(n?.proposedTotalAmount),includedAmount:Fn(n?.proposedTotalIncludedAmount)}:void 0}}({proposedTotalAmount:Fe,proposedTotalIncludedAmount:Be,proposedMixedStateTotalAmount:Oe}),Ue=Me.allViolations?.map(e=>e.code)??[],Ve=Ue.includes("TAX_NEW_TAX_MUST_BE_ACCEPTED"),He=Ue.includes("PAYMENTS_UNACCEPTABLE_PAYMENT_AMOUNT"),je=Me.taxes?.status??"missing";o&&t&&function(e,t){if(t.mixedState){const n=t.mixedState.amount,o=t.mixedState.includedAmount;if("available_total"===e)return"value"!==n.type&&"interval"!==n.type||Bn(n.amount);if("available_total_included"===e)return"value"!==o.type&&"interval"!==o.type||Bn(o.amount)}if("available_total"===e)return"value"!==t.amount.type&&"interval"!==t.amount.type||Bn(t.amount.amount);if("available_total_included"===e){const e="none"===t.includedAmount.type?t.mixedState?.includedAmount:t.includedAmount;return!e||"value"!==e.type||Bn(e.amount)}return!0}(je,qe)&&o.log("shop_pay_installments_tax_terms_missing_on_negotiation","[Negotiate] Completing without accepted tax terms",{hasTaxViolation:Ve,hasPaymentAmountViolation:He,taxProposalSummary:qe,taxes:Me.taxes,installmentsPaymentSet:Boolean(e.shopPay.installments.payment.value),violationCodes:Ue});const ze=function(e){const t=null,n=new Map;return e?.forEach((e,o)=>{switch(e.status){case"available_total_included":return n.set(o,{proposedTotalAmount:null,proposedTotalIncludedAmount:{value:{amount:e.totalIncludedInTarget.amount.toString(),currencyCode:e.totalIncludedInTarget.currencyCode}},proposedMixedStateTotalAmount:t});case"available_total":return n.set(o,{proposedTotalAmount:{value:{amount:e.totalCost.amount.toString(),currencyCode:e.totalCost.currencyCode}},proposedTotalIncludedAmount:null,proposedMixedStateTotalAmount:t});
1case"pending":case"unavailable":return n.set(o,{proposedTotalAmount:vn,proposedTotalIncludedAmount:null,proposedMixedStateTotalAmount:t});default:return rt(e)}}),n}(Me.remoteTaxDetails?.perShopTaxes),Ge=Me.buyerIdentity?.customerProfile,Ye=M(Ge),We=De(r),$e=e.context.emailMarketingOptInShownSignal.value,Ke=e.context.emailMarketingConsentGrantReachedSignal.value||Me.emailMarketingConsentGrantReached,Qe=e.context.smsMarketingOptInShownSignal.value,Je=t&&U&&a?.activeSession.value&&e.context.marketingPhoneInputError.peek()?void 0:V,Xe=ot({isShippingRequired:l.isShippingRequired.peek(),isPickupSelected:On({proposedDeliveryLines:ee,negotiatedDeliveryNext:p,shipPickupInOneOrderEnabled:c}),shippingCountryCode:$.countryCode,billingCountryCode:K.countryCode}),Ze=Boolean(it(e.shop,Xe)),et=function({acceptEmailMarketing:e,acceptSmsMarketing:t,smsMarketingPhone:n,smsMarketingCountryCode:o,email:i,isBusinessCustomer:a,emailMarketingConsentGrantReached:r,useMessagingMarketingConsent:s,emailMarketingOptInShown:l}){const d=[];if(a)return d;if(!s&&n&&d.push({sms:{consentState:t?"GRANTED":"DECLINED",value:n,countryCode:o}}),i){const t=function({acceptEmailMarketing:e,emailMarketingConsentGrantReached:t,emailMarketingOptInShown:n}){return e?n&&!t?"PARTIALLY_GRANTED":"GRANTED":n?"DECLINED":void 0}({acceptEmailMarketing:e,emailMarketingConsentGrantReached:r,emailMarketingOptInShown:l});t&&d.push({email:{consentState:t,value:i}})}return d}({acceptEmailMarketing:q,acceptSmsMarketing:U,smsMarketingPhone:Je,smsMarketingCountryCode:We,email:N,isBusinessCustomer:Ye,emailMarketingConsentGrantReached:Ke,useMessagingMarketingConsent:Ze,emailMarketingOptInShown:$e}),tt=Ze?function({acceptSmsMarketing:e,smsMarketingPhone:t,countryCode:n,disclosureCountryCode:o,isBusinessCustomer:i,smsMarketingOptInShown:a}){if(!i&&a){if(e){if(!t)return;return{consentState:"GRANTED",phoneNumber:t,...n?{countryCode:n}:{},...o?{disclosureCountryCode:o}:{}}}return{consentState:"DECLINED",...t?{phoneNumber:t}:{},...n?{countryCode:n}:{},...o?{disclosureCountryCode:o}:{}}}}({acceptSmsMarketing:U,smsMarketingPhone:Je,countryCode:We,disclosureCountryCode:Xe,isBusinessCustomer:Ye,smsMarketingOptInShown:Qe}):void 0,nt=!Qe||!U,at=e.context.shopPayMobilePhoneInputShownSignal.value,st=!(O||$?.phone||K?.phone||at),{isOnePage:lt}=e.checkout.configuration.layout,dt=lt.peek()?"one-page":"three-page",ut=Me.smsMarketingPhone??"";let ct;ct=""===ut?"not-in-negotiated":ut===Je?"matches-negotiated":"differs-from-negotiated",o&&Je&&st&&nt&&o.log("sms_marketing_phone_sent_without_visible_phone_input","[Proposal] SMS marketing phone included while no phone input was visible",{acceptSmsMarketing:U,checkoutLayout:dt,contactPhonePresent:Boolean(O),contactEmailPresent:Boolean(N),hasSmsMarketingPhone:!0,isCompleting:t,shopSmsMarketingSetting:e.shop.smsMarketing,smsMarketingOptInShown:Qe,smsMarketingPhoneSource:ct,sourceType:e.source?.type});const pt=C(Me.merchandiseLines?.lines),mt=T(Me.merchandiseLines?.lines).some(e=>e.sellingPlan?.isFixed),yt=Me.canUpdateDiscountCodes??!1,ht=St({customAttributes:Me.customAttributes}),gt=Pt({customAttributes:Me.customAttributes}),ft=ht&&Boolean($)&>,vt=e.shopPay.session.secureData.value,Mt="draftOrder"===e.source?.type,Ct=pe?function(e,t,n){if("filled"!==e.status)return{memberships:[],violations:[]};const o=function(e,t,n){const o=F(t);return e.cachedMembershipViolations.value.filter(e=>B(e,n,o))}(t,e,n),i=o.map(e=>e.handle);return{memberships:e.memberships.map(e=>{const t=!i.includes(e.handle);return{handle:e.handle,apply:!!t&&e.apply}}),violations:o}}(pe,e.context,$):void 0;e.context.cachedMembershipViolations.value=Ct?.violations||[];const Tt=function(e){return{memberships:e.map(e=>({handle:e.handle,apply:e.apply}))}}(Ct?.memberships||[]),_t=m(ve,Pe),It=bt(he,ve,r.billingAddressOption.peek(),Pe,Mt),kt=It?.streetAddress;if(kt&&_t){const e=["address1","city","countryCode","postalCode"].filter(e=>_t[e]!==kt[e]);e.length>0&&o?.log("get_negotiation_input_billing_address_mismatch_detected","Billing address mismatch detected between payment lines and billing address inputs",{mismatchedFields:e,paymentLinesBillingAddress:_t,billingAddress:kt,billingAddressOption:r.billingAddressOption.peek()})}if(t&&o){const e=Me.paymentMethods?.map(e=>"direct"===e.type?{paymentMethodIdentifier:e.paymentMethodIdentifier,name:e.name}
1:void 0).filter(Boolean),t=he.find(e=>Boolean("direct"===e.method.type&&e.method.creditCardLastFourDigits&&e.method.brand))?.method.paymentMethodIdentifier;"US"===$.countryCode&&t&&!e?.some(e=>e?.paymentMethodIdentifier===t)&&o?.error(new Vn("Completing with a direct payment line mismatch with seller proposal available payment methods"),{metadata:{value:{buyerDirectPaymentMethodIdentifiers:JSON.stringify(t),availableDirectPaymentMethods:JSON.stringify(e)}}})}const xt=function(e){let t=null;const n=()=>(null===t&&(t=new Map(e.lines.map(e=>[e.stableId,e]))),t);return{merchandiseLines:e.lines.map(e=>({...Jt(e,n),lineComponentsSource:e.lineComponentsSource,lineComponents:e.lineComponents.map(e=>Jt(e,n))}))}}({lines:Ie}),Et=Me.remoteMerchandiseDetails?.stableIdToShopId;t&&_($.postalCode,$.countryCode)&&o?.log("wallets_shipping_address_postal_code_in_submit_input","Padded postal code detected in shipping address at SubmitForCompletion time",{countryCode:$.countryCode});const Dt={deliveryLines:tn({shippingAddress:$,proposedDeliveryLines:ee,externalDeliveryIds:te,destinationChanged:Re,isSubmitForCompletion:t,isPointOfSale:ht,isPointOfSaleShipToHome:ft,negotiatedDelivery:Me.deliveryNext,filteredMerchandiseStableIds:ke,locationAddress:ie,geolocationCoordinates:u,retailLocationId:At({customAttributes:Me.customAttributes}),isShippingRequired:Me.isShippingRequired,availableDeliveryAddresses:Me.availableDeliveryAddresses,isConstrainedAddress:Ce,extendedAddressMode:d,marketDrivenShippingEnabled:e.shop.marketDrivenShippingEnabled,stableIdToShopId:Et,remoteShopsConfigMap:e.shop.remoteShopsConfigMap}),noDeliveryRequired:[],useProgressiveRates:ae,prefetchShippingRatesStrategy:null,interfaceFlow:re,supportsSplitShipping:l.supportsSplitShipping.value,acceptSplitDelivery:y},wt=Boolean(Et&&Et.size>0),{delivery:Rt,merchandise:Ft,remoteNegotiations:Bt}=wt?(()=>{const n=new Map,i=e.parts.remotePaymentDetails.peek();if(i&&he.length>0){const{method:e}=he.find(e=>"direct"===e.method.type)??{};for(const[t,o]of i){const i={...o,cardSource:e?.cardSource??null,paymentAttributes:e?.paymentAttributes,billingAddress:ve,preserveBillingAddressExtendedFields:Se===Rn};n.set(t,i)}}const{delivery:a,merchandiseLines:r,remote:s}=Cn({deliveryInput:{deliveryTermsInput:Dt,shippingAddress:$,negotiatedMerchandiseLines:Me.merchandiseLines?.lines??[],availableDeliveryAddresses:Me.availableDeliveryAddresses},perShopSessionToken:Me.remoteSessionDetails?.perShopSessionToken,perShopQueueToken:Me.remoteSessionDetails?.perShopQueueToken,perShopTaxes:ze,merchandiseDetails:{merchandiseLines:xt.merchandiseLines,stableIdToShopId:Et},paymentDetailsByShop:n,primaryPaymentMethod:ge,observability:o,isCompleting:t,extendedAddressMode:d});return{delivery:a,merchandise:{...xt,merchandiseLines:r},remoteNegotiations:s}})():{merchandise:xt,delivery:Dt,remoteNegotiations:void 0},Ot=!(wt&&0===Ft.merchandiseLines.length),qt=e.checkout.rememberMe.createAccountOptIn.value,Ut=In(z)?void 0:$.phone||K.phone,Vt=function({buyerEditedAddress:e,shopUserSecureData:t,shopPayVerificationTrigger:n,customerProfile:o}){if(!e)return Boolean(t)&&null==n?"SHOP_PAY":o?"CUSTOMER":void 0}({buyerEditedAddress:(r.shippingAddress?.dirtyFields?.value?.size??0)>0||(r.billingAddress?.dirtyFields?.value?.size??0)>0,shopUserSecureData:vt,shopPayVerificationTrigger:e.shopPay?.session?.verificationTrigger?.value,customerProfile:Ge}),Ht={checkpointData:l.checkpointToken.value,sessionInput:{sessionToken:e.sessionToken},queueToken:Nn(s),discounts:{lines:sn({lines:ne},oe,o),acceptUnexpectedDiscounts:Mt?Me.acceptUnexpectedDiscounts:yt},...Ot?{delivery:Rt}:{},deliveryExpectations:{deliveryExpectationLines:Un(Me)},merchandise:Ft,memberships:Tt,availableRedeemables:Zt(Q),...Ot?{payment:{totalAmount:wn,paymentLines:yn({runningTotal:Me.runningTotal,paymentDue:Me.paymentDue,deferredTotal:Me.deferredTotal,checkoutTotal:Me.checkoutTotal,orderDeposit:xe,paymentTermsTemplateType:Me.paymentFlexibilityPaymentTermsTemplate?.type,totalTaxRange:"available_total"===Me.taxes?.status?Me.taxes.totalTaxRange:void 0},{lines:he},m(ve,Pe),{isCompleting:t,hasSellingPlan:pt,hasFixedSellingPlan:mt,acceptPaymentVaulting:j,hasPayableDeposit:Ee,useIntervalForTaxAndPayment:Ne,fixSubscriptionRedeemablePaymentAmount:be,backendRedeemableCompletionAllocation:e.shop.hasFlagEnabled(x),negotiationRedeemableRecompute:k(e.shop),observability:o??i}),billingAddress:bt(he,ve,r.billingAddressOption.peek(),Pe,Mt),paymentFlexibilityTermsI
1d:Me.paymentFlexibilityPaymentTermsTemplate?.id,creditCardBin:h,allowStoreCredit:ye}}:{},buyerIdentity:{customer:{presentmentCurrency:Me.buyerIdentity?.presentmentCurrency,countryCode:Me.buyerIdentity?.countryCode},email:N||void 0,...N?{emailChanged:!_e||_e!==N}:{},phone:O||void 0,phoneCountryCode:We||void 0,marketingConsent:et,messagingMarketingConsent:tt,shopPayOptInPhone:{number:Ut,countryCode:$?.countryCode||K?.countryCode||Me.buyerIdentity?.countryCode},shopUserSecureData:vt,prefillSource:Vt,rememberMe:de,setShippingAddressAsDefault:t?ue:void 0},tip:{tipLines:we(Ae)},poNumber:""===H?null:H,...Ot?{taxes:{proposedAllocations:null,proposedTotalAmount:Fe,proposedTotalIncludedAmount:Be,proposedMixedStateTotalAmount:Oe,proposedExemptions:me}}:{},...Ot?{note:ln(Me,le,L)}:{},localizationExtension:{fields:qn(r)},shopPayArtifact:qt||xn({paymentLines:he,shopPayArtifact:z,shopPayRememberMeVisible:G,isManagedByMarketsPro:Boolean(Me.managedByMarketsPro),isApplePayInShopPayEnabled:!e.shop.hasFlagEnabled(I),isCompleting:t,wallets:a})?kn(t,N,z,qt,Ut):void 0,nonNegotiableTerms:Me.nonNegotiableTerms?(zt=Me.nonNegotiableTerms,{signature:zt.signature??void 0,contents:zt.contents.map(e=>({signature:e.signature,targetTerms:e.targetTerms,targetLine:void 0===e.targetLine?void 0:{allLines:e.targetLine?.allLines??!1,index:e.targetLine?.index},attributes:e.attributes}))}):null,scriptFingerprint:Me.scriptFingerprint,transformerFingerprintV2:Me.transformerFingerprintV2,optionalDuties:Y?(jt=Y.buyerRefusesDuties,{buyerRefusesDuties:jt}):null,attribution:J,captcha:en(W),reduction:Z,saleAttributions:X,alternativePaymentCurrency:Xt(Me.alternativePaymentCurrency),cartMetafields:ce,...Bt?{remote:Bt}:{}};var jt,zt;const Gt=n?n(Ht):Ht;return function(e){return Boolean(e?.some(({paymentMethod:e})=>"SHOPIFY_INSTALLMENTS"===e.walletPaymentMethod?.name||"SHOPIFY_INSTALLMENTS"===e.walletPaymentMethodConfig?.name))}(Gt.payment?.paymentLines)?{...Gt,tip:{tipLines:[]}}:Gt}const jn={id:"61ef8aa9aa3e5f49aab34e4853126d7ca8b13bda04ae608a4fae9343db775a37",type:"mutation",name:"SubmitForCompletion",source:""};function zn(){return{requestUrl:window.location.href,pageId:window.trekkie?.trekkie?.defaultAttributes?.microSessionId}}function Gn(e){const t=O(e??[]),n=t?.installmentPlans?.find(e=>"MSI"===e.type);return n?.supportedInstallments??[]}function Yn(e){switch(e.parts.postPurchaseInquiryStatus.peek()){case"success":case"done":return"SUCCESS";case"declined":return"DECLINED";case"error":return"ERROR";case"timeout":return"TIMEOUT";default:return}}function Wn({variables:e,errors:t,sellerProposal:n}){if(!Re(t))return e;const o=Sn(Mt(n.tax),Le(n.duty));return{...e,taxes:{...e.taxes,...n.tax?o:{}}}}function $n(e){if("NegotiationResultAvailable"!==e?.__typename&&"SubmitRejected"!==e?.__typename)return 1e3;const{sellerProposal:t}=e,{delivery:n,payment:o,tax:i,taxExemptions:a,merchandiseDiscount:r,remote:s,deliveryDiscount:l,captcha:d,cartCheckoutValidation:u,deliveryExpectations:c,memberships:p,shopCashBalance:m,shopPromotion:y,shopDiscountOffer:h}=t,g=Math.min(function(e){return e&&"PENDING"===e.consolidated.delivery.termsStatus?e.remoteNegotiations.reduce((e,{result:t})=>{if(U(t)){const n=t.sellerProposal.delivery;if("PendingTerms"===n?.__typename)return Math.min(e,n.pollDelay)}return e},1/0):1/0}(s),function(e){return e&&"PENDING"===e.consolidated.taxes.termsStatus?e.remoteNegotiations.reduce((e,{result:t})=>{if(U(t)){const n=t.sellerProposal.tax;if("PendingTerms"===n?.__typename)return Math.min(e,n.pollDelay)}return e},1/0):1/0}(s),function(e){return e&&"PENDING"===e.consolidated.payment.termsStatus?e.remoteNegotiations.reduce((e,{result:t})=>{if(U(t)){const n=t.sellerProposal.payment;if("PendingTerms"===n?.__typename)return Math.min(e,n.pollDelay)}return e},1/0):1/0}(s),"PendingTerms"===d?.__typename?d.pollDelay:1/0,"PendingTerms"===n.__typename?n.pollDelay:1/0,"PendingTerms"===c?.__typename?c.pollDelay:1/0,"PendingTerms"===o.__typename?o.pollDelay:1/0,"PendingTerms"===i.__typename?i.pollDelay:1/0,"PendingTerms"===a?.__typename?a.pollDelay:1/0,"PendingTerms"===r.__typename?r.pollDelay:1/0,"PendingTerms"===l.__typename?l.pollDelay:1/0,"PendingTerms"===u?.__typename?u.pollDelay:1/0,"PendingTerms"===p?.__typename?p.pollDelay:1/0,"PendingTerms"===m?.__typename?m.pollDelay:1/0,"PendingTerms"===y?.__typename?y.pollDelay:1/0,"PendingTerms"===h?.__typename?h.pollDelay:1/0);return g===1/0?0:g}
1class Kn extends Error{constructor(){super(...arguments),this.name="MissingSourceError"}}class Qn extends Error{constructor(){super(...arguments),this.name="ManagedMarketsOnDomesticCheckoutError"}}function Jn({sellerProposal:e,buyerProposal:t={__typename:"Proposal",buyerIdentity:{__typename:"UnavailableTerms"},merchandise:{__typename:"UnavailableTerms"},isShippingRequired:!0,merchandiseDiscount:{__typename:"FilledDiscountTerms",acceptUnexpectedDiscounts:!1,lines:[]},deliveryDiscount:{__typename:"FilledDiscountTerms",acceptUnexpectedDiscounts:!1,lines:[]},delivery:{__typename:"UnavailableTerms"},subtotalBeforeTaxesAndShipping:{__typename:"AnyConstraint"},runningTotal:{__typename:"AnyConstraint"},total:{__typename:"AnyConstraint"},legacySubtotalBeforeTaxesShippingAndFees:{__typename:"AnyConstraint"}},violations:n=[],silenceViolations:o,proposedPaymentLines:i,currentUcp:a,observability:r,shop:s}){const{remoteMerchandise:{remoteBuyerMerchandiseLines:l,remoteSellerMerchandiseLines:d,stableIdToShopId:c},remoteDelivery:p,remotePayment:m}=V(e?.remote),y=Boolean(e?.remote?.remoteNegotiations.length),[h,g]=y?[H(e?.merchandise,d),H(t?.merchandise,l)]:[e?.merchandise,t?.merchandise],f=j(e?.remote),v=z(n,o),S=G({sellerProposal:e,buyerProposal:t,negotiationViolations:v,sellerMerchandise:h}),A=Ct(e?.payment,S?.runningTotal);if(!e)throw new Kn("There is no receipt or sellerProposal");const M="UnavailableTerms"===e.buyerIdentity.__typename;"FilledBuyerIdentityTerms"!==e.buyerIdentity.__typename&&r?.leaveErrorBreadcrumb("getNegotiatedPartsForUI: buyer identity terms are unavailable/pending",{__typename:e.buyerIdentity.__typename});const T=Tt(e.buyerIdentity),_=t?.subtotalBeforeTaxesAndShipping,I="Proposal"===e.__typename?Y(e.subtotalBeforeTaxesAndShipping,_,v,h):void 0,k=t?.legacySubtotalBeforeTaxesShippingAndFees,x="Proposal"===e.__typename?W(e.legacySubtotalBeforeTaxesShippingAndFees,k,v,h):void 0,E="Proposal"===e.__typename?$(e.legacyAggregatedMerchandiseTermsAsFees):{lines:[]},D=t?.runningTotal,w="Proposal"===e.__typename?K(e.runningTotal,D,v,h):void 0,R=Q(e.payment),L=J(e.payment),N="FilledPaymentTerms"===e.payment?.__typename&&e.payment.isImmediateAmountReducedForRedeemables,F="Proposal"===e.__typename?X(e.deferredTotal??void 0,R?.dueDate??void 0):void 0,{checkoutTotal:B,checkoutTotalBeforeTaxesAndShipping:O,checkoutTotalTaxes:q}=t,U=e.poNumber??void 0,pe="Proposal"===e.__typename?Z(e.checkoutTotal,B,v,h):void 0,me="Proposal"===e.__typename?Z(e.checkoutTotalBeforeTaxesAndShipping,O,v,h):void 0,ye="Proposal"===e.__typename?Z(e.checkoutTotalTaxes,q,v,h):void 0,he=e.total&&"AnyConstraint"!==e.total.__typename?ee(e.total):void 0,ge=e.totalSavings&&"MoneyValueConstraint"===e.totalSavings.__typename?ee(e.totalSavings):void 0,be=Ut(e.recurringTotals),fe=e.subtotalAfterMerchandiseDiscounts&&"AnyConstraint"!==e.subtotalAfterMerchandiseDiscounts.__typename?ee(e.subtotalAfterMerchandiseDiscounts):void 0,ve=e.subtotalBeforeReductions&&"AnyConstraint"!==e.subtotalBeforeReductions.__typename?ee(e.subtotalBeforeReductions):void 0,Se="PendingTerms"===e.deliveryExpectations?.__typename,Pe="PendingTerms"===e.delivery.__typename,Ae="PendingTerms"===e.captcha?.__typename,Me=Ne(h,g,v),Ce=C(Me.lines),Te=te(Me.lines),_e=Ct(e.payment,w),Ie=Boolean(P({deferredTotal:F,checkoutTotal:pe,paymentFlexibilityPaymentTermsTemplate:R})?.amount),ke=ne(e.payment,m.availablePaymentLines),xe=oe({availablePayments:ke,hasPayableDeposit:Ie}),Ee=s.paymentMethodAutoSelectionDisabled,De=b(s)&&u({hasSellingPlan:Ce,hasFixedSellingPlan:Te,paymentTermsTemplateType:R?.type}),we=ie({payment:e.payment,sortedPaymentMethods:xe,runningTotal:w,paymentDue:_e,deferredTotal:F,checkoutTotal:pe,paymentMethodAutoSelectionDisabled:Ee,requiresVaulting:Ce,proposedPaymentLines:i,hasPayableDeposit:Ie,hasFixedSellingPlan:Te,paymentTermsTemplateType:R?.type,preserveAllocatedImmediatePaymentLineAmount:De,observability:r}),Re="FilledPaymentTerms"===e.payment.__typename?e.payment.paymentMethodHistory:[],Xe=M?void 0:_t(e.buyerIdentity),Ze=St(e.note),et=Pt(e.note),tt=Ze&&Boolean(e.delivery)&&et,nt=ae({delivery:e.delivery,remoteDelivery:p});"US"===nt?.countryCode&&xe.some(e=>"direct"===e.type&&"flow_commerce"===e.name)&&r?.error(new Qn("flow_commerce gateway returned from availablePaymentMethods for domestic shipping address"),{metadata:{value:{availablePaymentMethods:JSON.stringify(xe),proposedPaymentLines:JSON.stringify(i),paymentLines:JSON.stringify(we)}}});const ot=Fe({delivery:e.delivery,deliveryMethods:s.shipPickupInOneOrderEnabled?e.deliveryMethods:void 0,negotiatedMerchandise:h,buyerDelivery:t?.delivery,violations:v,isPointOfSale:Ze,isPointOfSaleShipToHome:tt,remoteDelivery:p}),it=It(e.attribution),at=Be(e.attribution),rt=Oe({deliveryExpectations:e.deliveryExpectations}),st=void 0===it&&void 0===at?void 0:{...it,...at},lt=qe(e.saleAttributions),dt=Ue(e.tip),ut=Ve(e.tip),ct=e.localizationExtension?.fields,pt=e.scriptFingerprint?He(e.scriptFingerprint):void 0,mt=e.transformerFingerprintV2||void 0,yt=je(e.availableRedeemables),ht=ze(e.shopCashBalance),gt=Ge(e.shopPromotion),bt=Ye(e.shopDiscountOffer),ft=e.checkoutCompletionTarget??"ORDER",vt="billingAddress"in e.payment?re(e.payment.billingAddress):void 0,At=e.memberships?We(e.memberships):void 0,Lt=p?.isShippingRequired??e.isShippingRequired??t?.isShippingRequired;return{billingAddress:vt,...Pe?void 0:{deliveryNext:ot},sellability:ce({shop:s,sellerProposal:e,missingSellerProposalReason:"Proposal.Unknown",isShippingRequired:Lt,observability:r}),deliveryExpectations:Se?void 0:rt,shippingAddress:nt,merchandiseLines:Me,paymentMethodHistory:Re,paymentMethods:xe,paymentLines:we,paymentDue:_e,...Xe?{contactInfo:Xe}:void 0,duties:Le(e.duty),optionalDuties:e.optionalDuties?Rt(e.optionalDuties):void 0,landedCostDetails:e.landedCostDetails?.incotermInformation??void 0,dutiesIncluded:e.dutiesIncluded?e.dutiesIncluded:void 0,taxes:Mt(e.tax),remoteTaxDetails:wt(e.remote),taxExemptions:Je(e.taxExemptions),discountLines:ue({merchandiseDiscount:e.merchandiseDiscount,deliveryDiscount:e.deliveryDiscount}),legacyRepresentProductsAsFees:e.legacyRepresentProductsAsFees,totalSavings:ge,subtotal:I,legacySubtotalBeforeTaxesShippingAndFees:x,legacyMerchandiseLinesAsFees:E,runningTotal:w,deferredTotal:F,checkoutTotal:pe,checkoutTotalBeforeTaxesAndShipping:me,checkoutTotalTaxes:ye,total:he,purchaseOrderNumber:U,recurringTotals:be,subtotalAfterMerchandiseDiscounts:fe,subtotalBeforeReductions:ve,hasOnlyDeferredShipping:e.hasOnlyDeferredShipping,acceptEmailMarketing:Dt(e.buyerIdentity),emailMarketingConsentGrantReached:Et(e.buyerIdentity),acceptSmsMarketing:xt(e.buyerIdentity),smsMarketingPhone:kt(e.buyerIdentity)??void 0,allViolations:n,buyerIdentity:T,tipOptions:dt,tipLines:ut,localizationExtensions:ct,scriptFingerprint:pt,transformerFingerprintV2:mt,attribution:st,managedByMarketsPro:e.managedByMarketsPro,managedMarketsPaymentProcessor:e.managedMarketsPaymentProcessor,...Ae?void 0:{captcha:de(e.captcha,v)},availableRedeemables:yt,shopCashBalance:ht,shopPromotion:gt,shopDiscountOffer:bt,saleAttributions:lt,alternativePaymentCurrency:Qe(e.alternativePaymentCurrency,we),lpmDisclosure:e.lpmDisclosure??void 0,isImmediateAmountReducedForRedeemables:N,checkoutCompletionTarget:ft,paymentFlexibilityPaymentTermsTemplate:R,depositConfiguration:L,isShippingRequired:Lt,cartMetafields:Ke(e.cartMetafields),customFields:s.hasFlagEnabled(le)?$e(e.customFields):void 0,memberships:At,remoteMerchandiseDetails:{stableIdToShopId:c,mergedBuyerProposalMerchandise:g}
1,remotePaymentDetails:m.paymentDetails,remoteSessionDetails:f,remoteConsolidatedTotals:S,remotePaymentDue:A,remoteTotalDetails:se({remote:e?.remote,negotiationViolations:v,sellerMerchandise:h}),shopPayEnabledForSellerOfRecord:e.shopPayEnabled,ucp:{...a,continueUrl:e.ucp?.continueUrl??void 0}}}function Xn(e){return e.split(".").reduce((e,t)=>{if("$"===t[0])return e;const n=function(e){const t=e.split("["),n=t[0],o=t[1];if(void 0===n||void 0===o)return[e];const i=o.replace(/[[\]']+/g,"");return[n,Number(i)]}(t);return e.concat(n)},[])}function Zn(e,t){return e.reduce((e,t)=>null!=e&&"object"==typeof e?e[t]:null,t)??null}function eo(e,t){return e.reduce((e,n)=>{if(!n.__typename)return e;const{code:o,localizedMessage:i,nonLocalizedMessage:a,localizedMessageHtml:r}=n;let s;"target"in n&&"string"==typeof n.target?s=n.target:"from"in n&&"string"==typeof n.from&&(s=n.from);const l=s?function(e,t,n){if(Vt.has(t)){const t=Zn(Xn(e),n);return t?pe(t)??null:null}if(!me.has(t))return null;const o=ye(e);if(!o)return null;const i=Zn(Xn(o.linePath),n);return"string"==typeof i?.stableId?{merchandiseLine:{stableId:i.stableId}}:null}(s,o,t):null,d={code:o,localizedMessage:i,nonLocalizedMessage:a,localizedMessageHtml:r};switch(n.__typename){case"InputValidationError":e.push({...d,type:n.__typename});break;case"RemoveTermViolation":e.push({...d,type:n.__typename,target:n.target,targetEntity:l});break;case"AcceptNewTermViolation":case"UnresolvableTermViolation":e.push({...d,type:n.__typename,target:n.target});break;case"ConfirmChangeViolation":e.push({...d,type:n.__typename,from:n.from,targetEntity:l,to:n.to});break;case"UnprocessableTermViolation":e.push({...d,type:n.__typename,target:n.target,...l?{targetEntity:l}:{}});break;case"ApplyChangeViolation":e.push({...d,type:n.__typename,target:n.target,from:n.from,to:n.to,...l?{targetEntity:l}:{}});break;default:e.push({...d,type:"GenericError"})}return e},[])}class to extends Error{constructor(){super(...arguments),this.name="UnknownCompletionTypeError"}}class no extends Ft{constructor(){super(...arguments),this.name="SubmitRejectedMissingContactMethod"}}class oo extends Error{constructor(){super(...arguments),this.name="UnknownMetafieldTypeError"}}const io={CheckpointDenied:"SubmitForCompletion.CheckpointDenied",SubmitAlreadyAccepted:"SubmitForCompletion.SubmitAlreadyAccepted",SubmitFailed:"SubmitForCompletion.SubmitFailed",SubmitRejected:"SubmitForCompletion.Unknown",SubmitSuccess:"SubmitForCompletion.SubmitSuccess",SubmittedForCompletion:"SubmitForCompletion.SubmittedForCompletion",Throttled:"SubmitForCompletion.Throttled",TooManyAttempts:"SubmitForCompletion.TooManyAttempts",TooManyRequests:"SubmitForCompletion.TooManyRequests"};function ao({submitForCompletion:e,buyerProposal:t,violations:n,proposedPaymentLines:o,observability:i,negotiator:a}){switch(e.__typename){case"SubmitRejected":return Jn({sellerProposal:e.sellerProposal,buyerProposal:t,violations:n,proposedPaymentLines:o,currentUcp:a.current.fields.ucp.value,observability:i,shop:a.shop});case"CheckpointDenied":case"SubmitFailed":case"Throttled":case"TooManyAttempts":case"TooManyRequests":return{sellability:ce({shop:a.shop,missingSellerProposalReason:(r=e.__typename,null==r?"SubmitForCompletion.Unknown":io[r]),observability:i})};default:return{}}var r}function ro(e){return"receipt"in e&&"ReceiptNotFound"===e.receipt.__typename}function so(e){switch(e.valueType.toUpperCase()){case"STRING":return"STRING";case"JSON_STRING":return"JSON_STRING";case"INTEGER":return"INTEGER";default:throw new oo(`Unexpected metafield valueType: ${e.valueType}`)}}function lo(e){const{extensibility:t}=e.checkout;return t.ui.metafields.value.map(e=>({...e,value:String(e.value),valueType:so(e)}))}function uo({paymentLineTypes:e,status:t,observability:n,interfaceFlow:o,blockedByExtension:i,activeWalletSession:a}){const r=e.at(0);"APPLE_PAY"!==r&&"GOOGLE_PAY"!==r||n.counter({name:"wallet_completion_extension_result",value:1,attributes:{wallet_type:r,status:t,interface_flow:o,blocked_by_extension:i,active_wallet_session:a?.wallet,wallet_as_payment_method:a?.asPaymentMethod}})}async function co(e,t,n){const{negotiating:o,isActive:i}=e.start();t.leaveErrorBreadcrumb("[SubmitForCompletion] Running completion interceptors");const a=await e.runInterceptors({negotiationStage:"completion"});if(t.leaveErrorBreadcrumb("[SubmitForCompletion] completion isActive",{isActive:i()}),!i()){const n="[SubmitForCompletion] Blocked due to stale negotiation";return t.leaveErrorBreadcrumb(n),e.observability.log("submit_for_completion_progression_blocked",n,{reason:"stale_negotiation"}),{status:"stale",phase:"interceptors"}}if(!e.source.sourceId){const e=[he.MissingSourceId];return t.leaveErrorBreadcrumb("[SubmitForCompletion] Blocked due to missing sourceId",{reasons:e}),{status:"invalid",reasons:e}}const r=e.parts.paymentLines.value.map(e=>"wallet"===e.method.type||"walletsPlatformPaymentMethod"===e.method.type?e.method.name:e.method.type),s=e.checkout.extensibility.ui.search().peek().some(e=>e.capabilities.blockProgress);if("block"===a.behavior){const{reasons:n,errors:o,context:i}=a;return t.leaveErrorBreadcrumb("[SubmitForCompletion] Blocked by client side interceptors",{reasons:n,paymentLineNames:r,interfaceFlow:e.parts.interfaceFlow.value,activeWalletSession:e.checkout.wallets.activeSession.value}),e.observability.log("submit_for_completion_progression_blocked","[SubmitForCompletion] Blocked by client side interceptors",{reason:"interceptor_block",reasons:n,errors:o,context:i,paymentLineNames:r,interfaceFlow:e.parts.interfaceFlow.value,activeWalletSession:e.checkout.wallets.activeSession.value}),s&&uo({paymentLineTypes:r,status:"blocked",observability:e.observability,interfaceFlow:e.parts.interfaceFlow.value,blockedByExtension:Boolean(i?.some(e=>e?.extension)),activeWalletSession:e.checkout.wallets.activeSession.value}),e.setValidationErrors(o),e.checkout.rememberMe.unstable_setCreateAccountOptIn(!1),{status:"invalid",reasons:n}}s&&uo({paymentLineTypes:r,status:"allowed",observability:e.observability,interfaceFlow:e.parts.interfaceFlow.value,activeWalletSession:e.checkout.wallets.activeSession.value}),e.setValidationErrors([]),n?.onValidationSuccess?.(),e.track();const l=e.current.peek();!function({observability:e,userEvents:t,paymentLines:n,paymentMethods:o,paymentDue:i,remotePaymentDue:a,remoteMerchandiseDetails:r,shopId:s,checkoutToken:l}){try{const e=qt(n);if(!e)return;const d=function({paymentDue:e,remotePaymentDue:t,remoteMerchandiseDetails:n}){return Boolean(n?.stableIdToShopId.size)&&t?t:e}({paymentDue:i,remotePaymentDue:a,remoteMerchandiseDetails:r}),u=d?.amount,c=d?.currencyCode;if(null==u||!c)return;t.monorailEvent({schemaId:"checkout_credit_card_installment_track/1.0",payload:{eventName:"credit_card_installment_submit_attempted",shopId:parseInt(q(s),10),checkoutToken:l??"",planCount:e,eligiblePlans:Gn(o).join(","),cartTotal:u.toFixed(2),cartCurrency:c}},{exportImmediately:!0})}catch(d){d instanceof Error&&e.error(d)}}({observability:t,userEvents:e.userEvents,paymentLines:e.parts.paymentLines.peek(),paymentMethods:l.paymentMethods,paymentDue:l.paymentDue,remotePaymentDue:l.remotePaymentDue,remoteMerchandiseDetails:l.remoteMerchandiseDetails,shopId:e.shop.id,checkoutToken:e.source.checkoutSessionIdentifier});const d=ge(e.source,e.persistenceManager),u=e.parts.paymentLines.peek();try{let a;try{a=await be()}catch(c){return t.leaveErrorBreadcrumb("[SubmitForCompletion] Blocked completion because receipt mapper failed to load",{error:String(c)}),{status:"fetch_failed",reason:"Receipt mapper failed to load before submit for completion",isActionable:!1}}if(!i()){const n="[SubmitForCompletion] Blocked due to stale negotiation";return t.leaveErrorBreadcrumb(n),e.observability.log("submit_for_completion_progression_blocked",n,{reason:"stale_negotiation"}),{status:"stale",phase:"submission"}}const r=o([]);return await(async()=>{let o;const i=function(){let e,t=0;return{shouldRetry:n=>!!ro(n)&&(t+=1,e??=Date.now(),t<=5&&Date.now()-e<=5e3),get attempts(){return t}}}();for(;;){const s=yo(Hn(e,{isCompleting:!0,customizeNegotiation:n?.customizeCompletion,observability:e.observability,wallets:e.checkout.wallets,selectedBillingAddress:e.shopPay.session.selectedBillingAddress.value}),o),{data:l,error:c}=await e.graphql.mutate(jn,{variables:{input:s,attemptToken:d,metafields:lo(e),postPurchaseInquiryResult:Yn(e),analytics:zn()}});if(!l)return{status:"fetch_failed",reason:c?`${c.message}`:"Submit for completion failed",isActionable:Ot(c).actionable};
1if(ro(l.submitForCompletion)){if(!i.shouldRetry(l.submitForCompletion))return{status:"fetch_failed",reason:"Submit for completion returned ReceiptNotFound",isActionable:!1};t.leaveErrorBreadcrumb("[SubmitForCompletion] Receipt not found; retrying completion",{submitForCompletionType:l.submitForCompletion.__typename,receiptNotFoundAttempts:i.attempts}),await st(fe);continue}const p=ve("SubmitRejected"===l.submitForCompletion.__typename?l.submitForCompletion.errors:void 0,"SubmitRejected"===l.submitForCompletion.__typename?l.submitForCompletion.sellerProposal:void 0,"SubmitRejected"===l.submitForCompletion.__typename?l.submitForCompletion.buyerProposal:void 0),m=Xe(l.submitForCompletion,p);if("SubmitRejected"===l.submitForCompletion.__typename&&m.length){o=l.submitForCompletion,await st($n(l.submitForCompletion));const n=await e.runInterceptors({negotiationStage:"completion"});if("block"===n.behavior){const e=n.reasons;return t.leaveErrorBreadcrumb("Blocked polled completion",{reasons:e,pendingFields:m}),{status:"invalid",reasons:e}}continue}const y="SubmitRejected"===l?.submitForCompletion.__typename?l.submitForCompletion.buyerProposal:void 0,h=ao({submitForCompletion:l.submitForCompletion,buyerProposal:y,violations:p,proposedPaymentLines:u,observability:t,negotiator:e});r({updated:h,buyerProposal:y}),"SubmitRejected"===l?.submitForCompletion.__typename&&p&&p.length>0&&(t.leaveErrorBreadcrumb("Submit for completion was rejected",{violations:p.map(e=>e.code)}),p.some(e=>"BUYER_IDENTITY_MISSING_CONTACT_METHOD"===e.code)&&(t.log("submit_for_completion_rejected_with_missing_contact_method","Missing contact method",{proposedEmail:e.parts.email.peek(),negotiatedCustomerProfileEmail:e.current.peek().buyerIdentity?.customerProfile?.email,negotiatedContactInfoEmail:e.current.peek().contactInfo?.email}),t.error(new no("SubmitForCompletion returned BUYER_IDENTITY_MISSING_CONTACT_METHOD",{groupingHash:po(e)}),{severity:"info"})),Se(p,e.parts,e.context,e.observability));const g=mo(l,e,h,p??[],a);return"alreadyCompleted"!==g.status&&"success"!==g.status||(e.checkout.configuration.renderContextToken.update(g.renderContextToken??void 0),e.checkout.configuration.update({deferredProfileChangeId:g.configurationRecordId})),g}})()}finally{e.checkout.rememberMe.unstable_setCreateAccountOptIn(!1)}}function po(e){const t=e.current.peek().buyerIdentity?.customerProfile?.email,n=e.current.peek().contactInfo?.email,o=e.current.peek().buyerIdentity?.customerProfile?.__typename,i=[];return t||n||"orderEdit"!==e.source.type?(e.checkout.configuration.layout.isOnePage.value?i.push("onePage"):i.push("threePage"),e.checkout.wallets.escalatedWallet.value?i.push(e.checkout.wallets.escalatedWallet.value):"shopPay"===e.checkout.identity.current.value?i.push("shopPay"):"CustomerProfile"===o?i.push("customerAccount"):"BusinessCustomerProfile"===o?i.push("businessCustomer"):i.push("guest")):i.push("orderEditWithBlankNegotiatedEmail"),i.join("::")}function mo({submitForCompletion:e},t,n,o,i){const{persistenceManager:a,router:r,source:s}=t;switch(e.__typename){case"SubmitSuccess":case"SubmitAlreadyAccepted":{const t=i(e.receipt);return"processed"!==t.status&&"failed"!==t.status||!a||Pe(a,s),{status:"success",receipt:t,configurationRecordId:e.configurationRecordId??void 0,renderContextToken:e.renderContextToken??void 0}}case"SubmittedForCompletion":{const t=i(e.receipt,{skipToThankYouPage:!0});return a&&Pe(a,s),{status:"alreadyCompleted",receipt:t,configurationRecordId:e.configurationRecordId??void 0,renderContextToken:e.renderContextToken??void 0}}case"Throttled":return a&&Pe(a,s),t.setThrottle(Ze(e)),{status:"throttled"};case"SubmitRejected":return a&&Pe(a,s),{status:"rejected",negotiated:n,violations:o,errors:eo(o,e.buyerProposal)};case"TooManyRequests":{a&&Pe(a,s);const e={type:"failed",negotiationStage:"completion",fetchFailed:!1,reason:"tooManyRequests"};return t.recordProgression(e),{status:"tooManyRequests"}}case"SubmitFailed":return a&&Pe(a,s),{status:"failed",reason:e.reason};case"CheckpointDenied":{a&&Pe(a,s);const t="undefined"==typeof window,n=t?r.currentUrl.value.toString():void 0,o=Ae(e.redirectUrl,n);return t||window.location.assign(o.href),{status:"denied"}}case"TooManyAttempts":if(a&&Pe(a,s),"undefined"!=typeof window){const t=new URL(e.redirectUrl);window.location.assign(t.href)}return{status:"denied"};default:throw a&&Pe(a,s),new to(`Unknown submitForCompletion type: ${e.__typename}`)}}function yo(e,t){return t?Wn({variables:e,errors:t.errors,sellerProposal:{tax:t.sellerProposal?.tax,duty:t.sellerProposal?.duty}}):e}const ho={id:"2792a3a112d002bc1e62e25a8ab2bd44b74222a431426610ecf915447685816b",type:"query",name:"Proposal",source:""};
1class go extends Error{constructor(){super(...arguments),this.name="StaleNegotiationError"}}class bo extends Error{constructor(){super(...arguments),this.name="MissingNegotiationDataError"}}class fo extends Ft{constructor(){super(...arguments),this.name="NegotiationFailedError"}}class vo extends Ft{constructor(){super(...arguments),this.name="UnactionableNegotiationFailedError",this.unactionable=!0}}class So extends Error{constructor(){super(...arguments),this.name="GenericError"}}class Po extends Error{constructor(){super(...arguments),this.name="UnexpectedNegotiationResult"}}class Ao extends Error{constructor(){super(...arguments),this.name="EmptyMerchandiseLinesNegotiationResult"}}function Mo(e,t,n){if(!function(e,t){const{lines:n}=e;return n.length>0&&0===Me(n,t).length}(e,t))return;const o=function(e){return e.ui.search().peek().filter(e=>"persisted"===e.type)}(n);o.length>0&&n.ui.remove(o.map(e=>e.targetPublicIdentifier),{keepAlive:!1,reason:"remote_only_transition"})}function Co({state:e,sendSequence:t,result:n,fromNetwork:o,checkout:i,negotiator:a}){if(!o)return;if("NegotiationResultAvailable"!==n?.__typename)return;if(t<=e.seen)return;e.seen=t,i.unstable_overwriteCheckpointToken(n.checkpointData??void 0);const r=a.throttleState.peek();"complete"===r.status&&null!=n.queueToken?a.setThrottle({...r,token:n.queueToken}):"inactive"!==r.status&&"complete"!==r.status||a.setThrottle({status:"inactive",token:n.queueToken??void 0})}const To=new Set(["orderEdit","paymentCollection"]);function _o(e,t){if("NegotiationResultAvailable"!==t.result.__typename||To.has(e))return!1;if(t.errors.some(e=>Ce.has(e.code)))return!1;const n=t.result.sellerProposal.merchandise;return"FilledMerchandiseTerms"===n.__typename&&0===n.merchandiseLines.length&&(o=t.result.sellerProposal?.remote,!(o?.remoteNegotiations&&0!==o.remoteNegotiations.length&&o.remoteNegotiations.some(e=>{if("RemoteNegotiationResultAvailable"!==e.result?.__typename)return!1;const t=e.result.sellerProposal?.merchandise,n=e.result.buyerProposal?.merchandise,o="FilledMerchandiseTerms"===t?.__typename&&(t.merchandiseLines?.length??0)>0,i="FilledMerchandiseTerms"===n?.__typename&&(n.merchandiseLines?.length??0)>0;return o||i})));var o}async function*Io(e,t,n,o={reportedMissingContact:!1,reportedMissingContactCommit:!1}){const{identifier:i,negotiationStage:a}=n,r=e.checkout.wallets.activeSession.peek()?.wallet,s=n.startedInAcceleratedWalletSession??("APPLE_PAY"===r||"GOOGLE_PAY"===r),{isActive:l,negotiating:d}=e.start();t.leaveErrorBreadcrumb("[Negotiate] Running negotiation interceptors",{identifier:i.toString(),negotiationStage:a});const u=await e.runInterceptors({negotiationStage:a,skipEffects:n.skipStateUpdates});if(!l()){const e="[Negotiate] Not doing negotiation due to stale negotiation";return t.leaveErrorBreadcrumb(e),void(yield{status:"stale"})}if(!n.skipStateUpdates){const{errors:t}=u;e.setValidationErrors(t)}if("block"===u.behavior){const{reasons:e,errors:n,context:o}=u;return t.leaveErrorBreadcrumb("[Negotiate] Blocked negotiation",{reasons:e,errors:n,context:o}),void(yield{status:"invalid",reasons:e})}let c,p=Hn(e,{customizeNegotiation:n?.customizeNegotiation,paymentLinesObservability:t,selectedBillingAddress:e.shopPay.session.selectedBillingAddress.value});function m(){c?.({updated:{}})}n.skipStateUpdates||(c=d(n.loading));const{graphql:y}=e,h=e.parts.paymentLines.peek();try{let r,d=!0;for(;;){if(!l())throw new go;d||o.reportedMissingContact||(o.reportedMissingContact=ko({variables:p,negotiator:e,negotiationStage:a,customized:null!=n.customizeNegotiation})),p=Do(p,r);const{dirty:u}=e.track(p),m=!u&&d&&!n.force,b=e.collectPendingNegotiationEventIds(i,a),f=await lt(async()=>{const i=Date.now(),{data:r,error:s}=await e.serializeNegotiationRequest(async()=>{if(!l())throw new go;p={...p,checkpointData:e.checkout.checkpointToken.value,queueToken:Nn(e.throttleState)},xo({negotiator:e,negotiationStage:a,waitedMs:Date.now()-i}),e.serializedTokenRotation??={sent:0,seen:0};const t=e.serializedTokenRotation,n=((o=t).sent+=1,o.sent);var o;const r=y.staticQuery(ho,{cache:m,variables:p,getCacheKey:({id:e},t)=>`${e}${Te(t?dt(t):{})}`,...b.length&&{additionalHeaders:{"Shopify-Checkout-Event-Ids":b.join(",")}}}),s=r instanceof Promise,d=await r;return Co({state:t,sendSequence:n,result:d.data?.session?.negotiate?.result,fromNetwork:s,checkout:e.checkout,negotiator:e}),d});if(s)throw s;const d=r?.session?.negotiate;if(null==d)throw new bo("negotiation data is missing");if(Eo({result:d.result,negotiator:e,negotiationStage:a,customized:null!=n.customizeNegotiation,superseded:!l(),telemetry:o}),!l()){const n="[Negotiate] Negotiation is stale";throw t.leaveErrorBreadcrumb(n),e.observability.log("negotiate_stale_negotiation_detected",n),new go}if(_o(e.source.type,d))throw new Ao;return d},{shouldRetry:e=>!(null==e||e instanceof go||e instanceof Ao||e instanceof bo)}),v=f.result,S=f.errors;switch(t.leaveErrorBreadcrumb("[Negotiate] Negotiation completed",{negotiationResult:v.__typename,negotiationViolations:S.map(e=>e.nonLocalizedMessage)}),v.__typename){case"NegotiationResultAvailable":{const i=ve(S,v.sellerProposal,v.buyerProposal)??[];e.checkout.unstable_overwriteCheckpointToken(v.checkpointData??void 0),e.setThrottle(Ze(v));const d=Xe(v,i);e.checkout.configuration.renderContextToken.update(v.renderContextToken??void 0),r=f;const u=v.buyerProposal,m=Jn({sellerProposal:v.sellerProposal,buyerProposal:u,violations:i,silenceViolations:n.silenceViolations,proposedPaymentLines:h,currentUcp:e.current.fields.ucp.value,observability:t,shop:e.shop}),y=Object.entries(m).reduce((e,t)=>
1{const[o,i]=t;return n.fieldsToResolve?.includes(o)&&d.includes(o)?e:{...e,[o]:i}},{}),g=z(i,n.silenceViolations);_e({observability:t,negotiationStage:a,silenceViolations:n.silenceViolations,violations:i,retainedViolations:g,reportedCodes:e.reportedSilencedViolationCodes});const b=Se(g,e.parts,e.context,e.observability),{autoResolved:P,blockingProgress:A,informational:M,removingItems:C,invalidInputs:T,mustAcceptTerms:_,unresolvable:I,other:k}=Ie(g);if(t.leaveErrorBreadcrumb("[Negotiate]: Violation handling result",{silenceViolations:n.silenceViolations,hasErrors:b.hasErrors,requiresRenegotiation:b.requiresRenegotiation,surfacedToBuyer:{blockingProgress:A,informational:M,removingItems:C,invalidInputs:T,mustAcceptTerms:_,unresolvable:I},autoResolved:P,other:k}),b.requiresRenegotiation)return void(yield*Io(e,t,{...n,startedInAcceleratedWalletSession:s},o));let x=Ht({checkout:e.checkout,shop:e.shop,profileId:v.configurationRecordId??e.checkout.configuration.profileId.peek()});if(x&&s&&!n.threePageWalletEscalation&&!e.hasPendingThreePageWalletEscalation()){const t=e.checkout.configuration.profileKey.peek();x=t?.id===x.id?t:{...x,requireBusinessCriticalOnly:!1}}const E=await jt(()=>{c?.({updated:y,loadingFields:d,buyerProposal:u})},{trigger:"negotiation",profileRequest:x,graphql:e.graphql,extensibility:e.checkout.extensibility,configuration:e.checkout.configuration,observability:e.observability,userEvents:e.userEvents,isActive:l,runInterceptors:e.runInterceptors.bind(e),setValidationErrors:e.setValidationErrors.bind(e),telemetryContext:{source:e.source,shop:e.shop,sessionToken:e.sessionToken,current:e.current}});if(!l())throw E?.(),new go;if(E&&Bt(E,["checkout-profile-change"]),Mo(e.current.fields.merchandiseLines.value??{lines:[]},e.current.fields.remoteMerchandiseDetails.value,e.checkout.extensibility),(ke(i).length||xe(i).length)&&e.track(p),!n.skipStateUpdates&&l()&&b.hasErrors){const{inventoryRecoverySignal:t}=e.context,n=t.value;n&&!n.dismissed&&(t.value={...n,dismissed:!0})}if(yield b.hasErrors?{status:"error",negotiated:e.current.peek(),violations:i,errors:eo(i??[],v.buyerProposal),pendingFields:d}:{status:"success",negotiated:e.current.peek(),violations:i,errors:eo(i??[],v.buyerProposal),pendingFields:d},0===d.length)return;break}case"CheckpointDenied":{c?.({updated:wo({negotiator:e,observability:t,typename:v.__typename})});const n="undefined"==typeof window,o=n?e.router.currentUrl.value.toString():void 0,i=Ae(v.redirectUrl,o);return n||window.location.assign(i.href),void(yield{status:"denied"})}case"Throttled":return c?.({updated:wo({negotiator:e,observability:t,typename:v.__typename})}),yield{status:"throttled"},void e.setThrottle(Ze(v));case"TooManyRequests":{c?.({updated:wo({negotiator:e,observability:t,typename:v.__typename})});const n={type:"failed",negotiationStage:a,fetchFailed:!1,reason:"tooManyRequests"};return e.recordProgression(n),yield{status:"tooManyRequests"},e.observability.log("negotiate_result_returned","[Negotiate] Negotiation halted due to too many requests"),void e.observability.counter({name:"negotiation_result_too_many_requests",value:1})}case"SubmittedForCompletion":{let n;c?.({updated:wo({negotiator:e,observability:t,typename:v.__typename})});try{n=await be()}catch(g){if(!l())throw new go;const e=v.receipt,n=nt(e);return t.leaveErrorBreadcrumb("[Negotiate] Receipt mapper failed to load for already completed negotiation",{error:String(g),receiptType:e.__typename}),n?void(yield{status:"alreadyCompleted",receipt:n}):"ProcessedReceipt"===e.__typename&&e.orderStatusPageUrl?void window.location.replace(e.orderStatusPageUrl):void(yield{status:"fetch_failed",reason:"Receipt mapper failed to load after submitted for completion",isActionable:!1})}if(!l())throw new go;const o=n(v.receipt,{skipToThankYouPage:!0});return void(yield{status:"alreadyCompleted",receipt:o})}case"NegotiationResultFailed":{c?.({updated:wo({negotiator:e,observability:t,typename:v.__typename})});const n=f.errors.map(e=>e.code);throw!1===v.reportable&&(e.observability.log("negotiate_result_returned",`[Negotiate] Negotiation result failed, violations: ${n.join(",")}`),e.observability.counter({name:"negotiation_result_failed",value:1})),new So("Server failed to fulfill the request and to identify the exact issue.",{cause:v.reportable?new fo(`Negotiation request failed. Violations = ${n.join(",")}`):new vo(`Negotiation request failed. Violations = ${n.join(",")}`)})}default:throw c?.({updated:wo({negotiator:e,observability:t,typename:void 0})}),new Po(`Negotiation result type not implemented yet: ${v.__typename}`)}if(d=!1,n.skipStateUpdates)break;await st($n(v))}}catch(b){if([ut,ct,pt].some(e=>b instanceof e)){const{actionable:t}=Ot(b),n=b.message??"Negotiation fetch failed";if(zt(n)||!t)return e.observability.log("negotiate_result_error_returned","[Negotiate] Negotiation network error",{reason:n}),e.observability.counter({name:"negotiation_network_error",value:1,attributes:{reason:Gt(n)}}),m(),void(yield{status:"fetch_failed",reason:n,isActionable:t,networkError:!0})}if(b instanceof go)return void(yield{status:"stale"});if(b instanceof Ao)return void(e.checkout.configuration.allowRedirectToStorefront?(e.observability.counter({name:"empty_merchandise_lines_redirect",value:1,attributes:{source:e.source.type}}),Ee({client:e.client,url:e.url,source:e.source,configuration:e.checkout.configuration})):(m(),yield{status:"stale"}));throw e.track(),b}}function ko({variables:e,negotiator:t,negotiationStage:n,customized:o}){const i=e.buyerIdentity,a=Boolean(t.parts.email.peek().trim())&&void 0===i?.email,r=Boolean(t.parts.p
1hone.peek().trim())&&void 0===i?.phone;if(!a&&!r)return!1;let s="both";r||(s="email"),a||(s="phone");const l={negotiationStage:n,customized:o,channel:s};return t.observability.counter({name:"negotiate_missing_contact_snapshot",value:1,attributes:l}),t.observability.log("negotiate_missing_contact_snapshot","[Negotiate] Poll is about to re-send a snapshot missing the contact method the buyer has since supplied",l),!0}function xo({negotiator:e,negotiationStage:t,waitedMs:n}){if(n<=0)return;let o=">=5000ms";n<100?o="<100ms":n<500?o="100-500ms":n<1e3?o="500-1000ms":n<5e3&&(o="1000-5000ms"),e.observability.counter({name:"negotiation_request_serialized_wait",value:1,attributes:{negotiationStage:t,bucket:o}})}function Eo({result:e,negotiator:t,negotiationStage:n,customized:o,superseded:i,telemetry:a}){if("NegotiationResultAvailable"!==e.__typename)return;const r=e.buyerProposal.buyerIdentity;if("FilledBuyerIdentityTerms"!==r.__typename)return;const s={email:tt(l=r,{emptyContactFallback:void 0})??null,phone:et(l,{emptyContactFallback:void 0})??null};var l;const d=t.lastNegotiatedContactEcho;if(t.lastNegotiatedContactEcho=s,!a.reportedMissingContact||a.reportedMissingContactCommit)return;const u=Boolean(t.parts.email.peek().trim())&&null==s.email&&Boolean(d?.email),c=Boolean(t.parts.phone.peek().trim())&&null==s.phone&&Boolean(d?.phone);if(!u&&!c)return;a.reportedMissingContactCommit=!0;let p="both";c||(p="email"),u||(p="phone");const m={negotiationStage:n,customized:o,channel:p,superseded:i};t.observability.counter({name:"negotiate_missing_contact_committed",value:1,attributes:m}),t.observability.log("negotiate_missing_contact_committed","[Negotiate] Server committed a poll snapshot missing the contact method a previous response had confirmed",m)}function Do(e,t){return t&&"NegotiationResultAvailable"===t.result.__typename?Wn({variables:e,errors:t.errors,sellerProposal:{tax:t.result.sellerProposal?.tax,duty:t.result.sellerProposal?.duty}}):e}function wo({negotiator:e,observability:t,typename:n}){return{sellability:ce({shop:e.shop,missingSellerProposalReason:Ro(n),observability:t})}}function Ro(e){switch(e){case"CheckpointDenied":return"Proposal.CheckpointDenied";case"NegotiationResultFailed":return"Proposal.NegotiationResultFailed";case"SubmittedForCompletion":return"Proposal.SubmittedForCompletion";case"Throttled":return"Proposal.Throttled";case"TooManyRequests":return"Proposal.TooManyRequests";default:return"Proposal.Unknown"}}export{co as complete,Hn as getNegotiationInput,Io as negotiate};
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.