PageSourceSearch

https://andaraaccesorios.com/cdn/shopifycloud/checkout-web/assets/c1/web-mcp-runtime.DUJM2mp0.js

js andaraaccesorios.com collected 2026-09-29 01:53:55 UTC 87,830 bytes, 1 lines download raw bytes

1import{c as Mt,j as tt,n as B,a as Dt,b as Nt}from"./esnext-vendor.DDpcaSqU.js";import{c as Rt,s as Ce,a as fe,b as Te,R as Ae,d as Ot,i as U,e as Ut,n as Se,r as xt,f as nt,g as Ft,h as $t,j as qt,C as Ht,k as jt,V as te,p as Bt,l as Gt,m as Yt,U as Wt,o as Vt,q as zt,t as Xt,u as Kt,F as Jt,v as Zt,w as Ne,x as Re,y as Qt,z as en,A as tn,B as nn,D as on,E as rn}from"./utilities-previous.Cnwy8G2v.js";import{c as sn,i as an}from"./graphql-PaymentSessionMutation.C-nDEOnn.js";import{i as dn}from"./cvv-cvvBridge.CLYVr7ZJ.js";import{s as cn}from"./helpers-derivations.K4r9DEFp.js";import{a as q,i as ln}from"./context-browser.Cjla8Cf_.js";class un{#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)}}}const pn=["buyer_action_required","checkout_busy","completion_failed","completion_in_progress","internal_error","invalid_request","navigation_failed","rejected","update_failed"];function fn(e){return pn.includes(e)}function S(e){return typeof e=="object"&&e!==null&&"error"in e}const he=Symbol("WebMcpFailureDetails");function hn(e){if(!S(e))return;const t=e.error;if(!(typeof t!="object"||t===null||!(he in t)))return t[he]}function g(e,t,n){const i={code:e,message:t};return n&&Object.defineProperty(i,he,{value:n}),{error:i}}function R(e){return`Do not attempt to ${e} by interacting with the page.`}const ke="Retry shortly.",it=`Checkout is still initializing. ${ke}`,X="Nothing was applied.",mn="Call get_checkout before retrying.",yn="Correct the input and retry.",_n=`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. ${R("update the checkout")}`,gn=`Checkout completion could not be confirmed. Call get_checkout for the current state and its messages before retrying. ${R("complete the checkout")}`;function oe(e,t,n,i=mn){return g(e,`${t}: ${n} ${X} ${i}`)}function ot(e,t){return g("invalid_request",`${e.message} ${yn} ${R(t)}`,{invalidInputPath:e.loggablePath.replace(/\[\d+\]/g,"[]"),invalidInputExpected:e.expected})}function vn(){return g("checkout_busy","Another checkout tool is running. Wait for it to finish before retrying.")}function bn(){return g("internal_error",`Checkout data is not available yet. ${ke} ${R("read checkout state")}`)}function En(){return g("internal_error",`Unable to read the checkout. ${R("read checkout state")}`)}function Oe(){return g("internal_error",`Checkout is not available for updates. ${ke} ${R("update the checkout")}`)}function E(e="update_failed"){return g(e,_n)}function In(e){return g("update_failed",`Unable to update ${e}. Call get_checkout to review the checkout and its messages before retrying. ${R("update the checkout")}`)}function Ue(e){return g("rejected",`The selected delivery option does not support selected_option_details.${e}. ${X} Remove ${e} from selected_option_details or choose an option that supports it, then retry. ${R("update the checkout")}`)}function Cn(e,t,n){const i=n?` Supported countries: ${n.join(", ")}.`:"";return g("rejected",`${e} ${t} is not a country this shop ships to. ${X}${i} Tell the buyer. ${R("update the checkout")}`)}const rt=`${X} 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. ${R("update the checkout")}`;function Tn(){return g("rejected",`fulfillment.methods[].groups[] does not match a delivery group in the current checkout. ${rt}`)}function An(){return g("rejected",`fulfillment.methods[].groups[] has no selectable delivery option in the current checkout. ${X} Send the update without groups, then choose an option from the next get_checkout. ${R("update the checkout")}`)}function Sn(){return g("rejected",`fulfillment.methods[].groups[].selected_option_id is not an option for this group in the current checkout. ${rt}`)}function O(e){return oe("rejected","fulfillment",e)}function ae(e,t){return oe("rejected",e,`${t}.`)}function kn(){return oe("update_failed","context","Pickup locality lookup is unavailable.",`Call get_checkout and retry with the latest checkout. ${R("update the checkout")}`)}function Pn(){return oe("rejected","context","Could not resolve a unique postal locality.","Check address_country, address_regi
1on and postal_code, then retry.")}function Y(){return g("completion_in_progress","A credentialed completion is in progress. Wait for it to finish before updating payment.")}function Ln(){return g("invalid_request","This checkout does not accept the supplied payment handler. Call get_checkout for the current checkout state.",{invalidInputPath:"payment.instruments[].handler_id",invalidInputExpected:"a handler this checkout accepts"})}function wn(){return g("completion_in_progress","A checkout completion is already in progress. Wait for it to finish, then call get_checkout before retrying.")}function Mn(){return g("buyer_action_required","The buyer must manually complete checkout on the page. Do not attempt to complete checkout on their behalf.")}function de(){return g("internal_error",`${it} ${R("complete the checkout")}`)}function J(e="completion_failed",t){return g(e,gn,t)}function Dn(){return g("invalid_request","This checkout requires no payment. Retry complete_checkout without the payment field.",{invalidInputPath:"input.payment",invalidInputExpected:"no payment"})}function Nn(){return g("invalid_request","navigate_to_storefront takes no input. Retry with an empty object.",{invalidInputPath:"input",invalidInputExpected:"an empty object"})}function Rn(){return g("internal_error",it)}function On(){return g("navigation_failed","Checkout updates are still pending. Navigation was not started. Retry after updates finish.")}function Un(){return g("navigation_failed","Unable to navigate to the storefront. Refresh the available tools and check the current page before retrying.")}function xe(){return g("navigation_failed","Navigation was cancelled. The tool did not leave checkout.")}function Fe(){return g("checkout_busy","Checkout submission or payment is in progress. Wait for it to finish and call get_checkout before navigating away.")}function xn(){return g("navigation_failed","A supported storefront destination is not available. Stay on the current checkout.")}function Fn(e){return Array.from(e.values()).flatMap(t=>{const n=t.read();return n?[n]:[]}).sort((t,n)=>$n(t.key,n.key))}function $n(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 ae(`${d}.key`,"must identify a declared field available in the current checkout");const l=c.prepare(a);if("requirement"in l)return ae(`${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 ae("$.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 qn(e){const{email:t,phone:n}=e??{};if(!(!t&&!n))return{...t?{email:t}:{},...n?{phone_number:n}:{}}}function w(e){if(!e)return 0;const t=Mt(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 Hn(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=jn(r,n);a.amount>0&&o.push(a)}}return{codes:[...i.values()],applied:o}}function jn(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=w(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:w(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 ne(e,{extendedAddressMode:t}){const n=e.address_country?.toUpperCase()??"",i=t.get(n),o=i===null?Bn(n,e):Gn(n,e,i);return{...Rt({...e,street_address:o.address1,extended_address:o.address2}),company:e.company??"",district:void 0,subdistrict:void 0,...o}}function Pe(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?Vn(n,e):Xn(n,e,i),address_locality:e.city,address_regi
1on:e.zoneCode,address_country:e.countryCode,postal_code:e.postalCode}}function st({street_address:e="",street_name:t,street_number:n=""}){return t?.trim()?{streetName:t,streetNumber:n}:{line:e}}function Bn(e,t){const n=st(t);return{address1:"line"in n?n.line:Zn(e,n),address2:t.extended_address??""}}function Gn(e,t,n){const{packedLine2:i,...o}=Yn(e,st(t)),{neighborhood:r,...s}=Wn(e,t,i);return{...o,...s,...n==="dedicated"?r!==void 0&&{district:r,neighborhood:""}:{neighborhood:r}}}function Yn(e,t){if("line"in t){const i=Ce(e,t.line,!0);if(!i?.streetNumber)return{address1:t.line};const o=fe({countryCode:e,streetName:i.streetName??"",streetNumber:i.streetNumber});return o==null?{address1:t.line}:{address1:o,packedLine2:i.line2}}const n=fe({countryCode:e,...t});return n==null?{address1:lt(t)}:{address1:n,...t}}function Wn(e,{extended_address:t="",district:n},i){const o=Te(e,t);if(!o)return{address2:$e(t,i)};const r=$e(o.line2??"",i),s=n??o.neighborhood??"";return{address2:ct(e,r,s),line2:r,neighborhood:s}}function $e(e,t){return!t||t===e.trim()?e:ut(e,t)}function Vn(e,t){return{street_address:at(e,t),extended_address:zn(e,t)}}function at(e,{address1:t,streetName:n,streetNumber:i}){return t||!(n||i)?t:dt(e,{streetName:n??"",streetNumber:i??""})}function zn(e,{address2:t,line2:n,district:i,neighborhood:o}){const r=i||o;return n==null&&!r?t:ct(e,n??"",r??"")}function Xn(e,t,n){const i=Kn(e,t,n);return{...i?.streetName?{street_name:i.streetName,street_number:i.streetNumber??""}:{street_address:at(e,t)},...Jn(e,t,n)}}function Kn(e,t,n){return n==="dedicated"&&(t.streetName!=null||t.streetNumber!=null)?t:t.address1?.includes(Ae)?Ce(e,t.address1):null}function Jn(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)?Te(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 dt(e,t){return fe({countryCode:e,...t})??lt(t)}function ct(e,t,n){return Ot({countryCode:e,line2:t,neighborhood:n})??ut(t,n)}function Zn(e,t){return Qn(dt(e,t))}function lt({streetName:e,streetNumber:t}){return[t,e].filter(Boolean).join(" ")}function ut(e,t){return[e,t].filter(Boolean).join(", ")}function Qn(e){return e.split(Ae).join("")}function ei(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}=ni(o.lineAllocations),c=[];n+=d,s&&c.push({type:"subtotal",amount:w(s)}),a!==0&&s&&(t+=a,c.push({type:"items_discount",amount:w({...s,amount:-a})}));const l=s?{...s,amount:s.amount-a}:o.totalPrice;return c.push({type:"total",amount:w(l)}),{id:A(o),...o.parentRelationship?.parent?.stableId?{parent_id:o.parentRelationship.parent.stableId}:{},quantity:o.quantity,item:{id:o.variantId??o.stableId,title:o.title,price:w(r),...o.image?.url?{image_url:o.image.url}:{}},totals:c}}),itemsDiscountAmount:t,cartLevelDiscountAmount:n}}function re(e){return e?.flatMap(t=>(t.lineComponents.length?t.lineComponents:[t]).filter(n=>n.requiresShipping).map(A))??[]}function ti(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 A(e){return e.stableId}function ni(e){let t=0,n=0;for(const i of e)for(const{discountDetails:o,amount:r}of i.allocations)ii(o.discount)?n+=r.amount:t+=r.amount;return{lineLevel:t,cartLevel:n}}function ii(e){return"presentationLevel"in e&&e.presentationLevel==="CART"}function Q(e){return e==="SHIPPING"||e==="LOCAL"||U(e)}function oi(e,t,n){return!!(e&&!n&&(t.some(i=>!Q(i))||t.some(U)&&t.some(i=>i==="SHIPPING"||i==="LOCAL")))}function ri(e,t,n){return!n||e===t}function ie(e,t){switch(t){case"phone_number":return!!e.phoneRequired;case"instructions":return!!e.acceptsInstructions}}function V(e,t){if(!e?.length||!t?.length)return!1;const n=new Set(t),i=e.filter(o=>o.requiresShipping).map(o=>A(o));return i.length===n.size&&i.every(o=>n.has(o))}const me="pickup";function z(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 U(n)?"pickup":"shipping"}function pt(e){const t=e.filter(r=>z(r)==="pickup"),n=t.map(r=>{const s=new Map;for(const a of r.methods){if(!a.pickupLocation)continue;const d=si(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 si(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 ai(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})=>Ut(r,t)):void 0;return{destinations:i,selectedDestinationId:o?.id}}function di(e){const t=li(e);return t.length?{methods:t}:void 0}function ci(e){const{deliveryNext:t}=e;if(t?.status!=="filled"||!t.lines)return;const n=[];let i;for(const r of t.lines){if(r.status!=="available"||!r.selectedDeliveryMethodHandle)continue;const s=Se(r);s?.cost&&(n.push({cost:s.costAfterDiscounts.amount,costBeforeDiscounts:s.cost.amount,rateGroupKey:s.methodType==="SHIPPING"?xt({line:r,method:s,localShopId:e.shopId,marketDrivenShippingEnabled:e.marketDrivenShippingEnabled,remoteShopsConfigMap:e.remoteShopsConfigMap,remoteMerchandiseDetails:e.remoteMerchandiseDetails}):void 0}),i??=s.cost.currencyCode)}if(i==null)return;const{priceBeforeDiscounts:o}=sn(n,({rateGroupKey:r})=>r);return{amount:o,currencyCode:i}}const Le=Pe;function li(e){const{deliveryNext:t}=e;if(e.readMode!=="proposed"&&(t?.status!=="filled"&&t?.status!=="partial"||!t.lines))return qe(e);const n=(t?.status==="filled"||t?.status==="partial")&&t.lines?t.lines.filter(bi):[],o=(e.readMode==="proposed"?_i(n,e.proposedDeliveryLines,e.merchandiseLines):n).filter(d=>(d.proposedLine?d.proposedLine.deliveryMethodTypes.some(He):d.methods.some(c=>He(c.methodType)))&&d.targetMerchandiseLines?.some(c=>
1c.requiresShipping));if(e.readMode==="proposed"&&!o.length)return qe(e);const r=t?.status==="partial"?ft(e,o):new Map,s=new Set([...ui(o),...r.keys()]),a=[];for(const d of s){const c=o.filter(p=>z(p)===d),l=c.map(p=>yi(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:[],...pi(d,c,e),groups:l})}return a}function ft(e,t){const n=new Set(t.flatMap(r=>r.targetMerchandiseLines?.map(A)??[])),i=new Map,o=new Set;for(const r of e.merchandiseLines??[]){if(e.readMode!=="proposed"&&!r.requiresShipping)continue;const s=A(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(A(u))).map(A));if(!a.size)continue;const d=e.proposedDeliveryLines?.filter(u=>u.targetMerchandiseLines.some(p=>A(p)===s||a.has(A(p)))).flatMap(u=>u.deliveryMethodTypes),c=d?.length&&d.every(U)?"pickup":"shipping",l=i.get(c)??[];l.push(...e.readMode==="proposed"?a:[s]),i.set(c,l)}return i}function qe(e){return[...ft(e,[])].map(([n,i])=>({id:n,type:n,line_item_ids:i,destinations:[],...n==="shipping"?ht(e):{},groups:[]}))}function ui(e){const t=new Set;for(const n of e){const i=z(n);i&&t.add(i)}return Array.from(t)}function He(e){return e==="SHIPPING"||e==="LOCAL"||U(e)}function pi(e,t,n){if(e==="shipping")return ht(n);const i=pt(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=fi(s[0].method,n.addressContext);return a?[{...a,id:r}]:[]}),...o&&{selected_destination_id:o.id}}}function ht({savedDestinations:e,shippingAddress:t,addressContext:n}){if(e===void 0)return t&&nt(t)?{destinations:[hi(t,n)]}:{};const{destinations:i,selectedDestinationId:o}=ai(e,t);return i.length?{destinations:i.map(({id:r,address:s})=>({id:r,type:"shipping_address",...Le(s,n)})),...o&&{selected_destination_id:o}}:{}}function fi(e,t){const{pickupLocation:n}=e;if(n)return{id:e.handle,type:"business_location",name:n.name??"",pickup_location_address:Le(n.address,t)}}function hi(e,t){return{...Le(e,t),id:mi(e),type:"shipping_address"}}function mi(e){return["shipping",e.countryCode,e.postalCode].filter(Boolean).join("-").replace(/\s+/g,"")}function yi(e,t){const n=mt(e),i=Se(e),o=e.proposedLine?e.selectedDeliveryMethodHandle:i?.handle,r=o?gi(e,n,t):void 0,s=z(e)==="pickup",a=s?[{...i?je(i):{totals:[]},id:me,title:"Pickup"}]:e.methods.filter(({methodType:d})=>d==="SHIPPING"||d==="LOCAL").map(je);return{id:e.id??"",line_item_ids:n,options:a,...o&&{selected_option_id:s?me:o},...r&&{selected_option_details:r}}}function _i(e,t,n){const i=new Map;for(const o of n??[]){i.set(A(o),re([o]).length>0);for(const r of o.lineComponents)i.set(A(r),r.requiresShipping)}return(t??[]).map(o=>{const r=o.targetMerchandiseLines.filter(a=>a.requiresShipping).map(a=>A(a)),s=e.find(a=>o.id!==void 0&&a.id===o.id)??e.find(a=>a.type===o.type&&V(a.targetMerchandiseLines,r));return{...s,status:"available",id:o.id,type:o.type,targetMerchandiseLines:o.targetMerchandiseLines.flatMap(a=>{const d=i.get(A(a));return d===void 0?[]:[{...a,requiresShipping:d}]}),selectedDeliveryMethodHandle:o.deliveryMethodHandle,methods:s?.methods.filter(a=>o.deliveryMethodTypes.includes(a.methodType))??[],proposedLine:o}})}function gi(e,t,n){const i=vi(e,n,t);if(!i||!e.selectedDeliveryMethodHandle||i.deliveryMethodHandle!==e.selectedDeliveryMethodHandle)return;const o=i.deliveryMethodOptions;if(!o)return;const r=Se(e),s=r&&!ie(r,"phone_number")?void 0:o.phone,a=r&&!ie(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 vi(e,t,n=mt(e)){return t?.find(i=>!!e.id&&i.id===e.id)??t?.find(i=>V(i.targetMerchandiseLines,n))}function mt(e){return e.targetMerchandiseLines?.filter(t=>t.requiresShipping).map(t=>A(t))??[]}function je(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:U(e.methodType)?"Pickup":"Shipping",amount:w(e.costAfterDiscounts)}]}}function bi(e){return e.status==="available"}const Ei=new Map([["terms-of-service","terms_of_service"],["privacy-policy","privacy_policy"],["refund-policy","refund_policy"],["shipping-policy","shipping_policy"]]);function Ii(e){const t=[];for(const{handle:n,url:i}of e){const o=Ei.get(n);o&&t.push({type:o,url:i})}return t}function Ci(e){if(e?.status!=="processed")return;const t=e.orderIdentity.buyerIdentifier,n=Ft(e.orderIdentity.id);return{...n?{id:$t("Order",n)}:{},...t?{label:t}:{},permalink_url:e.confirmationPage.url}}
1function Ti(e,t,n){const i=n?.filter(({instrument:o,usable:r})=>o.selected||r).map(({instrument:o})=>o);return i?.length?{instruments:i}:{instruments:e?[{billing_address:Pe(e,t)}]:[]}}function Ai(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 Si={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 ki(e){return Si[e]}const Pi=new Set(["AcceptNewTermViolation","RequiredArtifactsUnavailableViolation"]),Li=new Set(["PendingTermViolation"]),wi=new Set(["PAYMENTS_UNACCEPTABLE_PAYMENT_AMOUNT"]),Mi={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 Di(e){const{receipt:t,isShippingRequired:n,hasShippingAddress:i,deliveryNext:o,skipsShippingAddress:r=qt(o)}=e,s=Ni(e),a=Oi({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(Mi),{status:a,messages:s}}function Ni(e){const t=[];for(const n of e.violations??[]){if(Pi.has(n.__typename)||wi.has(n.code)||e.requiresCaptcha&&Ht.has(n.code))continue;const i=n.code.startsWith("DISCOUNTS_"),o=i||Li.has(n.__typename),r=ki(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:Ri(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 Ri(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 Oi({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 Ui({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:w(e)}),c.push(...xi({currencyCode:e.currencyCode,discountLines:i,itemsDiscountAmount:t,cartLevelDiscountAmount:n}))),o!=null&&c.push({type:"fulfillment",display_text:"Shipping",amount:w(o)}),s!=null&&!a&&c.push({type:"duty",display_text:"Duties",amount:w(s)}),r!=null&&c.push({type:"tax",display_text:"Taxes",amount:w(r)}),d!=null&&c.push({type:"total",display_text:"Total",amount:w(d)}),c}function xi({currencyCode:e,discountLines:t,itemsDiscountAmount:n,cartLevelDiscountAmount:i}){let o=i;for(const s of t?.lines??[])if(jt(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:w({amount:-n,currencyCode:e})}),o>0&&r.push({type:"discount",display_text:"Discount",amount:w({amount:-o,currencyCode:e})}),r}function Fi(e){const t=e.merchandiseLines?.lines;if(!t||!Hi(t)||e.runningTotal==null)return;const n=e.readMode==="proposed"&&t.length===0?{...e.runningTotal,amount:0}:ti(t)??e.subtotal;if(n==null)return;const{lineItems:i,itemsDiscountAmount:o,cartLevelDiscountAmount:r}=ei(t),s=ci(e),a=e.receipt?.status==="processed"&&e.receipt.isRedacted?void 0:qn(e.contactInfo),d=Hn(e.discountLines,e.readMode==="proposed"?i:void 0),c=di({readMode:e.readMode,deliveryNext:e.deliveryNext,shippingAddress:e.shippingAddress,merchandiseLines:t,savedDestinations:e.savedDestinations,addressContext:e.addressContext,proposedDeliveryLines:e.proposedDeliveryLines}),{status:l,messages:u}=Di({i18n:e.i18n,requiresBuyerReview:e.buyerReviewUrl!=null,requiresCaptcha:e.requiresCaptcha,violations:e.violations,receipt:e.receipt,isShippingRequired:e.readMode==="proposed"?re(t).length>0:e.isShippingRequired,hasShippingAddress:e.readMode==="proposed"?nt(e.shippingAddress):e.shippingAddress!=null,deliveryNext:e.deliveryNext,skipsShippingAddress:e.readMode==="proposed"?qi(c,t):void 0,hasUnselectableShippingGroup:$i(c,t,e.readMode)}),p=Ci(e.receipt),f=Ti(e.billingAddress,e.addressContext,e.savedCards),m=Ai(e.savedCards??[]),v=[...u,...m];return{...e.id?{id:e.id}:{},...e.continueUrl?{continue_url:e.continueUrl}:{},currency:e.runningTotal.currencyCode,status:l==="ready_for_complete"&&m.length?"incomplete":l,...l==="requires_escalation"&&e.buyerReviewUrl?{continue_url:e.buyerReviewUrl}:{},links:Ii(e.merchantPolicies),line_items:i,totals:Ui({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:f,...v.length?{messages:v}:{},...p&&{order:p}}}function $i(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=re([o]);return r.length>0&&!i.has(A(o))&&!r.every(s=>i.has(s))})}function qi(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(A(i))||re([i]).every(o=>n.has(o)))}function Hi(e){return e.every(t=>t.itemPrice!=null&&t.title!=null)}function ji({checkout:e,i18n:t,shop:n,router:i,readMode:o="negotiated",savedCards:r,declaredFields:s=new Map,paymentInstrument:a}){const d=Fi({...Gi(e,t,n,o,i),savedCards:e.isPaymentRequired.value?r:void 0});if(!d)return;const c=Fn(s),l=d.payment.instruments[0],u={...d,...a?{payment:{instruments:[Bi(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 Bi(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 Gi(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??Vi(s.fields.taxes.value),duty:e.proposal.facts.duty??zi(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,shopId:n.id,marketDrivenShippingEnabled:n.marketDrivenShippingEnabled,remoteShopsConfigMap:n.remoteShopsConfigMap,remoteMerchandiseDetails:s.fields.remoteMerchandiseDetails.value,shippingAddress:i==="proposed"?r.shippingAddress.value:l,billingAddress:e.identity.current.value==="shopPay"?void 0:Yi(e,n,i),addressContext:e.address,savedDestinations:c,proposedDeliveryLines:r.deliveryLines.value.map(f=>
1f.value),isShippingRequired:!!s.fields.isShippingRequired.value,violations:s.fields.allViolations.value,receipt:e.latestReceipt.value}}function Yi(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"?Wi(e,t):e.proposal.negotiated.fields.billingAddress.value}function Wi(e,t){const{proposed:n,negotiated:i,facts:o}=e.proposal,r=n.paymentLines.value;for(const{method:c}of r)if(c.type===te.CreditCard||c.type===te.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||!Bt(r))return a;const d=r[0]?.method;if(d?.type==="wallet"){const c=i.fields.runningTotal.value,l=c&&c.amount<=0,u=Gt(i.fields.merchandiseLines.value?.lines).some(f=>!!f.sellingPlan?.subscriptionDetails);if((!l||u||i.fields.deferredTotal.value?.amount.amount)&&(d.name==="GOOGLE_PAY"||d.name==="APPLE_PAY"||d.name==="PAYPAL_EXPRESS"&&an({checkout:e,shop:t,paymentMethods:i.fields.paymentMethods.value})))return a}return o.delivery?.[0]?.deliveryAddress??n.shippingAddress.value}function Vi(e){return e?.status==="available_total"?e.totalTax:void 0}function zi(e){return e?.status==="available_total"?e.totalDuty:void 0}const Be="store_credit",Xi=1e4;function Ki(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,Xi),o=tt(()=>{i.settling.value||s()})}).then(()=>{clearTimeout(r),o()})};return{key:Be,read(){const i=e();if(i?.available.value)return{key:Be,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 Ge="tax_number",Ji=["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 Zi(e){const t={key:Ge,read(){const n=Ye(e);if(!n)return;const{title:i,value:o,required:r}=n.fields;return{key:Ge,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=Ye(e);if(!i)return!1;const{value:o}=i.fields;return o.value=n??"",!0}}}};return t}function Ye(e){const n=e.proposal.proposed.localizationExtensions.value.flatMap(i=>Ji.some(r=>r===i.fields.key.value)?[i]:[]);return n.length===1?n[0]:void 0}function we(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 ye(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 Qi(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=we(t.merchandiseLines.value,r);if(!eo(o,n)){e.applyMethodChange(n,o,i);return}B(()=>{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 eo(e,t){return e.length>0&&e.every(n=>n==="SHIPPING"||n==="LOCAL"?t.includes("SHIPPING")||t.includes("LOCAL"):t.includes(n))}function to(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 K(e,t){return{...e,ucp:to(S(e)?"error":"success",t.proposal.negotiated.fields.ucp.value?.paymentHandlers)}}function no({checkout:e,shopPay:t}){const n=cn({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(Yt).filter(({id:l})=>l!==Wt).sort(Vt),a=zt(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)&&!dn(u,i,o,r)}})}}function We(e){return e?.replace(/[\s-]/g,"").toUpperCase()}function io(e,t){return!!e?.coordinates&&e?.countryCode===t.countryCode&&(!t.zoneCode||e.zoneCode===t.zoneCode)&&We(e.postalCode)===We(t.postalCode)}function ce(e,{checkout:t},n){const i=e.fulfillmentMethods.methods;if(i.length>1)return O("At most one fulfillment method is supported.");const o=i[0];if(o?.id!==void 0&&o.id!==o.type)return O("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(h=>h.value),d=we(r.merchandiseLines.value,a),c=ye(a,d);if(c.some(U)&&c.some(le)){const h=s.fields.deliveryNext.value,C=h?.status==="filled"||h?.status==="partial"?h.lines.filter(I=>I.status==="available"):[],D=a.map(I=>{const T=(C.find(({id:L})=>!!I.id&&L===I.id)??C.find(L=>V(L.targetMerchandiseLines,I.targetMerchandiseLines.filter(x=>x.requiresShipping).map(A))))?.methods.find(({handle:L,methodType:x})=>L===I.deliveryMethodHandle&&I.deliveryMethodTypes.includes(x))?.methodType??(I.deliveryMethodHandle?void 0:I.deliveryMethodTypes[0]);return T?{...I,deliveryMethodTypes:[T]}:I}),k=ye(D,d);if(k.some(U)&&k.some(le))return O("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(U)?"pickup":void 0),u=!!(e.context&&!_e(r.locationAddress.value,e.context));if(u&&l!=="pickup")return O("Changing context locality requires a pickup method.");if(!o&&l!=="pickup")return;const p=h=>l==="pickup"?U(h):le(h);if(o&&(o.selected_destination_id!==void 0||o.groups.length))return u||c.length&&!c.some(p)?O("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(h=>h==="PICKUP_POINT"))return u?O("Pickup-point locality discovery is not supported. Select an existing destination instead."):void 0;if(!d.size)return O("This checkout has no physical items to fulfill.");if(l==="pickup"&&e.context){const h=r.shippingAddress.value?.countryCode||r.locationAddress.value?.countryCode;if(!h)return O("Pickup search requires an established checkout country. Ask the buyer to choose a country in checkout.");if(e.context.address_country!==h)return O("Pickup search must remain in the checkout country.")}if(!n&&!u&&c.every(p)&&c.length)return;const f=!c.length||!c.every(p);if(!n&&f)return O("The delivery selector is not ready.");const m=n?n.getAvailableMethodTypes().find(h=>l==="pickup"?h.includes("PICK_UP"):h.some(p)):c;if(!m)return O(`The checkout does not offer ${l}.`);const v=s.fields;return(f||u)&&(v.mustSelectProvidedShippingRate.value||v.mustSelectProvidedAddress.value||v.canUpdateDeliveryAddress.value===!1)?O("The checkout locks its delivery method or address."):{methodTypes:m,needsLocalityLookup:u,changesMo
1de:f}}function le(e){return e==="SHIPPING"||e==="LOCAL"}function _e(e,t){return io(e,{countryCode:t.address_country,zoneCode:t.address_region,postalCode:t.postal_code})}const j={status:"written"};function oo(e){return e.paymentLines.value.some(t=>t.method.type===te.CreditCard||t.method.type===te.PayPal||ro(t))}function ro(e){if(e.method.type!=="wallet")return!1;switch(e.method.name){case"APPLE_PAY":return nn(e);case"GOOGLE_PAY":return tn(e);case"PAYPAL_EXPRESS":return en(e);default:return!1}}const so=({buyer:e},{checkout:t,shopPay:n})=>{const i=ln({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,j}}},yt=({shippingAddress:e},t)=>{if("saved_address_id"in e)return co(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=bt(e.address_country,"fulfillment.methods[0].destinations[0].address_country",t.shop);if(a)return a;const d=ne(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(),j)}}};function Ve(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)?j:{status:"failed"}}}:{status:"rejected",field:"payment"}}function ao(e,{readSavedCards:t}){return!!t()?.some(({instrument:n,usable:i})=>n.id===e&&n.selected&&i)}function co(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=bt(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(),j):{status:"failed"}}}}function ge({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(Io):[],a=new Map;for(const c of i.deliveryLines.peek()){const{id:l,targetMerchandiseLines:u,deliveryMethodTypes:p,deliveryMethodHandle:f}=c.peek();if(p.filter(Q).length===0)continue;const h=(s.find(C=>!!l&&C.id===l)??s.find(C=>V(C.targetMerchandiseLines,u.filter(D=>D.requiresShipping).map(A))))?.methods.find(C=>C.handle===f);if(h){if(!Q(h.methodType))continue}else if(oi(f,p,h))return{status:"rejected",field:"fulfillmentMethods"};a.set(c,{deliveryLine:c,selectedOptionId:void 0,selectedOptionDetails:void 0})}try{for(const c of go(e,i.deliveryLines.peek(),s))a.set(c.deliveryLine,c)}catch(c){if(!(c instanceof $))throw c;return{status:"rejected",field:"fulfillmentMethods",reason:c.reason}}const d=o.fields.mustSelectProvidedShippingRate.peek();return[...a.values()].some(({deliveryLine:c,selectedOptionId:l})=>!ri(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(Q)))continue;
1const{selectedOptionId:u,selectedOptionDetails:p}=l??{};c.value={...c.peek(),deliveryMethodHandle:u,deliveryMethodOptions:Eo(p),...u===void 0&&{isCustomRate:void 0,customDeliveryStrategy:void 0}}}return j}}}const lo=({discountCodes:e=[]},t)=>{const{proposed:n,negotiated:i}=t.checkout.proposal,o=new Map,r=[];for(const s of n.discountLines.value){const{discount:a}=s;if(a.type==="code"||a.type==="discountCodeTrigger"){const d=a.title.toUpperCase(),c=o.get(d);c?c.push(s):o.set(d,[s])}else r.push(s)}if(i.fields.canUpdateDiscountCodes.value===!1){const s=new Set(e.map(d=>d.toUpperCase()));return s.size===o.size&&[...s].every(d=>o.has(d))?void 0:{status:"rejected",field:"discountCodes"}}return{status:"ready",negotiation:{include:["discountLines","deliveryNext"],loading:["discountLines","deliveryNext"],fieldsToResolve:["discountLines","totalSavings","merchandiseLines","deliveryNext"]},async apply(){const s=new Set;for(const a of e){const d=a.toUpperCase();if(s.has(d))continue;s.add(d);const c=o.get(d);c?r.push(...c):r.push({title:a,discount:{type:"discountCodeTrigger",title:a}})}return B(()=>{n.discountLines.value=r,n.reduction.value=void 0;const{discountCodeWarningSignal:a,currentDiscountCodeAttemptSignal:d}=t.negotiator.context;a.value=null,d.value=null}),j}}},uo=[so,lo,yt,ge];function ze(e,t,{fulfillmentRequest:n,fulfillment:i,locationAddress:o}={}){const r=[];for(const s of uo){if(s===yt&&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),j}})}const a=s===ge?ge(e,t,n!==void 0):s(e,t);if(a!==void 0){if(a.status==="rejected")return gt(a.field,a.reason);r.push(a)}}return r}class _t{#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 S(r)?r:(B(()=>{r?.apply(),o?.apply()}),{status:"applied"})}#t(t){const{checkout:n}=this.#e;if(!q(n))return;const i=t===void 0?void 0:ne(t,n.address);return{apply({replacement:o=!1}={}){if(!q(n))return!1;const{proposed:r,negotiated:s,facts:a}=n.proposal,d=s.fields.isShippingRequired.value===!1;if(i&&!Xt(i)&&(d||!yo(i,n)))return B(()=>{r.billingAddress.value=i,r.billingAddressOption.value="custom"}),!0;if(o&&d)return a.billingAddress||oo(r)?!1:(B(()=>{r.billingAddress.value=ne({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(!q(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=Kt(a??[],d?.method.type==="direct"&&!!d.method.alternative);return t&&(t.handler_id==="shopify.card"?!c:!i.hasFlagEnabled(Jt)||!Zt(a))?Ln():{apply(){q(n)&&B(()=>{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=Ne(r.paymentLines.value,{method:{type:"direct",paymentMethodIdentifier:c.paymentMethodIdentifier,alternative:c.alternative}},Re(i))):t.handler_id==="shop_pay"&&t.credential?.approval_id&&(r.paymentLines.value=Ne(r.paymentLines.value,{method:{type:"shopWallet",shopPayApprovalId:t.credential.approval_id}},Re(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,q(this.#e.checkout)?o:void 0]),n?.())return E();if(this.#e.isSubmitting.value)return Y();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 E();let s=Z(t.declaredFields,this.#e.declaredFields);if(S(s))return s;if(s.some(({changed:y})=>y)){if(await this.#e.waitForPendingNegotiations(),n?.())return E();if(this.#e.isSubmitting.value)return Y();if(s=Z(t.declaredFields,this.#e.declaredFields),S(s))return s}let a=this.#e.getFulfillmentController?.(),d=ce(t,this.#e,a);if(S(d))return d;let c;if(d?.needsLocalityLookup&&t.context){try{const y=this.#e.resolvePickupLocality;if(!y)throw new ue;c=await y(t.context)}catch(y){return this.#e.observability.error(y instanceof ue?y:new ue(y)),n?.()?E():kn()}if(n?.())return E();if(!c)return Pn();if(s=Z(t.declaredFields,this.#e.declaredFields),S(s))return s}if(t.context){const y=this.#e.checkout.proposal.proposed.locationAddress.value;_e(y,t.context)&&(c=y)}if(a=this.#e.getFulfillmentController?.(),d=ce(t,this.#e,a),S(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(S(p))return p;let f=r===void 0?void 0:Ve(r,this.#e);if(f?.status==="rejected")return gt(f.field);let m=ze(t,this.#e,{fulfillmentRequest:d,fulfillment:a,locationAddress:c});if(S(m))return m;if(n?.())return E();const v=[];let h=!1;for(const y of["negotiate","stage"]){if(y==="stage"&&h&&(s=Z(t.declaredFields,this.#e.declaredFields),S(s)))return E();for(const T of s)if(!(T.phase!==y||!T.changed)){if(n?.())return E();try{if(!await T.apply()||n?.())return E()}catch{return E()}if(T.phase==="stage")v.push(T.negotiation);else if(h=!0,a=this.#e.getFulfillmentController?.(),d=ce(t,this.#e,a),S(d)||(m=ze(t,this.#e,{fulfillmentRequest:d,fulfillment:a,locationAddress:c}),S(m))||(l=this.#t(o),p=this.#n(u),S(p))||(f=r===void 0?void 0:Ve(r,this.#e),f?.status==="rejected"))return E()}}if(p){const y=p;m.push({status:"ready",negotiation:{include:["paymentLines"],loading:["paymentLines"],fieldsToResolve:["paymentLines"]},async apply(){return y.apply(),j}})}if(!f&&m.length===0&&v.length===0&&!l)return{status:"applied"};if(n?.())return E();if(this.#e.isSubmitting.value)return Y();if((await Promise.all(B(()=>m.map(y=>y.apply())))).find(y=>y.status==="failed")||n?.())return E();if(this.#e.isSubmitting.value)return Y();if(f){if((await f.apply()).status==="failed"||n?.()||(await this.#e.waitForPendingNegotiations(),n?.()))return E();if(this.#e.isSubmitting.value)return Y()}const k=l?.apply({replacement:!0})??!1;if(!f&&m.length===0&&v.length===0&&!k)return{status:"applied"};const I=await this.#i(fo([...m.map(y=>y.negotiation),...v,...f?[f.negotiation]:[],...k?[{include:["billingAddress"],loading:["billingAddress"],fieldsToResolve:["billingAddress"]}]:[]]));await this.#e.waitForPendingNegotiations();const b=ho(I);if(r!==void 0&&!ao(r,this.#e))return E();if(!S(b)&&!n?.()&&d?.needsLocalityLookup&&c&&t.context&&_e(this.#e.checkout.proposal.proposed.locationAddress.value,t.context)){const{proposed:y}=this.#e.checkout.proposal,T=y.deliveryLines.value.map(F=>F.value),L=we(y.merchandiseLines.value,T),x=ye(T,L);x.length&&x.every(U)&&this.#e.announcePickupLocality?.(c)}return n?.()?E():b}async loadAddressMetadata(t){const n=new Set;for(const o of t){const r=o?.address_country?.toUpperCase();o&&r&&po(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}}
1class ue extends Error{constructor(t){super("WebMCP pickup locality lookup failed",{cause:t}),this.name="WebMcpLocalityLookupError"}}function po(e,t){const n=!!(t.street_address||t.street_name||t.street_number),i=!!(t.extended_address||t.district),o=Ce(e,"")!==null,r=Te(e,"")!==null;return n&&o||i&&r}function fo(e){return{include:pe(e,"include"),loading:pe(e,"loading"),fieldsToResolve:pe(e,"fieldsToResolve")}}function pe(e,t){return[...new Set(e.flatMap(n=>n[t]))]}function ho(e){return e?.status==="success"||e?.status==="error"?{status:"applied"}:E()}const mo={context:"context",buyer:"buyer",discountCodes:"discounts",declaredFields:"declared_fields",shippingAddress:"fulfillment",fulfillmentMethods:"fulfillment",payment:"payment"};function yo(e,t){const n=Pe(t.proposal.proposed.shippingAddress.value,t.address);return Qt(e,ne(n,t.address))}function gt(e,t){return t instanceof vt?Cn(t.path,t.countryCode,t.listedCountryCodes):t==="unsupported_option_instructions"?Ue("instructions"):t==="unsupported_option_phone"?Ue("phone_number"):t==="unknown_fulfillment_group"?Tn():t==="unselectable_fulfillment_group"?An():t==="unknown_fulfillment_option"?Sn():In(mo[e])}class $ extends Error{constructor(t){super(t),this.name="WebMcpFulfillmentMethodUpdateError",this.reason=t}}const _o=20;class vt 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 bt(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 vt(i,t,n.length<=_o?n.map(({value:o})=>o):void 0)}}function go(e,t,n){return e.methods.flatMap(i=>i.type==="pickup"?vo(i,t,n):i.groups.map(o=>{const r=Et(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||z(r)!=="shipping")throw new $("unknown_fulfillment_option");return ve(r,s,o.selected_option_details,t)}))}function vo(e,t,n){const i=e.selected_destination_id===void 0?void 0:pt(n).find(({id:r})=>r===e.selected_destination_id);if(e.selected_destination_id!==void 0&&!i)throw new $("unknown_pickup_destination");const o=new Map;for(const r of e.groups){if(r.selected_option_id!==me)throw new $("unknown_fulfillment_option");const s=Et(r,n);if(z(s)!=="pickup"||i&&!i.selections.some(a=>a.line===s)||o.has(s))throw new $("unknown_fulfillment_group");o.set(s,r)}return i?i.selections.map(({line:r,method:s})=>ve(r,s,o.get(r)?.selected_option_details,t)):[...o].map(([r,s])=>{const a=r.methods.find(d=>d.handle===r.selectedDeliveryMethodHandle&&U(d.methodType)&&d.pickupLocation);if(!a)throw new $("unknown_pickup_destination");return ve(r,a,s.selected_option_details,t)})}function Et(e,t,n="unknown_fulfillment_group"){const i=t.find(o=>!!e.id&&o.id===e.id)??t.find(o=>V(o.targetMerchandiseLines,e.line_item_ids));if(!i)throw new $(n);return i}function ve(e,t,n,i){const o=i.find(r=>!!e.id&&r.value.id===e.id)??i.find(r=>V(r.value.targetMerchandiseLines,e.targetMerchandiseLines?.filter(s=>s.requiresShipping).map(A)));if(!o)throw new $("unknown_fulfillment_group");if(!o.value.deliveryMethodTypes.includes(t.methodType))throw new $("unsupported_fulfillment_transition");return bo(t,n),{deliveryLine:o,selectedOptionId:t.handle,selectedOptionDetails:n}}function bo(e,t){if(t){if(t.instructions!==void 0&&!ie(e,"instructions"))throw new $("unsupported_option_instructions");
1if(t.phone_number!==void 0&&!ie(e,"phone_number"))throw new $("unsupported_option_phone")}}function Eo(e){return{phone:e?.phone_number,instructions:e?.instructions}}function Io(e){return e.status==="available"}const Xe=Nt()(["shipping","pickup"]);class _ extends Error{constructor(t,n,i,{loggablePath:o=t}={}){super(`${t}: expected ${n}, got ${i} instead.`),this.name="WebMcpInputError",this.expected=n,this.loggablePath=o}}const It='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.',Ct={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)."}},Co={type:"object",description:`Replacement address. Include all fields to retain; omitted fields are cleared. Use PUT semantics, not PATCH. ${It}`,properties:Ct},ee={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:Co}}}}};function To(e,{ignorePayment:t=!1}={}){const n=M(e,"input");return Ee({object:n,allowedFields:["payment"],path:"input"}),t||n.payment===void 0?{}:{payment:Tt(n.payment,{path:"input.payment",requireCredential:!0})}}function Tt(e,{path:t,requireCredential:n=!1,savedPaymentMethodsOnly:i=!1}){const o=M(e,t);if(!n&&(o.instruments===void 0||Array.isArray(o.instruments)&&o.instruments.length===0))return;const r=`${t}.instruments[0]`,s=qo(o.instruments,`${t}.instruments`);if(!n&&i)return Mo(s,r);const a=s.handler_id;if(!n&&a===void 0&&s.credential===void 0){const m=Ke(s,r);return m===void 0?void 0:{billing_address:m}}if(a!=="shopify.card"&&a!=="shop_pay")throw new _(`${r}.handler_id`,"shopify.card or shop_pay","an unsupported handler");const d=H(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 _(`${r}.type`,c,"an unsupported instrument type");const l=Ke(s,r),u={id:d.id??on(),...l===void 0?{}:{billing_address:l}},p=`${r}.credential`,f=!n&&s.credential===void 0?void 0:M(s.credential,p);if(a==="shopify.card"){if(f===void 0)return{...u,handler_id:a,type:"card"};if(Ee({object:f,allowedFields:["type","token"],path:p}),f.type!==void 0&&f.type!=="shopify_token")throw new _(`${p}.type`,"shopify_token","an unsupported credential type");return{...u,handler_id:a,type:"card",credential:{type:"shopify_token",...n||f.token!==void 0?{token:be(f.token,`${p}.token`)}:{}}}}if(f===void 0)return{...u,handler_id:a,type:"shop_pay"};if(Ee({object:f,allowedFields:["type","approval_id"],path:p}),f.type!==void 0&&f.type!=="shop_token")throw new _(`${p}.type`,"shop_token","an unsupported credential type");return{...u,handler_id:a,type:"shop_pay",credential:{type:"shop_token",...n||f.approval_id!==void 0?{approval_id:be(f.approval_id,`${p}.approval_id`).trim()}:{}}}}function be(e,t){if(typeof e!="string"||e.trim().length===0)throw new _(t,"a non-empty string",P(e));return e}function Ke(e,t){if(e.billing_address!==void 0)return H(e.billing_address,St,`${t}.billing_address`)}function Ee({object:e,allowedFields:t,path:n}){if(Object.keys(e).some(i=>!t.includes(i)))throw new _(n,"only supported fields","extra properties")}
1const At={email:"",phone_number:""},W={first_name:"",last_name:"",phone_number:"",street_address:void 0,extended_address:void 0,address_locality:"",address_region:"",address_country:"",postal_code:""},St={...W,company:void 0,street_name:void 0,street_number:void 0,district:void 0},Je={phone_number:void 0,instructions:void 0};function Ao(e,t={}){const n=Po(e,t);return ko(So(),n)}function So(){return{buyer:{...At},discountCodes:[],declaredFields:[],shippingAddress:{...W},fulfillmentMethods:{methods:[]},payment:void 0}}function ko(e,t){return{...e,...t,buyer:{...e.buyer,...t.buyer}}}function Po(e,t){const n=M(M(e,"input").checkout,"input.checkout"),i={};if(n.context!==void 0){const o="input.checkout.context",r=H(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 _(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=H(n.buyer,At,"input.checkout.buyer")),n.discounts!==void 0&&(i.discountCodes=Do(n.discounts)??[]),n.declared_fields!==void 0&&(i.declaredFields=wo(n.declared_fields)),n.fulfillment!==void 0&&Object.assign(i,No(n.fulfillment)),!t.ignorePayment&&n.payment!==void 0&&(i.payment=Tt(n.payment,{path:"input.checkout.payment",savedPaymentMethodsOnly:t.savedPaymentMethodsOnly})),i}const Lo=new Set(["purpose","title","description","value_schema","presentation","required"]);function wo(e){const t="input.checkout.declared_fields";if(!Array.isArray(e))throw new _(t,"an array",P(e));const n=new Set;return e.map((i,o)=>{const r=`${t}[${o}]`,s=M(i,r);for(const a of Object.keys(s))if(!["key","value"].includes(a)&&!Lo.has(a))throw new _(`${r}.${a}`,"a declared field key or value","an unknown field",{loggablePath:r});if(typeof s.key!="string"||s.key.length===0)throw new _(`${r}.key`,"a non-empty string",P(s.key));if(n.has(s.key))throw new _(`${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 _(`${r}.value`,"a value","undefined");return{key:s.key,value:s.value}})}function Mo(e,t){for(const n of Object.keys(e))if(!["id","type","selected","display"].includes(n))throw new _(`${t}.${n}`,"a saved instrument id from get_checkout, not new payment data","an unsupported field",{loggablePath:t});return{instrument_id:be(e.id,`${t}.id`)}}function Do(e){const t="input.checkout.discounts",{codes:n}=M(e,t);if(n!==void 0){if(!kt(n))throw new _(`${t}.codes`,"an array of strings",P(n));return n}}function No(e){const t="input.checkout.fulfillment",n=M(e,t);if(!Array.isArray(n.methods))throw new _(`${t}.methods`,"an array",P(n.methods));if(n.methods.length>1)throw new _(`${t}.methods`,"at most 1 fulfillment method",`${n.methods.length} methods`);let i={...W};const o=[];for(const[r,s]of n.methods.entries()){const a=`${t}.methods[${r}]`,d=M(s,a),c=Ro(d.type??"shipping",`${a}.type`),{id:l}=H(d,{id:void 0},a),u={...l!==void 0&&{id:l}},p=d.groups===void 0?[]:Fo(d.groups,`${a}.groups`),f=Uo(d,a);switch(c){case"pickup":{f===void 0&&Oo(d.destinations,`${a}.destinations`),o.push({...u,type:c,...f!==void 0&&{selected_destination_id:f},groups:p});break}case"shipping":{i=f===void 0?xo(d,a):{saved_address_id:f},o.push({...u,type:c,groups:p});break}default:Dt(c)}}return{shippingAddress:i,fulfillmentMethods:{methods:o}}}function Ro(e,t){const n=Xe.find(i=>i===e);if(n!==void 0)return n;throw new _(t,Xe.map(i=>JSON.stringify(i)).join(" or "),typeof e=="string"?JSON.stringify(e):P(e))}function Oo(e,t){if(e!==void 0){if(!Array.isArray(e))throw new _(t,"an array",P(e));for(const[n,i]of e.entries()){const o=M(i,`${t}[${n}]`);if(o.type!=="business_location")throw new _(`${t}[${n}].type`,'a read-only "business_location" from get_checkout; select pickup through selected_destination_id',P(o.type))}}}function Uo(e,t){if(e.selected_destination_id===null)return;const{selected_destination_id:n}=H(e,{selected_destination_id:void 0},t);
1if(n==="")throw new _(`${t}.selected_destination_id`,"a non-empty string or null","an empty string");return n}function xo(e,t){const n=`${t}.destinations[0]`,i=`${t}.destinations`,{destinations:o}=e;if(o===void 0)return{...W};if(!Array.isArray(o))throw new _(i,"an array",P(o));if(o.length===0)return{...W};if(o.length!==1)throw new _(i,"1 item",`${o.length} items`);const r=M(o[0],n);if(r.pickup_location_address!==void 0||r.type==="business_location")throw new _(n,"a flat shipping address","a pickup location");const s=H(r,St,n);return{...W,...s,address_country:(s.address_country??"").trim()}}function Fo(e,t){if(!Array.isArray(e))throw new _(t,"an array",P(e));return e.flatMap((n,i)=>{const o=`${t}[${i}]`,r=M(n,o),s=r.selected_option_id,a=r.selected_option_details;if(s===void 0){if(a!==void 0)throw new _(`${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 _(`${o}.selected_option_id`,"a string",P(s));const d=r.id;if(typeof d!="string")throw new _(`${o}.id`,"a string",P(d));const c=r.line_item_ids;if(c!==void 0&&!kt(c))throw new _(`${o}.line_item_ids`,"an array of strings",P(c));const l={...Je,...H(a===void 0?{}:a,Je,`${o}.selected_option_details`)};return[{id:d,line_item_ids:c,selected_option_id:s,selected_option_details:l}]})}function M(e,t){if(!$o(e))throw new _(t,"an object",P(e));return e}function $o(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function qo(e,t){if(!Array.isArray(e))throw new _(t,"an array",P(e));if(e.length!==1)throw new _(t,"1 item",`${e.length} items`);return M(e[0],`${t}[0]`)}function H(e,t,n){const i=M(e,n),o={};for(const r in t){if(!Object.hasOwn(i,r))continue;const s=i[r];if(typeof s!="string")throw new _(`${n}.${r}`,"a string",P(s));o[r]=s}return o}function kt(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function P(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?"an array":typeof e=="object"?"an object":`a ${typeof e}`}const Me="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.",Ho={type:"object",additionalProperties:!1,properties:{payment:{...ee,required:["instruments"],properties:{instruments:{...ee.properties.instruments,minItems:1,items:{...ee.properties.instruments.items,required:["handler_id","credential"]}}}}}};class jo extends Error{constructor(){super("WebMCP complete_checkout failed"),this.name="WebMcpCompleteCheckoutError"}}function Ze(e){return!!(e?.handler_id==="shopify.card"?e.credential?.token:e?.credential?.approval_id)}function Bo(e){return e.status==="invalid"?e.reasons:"violations"in e?[...e.violations,...e.errors].map(({code:t})=>t):[]}function Go(e){const t=Bo(e);return{progressionStatus:e.status,...t.length>0&&{progressionReasons:[...new Set(t)].sort().join(",")}}}function Yo({isSubmitting:e,paymentInstrument:t,signal:n,checkout:i,shop:o,readCheckout:r,readSavedCards:s,shopPay:a,observability:d,getPreactContext:c,declaredFields:l}){let u=!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. ${Me}
1`,inputSchema:Ho,annotations:{consequentialHint:!0,readOnlyHint:!1,untrustedContentHint:!0},execute:async f=>K(await p(f),i)};async function p(f){if(u||e.value)return wn();u=!0;try{if(!o.hasFlagEnabled(rn))return Mn();const{payment:m}=To(f,{ignorePayment:!q(i)}),v=i.latestReceipt.value?.status;if(v==="processing"||v==="processing_remote_checkouts"||v==="polling_for_order"||v==="processed"||v==="action_required")return r()??J();const h=c();if(!h||n?.aborted)return de();if(q(i)&&(m||t.value)){if(await h.waitForPendingNegotiations(),n?.aborted)return de();const b=q(i)?m??t.value:void 0;if(b&&m&&!i.isPaymentRequired.value)return Dn();if(b&&Ze(b)&&i.isPaymentRequired.value){const y=new _t({isSubmitting:e,paymentInstrument:t,checkout:i,shop:o,shopPay:a,observability:d,declaredFields:l,...h,readSavedCards:s});if(m&&(await y.loadAddressMetadata([m.billing_address]),n?.aborted))return de();const T=y.writePayment({payment:b,applyBilling:m!==void 0});if(S(T))return T}}let C=!1,D=!1,k={progressionStatus:"none"};try{e.value=q(i)&&i.isPaymentRequired.value&&Ze(t.value),await h.journey.progress("web-mcp-complete-checkout",b=>{k=Go(b),C=b.status==="success"||b.status==="alreadyCompleted",D||="negotiated"in b||"receipt"in b})}finally{e.value&&D&&(t.value=void 0),e.value=!1}const I=r();return!C&&!I?.messages?.some(b=>b.type==="error"&&b.severity==="requires_buyer_input")?J("completion_failed",k):I??J("completion_failed",k)}catch(m){return m instanceof _?ot(m,"complete the checkout"):(d.error(new jo),J("internal_error"))}finally{u=!1}}}class Wo extends Error{constructor(){super("WebMCP get_checkout failed to read the checkout"),this.name="WebMcpGetCheckoutError"}}function Vo({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. ${Me}`,inputSchema:{type:"object",properties:{}},annotations:{consequentialHint:!1,readOnlyHint:!0,untrustedContentHint:!0},execute:()=>K(i(),e)};function i(){try{const o=t(e.latestReceipt.value?.status==="processed"?"negotiated":"proposed");return o||bn()}catch{return n.error(new Wo),En()}}}const zo=3e4;class Xo extends Error{constructor(t){super("WebMCP navigate_to_storefront failed",{cause:t}),this.name="WebMcpStorefrontNavigationError"}}function Pt({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 Ko({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)=>K(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 Nn();if(c.aborted||o.aborted)return xe();const u=r();if(!u)return Rn();if(a(u))return Fe();const p=Pt({shop:t,url:n});if(!p)return xn();const f=new Promise(v=>{l=setTimeout(()=>v("timeout"),zo)}),m=await Promise.race([u.waitForPendingNegotiations(),f]);return c.aborted||o.aborted?xe():m==="timeout"?(i.log("web_mcp_storefront_navigation_timed_out","Storefront navigation timed out waiting for pending checkout updates"),On()):a(u)?Fe():(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 Xo(u)),Un()}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)}}const Qe=3e4,Jo={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:{...ee,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. ${It}`,properties:Ct}},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"}}}}}}}}}}}}}}},Zo="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 Qo extends Error{constructor(){super("WebMCP update_checkout failed to apply"),this.name="WebMcpUpdateCheckoutError"}}function er({isSubmitting:e,paymentInstrument:t,signal:n,checkout:i,shop:o,shopPay:r,router:s,getSavedCardSelector:a,readCheckout:d,readSavedCards:c,observability:l,getPreactContext:u,declaredFields:p,getFulfillmentController:f}){return{name:"update_checkout",title:"Update checkout",description:`${Zo} ${Me}`,inputSchema:Jo,annotations:{consequentialHint:!1,readOnlyHint:!1,untrustedContentHint:!0},execute:async v=>K(await m(v),i)};async function m(v){let h;try{if(e.value)return Y();const C=i.identity.current.value==="shopPay",D=Ao(v,{savedPaymentMethodsOnly:C,ignorePayment:C?!i.isPaymentRequired.value:!q(i)}),k=u();if(!k||n?.aborted||(s.currentUrl.value.normalizedPath==="/review"&&s.navigate("/"),D.payment&&"instrument_id"in D.payment&&!a()))return Oe();const{loadPickupLocalityServices:I}=k;let b;const y=new _t({isSubmitting:e,paymentInstrument:t,checkout:i,shop:o,shopPay:r,getSavedCardSelector:a,observability:l,declaredFields:p,...k,readSavedCards:c,getFulfillmentController:f,resolvePickupLocality:I?async F=>(b=await I(),b.resolvePickupLocality(F)):void 0,announcePickupLocality:F=>b?.announcePickupLocality(F),get negotiator(){return k.negotiator}});let T=!1;const L=new Promise(F=>{h=setTimeout(()=>{T=!0,F("timeout")},Qe)}),x=await Promise.race([y.applyUpdate(D,{isExpired:()=>T||!!n?.aborted}),L]);return x==="timeout"?(l.log("web_mcp_update_timed_out","[WebMcp] Update did n
1ot finish in time; update outcome is unknown",{timeoutMs:Qe}),E()):S(x)?x:d()??E()}catch(C){return C instanceof _?ot(C,"update the checkout"):(l.error(new Qo),E("internal_error"))}finally{clearTimeout(h)}}}function tr(e){return typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="object"}function nr(e){if(typeof e!="object"||e===null||!("error"in e))return"unknown";const{error:t}=e;return typeof t!="object"||t===null||!("code"in t)?"unknown":fn(t.code)?t.code:"unknown"}function Ie(e,t,n,i){const o=Math.round(performance.now()-i),r=tr(n),s={tool:t,outcome:r?"error":"success",...r&&{errorCode:nr(n)}};e.log("web_mcp_tool_executed","[WebMcp] tool executed",{...s,...hn(n),durationMs:o}),e.histogram({name:"web_mcp_tool_execution",value:o,unit:"ms",attributes:s})}function et(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=K(vn(),i);return Ie(n,o,a,s),a}return t.during(o,async()=>{const a=await e.execute(...r);return Ie(n,o,a,s),a})}}}function ir(e,t){const n=e.name;return{...e,execute:(...i)=>{const o=performance.now(),r=e.execute(...i);return Ie(t,n,r,o),r}}}class or extends Error{constructor(t,n){super(`WebMCP tool registration failed for ${t}: ${String(n)}`),this.name="WebMcpRegistrationError",n instanceof Error&&(this.cause=n)}}function rr(e,t){const n=new AbortController,i=tt(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 sr({modelContext:e,signal:t,isSubmitting:n,paymentInstrument:i,checkout:o,i18n:r,shop:s,shopPay:a,url:d,router:c,observability:l,activeTool:u,onActiveToolCreated:p,getPreactContext:f,markToolCallStarted:m,getSavedCardSelector:v,declaredFields:h,getFulfillmentProvider:C,getStoreCreditProvider:D,unregisterInitializingTool:k}){if(t.aborted)return;const I=no({checkout:o,shopPay:a}),b=N=>ji({checkout:o,i18n:r,shop:s,router:c,readMode:N,savedCards:I(),declaredFields:h,paymentInstrument:i.value}),y=Zi(o);h.set(y.key,y);const T=Ki(()=>D?.());h.set(T.key,T);const L=u??new un;p?.(L);const F=[{tool:ir(Vo({checkout:o,readCheckout:b,observability:l}),l),signal:t}],De=rr(o,t);De.aborted||F.push(...[er({isSubmitting:n,paymentInstrument:i,signal:t,checkout:o,shop:s,shopPay:a,router:c,getSavedCardSelector:v,readCheckout:b,readSavedCards:I,observability:l,getPreactContext:f,declaredFields:h,getFulfillmentController:()=>{const N=C?.();return N?Qi(N,o.proposal):void 0}}),Yo({isSubmitting:n,paymentInstrument:i,signal:t,checkout:o,shop:s,shopPay:a,readCheckout:b,readSavedCards:I,observability:l,getPreactContext:f,declaredFields:h})].map(N=>({tool:et(N,{activeTool:L,observability:l,checkout:o}),signal:De}))),Pt({shop:s,url:d})&&F.push({tool:et(Ko({checkout:o,shop:s,url:d,observability:l,signal:t,getPreactContext:f}),{activeTool:L,observability:l,checkout:o}),signal:t}),k?.();const Lt=F.map(async({tool:N,signal:G})=>{try{return await e.registerTool({...N,execute(se,wt){return m(),N.execute(se,wt)}},{signal:G}),"registered"}catch(se){return G.aborted?"withdrawn":(l.error(new or(N.name,se)),"failed")}});return Promise.all(Lt).then(N=>{t.aborted||l.log("web_mcp_tools_registered","[WebMcp] tools registered",{registered:N.filter(G=>G==="registered").length,failed:N.filter(G=>G==="failed").length})}).catch(()=>{}),L}const fr=Object.freeze(Object.defineProperty({__proto__:null,registerWebMcpTools:sr},Symbol.toStringTag,{value:"Module"}));export{We as n,fr 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.