1import{c as It,j as Xe,n as F,a as Tt,b as Et}from"./esnext-vendor.B9Da21W6.js";import{c as St,s as ve,a as le,b as be,R as Ae,d as wt,i as O,e as kt,n as Ke,f as Je,g as Dt,h as Lt,j as Pt,C as Nt,V as Z,p as Mt,k as Ot,l as Rt,m as Ut,U as xt,o as qt,q as Ht,r as Ft,t as jt,F as $t,u as Bt,v as we,w as ke,x as Gt,y as Yt,z as Wt,A as Vt,B as zt,D as Xt}from"./addresses-is-address-empty.BgqK_zG_.js";import{i as Kt}from"./graphql-PaymentSessionMutation.DJrmXbx9.js";import{i as Jt}from"./cvv-cvvBridge.hYfPqjG6.js";import{s as Qt}from"./helpers-derivations.Cr-il7Z-.js";import{a as U,i as Zt}from"./context-browser.Q2R3PORz.js";class en{#e;#t=0;get current(){return this.#e}async during(t,n){this.#e=t,this.#t+=1;try{return await n()}finally{this.#t-=1,this.#t===0&&(this.#e=void 0)}}}function tn(e){return Array.from(e.values()).flatMap(t=>{const n=t.read();return n?[n]:[]}).sort((t,n)=>nn(t.key,n.key))}function nn(e,t){return e===t?0:e<t?-1:1}function z(e,t){const n=e??[],i=new Map;for(const[r,{key:s,value:a}]of n.entries()){const d=`$.checkout.declared_fields[${r}]`,c=t.get(s);if(!c?.read())return oe(`${d}.key`,"must identify a declared field available in the current checkout");const l=c.prepare(a);if("requirement"in l)return oe(`${d}.value`,l.requirement);i.set(s,l)}const o=[];for(const[r,s]of t){if(!s.read())continue;const a=i.get(r)??s.prepare(null);if("requirement"in a)return oe("$.checkout.declared_fields",a.requirement);o.push({...a,get changed(){return a.changed},async apply(){return t.get(r)===s&&s.read()?a.apply():!1}})}return o}function oe(e,t){return{error:{code:"rejected",message:`${e}: ${t}. Nothing was applied. Call get_checkout before retrying.`}}}function on(e){const{email:t,phone:n}=e??{};if(!(!t&&!n))return{...t?{email:t}:{},...n?{phone_number:n}:{}}}function k(e){if(!e)return 0;const t=It(e.currencyCode),n=new Intl.NumberFormat("en",{style:"decimal",useGrouping:!1,minimumFractionDigits:t,maximumFractionDigits:t}),[i,o=""]=n.format(e.amount).split(".");return Number(i+o.padEnd(t,"0"))}function rn(e,t){if(!e?.lines.length)return;const n=t?new Map(t.map(({id:r},s)=>[r,s])):void 0,i=new Map,o=[];for(const r of e.lines){const{discount:s}=r;if(s.type==="code"||s.type==="discountCodeTrigger"){const a=s.title.toUpperCase();i.has(a)||i.set(a,s.title)}if("allocations"in r){const a=sn(r,n);a.amount>0&&o.push(a)}}return{codes:[...i.values()],applied:o}}function sn(e,t){const{discount:n}=e,i=[];let o=0,r=!1;for(const{target:d}of e.allocations){let c=d.index;if(d.type==="MERCHANDISELINE"&&t&&(c=d.stableId==null?void 0:t.get(d.stableId),c==null)){r=!0;continue}const l=k(d.amount);o+=l,d.type==="MERCHANDISELINE"&&c!=null?i.push({path:`$.line_items[${c}]`,amount:l}):d.type==="DELIVERYLINE"&&i.push({path:"$.totals.shipping",amount:l})}const s=n.type==="code"&&n.codeHidden,a=r?0:k(e.amount);return{title:s?"Discount":n.title,amount:o||a,...n.type==="code"&&!s&&{code:n.title},...n.type!=="code"&&{automatic:!0},...n.allocationMethod==="EACH"&&{method:"each"},...n.allocationMethod==="ACROSS"&&{method:"across"},...i.length>0&&{allocations:i}}}function ee(e,{extendedAddressMode:t}){const n=e.address_country?.toUpperCase()??"",i=t.get(n),o=i===null?an(n,e):dn(n,e,i);return{...St({...e,street_address:o.address1,extended_address:o.address2}),company:e.company??"",district:void 0,subdistrict:void 0,...o}}function Ce(e,t){const n=e.countryCode??"",i=t?.extendedAddressMode.get(n)??null;return{company:e.company,first_name:e.firstName,last_name:e.lastName,phone_number:e.phone,...i===null?un(n,e):hn(n,e,i),address_locality:e.city,address_region:e.zoneCode,address_country:e.countryCode,postal_code:e.postalCode}}function Qe({street_address:e="",street_name:t,street_number:n=""}){return t?.trim()?{streetName:t,streetNumber:n}:{line:e}}function an(e,t){const n=Qe(t);return{address1:"line"in n?n.line:yn(e,n),address2:t.extended_address??""}}function dn(e,t,n){const{packedLine2:i,...o}=cn(e,Qe(t)),{neighborhood:r,...s}=ln(e,t,i);return{...o,...s,...n==="dedicated"?r!==void 0&&{district:r,neighborhood:""}:{neighborhood:r}}}function cn(e,t){if("line"in t){const i=ve(e,t.line,!0);if(!i?.streetNumber)return{address1:t.line};const o=le({countryCode:e,streetName:i.streetName??"",streetNumber:i.streetNumber});return o==null?{address1:t.line}:{address1:o,packedLine2:i.line2}}const n=le({countryCode:e,...t});return n==null?{address1:nt(t)}:{address1:n,...t}}function ln(e,{extended_address:t="",district:n},i){const o=be(e,t);if(!o)return{address2:De(t,i)};const r=De(o.line2??"",i),s=n??o.neighborhood??"";return{address2:tt(e,r,s),line2:r,neighborhood:s}}function De(e,t){return!t||t===e.trim()?e:it(e,t)}function un(e,t){return{street_address:Ze(e,t),extended_address:pn(e,t)}}function Ze(e,{address1:t,streetName:n,streetNumber:i}){return t||!(n||i)?t:et(e,{streetName:n??"",streetNumber:i??""})}function pn(e,{address2:t,line2:n,district:i,neighborhood:o}){const r=i||o;return n==null&&!r?t:tt(e,n??"",r??"")}
1function hn(e,t,n){const i=fn(e,t,n);return{...i?.streetName?{street_name:i.streetName,street_number:i.streetNumber??""}:{street_address:Ze(e,t)},...mn(e,t,n)}}function fn(e,t,n){return n==="dedicated"&&(t.streetName!=null||t.streetNumber!=null)?t:t.address1?.includes(Ae)?ve(e,t.address1):null}function mn(e,t,n){if(n==="dedicated"&&(t.line2!=null||t.district!=null)){const o=t.district??t.neighborhood;return{extended_address:t.line2,...o!=null&&{district:o}}}const i=t.address2?.includes(Ae)?be(e,t.address2):null;return i?{extended_address:i.line2??"",district:i.neighborhood??""}:{extended_address:t.address2||t.line2,...n==="concatenated"&&t.neighborhood!=null&&{district:t.neighborhood}}}function et(e,t){return le({countryCode:e,...t})??nt(t)}function tt(e,t,n){return wt({countryCode:e,line2:t,neighborhood:n})??it(t,n)}function yn(e,t){return _n(et(e,t))}function nt({streetName:e,streetNumber:t}){return[t,e].filter(Boolean).join(" ")}function it(e,t){return[e,t].filter(Boolean).join(", ")}function _n(e){return e.split(Ae).join("")}function gn(e){if(!e?.length)return{lineItems:[],itemsDiscountAmount:0,cartLevelDiscountAmount:0};let t=0,n=0;return{lineItems:e.map(o=>{const{itemPrice:r}=o,s=r?{...r,amount:r.amount*o.quantity}:void 0,{lineLevel:a,cartLevel:d}=bn(o.lineAllocations),c=[];n+=d,s&&c.push({type:"subtotal",amount:k(s)}),a!==0&&s&&(t+=a,c.push({type:"items_discount",amount:k({...s,amount:-a})}));const l=s?{...s,amount:s.amount-a}:o.totalPrice;return c.push({type:"total",amount:k(l)}),{id:T(o),...o.parentRelationship?.parent?.stableId?{parent_id:o.parentRelationship.parent.stableId}:{},quantity:o.quantity,item:{id:o.variantId??o.stableId,title:o.title,price:k(r),...o.image?.url?{image_url:o.image.url}:{}},totals:c}}),itemsDiscountAmount:t,cartLevelDiscountAmount:n}}function ne(e){return e?.flatMap(t=>(t.lineComponents.length?t.lineComponents:[t]).filter(n=>n.requiresShipping).map(T))??[]}function vn(e){if(e)return e.reduce((t,n)=>{const{itemPrice:i}=n;if(!i)return t;const o=i.amount*n.quantity;return t?{...t,amount:t.amount+o}:{...i,amount:o}},void 0)}function T(e){return e.stableId}function bn(e){let t=0,n=0;for(const i of e)for(const{discountDetails:o,amount:r}of i.allocations)An(o.discount)?n+=r.amount:t+=r.amount;return{lineLevel:t,cartLevel:n}}function An(e){return"presentationLevel"in e&&e.presentationLevel==="CART"}function K(e){return e==="SHIPPING"||e==="LOCAL"||O(e)}function Cn(e,t,n){return!!(e&&!n&&(t.some(i=>!K(i))||t.some(O)&&t.some(i=>i==="SHIPPING"||i==="LOCAL")))}function In(e,t,n){return!n||e===t}function te(e,t){switch(t){case"phone_number":return!!e.phoneRequired;case"instructions":return!!e.acceptsInstructions}}function Y(e,t){if(!e?.length||!t?.length)return!1;const n=new Set(t),i=e.filter(o=>o.requiresShipping).map(o=>T(o));return i.length===n.size&&i.every(o=>n.has(o))}const ue="pickup";function W(e){const t=e.methods.find(({handle:i})=>i===e.selectedDeliveryMethodHandle),n=e.proposedLine?t?.methodType??e.proposedLine.deliveryMethodTypes[0]:(t??e.methods[0])?.methodType;if(n)return O(n)?"pickup":"shipping"}function ot(e){const t=e.filter(r=>W(r)==="pickup"),n=t.map(r=>{const s=new Map;for(const a of r.methods){if(!a.pickupLocation)continue;const d=Tn(a.pickupLocation);(!s.has(d)||a.handle===r.selectedDeliveryMethodHandle)&&s.set(d,a)}return s}),i=n[0];if(!i)return[];const o=[];for(const[r,s]of i){const a=[];for(const[d,c]of t.entries()){const l=n[d].get(r);if(!l)break;a.push({line:c,method:l})}a.length===t.length&&o.push({id:s.handle,selections:a})}return o}function Tn(e){if(e.type==="PickupPointLocation"&&e.handle)return JSON.stringify([e.type,e.carrierCode||e.carrierName,e.handle]);const{address:t}=e;return JSON.stringify([e.type,e.name??"",t.address1??"",t.address2??"",t.city??"",t.zoneCode??"",t.countryCode??"",t.postalCode?.replace(/\s+/g,"").toUpperCase()??"",t.streetName??"",t.streetNumber??"",t.neighborhood??"",t.district??"",t.subdistrict??"",t.line2??""])}function En(e,t){const n=new Map;for(const r of e)n.has(r.id)||n.set(r.id,r);const i=[...n.values()],o=t?i.find(({address:r})=>kt(r,t)):void 0;return{destinations:i,selectedDestinationId:o?.id}}function Sn(e){const t=kn(e);return t.length?{methods:t}:void 0}function wn(e){if(e?.status!=="filled"||!e.lines)return;let t=0,n;for(const i of e.lines){if(i.status!=="available")continue;const o=i.selectedDeliveryMethodHandle;if(!o)continue;const r=i.methods.find(s=>s.handle===o);r?.cost&&(t+=r.cost.amount,n??=r.cost.currencyCode)}if(n!=null)return{amount:t,currencyCode:n}}const Ie=Ce;function kn(e){const{deliveryNext:t}=e;if(e.readMode!=="proposed"&&(t?.status!=="filled"&&t?.status!=="partial"||!t.lines))return Le(e);const n=(t?.status==="filled"||t?.status==="partial")&&t.lines?t.lines.filter(qn):[],o=(e.readMode==="proposed"?Rn(n,e.proposedDeliveryLines,e.merchandiseLines):n).filter(d=>(d.proposedLine?d.proposedLine.deliveryMethodTypes.some(Pe):d.methods.some(c=>Pe(c.methodType)))&&d.targetMerchandiseLines?.some(c=>
1c.requiresShipping));if(e.readMode==="proposed"&&!o.length)return Le(e);const r=t?.status==="partial"?rt(e,o):new Map,s=new Set([...Dn(o),...r.keys()]),a=[];for(const d of s){const c=o.filter(p=>W(p)===d),l=c.map(p=>On(p,p.proposedLine?[p.proposedLine]:e.proposedDeliveryLines)),u=[...new Set([...l.flatMap(p=>p.line_item_ids),...r.get(d)??[]])];a.push({id:d,type:d,line_item_ids:u,destinations:[],...Ln(d,c,e),groups:l})}return a}function rt(e,t){const n=new Set(t.flatMap(r=>r.targetMerchandiseLines?.map(T)??[])),i=new Map,o=new Set;for(const r of e.merchandiseLines??[]){if(e.readMode!=="proposed"&&!r.requiresShipping)continue;const s=T(r);if(n.has(s)||o.has(s))continue;o.add(s);const a=new Set((r.lineComponents.length?r.lineComponents:[r]).filter(u=>u.requiresShipping&&!n.has(T(u))).map(T));if(!a.size)continue;const d=e.proposedDeliveryLines?.filter(u=>u.targetMerchandiseLines.some(p=>T(p)===s||a.has(T(p)))).flatMap(u=>u.deliveryMethodTypes),c=d?.length&&d.every(O)?"pickup":"shipping",l=i.get(c)??[];l.push(...e.readMode==="proposed"?a:[s]),i.set(c,l)}return i}function Le(e){return[...rt(e,[])].map(([n,i])=>({id:n,type:n,line_item_ids:i,destinations:[],...n==="shipping"?st(e):{},groups:[]}))}function Dn(e){const t=new Set;for(const n of e){const i=W(n);i&&t.add(i)}return Array.from(t)}function Pe(e){return e==="SHIPPING"||e==="LOCAL"||O(e)}function Ln(e,t,n){if(e==="shipping")return st(n);const i=ot(t);if(!i.length)return{};const o=i.find(({selections:r})=>r.every(({line:s,method:a})=>s.selectedDeliveryMethodHandle===a.handle));return{destinations:i.flatMap(({id:r,selections:s})=>{const a=Pn(s[0].method,n.addressContext);return a?[{...a,id:r}]:[]}),...o&&{selected_destination_id:o.id}}}function st({savedDestinations:e,shippingAddress:t,addressContext:n}){if(e===void 0)return t&&Je(t)?{destinations:[Nn(t,n)]}:{};const{destinations:i,selectedDestinationId:o}=En(e,t);return i.length?{destinations:i.map(({id:r,address:s})=>({id:r,type:"shipping_address",...Ie(s,n)})),...o&&{selected_destination_id:o}}:{}}function Pn(e,t){const{pickupLocation:n}=e;if(n)return{id:e.handle,type:"business_location",name:n.name??"",pickup_location_address:Ie(n.address,t)}}function Nn(e,t){return{...Ie(e,t),id:Mn(e),type:"shipping_address"}}function Mn(e){return["shipping",e.countryCode,e.postalCode].filter(Boolean).join("-").replace(/\s+/g,"")}function On(e,t){const n=at(e),i=Ke(e),o=e.proposedLine?e.selectedDeliveryMethodHandle:i?.handle,r=o?Un(e,n,t):void 0,s=W(e)==="pickup",a=s?[{...i?Ne(i):{totals:[]},id:ue,title:"Pickup"}]:e.methods.filter(({methodType:d})=>d==="SHIPPING"||d==="LOCAL").map(Ne);return{id:e.id??"",line_item_ids:n,options:a,...o&&{selected_option_id:s?ue:o},...r&&{selected_option_details:r}}}function Rn(e,t,n){const i=new Map;for(const o of n??[]){i.set(T(o),ne([o]).length>0);for(const r of o.lineComponents)i.set(T(r),r.requiresShipping)}return(t??[]).map(o=>{const r=o.targetMerchandiseLines.filter(a=>a.requiresShipping).map(a=>T(a)),s=e.find(a=>o.id!==void 0&&a.id===o.id)??e.find(a=>a.type===o.type&&Y(a.targetMerchandiseLines,r));return{...s,status:"available",id:o.id,type:o.type,targetMerchandiseLines:o.targetMerchandiseLines.flatMap(a=>{const d=i.get(T(a));return d===void 0?[]:[{...a,requiresShipping:d}]}),selectedDeliveryMethodHandle:o.deliveryMethodHandle,methods:s?.methods.filter(a=>o.deliveryMethodTypes.includes(a.methodType))??[],proposedLine:o}})}function Un(e,t,n){const i=xn(e,n,t);if(!i||!e.selectedDeliveryMethodHandle||i.deliveryMethodHandle!==e.selectedDeliveryMethodHandle)return;const o=i.deliveryMethodOptions;if(!o)return;const r=Ke(e),s=r&&!te(r,"phone_number")?void 0:o.phone,a=r&&!te(r,"instructions")?void 0:o.instructions;if(!(s===void 0&&a===void 0))return{...s!==void 0&&{phone_number:s},...a!==void 0&&{instructions:a}}}function xn(e,t,n=at(e)){return t?.find(i=>!!e.id&&i.id===e.id)??t?.find(i=>Y(i.targetMerchandiseLines,n))}function at(e){return e.targetMerchandiseLines?.filter(t=>t.requiresShipping).map(t=>T(t))??[]}function Ne(e){return{id:e.handle,title:e.title,...e.description&&{description:{plain:e.description}},...e.carrierName&&{carrier:e.carrierName},...e.minDeliveryDateTime&&{earliest_fulfillment_time:e.minDeliveryDateTime},...e.maxDeliveryDateTime&&{latest_fulfillment_time:e.maxDeliveryDateTime},totals:[{type:"fulfillment",display_text:O(e.methodType)?"Pickup":"Shipping",amount:k(e.costAfterDiscounts)}]}}function qn(e){return e.status==="available"}const Hn=new Map([["terms-of-service","terms_of_service"],["privacy-policy","privacy_policy"],["refund-policy","refund_policy"],["shipping-policy","shipping_policy"]]);function Fn(e){const t=[];for(const{handle:n,url:i}of e){const o=Hn.get(n);o&&t.push({type:o,url:i})}return t}function jn(e){if(e?.status!=="processed")return;const t=e.orderIdentity.buyerIdentifier,n=Dt(e.orderIdentity.id);return{...n?{id:Lt("Order",n)}:{},...t?{label:t}:{},permalink_url:e.confirmationPage.url}}function $n(e,t,n){const i=n?.filter(({instrument:o,usable:r})=>
1o.selected||r).map(({instrument:o})=>o);return i?.length?{instruments:i}:{instruments:e?[{billing_address:Ce(e,t)}]:[]}}function Bn(e){return e.some(({instrument:n,usable:i})=>n.selected&&!i)?[{type:"error",severity:e.some(({usable:n})=>n)?"recoverable":"requires_buyer_input",code:"payment_instrument_unusable",path:"$.payment",content:"The selected card cannot be used for this checkout. Select another instrument by id, or ask the buyer to update payment on the page."}]:[]}const Gn={DELIVERY_NO_DELIVERY_STRATEGY_AVAILABLE_FOR_MERCHANDISE_LINE:"address_undeliverable",DELIVERY_OUT_OF_STOCK_AT_ORIGIN_LOCATION:"out_of_stock",DELIVERY_ZONE_NOT_FOUND:"address_undeliverable",DELIVERY_ZONE_REQUIRED_FOR_COUNTRY:"address_undeliverable",DISCOUNTS_ADDITIONAL_REQUESTED_DISCOUNT_CODE_DISCARDED:"discount_code_not_applied",DISCOUNTS_ALLOCATIONS_MISMATCH:"discount_changed",DISCOUNTS_CURRENTLY_INACTIVE:"discount_code_expired",DISCOUNTS_CUSTOMER_NOT_ELIGIBLE:"discount_code_user_ineligible",DISCOUNTS_CUSTOMER_USAGE_LIMIT_REACHED:"discount_code_user_ineligible",DISCOUNTS_CUSTOM_DISCOUNT_NOT_HONOURED:"discount_code_rejected",DISCOUNTS_DISCOUNTS_NOT_ALLOWED_FOR_B2B:"discount_code_rejected",DISCOUNTS_DISCOUNT_ALREADY_APPLIED:"discount_code_already_applied",DISCOUNTS_DISCOUNT_CODE_APPLICATION_FAILED:"discount_code_rejected",DISCOUNTS_DISCOUNT_CODE_NOT_HONOURED:"discount_code_rejected",DISCOUNTS_DISCOUNT_TITLE_TOO_LONG:"checkout_warning",DISCOUNTS_ELIGIBLE_CUSTOMER_MISSING:"discount_code_user_ineligible",DISCOUNTS_HIGHER_VALUE_DISCOUNT_APPLIED:"discount_code_not_applied",DISCOUNTS_INCOMPATIBLE_PURCHASE_TYPE:"discount_code_combination_disallowed",DISCOUNTS_INCOMPATIBLE_SCRIPT_DISCOUNT:"discount_code_combination_disallowed",DISCOUNTS_INVALID_SIGNATURE:"checkout_warning",DISCOUNTS_MAXIMUM_DISCOUNT_CODE_LIMIT_REACHED:"discount_code_rejected",DISCOUNTS_MIXED_DESTINATION_COUNTRIES:"discount_code_rejected",DISCOUNTS_NOT_FOUND:"discount_code_invalid",DISCOUNTS_NO_ENTITLED_LINE_ITEMS:"discount_code_rejected",DISCOUNTS_NO_ENTITLED_SHIPPING_LINES:"discount_code_rejected",DISCOUNTS_ONLY_EMPTY_TERMS_ACCEPTED:"checkout_warning",DISCOUNTS_PURCHASE_NOT_IN_RANGE:"discount_code_rejected",DISCOUNTS_QUANTITY_NOT_IN_RANGE:"discount_code_rejected",DISCOUNTS_UNSUPPORTED_EXPECTATION:"checkout_warning",DISCOUNTS_USAGE_LIMIT_REACHED:"discount_code_rejected",MERCHANDISE_INVENTORY_NOT_FOUND:"out_of_stock",MERCHANDISE_NOT_APPLICABLE:"item_unavailable",MERCHANDISE_NOT_ENOUGH_STOCK_AVAILABLE:"out_of_stock",MERCHANDISE_NOT_FOUND:"item_unavailable",MERCHANDISE_OUT_OF_STOCK:"out_of_stock",MERCHANDISE_OUT_OF_STOCK_IN_CONTEXT:"out_of_stock",MERCHANDISE_PRODUCT_NOT_PUBLISHED:"item_unavailable",MERCHANDISE_PRODUCT_NOT_PUBLISHED_IN_BUYER_LOCATION:"item_unavailable",MERCHANDISE_PRODUCT_VARIANT_NOT_FOUND:"item_unavailable",PAYMENTS_CREDIT_CARD_BASE_EXPIRED:"payment_failed",PAYMENTS_CREDIT_CARD_BASE_GATEWAY_NOT_SUPPORTED:"payment_failed",PAYMENTS_CREDIT_CARD_GENERIC:"payment_failed",PAYMENTS_CREDIT_CARD_YEAR_EXPIRED:"payment_failed",PAYMENTS_PAYMENT_METHOD_INCOMPATIBLE_WITH_PAYMENT_TERMS:"payment_failed",PAYMENTS_PROPOSED_GATEWAY_UNAVAILABLE:"payment_failed"};function Yn(e){return Gn[e]}const Wn=new Set(["AcceptNewTermViolation","RequiredArtifactsUnavailableViolation"]),Vn=new Set(["PendingTermViolation"]),zn=new Set(["PAYMENTS_UNACCEPTABLE_PAYMENT_AMOUNT"]),Xn={type:"error",severity:"requires_buyer_review",code:"buyer_review_required",content:"The buyer must review the order on the checkout page. After the buyer authorizes submission, call complete_checkout again to submit."};function Kn(e){const{receipt:t,isShippingRequired:n,hasShippingAddress:i,deliveryNext:o,skipsShippingAddress:r=Pt(o)}=e,s=Jn(e),a=Zn({receipt:t,isShippingRequired:n,hasShippingAddress:i,skipsShippingAddress:r,hasUnselectableShippingGroup:e.hasUnselectableShippingGroup??!1,requiresBuyerReview:e.requiresBuyerReview??!1,requiresCaptcha:e.requiresCaptcha??!1});return a==="incomplete"&&e.requiresCaptcha&&t?.status!=="action_required"&&s.push({type:"error",severity:"requires_buyer_input",code:"buyer_action_required",content:"The buyer must complete the CAPTCHA on the checkout page. After the buyer completes it, call get_checkout before retrying complete_checkout. Do not attempt to solve the CAPTCHA on the buyer's behalf."}),a==="requires_escalation"&&s.push(Xn),{status:a,messages:s}}function Jn(e){const t=[];for(const n of e.violations??[]){if(Wn.has(n.__typename)||zn.has(n.code)||e.requiresCaptcha&&Nt.has(n.code))continue;const i=n.code.startsWith("DISCOUNTS_"),o=i||Vn.has(n.__typename),r=Yn(n.code)??(o?"checkout_warning":"checkout_error"),s="target"in n?n.target:void 0,a=i?"$.discounts.codes":s;t.push({...o?{type:"warning"}:{type:"error",severity:"recoverable"},code:r,content:Qn(n,r,e.i18n),...a?{path:a}:{}})}return e.receipt?.status==="action_required"&&t.push({type:"error",severity:"requires_buyer_input",code:"buyer_action_required",content:"Payment requires buyer action. Ask the buyer to complete the payment challenge on the checkout page, then call get_checkout. Do not resubmit checkout."}),t}function Qn(e,t,n){if(e.localizedMessage)return e.localizedMessage;switch(t){case"address_undeliverable":return n.translate("shipping_errors.shipping_method_not_available_generic.one");case"checkout_error":case"checkout_warning":case"discount_changed":case"discount_code_already_applied":case"discount_code_combination_disallowed":case"discount_code_expired":case"discount_code_invalid":case"discount_code_not_applied":case"discount_code_rejected":case"discount_code_user_ineligible":return n.translate("notice_banner.generic_processing_error.title");case"item_unavailable":case"out_of_stock":return n.translate("ucp.standard_errors.item_unavailable");case"payment_failed":return n.translate("payment_errors.generic_error")}}function Zn({receipt:e,isShippingRequired:t,hasShippingAddress:n,skipsShippingAddress:i,hasUnselectableShippingGroup:o,requiresBuyerReview:r,requiresCaptcha:s}){const a=e?.status;return a==="processed"?"completed":a==="processing"||a==="processing_remote_checkouts"||a==="polling_for_order"?"complete_in_progress":a==="action_required"||s?"incomplete":r?"requires_escalation":t&&!n&&!i||t&&o?"incomplete":"ready_for_complete"}function ei({subtotal:e,itemsDiscountAmount:t,cartLevelDiscountAmount:n,discountLines:i,fulfillmentTotal:o,tax:r,duty:s,dutiesIncluded:a,runningTotal:d}){const c=[];return e!=null&&(c.push({type:"subtotal",display_text:"Subtotal",amount:k(e)}),c.push(...ti({currencyCode:e.currencyCode,discountLines:i,itemsDiscountAmount:t,cartLevelDiscountAmount:n}))),o!=null&&c.push({type:"fulfillment",display_text:"Shipping",amount:k(o)}),s!=null&&!a&&c.push({type:"duty",display_text:"Duties",amount:k(s)}),r!=null&&c.push({type:"tax",display_text:"Taxes",amount:k(r)}),d!=null&&c.push({type:"total",display_text:"Total",amount:k(d)}),c}function ti({currencyCode:e,discountLines:t,itemsDiscountAmount:n,cartLevelDiscountAmount:i}){let o=i;for(const s of t?.lines??[])if(Kt(s))for(const a of s.allocations)a.target.type==="DELIVERYLINE"&&(o+=a.target.amount.amount);const r=[];return n>0&&r.push({type:"items_discount",display_text:"Discounts",amount:k({amount:-n,currencyCode:e})}),o>0&&r.push({type:"discount",display_text:"Discount",amount:k({amount:-o,currencyCode:e})}),r}function ni(e){const t=e.merchandiseLines?.lines;if(!t||!ri(t)||e.runningTotal==null)return;const n=e.readMode==="proposed"&&t.length===0?{...e.runningTotal,amount:0}:vn(t)??e.subtotal;if(n==null)return;const{lineItems:i,itemsDiscountAmount:o,cartLevelDiscountAmount:r}=gn(t),s=wn(e.deliveryNext),a=e.receipt?.status==="processed"&&e.receipt.isRedacted?void 0:on(e.contactInfo),d=rn(e.discountLines,e.readMode==="proposed"?i:void 0),c=Sn({readMode:e.readMode,deliveryNext:e.deliveryNext,shippingAddress:e.shippingAddress,merchandiseLines:t,savedDestinations:e.savedDestinations,addressContext:e.addressContext,proposedDeliveryLines:e.proposedDeliveryLines}),{status:l,messages:u}=Kn({i18n:e.i18n,requiresBuyerReview:e.buyerReviewUrl!=null,requiresCaptcha:e.requiresCaptcha,violations:e.violations,receipt:e.receipt,isShippingRequired:e.readMode==="proposed"?ne(t).length>0:e.isShippingRequired,hasShippingAddress:e.readMode==="proposed"?Je(e.shippingAddress):e.shippingAddress!=null,deliveryNext:e.deliveryNext,skipsShippingAddress:e.readMode==="proposed"?oi(c,t):void 0,hasUnselectableShippingGroup:ii(c,t,e.readMode)}),p=jn(e.receipt),h=$n(e.billingAddress,e.addressContext,e.savedCards),_=Bn(e.savedCards??[]),g=[...u,..._];return{...e.id?{id:e.id}:{},...e.continueUrl?{continue_url:e.continueUrl}:{},currency:e.runningTotal.currencyCode,status:l==="ready_for_complete"&&_.length?"incomplete":l,...l==="requires_escalation"&&e.buyerReviewUrl?{continue_url:e.buyerReviewUrl}:{},links:Fn(e.merchantPolicies),line_items:i,totals:ei({subtotal:n,itemsDiscountAmount:o,cartLevelDiscountAmount:r,discountLines:e.discountLines,fulfillmentTotal:s,tax:e.tax,duty:e.duty,dutiesIncluded:e.dutiesIncluded,runningTotal:e.runningTotal}),...a&&{buyer:a},...d&&{discounts:d},...c&&{fulfillment:c},payment:h,...g.length?{messages:g}:{},...p&&{order:p}}}function ii(e,t,n){const i=new Set(e?.methods.flatMap(o=>o.type==="pickup"?o.line_item_ids:(o.groups??[]).filter(({options:r})=>!!r?.length).flatMap(r=>r.line_item_ids)));return t.some(o=>{if(n!=="proposed"&&!o.requiresShipping)return!1;const r=ne([o]);return r.length>0&&!i.has(T(o))&&!r.every(s=>i.has(s))})}function oi(e,t){const n=new Set(e?.methods.filter(i=>i.type==="pickup").flatMap(i=>(i.groups??[]).filter(o=>!!o.selected_option_id).flatMap(o=>o.line_item_ids))??[]);return t.every(i=>n.has(T(i))||ne([i]).every(o=>n.has(o)))}function ri(e){return e.every(t=>t.itemPrice!=null&&t.title!=null)}function si({checkout:e,i18n:t,shop:n,router:i,readMode:o="negotiated",savedCards:r,declaredFields:s=new Map,paymentInstrument:a}){const d=ni({...di(e,t,n,o,i),savedCards:e.isPaymentRequired.value?r:void 0});if(!d)return;const c=tn(s),l=d.payment.instruments[0],u={...d,...a?{payment:{instruments:[ai(a,e,l&&"billing_address"in l?l.billing_address:{})]}}:{},...c.length>0?{declared_fields:c}:{}},p=e.proposal.proposed.locationAddress.value;return u.fulfillment?.methods.length!==1||u.fulfillment.methods[0].type!=="pickup"||!p?.countryCode||!p.postalCode||!p.coordinates?u:{...u,context:{address_country:p.countryCode,...p.zoneCode&&{address_regi
1on:p.zoneCode},postal_code:p.postalCode}}}function ai(e,t,n){const i=t.proposal.proposed.paymentLines.value[0]?.method.type;return{id:e.id,handler_id:e.handler_id,type:e.type,...e.credential?{credential:{type:e.credential.type}}:{},selected:e.handler_id==="shopify.card"?i==="direct":i==="shopWallet",billing_address:n}}function di(e,t,n,i,o){const{proposed:r,negotiated:s}=e.proposal,a=e.addressManager.shipping.value,d=e.identity.current.value==="shopPay"?a:void 0,c=d?[...d.addresses.value,...d.immutableAddresses.value]:void 0,l=s.fields.shippingAddress.value,u=o?.currentUrl.value,p=r.captcha.value;return{i18n:t,readMode:i,requiresCaptcha:!!(p?.provider==="hcaptcha"&&p.sitekey&&(!p.token||p.violationCode)),buyerReviewUrl:u?.normalizedPath==="/review"?u.href:void 0,id:s.fields.ucp.value?.id,continueUrl:s.fields.ucp.value?.continueUrl,merchantPolicies:n.merchantPolicies,merchandiseLines:i==="proposed"?{lines:r.merchandiseLines.value}:s.fields.merchandiseLines.value,subtotal:s.fields.subtotal.value,discountLines:i==="proposed"?{lines:r.discountLines.value}:s.fields.discountLines.value,tax:e.proposal.facts.tax??ui(s.fields.taxes.value),duty:e.proposal.facts.duty??pi(s.fields.duties.value),dutiesIncluded:!!s.fields.dutiesIncluded.value||!!e.proposal.facts.dutiesIncluded,runningTotal:s.fields.runningTotal.value,contactInfo:i==="proposed"?{email:r.email.value,phone:r.phone.value}:s.fields.contactInfo.value,deliveryNext:s.fields.deliveryNext.value,shippingAddress:i==="proposed"?r.shippingAddress.value:l,billingAddress:e.identity.current.value==="shopPay"?void 0:ci(e,n,i),addressContext:e.address,savedDestinations:c,proposedDeliveryLines:r.deliveryLines.value.map(h=>h.value),isShippingRequired:!!s.fields.isShippingRequired.value,violations:s.fields.allViolations.value,receipt:e.latestReceipt.value}}function ci(e,t,n){const i=e.latestReceipt.value;if(i?.status==="processed")return i.purchaseOrder.billingAddress;if(!(i?.status==="processing"||i?.status==="processing_remote_checkouts"||i?.status==="polling_for_order"))return n==="proposed"?li(e,t):e.proposal.negotiated.fields.billingAddress.value}function li(e,t){const{proposed:n,negotiated:i,facts:o}=e.proposal,r=n.paymentLines.value;for(const{method:c}of r)if(c.type===Z.CreditCard||c.type===Z.PayPal)return c.billingAddress;const s=n.billingAddress.value,a=!s.address1&&o.billingAddress?o.billingAddress:s;if(n.billingAddressOption.value!=="shipping"||!i.fields.isShippingRequired.value||!Mt(r))return a;const d=r[0]?.method;if(d?.type==="wallet"){const c=i.fields.runningTotal.value,l=c&&c.amount<=0,u=Ot(i.fields.merchandiseLines.value?.lines).some(h=>!!h.sellingPlan?.subscriptionDetails);if((!l||u||i.fields.deferredTotal.value?.amount.amount)&&(d.name==="GOOGLE_PAY"||d.name==="APPLE_PAY"||d.name==="PAYPAL_EXPRESS"&&Rt({checkout:e,shop:t,paymentMethods:i.fields.paymentMethods.value})))return a}return o.delivery?.[0]?.deliveryAddress??n.shippingAddress.value}function ui(e){return e?.status==="available_total"?e.totalTax:void 0}function pi(e){return e?.status==="available_total"?e.totalDuty:void 0}const Me="store_credit",hi=1e4;function fi(e){const t=(i,o)=>{if(i.hasGiftCard.value)return"cannot change while the cart contains a gift card";if(i.hasFixedSellingPlan.value)return"cannot change while the cart contains a fixed-date subscription";if(i.settling.value)return"is still updating from a previous change; retry shortly";if(o&&i.paymentDue.value?.amount===0&&!i.applied.value)return"cannot be applied when nothing is left to pay"},n=i=>{if(!i.settling.peek())return Promise.resolve();let o=()=>{},r;return new Promise(s=>{r=setTimeout(s,hi),o=Xe(()=>{i.settling.value||s()})}).then(()=>{clearTimeout(r),o()})};return{key:Me,read(){const i=e();if(i?.available.value)return{key:Me,purpose:"dev.shopify.shopping.declared_fields.generic",title:"Store credit",description:"Apply the buyer's available store credit balance to this checkout. Send true to apply and false to remove; omitting the field or sending null keeps the current choice. Removing it also stops store credit from covering subscription renewals.",value_schema:{type:"boolean"},value:i.redeeming.value,required:!1}},prepare(i){if(i!==null&&typeof i!="boolean")return{requirement:"must be a boolean or null"};const o=i??void 0,r=e();if(!r)return{requirement:"is no longer offered on this checkout"};if(o!==void 0&&o!==r.redeeming.value){const s=t(r,o);if(s)return{requirement:s}}return{phase:"negotiate",get changed(){if(o===void 0)return!1;const s=e();return s?o!==s.redeeming.value?!0:s.settling.value:!1},async apply(){if(o===void 0)return!1;const s=e();return!s||(await n(s),e()!==s||!s.available.value||t(s,o)!==void 0)?!1:(await s.setRedeeming(o),s.applied.peek()===o)}}}}}const Oe="tax_number",mi=["TAX_CREDENTIAL_BR","SHIPPING_CREDENTIAL_BR","TAX_CREDENTIAL_CL","SHIPPING_CREDENTIAL_CL","SHIPPING_CREDENTIAL_CN","TAX_CREDENTIAL_CO","SHIPPING_CREDENTIAL_CO","TAX_CREDENTIAL_CR","SHIPPING_CREDENTIAL_CR","TAX_CREDENTIAL_EC","SHIPPING_CREDENTIAL_EC","TAX_CREDENTIAL_ES","SHIPPING_CREDENTIAL_ES","TAX_CREDENTIAL_GT","SHIPPING_CREDENTIAL_GT","TAX_CREDENTIAL_ID","SHIPPING_CREDENTIAL_ID","TAX_CREDENTIAL_IT","SHIPPING_CREDENTIAL_KR","TAX_CREDENTIAL_MX","SHIPPING_CREDENTIAL_MX","TAX_CREDENTIAL_MY","SHIPPING_CREDENTIAL_MY","TAX_CREDENTIAL_PE","SHIPPING_CREDENTIAL_PE","TAX_CREDENTIAL_PT","SHIPPING_CREDENTIAL_PT","TAX_CREDENTIAL_PY","SHIPPING_CREDENTIAL_PY","TAX_CREDENTIAL_TR","SHIPPING_CREDENTIAL_TR","SHIPPING_CREDENTIAL_TW"];function yi(e){const t={key:Oe,read(){const n=Re(e);if(!n)return;const{title:i,value:o,required:r}=n.fields;return{key:Oe,purpose:"dev.shopify.shopping.declared_fields.generic",title:i.value,description:`Enter the buyer's ${i.value} tax number for this checkout.`,value_schema:{type:"string"},value:o.value||null,required:r.value??!1}}
1,prepare(n){return n!==null&&typeof n!="string"?{requirement:"must be a string or null"}:{phase:"stage",get changed(){return n!==t.read()?.value},negotiation:{include:["localizationExtensions"],loading:[],fieldsToResolve:["localizationExtensions"]},async apply(){const i=Re(e);if(!i)return!1;const{value:o}=i.fields;return o.value=n??"",!0}}}};return t}function Re(e){const n=e.proposal.proposed.localizationExtensions.value.flatMap(i=>mi.some(r=>r===i.fields.key.value)?[i]:[]);return n.length===1?n[0]:void 0}function Te(e,t){const n=new Map(t.flatMap(({targetMerchandiseLines:o})=>o.map(r=>[r.stableId,r]))),i=new Set;for(const o of e){const r=(o.lineComponents?.length?o.lineComponents:[o]).filter(s=>s.requiresShipping??n.get(s.stableId)?.requiresShipping);for(const{stableId:s}of r)i.add(s);r.length&&o.lineComponents?.length&&i.add(o.stableId)}return i}function pe(e,t){return[...new Set(e.filter(({targetMerchandiseLines:n})=>n.some(({stableId:i})=>t.has(i))).flatMap(({deliveryMethodTypes:n})=>n).filter(n=>n!=="NONE"))]}function _i(e,{proposed:t}){return{getAvailableMethodTypes:()=>e.getAvailableMethodTypes().filter(n=>!n.includes("PICKUP_POINT")),setDesiredMethod(n,i){const o=e.getSelectedMethodTypes();e.markBuyerSelection();const r=t.deliveryLines.value.map(a=>a.value),s=Te(t.merchandiseLines.value,r);if(!gi(o,n)){e.applyMethodChange(n,o,i);return}F(()=>{for(const a of t.deliveryLines.value){const d=a.value;d.targetMerchandiseLines.some(({stableId:c})=>s.has(c))&&(d.deliveryMethodTypes.length!==n.length||d.deliveryMethodTypes.some(c=>!n.includes(c)))&&(a.value={...d,deliveryMethodTypes:n})}if(e.reconcileSameMethod(n),i){if(i!==t.locationAddress.value)for(const a of t.deliveryLines.value)a.value={...a.value,deliveryMethodHandle:void 0};t.locationAddress.value=i}})}}}function gi(e,t){return e.length>0&&e.every(n=>n==="SHIPPING"||n==="LOCAL"?t.includes("SHIPPING")||t.includes("LOCAL"):t.includes(n))}function vi(e,t=[]){const n={};for(const i of t)i.name&&(n[i.name]??=[]).push(i);return{version:"2026-08-25",status:e,services:{"dev.ucp.shopping":[{version:"2026-08-25",transport:"webmcp"}]},capabilities:{"dev.ucp.shopping.checkout":[{version:"2026-08-25",spec:"https://ucp.dev/2026-08-25/specification/shopping/checkout/",schema:"https://ucp.dev/2026-08-25/schemas/shopping/checkout.json"}],"dev.ucp.shopping.fulfillment":[{version:"2026-08-25",spec:"https://ucp.dev/2026-08-25/specification/shopping/extensions/fulfillment/",schema:"https://ucp.dev/2026-08-25/schemas/shopping/fulfillment.json",extends:["dev.ucp.shopping.checkout"],requires:{protocol:{min:"2026-08-25"}}}],"dev.ucp.shopping.discount":[{version:"2026-08-25",extends:"dev.ucp.shopping.checkout",spec:"https://ucp.dev/2026-08-25/specification/discount",schema:"https://ucp.dev/2026-08-25/schemas/shopping/discount.json"}],"dev.shopify.shopping.declared_fields":[{version:"2026-09-04",extends:"dev.ucp.shopping.checkout",spec:"https://shopify.dev/ucp/specification/declared-fields",schema:"https://shopify.dev/ucp/schemas/2026-09-04/declared_fields.json",requires:{protocol:{min:"2026-04-08"}}}]},payment_handlers:n}}function V(e,t){return{...e,ucp:vi("error"in e?"error":"success",t.proposal.negotiated.fields.ucp.value?.paymentHandlers)}}function bi({checkout:e,shopPay:t}){const n=Qt({identity:e.identity,shopPay:t,negotiatedFields:e.proposal.negotiated.fields},{isApplePayAvailable:t.user.isApplePayAvailable}),i=e.proposal.negotiated.fields.paymentMethods,o=t.session.isInstallmentsSelected,r=e.installments.paymentMethodMustSupportInterestBearingLoans;return()=>{if(e.identity.current.value!=="shopPay"||t.session.isLoading.value)return;const s=t.user.paymentMethods.value.filter(Ut).filter(({id:l})=>l!==xt).sort(qt),a=Ht(s,n.value),d=t.session.selectedPaymentMethod.value,c=e.proposal.proposed.paymentLines.value.some(({method:l})=>l.type==="wallet"&&l.name==="SHOP_PAY");return s.map(l=>{const u=l.paymentAttributes;return{instrument:{id:l.id,type:"card",selected:c&&d?.paymentMethod==="CREDIT_CARD"&&d.id===l.id,display:{brand:u.brand,last_digits:u.lastDigits}},usable:!u.expired&&u.verified&&a.includes(l)&&!Jt(u,i,o,r)}})}}function Ue(e){return e?.replace(/[\s-]/g,"").toUpperCase()}function Ai(e,t){return!!e?.coordinates&&e?.countryCode===t.countryCode&&(!t.zoneCode||e.zoneCode===t.zoneCode)&&Ue(e.postalCode)===Ue(t.postalCode)}function re(e,{checkout:t},n){const i=e.fulfillmentMethods.methods;if(i.length>1)return M("At most one fulfillment method is supported.");const o=i[0];if(o?.id!==void 0&&o.id!==o.type)return M("Method id must match its shipping or pickup type; omit id when requesting a new method.");const{proposed:r,negotiated:s}=t.proposal,a=r.deliveryLines.value.map(m=>m.value),d=Te(r.merchandiseLines.value,a),c=pe(a,d);if(c.some(O)&&c.some(se)){const m=s.fields.deliveryNext.value,v=m?.status==="filled"||m?.status==="partial"?m.lines.filter(b=>b.status==="available"):[],S=a.map(b=>{const I=(v.find(({id:L})=>!!b.id&&L===b.id)??v.find(L=>
1Y(L.targetMerchandiseLines,b.targetMerchandiseLines.filter(P=>P.requiresShipping).map(T))))?.methods.find(({handle:L,methodType:P})=>L===b.deliveryMethodHandle&&b.deliveryMethodTypes.includes(P))?.methodType??(b.deliveryMethodHandle?void 0:b.deliveryMethodTypes[0]);return I?{...b,deliveryMethodTypes:[I]}:b}),w=pe(S,d);if(w.some(O)&&w.some(se))return M("Updates to checkouts with both shipping and pickup are not supported. Ask the buyer to continue in checkout.")}if(!i.length&&!e.context)return;const l=o?.type??(c.length&&c.every(O)?"pickup":void 0),u=!!(e.context&&!he(r.locationAddress.value,e.context));if(u&&l!=="pickup")return M("Changing context locality requires a pickup method.");if(!o&&l!=="pickup")return;const p=m=>l==="pickup"?O(m):se(m);if(o&&(o.selected_destination_id!==void 0||o.groups.length))return u||c.length&&!c.some(p)?M("Change the method/search origin first, then select a destination or option returned by that update."):void 0;if(l==="pickup"&&c.length&&c.every(m=>m==="PICKUP_POINT"))return u?M("Pickup-point locality discovery is not supported. Select an existing destination instead."):void 0;if(!d.size)return M("This checkout has no physical items to fulfill.");if(l==="pickup"&&e.context){const m=r.shippingAddress.value?.countryCode||r.locationAddress.value?.countryCode;if(!m)return M("Pickup search requires an established checkout country. Ask the buyer to choose a country in checkout.");if(e.context.address_country!==m)return M("Pickup search must remain in the checkout country.")}if(!n&&!u&&c.every(p)&&c.length)return;const h=!c.length||!c.every(p);if(!n&&h)return M("The delivery selector is not ready.");const _=n?n.getAvailableMethodTypes().find(m=>l==="pickup"?m.includes("PICK_UP"):m.some(p)):c;if(!_)return M(`The checkout does not offer ${l}.`);const g=s.fields;return(h||u)&&(g.mustSelectProvidedShippingRate.value||g.mustSelectProvidedAddress.value||g.canUpdateDeliveryAddress.value===!1)?M("The checkout locks its delivery method or address."):{methodTypes:_,needsLocalityLookup:u,changesMode:h}}function se(e){return e==="SHIPPING"||e==="LOCAL"}function he(e,t){return Ai(e,{countryCode:t.address_country,zoneCode:t.address_region,postalCode:t.postal_code})}function M(e){return{error:{code:"rejected",message:`fulfillment: ${e} Nothing was applied. Call get_checkout before retrying.`}}}const J="Unable to confirm the checkout update. Call get_checkout to review the checkout and its messages. Do not retry if the requested change is already present. Otherwise, build a complete replacement from the latest checkout, change only the requested values, and resend all other buyer, fulfillment, discount-code, and declared-field values to retain them. Do not attempt to update the checkout by interacting with the page.",xe="Nothing was applied. Group and option ids come from the latest get_checkout and change when the destination or fulfillment method changes. Use ids from the latest get_checkout. If this request also changes the destination, send it without groups, then choose an option from the next get_checkout. Do not attempt to update the checkout by interacting with the page.",H={status:"written"};function Ci(e){return e.paymentLines.value.some(t=>t.method.type===Z.CreditCard||t.method.type===Z.PayPal||Ii(t))}function Ii(e){if(e.method.type!=="wallet")return!1;switch(e.method.name){case"APPLE_PAY":return Vt(e);case"GOOGLE_PAY":return Wt(e);case"PAYPAL_EXPRESS":return Yt(e);default:return!1}}const Ti=({buyer:e},{checkout:t,shopPay:n})=>{const i=Zt({identity:t.identity,proposal:t.proposal,shopPay:n});if(i&&t.identity.current.value==="shopPay")return;const{proposed:o}=t.proposal;return{status:"ready",negotiation:{include:["contactInfo"],loading:["contactInfo"],fieldsToResolve:["contactInfo"]},async apply(){return i||(o.email.value=e.email),o.phone.value=e.phone_number,H}}},dt=({shippingAddress:e},t)=>{if("saved_address_id"in e)return Si(e.saved_address_id,t);const{checkout:n,observability:i,clearShippingAddressErrors:o}=t,r=n.addressManager.shipping.value;if(r.applyAddressChangeBlockReason("ucp").value)return;const a=pt(e.address_country,"fulfillment.methods[0].destinations[0].address_country",t.shop);if(a)return a;const d=ee(e,n.address);return{status:"ready",negotiation:{include:["shippingAddress","deliveryNext"],loading:["deliveryNext"],fieldsToResolve:["shippingAddress","deliveryNext"]},async apply(){const c=await r.applyAddressChange({source:"ucp",address:d});return c.type!=="success"?(i.log("web_mcp_address_change_declined","[WebMcp] address manager declined an admitted address",{reason:c.reason}),{status:"failed"}):(o(),H)}}};function qe(e,{readSavedCards:t,getSavedCardSelector:n}){return t()?.find(({instrument:o})=>o.id===e)?.usable?{status:"ready",negotiation:{include:["paymentLines","billingAddress"],loading:["paymentLines"],fieldsToResolve:["paymentLines"]},async apply(){const o=n?.();return o&&await o(e)?H:{status:"failed"}}}:{status:"rejected",field:"payment"}}function Ei(e,{readSavedCards:t}){return!!t()?.some(({instrument:n,usable:i})=>n.id===e&&n.selected&&i)}function Si(e,t){const{checkout:n,clearShippingAddressErrors:i}=t;if(n.identity.current.value!=="shopPay")return{status:"rejected",field:"shippingAddress"};const o=n.addressManager.shipping.value,r=[...o.addresses.value,...o.immutableAddresses.value].find(d=>d.id===e);if(!r||r.disabled)return{status:"rejected",field:"shippingAddress"};const s=o.applyAddressChangeBlockReason("ucp").value;if(s&&s!=="MUST_SELECT_PROVIDED_ADDRESS")return;const a=pt(r.address.countryCode,"fulfillment.methods[0].selected_destination_id",t.shop);return a||{status:"ready",negotiation:{include:["shippingAddress","deliveryNext"],loading:["deliveryNext"],fieldsToResolve:["shippingAddress","deliveryNext"]},async apply(){return await o.selectAddress(e)?(i(),H):{status:"failed"}}}}function fe({fulfillmentMethods:e},{checkout:t},n=!1){const{proposed:i,negotiated:o}=t.proposal,r=o.fields.deliveryNext.peek(),s=r?.status==="filled"||r?.status==="partial"?r.lines.filter(Fi):[],a=new Map;for(const c of i.deliveryLines.peek()){const{id:l,targetMerchandiseLines:u,deliveryMethodTypes:p,deliveryMethodHandle:h}=c.peek();if(p.filter(K).length===0)continue;const m=(s.find(v=>!!l&&v.id===l)??s.find(v=>Y(v.targetMerchandiseLines,u.filter(S=>S.requiresShipping).map(T))))?.methods.find(v=>v.handle===h);if(m){if(!K(m.methodType))continue}else if(Cn(h,p,m))return{status:"rejected",field:"fulfillmentMethods"};a.set(c,{deliveryLine:c,selectedOptionId:void 0,selectedOptionDetail
1s:void 0})}try{for(const c of Ui(e,i.deliveryLines.peek(),s))a.set(c.deliveryLine,c)}catch(c){if(!(c instanceof R))throw c;return{status:"rejected",field:"fulfillmentMethods",reason:c.reason}}const d=o.fields.mustSelectProvidedShippingRate.peek();return[...a.values()].some(({deliveryLine:c,selectedOptionId:l})=>!In(c.peek().deliveryMethodHandle,l,d))?{status:"rejected",field:"fulfillmentMethods"}:{status:"ready",negotiation:{include:["deliveryNext"],loading:["deliveryNext"],fieldsToResolve:["deliveryNext"]},async apply(){for(const c of i.deliveryLines.value){const l=a.get(c);if(!l&&(!n||!c.value.deliveryMethodTypes.some(K)))continue;const{selectedOptionId:u,selectedOptionDetails:p}=l??{};c.value={...c.peek(),deliveryMethodHandle:u,deliveryMethodOptions:Hi(p),...u===void 0&&{isCustomRate:void 0,customDeliveryStrategy:void 0}}}return H}}}const wi=({discountCodes:e=[]},t)=>{const{checkout:n,source:i}=t,{proposed:o,negotiated:r}=n.proposal,s=new Map,a=[];for(const d of o.discountLines.value){const{discount:c}=d;if(c.type==="code"||c.type==="discountCodeTrigger"){const l=c.title.toUpperCase(),u=s.get(l);u?u.push(d):s.set(l,[d])}else a.push(d)}if(r.fields.canUpdateDiscountCodes.value===!1||i.type==="orderEdit"||i.type==="paymentCollection"){const d=new Set(e.map(l=>l.toUpperCase()));return d.size===s.size&&[...d].every(l=>s.has(l))?void 0:{status:"rejected",field:"discountCodes"}}return{status:"ready",negotiation:{include:["discountLines","deliveryNext"],loading:["discountLines","deliveryNext"],fieldsToResolve:["discountLines","totalSavings","merchandiseLines","deliveryNext"]},async apply(){const d=new Set;for(const c of e){const l=c.toUpperCase();if(d.has(l))continue;d.add(l);const u=s.get(l);u?a.push(...u):a.push({title:c,discount:{type:"discountCodeTrigger",title:c}})}return F(()=>{o.discountLines.value=a,o.reduction.value=void 0;const{discountCodeWarningSignal:c,currentDiscountCodeAttemptSignal:l}=t.negotiator.context;c.value=null,l.value=null}),H}}},ki=[Ti,wi,dt,fe];function He(e,t,{fulfillmentRequest:n,fulfillment:i,locationAddress:o}={}){const r=[];for(const s of ki){if(s===dt&&n){const{methodTypes:d}=n,{proposed:c}=t.checkout.proposal;r.push({status:"ready",negotiation:{include:["deliveryNext"],loading:["deliveryNext"],fieldsToResolve:["deliveryNext"]},async apply(){return i?i.setDesiredMethod(d,o):o&&(c.locationAddress.value=o),H}})}const a=s===fe?fe(e,t,n!==void 0):s(e,t);if(a!==void 0){if(a.status==="rejected")return lt(a.field,a.reason);r.push(a)}}return r}class ct{#e;constructor(t){this.#e=t}writePayment({payment:t,billingAddress:n=t?.billing_address,applyBilling:i=!0}){const o=i?this.#t(n):void 0,r=this.#n(t);return r&&"error"in r?r:(F(()=>{r?.apply(),o?.apply()}),{status:"applied"})}#t(t){const{checkout:n}=this.#e;if(!U(n))return;const i=t===void 0?void 0:ee(t,n.address);return{apply({replacement:o=!1}={}){if(!U(n))return!1;const{proposed:r,negotiated:s,facts:a}=n.proposal,d=s.fields.isShippingRequired.value===!1;if(i&&!Ft(i)&&(d||!Oi(i,n)))return F(()=>{r.billingAddress.value=i,r.billingAddressOption.value="custom"}),!0;if(o&&d)return a.billingAddress||Ci(r)?!1:(F(()=>{r.billingAddress.value=ee({address_country:r.billingAddress.value.countryCode},n.address),r.billingAddressOption.value="custom"}),!0);const c=r.billingAddressOption.value;return r.billingAddressOption.value="shipping",i!==void 0||c!=="shipping"}}}#n(t){const{checkout:n,shop:i,paymentInstrument:o}=this.#e;if(!U(n)||!t&&!o.value)return;const{proposed:r,negotiated:s}=n.proposal,a=s.fields.paymentMethods.value,d=r.paymentLines.value.find(l=>!l.due&&l.method.type==="direct"),c=jt(a??[],d?.method.type==="direct"&&!!d.method.alternative);return t&&(t.handler_id==="shopify.card"?!c:!i.hasFlagEnabled($t)||!Bt(a))?Ni():{apply(){U(n)&&F(()=>{const l=o.value;if(l?.handler_id==="shop_pay"&&l.credential?.approval_id&&(r.paymentLines.value=r.paymentLines.value.map(u=>u.method.type==="shopWallet"&&u.method.shopPayApprovalId===l.credential?.approval_id?{...u,method:{...u.method,shopPayApprovalId:void 0}}:u)),o.value=t,!!t){t.handler_id==="shopify.card"&&t.credential?.token&&c?(d?.method.type!=="direct"||d.method.paymentMethodIdentifier!==c.paymentMethodIdentifier)&&(r.paymentLines.value=we(r.paymentLines.value,{method:{type:"direct",paymentMethodIdentifier:c.paymentMethodIdentifier,alternative:c.alternative}},ke(i))):t.handler_id==="shop_pay"&&t.credential?.approval_id&&(r.paymentLines.value=we(r.paymentLines.value,{method:{type:"shopWallet",shopPayApprovalId:t.credential.approval_id}},ke(i)));for(const u of Object.values(r.directPaymentErrors))u.value=void 0;r.generalPaymentError.value=void 0,r.generalPaymentErrorCode.value=void 0}})}}}async applyUpdate(t,{isExpired:n}={}){const{shippingAddress:i}=t,o=t.payment&&"billing_address"in t.payment?t.payment.billing_address:void 0;if(await this.loadAddressMetadata(["saved_address_id"in i?void 0:i,U(this.#e.checkout)?o:void 0]),n?.())return C();if(this.#e.isSubmitting.value)return B();const r=t.payment&&"instrument_id"in t.payment?t.payment.instrument_id:void 0;if(r!==void 0&&(await this.#e.waitForPendingNegotiations(),n?.()))return C();let s=z(t.declaredFields,this.#e.declaredFields);if("error"in s)return s;if(s.some(({changed:f})=>f)){if(await this.#e.waitForPendingNegotiations(),n?.())return C();if(this.#e.isSubmitting.value)return B();if(s=z(t.declaredFields,this.#e.declaredFields),"error"in s)return s}let a=this.#e.getFulfillmentController?.(),d=re(t,this.#e,a);if(d&&"error"in d)return d;let c;if(d?.needsLocalityLookup&&t.context){try{const f=this.#e.resolvePickupLocality;if(!f)throw new ae;c=await f(t.context)}catch(f){return this.#e.observability.error(f instanceof ae?f:new ae(f)),n?.()?C():{error:{code:"update_failed",message:"context: Pickup locality lookup is unavailable. Nothing was applied. Call get_checkout and retry with the latest checkout. Do not attempt to update the checkout by interacting with the page."}}}if(n?.())return C();if(!c)return{error:{code:"rejected",message:"context: Could not resolve a unique postal locality. Nothing was applied. Check address_country, address_regi
1on and postal_code, then retry."}};if(s=z(t.declaredFields,this.#e.declaredFields),"error"in s)return s}if(t.context){const f=this.#e.checkout.proposal.proposed.locationAddress.value;he(f,t.context)&&(c=f)}if(a=this.#e.getFulfillmentController?.(),d=re(t,this.#e,a),d&&"error"in d)return d;let l=this.#t(o);const u=t.payment&&"handler_id"in t.payment?t.payment:void 0;let p=this.#n(u);if(p&&"error"in p)return p;let h=r===void 0?void 0:qe(r,this.#e);if(h?.status==="rejected")return lt(h.field);let _=He(t,this.#e,{fulfillmentRequest:d,fulfillment:a,locationAddress:c});if("error"in _)return _;if(n?.())return C();const g=[];let m=!1;for(const f of["negotiate","stage"]){if(f==="stage"&&m&&(s=z(t.declaredFields,this.#e.declaredFields),"error"in s))return C();for(const I of s)if(!(I.phase!==f||!I.changed)){if(n?.())return C();try{if(!await I.apply()||n?.())return C()}catch{return C()}if(I.phase==="stage")g.push(I.negotiation);else if(m=!0,a=this.#e.getFulfillmentController?.(),d=re(t,this.#e,a),d&&"error"in d||(_=He(t,this.#e,{fulfillmentRequest:d,fulfillment:a,locationAddress:c}),"error"in _)||(l=this.#t(o),p=this.#n(u),p&&"error"in p)||(h=r===void 0?void 0:qe(r,this.#e),h?.status==="rejected"))return C()}}if(p){const f=p;_.push({status:"ready",negotiation:{include:["paymentLines"],loading:["paymentLines"],fieldsToResolve:["paymentLines"]},async apply(){return f.apply(),H}})}if(!h&&_.length===0&&g.length===0&&!l)return{status:"applied"};if(n?.())return C();if(this.#e.isSubmitting.value)return B();if((await Promise.all(F(()=>_.map(f=>f.apply())))).find(f=>f.status==="failed")||n?.())return C();if(this.#e.isSubmitting.value)return B();if(h){if((await h.apply()).status==="failed"||n?.()||(await this.#e.waitForPendingNegotiations(),n?.()))return C();if(this.#e.isSubmitting.value)return B()}const w=l?.apply({replacement:!0})??!1;if(!h&&_.length===0&&g.length===0&&!w)return{status:"applied"};const b=await this.#i(Li([..._.map(f=>f.negotiation),...g,...h?[h.negotiation]:[],...w?[{include:["billingAddress"],loading:["billingAddress"],fieldsToResolve:["billingAddress"]}]:[]]));await this.#e.waitForPendingNegotiations();const A=Pi(b);if(r!==void 0&&!Ei(r,this.#e))return C();if(!("error"in A)&&!n?.()&&d?.needsLocalityLookup&&c&&t.context&&he(this.#e.checkout.proposal.proposed.locationAddress.value,t.context)){const{proposed:f}=this.#e.checkout.proposal,I=f.deliveryLines.value.map(j=>j.value),L=Te(f.merchandiseLines.value,I),P=pe(I,L);P.length&&P.every(O)&&this.#e.announcePickupLocality?.(c)}return n?.()?C():A}async loadAddressMetadata(t){const n=new Set;for(const o of t){const r=o?.address_country?.toUpperCase();o&&r&&Di(r,o)&&n.add(r)}const{countryDetails:i}=this.#e.checkout.address;for(const o of n){const r=i.get(o);(!r||r.isFallback)&&await i.fetch(o)}}async#i(t){let n;return await this.#e.journey.negotiate({...t,runListenersOnError:t.include.includes("shippingAddress")||t.include.includes("discountLines"),onComplete:i=>{n=i}}),n}}class ae extends Error{constructor(t){super("WebMCP pickup locality lookup failed",{cause:t}),this.name="WebMcpLocalityLookupError"}}function Di(e,t){const n=!!(t.street_address||t.street_name||t.street_number),i=!!(t.extended_address||t.district),o=ve(e,"")!==null,r=be(e,"")!==null;return n&&o||i&&r}function Li(e){return{include:de(e,"include"),loading:de(e,"loading"),fieldsToResolve:de(e,"fieldsToResolve")}}function de(e,t){return[...new Set(e.flatMap(n=>n[t]))]}function Pi(e){return e?.status==="success"||e?.status==="error"?{status:"applied"}:C()}function B(){return{error:{code:"completion_in_progress",message:"A credentialed completion is in progress. Wait for it to finish before updating payment."}}}function Ni(){return{error:{code:"invalid_request",message:"This checkout does not accept the supplied payment handler. Call get_checkout for the current checkout state."}}}function C(){return{error:{code:"update_failed",message:J}}}const Mi={context:"context",buyer:"buyer",discountCodes:"discounts",declaredFields:"declared_fields",shippingAddress:"fulfillment",fulfillmentMethods:"fulfillment",payment:"payment"};function Oi(e,t){const n=Ce(t.proposal.proposed.shippingAddress.value,t.address);return Gt(e,ee(n,t.address))}function lt(e,t){if(t instanceof ut){const n=t.listedCountryCodes?` Supported countries: ${t.listedCountryCodes.join(", ")}.`:"";return{error:{code:"rejected",message:`${t.path} ${t.countryCode}
1 is not a country this shop ships to. Nothing was applied.${n} Tell the buyer. Do not attempt to update the checkout by interacting with the page.`}}}if(t==="unsupported_option_instructions"||t==="unsupported_option_phone"){const n=t==="unsupported_option_instructions"?"instructions":"phone_number";return{error:{code:"rejected",message:`The selected delivery option does not support selected_option_details.${n}. Nothing was applied. Remove ${n} from selected_option_details or choose an option that supports it, then retry. Do not attempt to update the checkout by interacting with the page.`}}}return t==="unknown_fulfillment_group"?{error:{code:"rejected",message:`fulfillment.methods[].groups[] does not match a delivery group in the current checkout. ${xe}`}}:t==="unselectable_fulfillment_group"?{error:{code:"rejected",message:"fulfillment.methods[].groups[] has no selectable delivery option in the current checkout. Nothing was applied. Send the update without groups, then choose an option from the next get_checkout. Do not attempt to update the checkout by interacting with the page."}}:t==="unknown_fulfillment_option"?{error:{code:"rejected",message:`fulfillment.methods[].groups[].selected_option_id is not an option for this group in the current checkout. ${xe}`}}:{error:{code:"update_failed",message:`Unable to update ${Mi[e]}. Call get_checkout to review the checkout and its messages before retrying. Do not attempt to update the checkout by interacting with the page.`}}}class R extends Error{constructor(t){super(t),this.name="WebMcpFulfillmentMethodUpdateError",this.reason=t}}const Ri=20;class ut extends Error{constructor(t,n,i){super(`${t} is not a shipping country`),this.name="UnsupportedShippingCountryError",this.countryCode=t,this.path=n,this.listedCountryCodes=i}}function pt(e,t,{shippingCountries:n}){const i=e?.trim().toUpperCase();if(!(!i||n.length===0)&&!n.some(({value:o})=>o===i))return{status:"rejected",field:"shippingAddress",reason:new ut(i,t,n.length<=Ri?n.map(({value:o})=>o):void 0)}}function Ui(e,t,n){return e.methods.flatMap(i=>i.type==="pickup"?xi(i,t,n):i.groups.map(o=>{const r=ht(o,n,o.id&&t.some(({value:a})=>a.id===o.id)?"unselectable_fulfillment_group":"unknown_fulfillment_group"),s=r.methods.find(({handle:a,methodType:d})=>a===o.selected_option_id&&(d==="SHIPPING"||d==="LOCAL"));if(!s||W(r)!=="shipping")throw new R("unknown_fulfillment_option");return me(r,s,o.selected_option_details,t)}))}function xi(e,t,n){const i=e.selected_destination_id===void 0?void 0:ot(n).find(({id:r})=>r===e.selected_destination_id);if(e.selected_destination_id!==void 0&&!i)throw new R("unknown_pickup_destination");const o=new Map;for(const r of e.groups){if(r.selected_option_id!==ue)throw new R("unknown_fulfillment_option");const s=ht(r,n);if(W(s)!=="pickup"||i&&!i.selections.some(a=>a.line===s)||o.has(s))throw new R("unknown_fulfillment_group");o.set(s,r)}return i?i.selections.map(({line:r,method:s})=>me(r,s,o.get(r)?.selected_option_details,t)):[...o].map(([r,s])=>{const a=r.methods.find(d=>d.handle===r.selectedDeliveryMethodHandle&&O(d.methodType)&&d.pickupLocation);if(!a)throw new R("unknown_pickup_destination");return me(r,a,s.selected_option_details,t)})}function ht(e,t,n="unknown_fulfillment_group"){const i=t.find(o=>!!e.id&&o.id===e.id)??t.find(o=>Y(o.targetMerchandiseLines,e.line_item_ids));if(!i)throw new R(n);return i}function me(e,t,n,i){const o=i.find(r=>!!e.id&&r.value.id===e.id)??i.find(r=>Y(r.value.targetMerchandiseLines,e.targetMerchandiseLines?.filter(s=>s.requiresShipping).map(T)));if(!o)throw new R("unknown_fulfillment_group");if(!o.value.deliveryMethodTypes.includes(t.methodType))throw new R("unsupported_fulfillment_transition");return qi(t,n),{deliveryLine:o,selectedOptionId:t.handle,selectedOptionDetails:n}}function qi(e,t){if(t){if(t.instructions!==void 0&&!te(e,"instructions"))throw new R("unsupported_option_instructions");
1if(t.phone_number!==void 0&&!te(e,"phone_number"))throw new R("unsupported_option_phone")}}function Hi(e){return{phone:e?.phone_number,instructions:e?.instructions}}function Fi(e){return e.status==="available"}const Fe=Et()(["shipping","pickup"]);class y extends Error{constructor(t,n,i){super(`${t}: expected ${n}, got ${i} instead.`),this.name="UpdateCheckoutInputError"}}const ft='Give the street either as street_address (e.g. "123 Yonge St") or as street_name plus street_number (e.g. "Yonge St" and "123"). Partial addresses are accepted; checkout reports missing or invalid address information in messages.',mt={id:{type:"string"},street_address:{type:"string",description:'First address line, typically the street address or PO Box number, e.g. "123 Yonge St". Ignored when street_name is nonempty.'},street_name:{type:"string",description:'Street name without the house or building number, e.g. "Yonge St". When nonempty, street_name and street_number replace street_address.'},street_number:{type:"string",description:'House or building number, e.g. "123". Used only with a nonempty street_name.'},extended_address:{type:"string",description:"Apartment, suite, unit, or other address complement."},district:{type:"string",description:"A regional or city subdivision, such as a neighborhood, district, or block. An empty string clears it. Ignored when the address country has no district field."},address_locality:{type:"string",description:"The city, town, or village used as the locality in the address country."},address_region:{type:"string",description:'State/province/region code (e.g. "ON", "NY") or full name; required for some countries. get_checkout returns the code.'},address_country:{type:"string",description:'ISO 3166-1 alpha-2 country code, e.g. "CA", "US". Not a country name.'},postal_code:{type:"string",description:'Postal or ZIP code in the address country format, e.g. "K1A 0B1", "94103". Case and spacing are normalized.'},company:{type:"string"},first_name:{type:"string"},last_name:{type:"string"},phone_number:{type:"string",description:"Contact phone: address-country national format or E.164 (e.g. +16135550123)."}},ji={type:"object",description:`Replacement address. Include all fields to retain; omitted fields are cleared. Use PUT semantics, not PATCH. ${ft}`,properties:mt},Q={type:"object",properties:{instruments:{type:"array",maxItems:1,items:{type:"object",properties:{handler_id:{type:"string",enum:["shopify.card","shop_pay"]},credential:{type:"object"},id:{type:"string"},type:{type:"string",enum:["card","shop_pay"]},selected:{type:"boolean"},billing_address:ji}}}}};function $i(e,{ignorePayment:t=!1}={}){const n=D(e,"input");return _e({object:n,allowedFields:["payment"],path:"input"}),t||n.payment===void 0?{}:{payment:yt(n.payment,{path:"input.payment",requireCredential:!0})}}function yt(e,{path:t,requireCredential:n=!1,savedPaymentMethodsOnly:i=!1}){const o=D(e,t);if(!n&&(o.instruments===void 0||Array.isArray(o.instruments)&&o.instruments.length===0))return;const r=`${t}.instruments[0]`,s=oo(o.instruments,`${t}.instruments`);if(!n&&i)return Xi(s,r);const a=s.handler_id;if(!n&&a===void 0&&s.credential===void 0){const _=je(s,r);return _===void 0?void 0:{billing_address:_}}if(a!=="shopify.card"&&a!=="shop_pay")throw new y(`${r}.handler_id`,"shopify.card or shop_pay","an unsupported handler");const d=q(s,{id:void 0,type:void 0},r),c=a==="shopify.card"?"card":"shop_pay";if(d.type!==void 0&&d.type!==c)throw new y(`${r}.type`,c,"an unsupported instrument type");const l=je(s,r),u={id:d.id??zt(),...l===void 0?{}:{billing_address:l}},p=`${r}.credential`,h=!n&&s.credential===void 0?void 0:D(s.credential,p);if(a==="shopify.card"){if(h===void 0)return{...u,handler_id:a,type:"card"};if(_e({object:h,allowedFields:["type","token"],path:p}),h.type!==void 0&&h.type!=="shopify_token")throw new y(`${p}.type`,"shopify_token","an unsupported credential type");return{...u,handler_id:a,type:"card",credential:{type:"shopify_token",...n||h.token!==void 0?{token:ye(h.token,`${p}.token`)}:{}}}}if(h===void 0)return{...u,handler_id:a,type:"shop_pay"};if(_e({object:h,allowedFields:["type","approval_id"],path:p}),h.type!==void 0&&h.type!=="shop_token")throw new y(`${p}.type`,"shop_token","an unsupported credential type");return{...u,handler_id:a,type:"shop_pay",credential:{type:"shop_token",...n||h.approval_id!==void 0?{approval_id:ye(h.approval_id,`${p}.approval_id`).trim()}:{}}}}function ye(e,t){if(typeof e!="string"||e.trim().length===0)throw new y(t,"a non-empty string",E(e));return e}function je(e,t){if(e.billing_address!==void 0)return q(e.billing_address,gt,`${t}.billing_address`)}function _e({object:e,allowedFields:t,path:n}){if(Object.keys(e).some(i=>!t.includes(i)))throw new y(n,"only supported fields","extra properties")}
1const _t={email:"",phone_number:""},G={first_name:"",last_name:"",phone_number:"",street_address:void 0,extended_address:void 0,address_locality:"",address_region:"",address_country:"",postal_code:""},gt={...G,company:void 0,street_name:void 0,street_number:void 0,district:void 0},$e={phone_number:void 0,instructions:void 0};function Bi(e,t={}){const n=Wi(e,t);return Yi(Gi(),n)}function Gi(){return{buyer:{..._t},discountCodes:[],declaredFields:[],shippingAddress:{...G},fulfillmentMethods:{methods:[]},payment:void 0}}function Yi(e,t){return{...e,...t,buyer:{...e.buyer,...t.buyer}}}function Wi(e,t){const n=D(D(e,"input").checkout,"input.checkout"),i={};if(n.context!==void 0){const o="input.checkout.context",r=q(n.context,{address_country:void 0,address_region:void 0,postal_code:void 0},o);if(!r.address_country?.trim()||!r.postal_code?.trim())throw new y(o,"address_country and postal_code for a pickup search","incomplete locality");i.context={address_country:r.address_country.trim().toUpperCase(),postal_code:r.postal_code.trim(),...r.address_region?.trim()&&{address_region:r.address_region.trim().toUpperCase()}}}return n.buyer!==void 0&&(i.buyer=q(n.buyer,_t,"input.checkout.buyer")),n.discounts!==void 0&&(i.discountCodes=Ki(n.discounts)??[]),n.declared_fields!==void 0&&(i.declaredFields=zi(n.declared_fields)),n.fulfillment!==void 0&&Object.assign(i,Ji(n.fulfillment)),!t.ignorePayment&&n.payment!==void 0&&(i.payment=yt(n.payment,{path:"input.checkout.payment",savedPaymentMethodsOnly:t.savedPaymentMethodsOnly})),i}const Vi=new Set(["purpose","title","description","value_schema","presentation","required"]);function zi(e){const t="input.checkout.declared_fields";if(!Array.isArray(e))throw new y(t,"an array",E(e));const n=new Set;return e.map((i,o)=>{const r=`${t}[${o}]`,s=D(i,r);for(const a of Object.keys(s))if(!["key","value"].includes(a)&&!Vi.has(a))throw new y(`${r}.${a}`,"a declared field key or value","an unknown field");if(typeof s.key!="string"||s.key.length===0)throw new y(`${r}.key`,"a non-empty string",E(s.key));if(n.has(s.key))throw new y(`${r}.key`,"a unique declared field key",`duplicate ${JSON.stringify(s.key)}`);if(n.add(s.key),!Object.hasOwn(s,"value")||s.value===void 0)throw new y(`${r}.value`,"a value","undefined");return{key:s.key,value:s.value}})}function Xi(e,t){for(const n of Object.keys(e))if(!["id","type","selected","display"].includes(n))throw new y(`${t}.${n}`,"a saved instrument id from get_checkout, not new payment data","an unsupported field");return{instrument_id:ye(e.id,`${t}.id`)}}function Ki(e){const t="input.checkout.discounts",{codes:n}=D(e,t);if(n!==void 0){if(!vt(n))throw new y(`${t}.codes`,"an array of strings",E(n));return n}}function Ji(e){const t="input.checkout.fulfillment",n=D(e,t);if(!Array.isArray(n.methods))throw new y(`${t}.methods`,"an array",E(n.methods));if(n.methods.length>1)throw new y(`${t}.methods`,"at most 1 fulfillment method",`${n.methods.length} methods`);let i={...G};const o=[];for(const[r,s]of n.methods.entries()){const a=`${t}.methods[${r}]`,d=D(s,a),c=Qi(d.type??"shipping",`${a}.type`),{id:l}=q(d,{id:void 0},a),u={...l!==void 0&&{id:l}},p=d.groups===void 0?[]:no(d.groups,`${a}.groups`),h=eo(d,a);switch(c){case"pickup":{h===void 0&&Zi(d.destinations,`${a}.destinations`),o.push({...u,type:c,...h!==void 0&&{selected_destination_id:h},groups:p});break}case"shipping":{i=h===void 0?to(d,a):{saved_address_id:h},o.push({...u,type:c,groups:p});break}default:Tt(c)}}return{shippingAddress:i,fulfillmentMethods:{methods:o}}}function Qi(e,t){const n=Fe.find(i=>i===e);if(n!==void 0)return n;throw new y(t,Fe.map(i=>JSON.stringify(i)).join(" or "),typeof e=="string"?JSON.stringify(e):E(e))}function Zi(e,t){if(e!==void 0){if(!Array.isArray(e))throw new y(t,"an array",E(e));for(const[n,i]of e.entries()){const o=D(i,`${t}[${n}]`);if(o.type!=="business_location")throw new y(`${t}[${n}].type`,'a read-only "business_location" from get_checkout; select pickup through selected_destination_id',E(o.type))}}}function eo(e,t){if(e.selected_destination_id===null)return;const{selected_destination_id:n}=q(e,{selected_destination_id:void 0},t);
1if(n==="")throw new y(`${t}.selected_destination_id`,"a non-empty string or null","an empty string");return n}function to(e,t){const n=`${t}.destinations[0]`,i=`${t}.destinations`,{destinations:o}=e;if(o===void 0)return{...G};if(!Array.isArray(o))throw new y(i,"an array",E(o));if(o.length===0)return{...G};if(o.length!==1)throw new y(i,"1 item",`${o.length} items`);const r=D(o[0],n);if(r.pickup_location_address!==void 0||r.type==="business_location")throw new y(n,"a flat shipping address","a pickup location");const s=q(r,gt,n);return{...G,...s,address_country:(s.address_country??"").trim()}}function no(e,t){if(!Array.isArray(e))throw new y(t,"an array",E(e));return e.flatMap((n,i)=>{const o=`${t}[${i}]`,r=D(n,o),s=r.selected_option_id,a=r.selected_option_details;if(s===void 0){if(a!==void 0)throw new y(`${o}.selected_option_details`,"selected_option_id to also be present","selected_option_details without selected_option_id");return[]}if(typeof s!="string")throw new y(`${o}.selected_option_id`,"a string",E(s));const d=r.id;if(typeof d!="string")throw new y(`${o}.id`,"a string",E(d));const c=r.line_item_ids;if(c!==void 0&&!vt(c))throw new y(`${o}.line_item_ids`,"an array of strings",E(c));const l={...$e,...q(a===void 0?{}:a,$e,`${o}.selected_option_details`)};return[{id:d,line_item_ids:c,selected_option_id:s,selected_option_details:l}]})}function D(e,t){if(!io(e))throw new y(t,"an object",E(e));return e}function io(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function oo(e,t){if(!Array.isArray(e))throw new y(t,"an array",E(e));if(e.length!==1)throw new y(t,"1 item",`${e.length} items`);return D(e[0],`${t}[0]`)}function q(e,t,n){const i=D(e,n),o={};for(const r in t){if(!Object.hasOwn(i,r))continue;const s=i[r];if(typeof s!="string")throw new y(`${n}.${r}`,"a string",E(s));o[r]=s}return o}function vt(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function E(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?"an array":typeof e=="object"?"an object":`a ${typeof e}`}const Ee="Recoverable messages may be stale and do not by themselves mean completion is blocked. Use supported update_checkout fields to correct known missing or invalid data. When status is ready_for_complete and the buyer has authorized the purchase, call complete_checkout even if recoverable messages remain. Do not retry an unchanged update just to clear messages. After a completion failure, inspect the current checkout and resolve the cause before retrying. requires_buyer_input means a confirmed buyer action, such as a payment challenge: follow the message instructions and do not resubmit checkout. requires_buyer_review means the buyer must review the checkout on the page and authorize submission before complete_checkout is called again to submit.",ro={type:"object",additionalProperties:!1,properties:{payment:{...Q,required:["instruments"],properties:{instruments:{...Q.properties.instruments,minItems:1,items:{...Q.properties.instruments.items,required:["handler_id","credential"]}}}}}},ce="Checkout is still initializing. Retry shortly. Do not attempt to complete the checkout by interacting with the page.",X="Checkout completion could not be confirmed. Call get_checkout for the current state and its messages before retrying. Do not attempt to complete the checkout by interacting with the page.";class so extends Error{constructor(){super("WebMCP complete_checkout failed"),this.name="WebMcpCompleteCheckoutError"}}function Be(e){return!!(e?.handler_id==="shopify.card"?e.credential?.token:e?.credential?.approval_id)}function ao({isSubmitting:e,paymentInstrument:t,signal:n,checkout:i,shop:o,readCheckout:r,readSavedCards:s,shopPay:a,source:d,observability:c,getPreactContext:l,declaredFields:u}){let p=!1;return{name:"complete_checkout",title:"Complete checkout",description:`Advances the current checkout toward placing an order, with optional payment details. Use this toolânot browser or DOM controlsâto progress or submit, and only after the buyer authorizes the purchase. Read get_checkout first and follow the field schemas. To change the saved Shop Pay card, select an available instrument using update_checkout first. If a review step is configured, the first call opens it without placing an order and returns buyer_review_required. Call complete_checkout again from review only after the buyer reviews the checkout and authorizes submission. Returns checkout state, which may still be processing, or an error. Use get_checkout to verify the outcome; do not resubmit while status is complete_in_progress or completed. A status of completed means the order was successfully placed. If buyer_action_required is returned, ask the buyer to follow the returned instructions on the page; do not act on their behalf. ${Ee}`,inputSchema:ro,annotations:{consequentialHint:!0,readOnlyHint:!1,untrustedContentHint:!0},execute:async _=>V(await h(_),i)};async function h(_){if(p||e.value)return{error:{code:"completion_in_progress",message:"A checkout completion is already in progress. Wait for it to finish, then call get_checkout before retrying."}};p=!0;try{if(!o.hasFlagEnabled(Xt))return{error:{code:"buyer_action_required",message:"The buyer must manually complete checkout on the page. Do not attempt to complete checkout on their behalf."}};const{payment:g}=$i(_,{ignorePayment:!U(i)}),m=i.latestReceipt.value?.status;if(m==="processing"||m==="processing_remote_checkouts"||m==="polling_for_order"||m==="processed"||m==="action_required")return r()??{error:{code:"completion_failed",message:X}};const v=l();if(!v||n?.aborted)return{error:{code:"internal_error",message:ce}};if(U(i)&&(g||t.value)){if(await v.waitForPendingNegotiations(),n?.aborted)return{error:{code:"internal_error",message:ce}};const A=U(i)?g??t.value:void 0;if(A&&g&&!i.isPaymentRequired.value)return{error:{code:"invalid_request",message:"This checkout requires no payment. Retry complete_checkout without the payment field."}};if(A&&Be(A)&&i.isPaymentRequired.value){const f=new ct({isSubmitting:e,paymentInstrument:t,checkout:i,shop:o,shopPay:a,source:d,observability:c,declaredFields:u,...v,readSavedCards:s});if(g&&(await f.loadAddressMetadata([g.billing_address]),n?.aborted))return{error:{code:"internal_error",message:ce}};const I=f.writePayment({payment:A,applyBilling:g!==void 0});if("error"in I)return I}}let S=!1,w=!1;try{e.value=U(i)&&i.isPaymentRequired.value&&Be(t.value),await v.journey.progress("web-mcp-complete-checkout",A=>{S=A.status==="success"||A.status==="alreadyCompleted",w||="negotiated"in A||"receipt"in A})}finally{e.value&&w&&(t.value=void 0),e.value=!1}const b=r();return!S&&!b?.messages?.some(A=>A.type==="error"&&A.severity==="requires_buyer_input")?{error:{code:"completion_failed",message:X}}:b??{error:{code:"completion_failed",message:X}}}catch(g){return g instanceof y?{error:{code:"invalid_request",message:`${g.message} Correct the input and retry. Do not attempt to complete the checkout by interacting with the page.`}}:(c.error(new so),{error:{code:"internal_error",message:X}})}finally{p=!1}}}const co="Checkout data is not available yet. Retry shortly. Do not attempt to read checkout state by interacting with the page.",lo="Unable to read the checkout. Do not attempt to read checkout state by interacting with the page.";
1class uo extends Error{constructor(){super("WebMCP get_checkout failed to read the checkout"),this.name="WebMcpGetCheckoutError"}}function po({checkout:e,readCheckout:t,observability:n}){return{name:"get_checkout",title:"Get checkout",description:`Reads the current checkout without changing it. Use it before updating, to inspect validation messages, or to check completion and order confirmation. Available Shop Pay saved cards are reported under payment.instruments for selection by id; raw credentials and security codes are never reported. A status of completed means the order was successfully placed. Monetary amounts are integers in the currencyâs minor units. Returns the checkout or an error with a code and message. ${Ee}`,inputSchema:{type:"object",properties:{}},annotations:{consequentialHint:!1,readOnlyHint:!0,untrustedContentHint:!0},execute:()=>V(i(),e)};function i(){try{const o=t(e.latestReceipt.value?.status==="processed"?"negotiated":"proposed");return o||{error:{code:"internal_error",message:co}}}catch{return n.error(new uo),{error:{code:"internal_error",message:lo}}}}}const ho=3e4;class fo extends Error{constructor(t){super("WebMCP navigate_to_storefront failed",{cause:t}),this.name="WebMcpStorefrontNavigationError"}}function bt({shop:e,url:t}){if(e.hasStorefront)try{const n=new URL(e.previewReturnUrl??t.storefront());return n.protocol!=="https:"&&n.protocol!=="http:"||n.username||n.password?void 0:n.href}catch{return}}function mo({checkout:e,shop:t,url:n,observability:i,signal:o,getPreactContext:r}){return{name:"navigate_to_storefront",title:"Return to storefront",description:"Leaves checkout and navigates this tab to the storeâs storefront to continue shopping. Does not place an order or change the cart. After navigation, refresh the available tools before searching for products or changing the cart.",inputSchema:{type:"object",properties:{},additionalProperties:!1},annotations:{readOnlyHint:!1,consequentialHint:!1},execute:async(d,c)=>V(await s(d,c?.signal??o),e)};async function s(d,c){let l;try{if(d===null||typeof d!="object"||Array.isArray(d)||Object.keys(d).length>0)return{error:{code:"invalid_request",message:"navigate_to_storefront takes no input. Retry with an empty object."}};if(c.aborted||o.aborted)return Ge();const u=r();if(!u)return{error:{code:"internal_error",message:"Checkout is still initializing. Retry shortly."}};if(a(u))return Ye();const p=bt({shop:t,url:n});if(!p)return yo();const h=new Promise(g=>{l=setTimeout(()=>g("timeout"),ho)}),_=await Promise.race([u.waitForPendingNegotiations(),h]);return c.aborted||o.aborted?Ge():_==="timeout"?(i.log("web_mcp_storefront_navigation_timed_out","Storefront navigation timed out waiting for pending checkout updates"),{error:{code:"navigation_failed",message:"Checkout updates are still pending. Navigation was not started. Retry after updates finish."}}):a(u)?Ye():(window.location.assign(p),{status:"navigation_started",destination_url:p,message:"Refresh the available tools after the storefront loads."})}catch(u){return i.error(new fo(u)),{error:{code:"navigation_failed",message:"Unable to navigate to the storefront. Refresh the available tools and check the current page before retrying."}}}finally{clearTimeout(l)}}function a({journey:d}){const c=e.latestReceipt.value;return d.completing.value||d.progressing.value||c!=null&&!["processed","failed","abandoned"].includes(c.status)}}function Ge(){return{error:{code:"navigation_failed",message:"Navigation was cancelled. The tool did not leave checkout."}}}function Ye(){return{error:{code:"checkout_busy",message:"Checkout submission or payment is in progress. Wait for it to finish and call get_checkout before navigating away."}}}function yo(){return{error:{code:"navigation_failed",message:"A supported storefront destination is not available. Stay on the current checkout."}}}const We=3e4,Ve="Checkout is not available for updates. Retry shortly. Do not attempt to update the checkout by interacting with the page.",_o="Correct the input and retry. Do not attempt to update the checkout by interacting with the page.",go={type:"object",required:["checkout"],properties:{checkout:{type:"object",description:"Replacement buyer, fulfillment, and discount-code state. Omitted sections and fields are cleared; resend values to retain them.",properties:{context:{type:"object",required:["address_country","postal_code"],description:"Optional pickup search origin. Omission retains the current search origin. An unchanged origin may be echoed when switching to shipping. Does not replace shipping or billing addresses. Resolve discovery before selecting a destination in a subsequent call.",properties:{address_country:{type:"string",description:"ISO country code."}
1,address_region:{type:"string",description:"Province or region code."},postal_code:{type:"string"}}},payment:{...Q,description:"Payment and billing replacement. Billing may be supplied without a handler or credential. When shipping is required, omitted billing or billing matching shipping uses shipping as billing; a different address becomes custom billing."},buyer:{type:"object",description:"Buyer contact details.",properties:{email:{type:"string",description:'Buyer email address, e.g. "[email protected]".'},phone_number:{type:"string",description:"Buyer phone number; E.164 recommended (e.g. +16135550123)."}}},discounts:{type:"object",description:"Buyer-entered discount codes.",properties:{codes:{type:"array",items:{type:"string"}}}},declared_fields:{type:"array",description:"Replacement values for declared checkout fields. Each field's description in get_checkout states its omission behavior. Echoed descriptor metadata is ignored; only key and value are used.",items:{type:"object",required:["key","value"],properties:{key:{type:"string"},value:{type:["string","boolean","null"]}}}},fulfillment:{type:"object",description:"Use a method type to switch all physical items between shipping and pickup while the delivery selector is mounted. Supply context locality to search for pickup locations. Select a returned destination in a subsequent call. selected_destination_id wins when both it and destinations are supplied.",required:["methods"],properties:{methods:{type:"array",maxItems:1,description:"At most one fulfillment method. Mode changes apply to all physical items; split shipping is not supported. Updates to checkouts with both shipping and pickup are rejected. Omitted methods clear selections without changing the active mode.",items:{type:"object",properties:{id:{type:"string",description:"Existing method ID; omit when changing type."},type:{type:"string",enum:["shipping","pickup"],description:"shipping or pickup. Defaults to shipping. Mode changes and locality discovery support store pickup only. Existing pickup-point destinations remain selectable. A new type or search origin cannot be combined with destination or option selections."},selected_destination_id:{type:["string","null"],description:"Pickup: a location id from get_checkout. Shipping: Shop Pay saved destination ids only. Null selects nothing, so destinations applies instead."},destinations:{type:"array",items:{type:"object",description:`One replacement shipping address, ignored when selected_destination_id is set. Use PUT semantics, not PATCH. ${ft}`,properties:mt}},groups:{type:"array",items:{type:"object",required:["id"],properties:{id:{type:"string"},line_item_ids:{type:"array",items:{type:"string"}},options:{type:"array",items:{type:"object",required:["id"],properties:{id:{type:"string"}}}},selected_option_id:{type:"string",description:'Option ID from get_checkout; "pickup" for pickup groups.'},selected_option_details:{type:"object",description:"Requires selected_option_id.",properties:{phone_number:{type:"string"},instructions:{type:"string"}}}}}}}}}}}}}}},vo="Updates the current checkout without placing an order. Use this toolânot browser or DOM controlsâwhenever checkout data needs to change, even if visible fields are partially filled. Supports buyer contact details, shipping addresses and options, billing addresses, discounts, and payment details. In Shop Pay, select one payment.instruments entry by its id from get_checkout, or omit payment to keep the current card; new payment credentials are not accepted. Read get_checkout first and follow the field schemasâ replacement rules; do not assume omitted data is preserved. Returns the resulting checkout or an error. If an update fails, call get_checkout and inspect its messages before retrying.";class bo extends Error{constructor(){super("WebMCP update_checkout failed to apply"),this.name="WebMcpUpdateCheckoutError"}}function Ao({isSubmitting:e,paymentInstrument:t,signal:n,checkout:i,shop:o,shopPay:r,source:s,router:a,getSavedCardSelector:d,readCheckout:c,readSavedCards:l,observability:u,getPreactContext:p,declaredFields:h,getFulfillmentController:_}){return{name:"update_checkout",title:"Update checkout",description:`${vo} ${Ee}`,inputSchema:go,annotations:{consequentialHint:!1,readOnlyHint:!1,untrustedContentHint:!0},execute:async m=>V(await g(m),i)};async function g(m){let v;try{if(e.value)return B();const S=i.identity.current.value==="shopPay",w=Bi(m,{savedPaymentMethodsOnly:S,ignorePayment:S?!i.isPaymentRequired.value:!U(i)}),b=p();if(!b||n?.aborted)return{error:{code:"internal_error",message:Ve}};if(a.currentUrl.value.normalizedPath==="/review"&&a.navigate("/"),w.payment&&"instrument_id"in w.payment&&!d())return{error:{code:"internal_error",message:Ve}};const{loadPickupLocalityServices:A}=b;let f;const I=new ct({isSubmitting:e,paymentInstrument:t,checkout:i,shop:o,shopPay:r,source:s,getSavedCardSelector:d,observability:u,declaredFields:h,...b,readSavedCards:l,getFulfillmentController:_,resolvePickupLocality:A?async x=>(f=await A(),f.resolvePickupLocality(x)):void 0,announcePickupLocality:x=>f?.announcePickupLocality(x),get negotiator(){return b.negotiator}});let L=!1;const P=new Promise(x=>{v=setTimeout(()=>{L=!0,x("timeout")},We)}),j=await Promise.race([I.applyUpdate(w,{isExpired:()=>L||!!n?.aborted}),P]);return j==="timeout"?(u.log("web_mcp_update_timed_out","[WebMcp] Update did n
1ot finish in time; update outcome is unknown",{timeoutMs:We}),{error:{code:"update_failed",message:J}}):"error"in j?j:c()??{error:{code:"update_failed",message:J}}}catch(S){return S instanceof y?{error:{code:"invalid_request",message:`${S.message} ${_o}`}}:(u.error(new bo),{error:{code:"internal_error",message:J}})}finally{clearTimeout(v)}}}function Co(e){return typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="object"}function Io(e){if(typeof e!="object"||e===null||!("error"in e))return"unknown";const{error:t}=e;if(typeof t!="object"||t===null||!("code"in t))return"unknown";switch(t.code){case"buyer_action_required":case"checkout_busy":case"completion_failed":case"completion_in_progress":case"internal_error":case"invalid_request":case"navigation_failed":case"rejected":case"update_failed":return t.code;default:return"unknown"}}function ge(e,t,n,i){const o=Math.round(performance.now()-i),r=Co(n),s={tool:t,outcome:r?"error":"success",...r&&{errorCode:Io(n)}};e.log("web_mcp_tool_executed","[WebMcp] tool executed",{...s,durationMs:o}),e.histogram({name:"web_mcp_tool_execution",value:o,unit:"ms",attributes:s})}function ze(e,{activeTool:t,observability:n,checkout:i}){const o=e.name;return{...e,execute:async(...r)=>{const s=performance.now();if(t.current==="navigate_to_storefront"||o==="navigate_to_storefront"&&t.current!==void 0){const a=V({error:{code:"checkout_busy",message:"Another checkout tool is running. Wait for it to finish before retrying."}},i);return ge(n,o,a,s),a}return t.during(o,async()=>{const a=await e.execute(...r);return ge(n,o,a,s),a})}}}function To(e,t){const n=e.name;return{...e,execute:(...i)=>{const o=performance.now(),r=e.execute(...i);return ge(t,n,r,o),r}}}class Eo extends Error{constructor(t,n){super(`WebMCP tool registration failed for ${t}: ${String(n)}`),this.name="WebMcpRegistrationError",n instanceof Error&&(this.cause=n)}}function So(e,t){const n=new AbortController,i=Xe(function(){e.latestReceipt.value?.status==="processed"&&(this.dispose(),n.abort())});return t.addEventListener("abort",()=>{i(),n.abort()},{once:!0,signal:n.signal}),n.signal}function wo({modelContext:e,signal:t,isSubmitting:n,paymentInstrument:i,checkout:o,i18n:r,shop:s,shopPay:a,source:d,url:c,router:l,observability:u,activeTool:p,onActiveToolCreated:h,getPreactContext:_,markToolCallStarted:g,getSavedCardSelector:m,declaredFields:v,getFulfillmentProvider:S,getStoreCreditProvider:w,unregisterInitializingTool:b}){if(t.aborted)return;const A=bi({checkout:o,shopPay:a}),f=N=>si({checkout:o,i18n:r,shop:s,router:l,readMode:N,savedCards:A(),declaredFields:v,paymentInstrument:i.value}),I=yi(o);v.set(I.key,I);const L=fi(()=>w?.());v.set(L.key,L);const P=p??new en;h?.(P);const x=[{tool:To(po({checkout:o,readCheckout:f,observability:u}),u),signal:t}],Se=So(o,t);Se.aborted||x.push(...[Ao({isSubmitting:n,paymentInstrument:i,signal:t,checkout:o,shop:s,shopPay:a,source:d,router:l,getSavedCardSelector:m,readCheckout:f,readSavedCards:A,observability:u,getPreactContext:_,declaredFields:v,getFulfillmentController:()=>{const N=S?.();return N?_i(N,o.proposal):void 0}}),ao({isSubmitting:n,paymentInstrument:i,signal:t,checkout:o,shop:s,shopPay:a,source:d,readCheckout:f,readSavedCards:A,observability:u,getPreactContext:_,declaredFields:v})].map(N=>({tool:ze(N,{activeTool:P,observability:u,checkout:o}),signal:Se}))),bt({shop:s,url:c})&&x.push({tool:ze(mo({checkout:o,shop:s,url:c,observability:u,signal:t,getPreactContext:_}),{activeTool:P,observability:u,checkout:o}),signal:t}),b?.();const At=x.map(async({tool:N,signal:$})=>{try{return await e.registerTool({...N,execute(ie,Ct){return g(),N.execute(ie,Ct)}},{signal:$}),"registered"}catch(ie){return $.aborted?"withdrawn":(u.error(new Eo(N.name,ie)),"failed")}});return Promise.all(At).then(N=>{t.aborted||u.log("web_mcp_tools_registered","[WebMcp] tools registered",{registered:N.filter($=>$==="registered").length,failed:N.filter($=>$==="failed").length})}).catch(()=>{}),P}const Oo=Object.freeze(Object.defineProperty({__proto__:null,registerWebMcpTools:wo},Symbol.toStringTag,{value:"Module"}));
1export{Ue as n,Oo as w};
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.