1import{ah as e,t,n,L as i,G as o,ac as s}from"./2c1ab0fe.Bywc2Brn.js";import{gM as r,hc as a,gN as d,hd as c,he as l,fp as u,gs as p,as as h,hf as m,bp as f,f8 as y,gw as _,g5 as g,K as v,a7 as b,hg as k,cK as C,bt as A,hh as w,hi as S,hj as I,bL as T,hk as E,cx as N,cy as P,cz as L,dk as D,Z as M,dj as R,c7 as O,hl as x,hm as U,hn as q}from"./9dba8418.DInoCEzY.js";import{c as j,a as $}from"./f67abd2c.CxgiarJo.js";import{r as H}from"./9ce08e25.DbZR-P3G.js";import{c as B}from"./cadec7c0.YKwcKXv2.js";import{h as F,a as G,i as Y}from"./6a2fc6d6.CktMoRVE.js";import{i as W}from"./8599b02a.83fij-dk.js";import{s as z}from"./08a3b809.5tqP2mr3.js";import{m as X}from"./9655ebc9.CX4pB1Ku.js";import{u as V}from"./app.D2wFhSFv.js";import"./2495faa4.Tu9qVTlu.js";import"./cf29e63b.Cl-tFGZz.js";import"./2bac2c53.gEGJwgcc.js";import"./cb38e5c2.BxvsOkWl.js";import"./2255f8fa.8KqxH4Pm.js";import"./d25d1b95.DsyU8-pY.js";import"./b8733b27.DhvkBeeV.js";import"./e39bc11c.gbgXD8RN.js";class K{#e;#t=0;get current(){return this.#e}async during(e,t){this.#e=e,this.#t+=1;try{return await t()}finally{this.#t-=1,0===this.#t&&(this.#e=void 0)}}}const J=["buyer_action_required","checkout_busy","completion_failed","completion_in_progress","internal_error","invalid_request","navigation_failed","rejected","update_failed"];function Z(e){return"object"==typeof e&&null!==e&&"error"in e}const Q=Symbol("WebMcpFailureDetails");function ee(e){if(!Z(e))return;const t=e.error;return"object"==typeof t&&null!==t&&Q in t?t[Q]:void 0}function te(e,t,n){const i={code:e,message:t};return n&&Object.defineProperty(i,Q,{value:n}),{error:i}}function ne(e){return`Do not attempt to ${e} by interacting with the page.`}const ie="Retry shortly.",oe=`Checkout is still initializing. ${ie}`,se="Nothing was applied.",re=`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. ${ne("update the checkout")}`,ae=`Checkout completion could not be confirmed. Call get_checkout for the current state and its messages before retrying. ${ne("complete the checkout")}`;function de(e,t,n,i="Call get_checkout before retrying."){return te(e,`${t}: ${n} ${se} ${i}`)}function ce(e,t){return te("invalid_request",`${e.message} Correct the input and retry. ${ne(t)}`,{invalidInputPath:e.loggablePath.replace(/\[\d+\]/g,"[]"),invalidInputExpected:e.expected})}function le(){return te("internal_error",`Checkout is not available for updates. ${ie} ${ne("update the checkout")}`)}function ue(e="update_failed"){return te(e,re)}function pe(e){return te("rejected",`The selected delivery option does not support selected_option_details.${e}. ${se} Remove ${e} from selected_option_details or choose an option that supports it, then retry. ${ne("update the checkout")}`)}const he=`${se} 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. ${ne("update the checkout")}`;function me(e){return de("rejected","fulfillment",e)}function fe(e,t){return de("rejected",e,`${t}.`)}function ye(){return te("completion_in_progress","A credentialed completion is in progress. Wait for it to finish before updating payment.")}function _e(){return te("internal_error",`${oe} ${ne("complete the checkout")}`)}function ge(e="completion_failed",t){return te(e,ae,t)}function ve(){return te("navigation_failed","Navigation was cancelled. The tool did not leave checkout.")}function be(){return te("checkout_busy","Checkout submission or payment is in progress. Wait for it to finish and call get_checkout before navigating away.")}function ke(e,t){const n=e??[],i=new Map;for(const[s,{key:r,value:a}]of n.entries()){const e=`$.checkout.declared_fields[${s}]`,n=t.get(r);if(!n?.read())return fe(`${e}.key`,"must identify a declared field available in the current checkout");const o=n.prepare(a);if("requirement"in o)return fe(`${e}.value`,o.requirement);i.set(r,o)}const o=[];for(const[s,r]of t){if(!r.read())continue;const e=i.get(s)??r.prepare(null);if("requirement"in e)return fe("$.checkout.declared_fields",e.requirement);o.push({...e,get changed(){return e.changed},apply:async()=>!(t.get(s)!==r||!r.read())&&e.apply()})}return o}function Ce(t){if(!t)return 0;const n=e(t.currencyCode),i=new Intl.NumberFormat("en",{style:"decimal",useGrouping:!1,minimumFractionDigits:n,maximumFractionDigits:n}),[o,s=""]=i.format(t.amount).split(".");return Number(o+s.padEnd(n,"0"))}function Ae(e,t){const{discount:n}=e,i=[];let o=0,s=!1;for(const{target:d}of e.allocations){let e=d.index;if("MERCHANDISELINE"===d.type&&t&&(e=null==d.stableId?void 0:t.get(d.stableId),null==e)){s=!0;continue}const n=Ce(d.amount);o+=n,"MERCHANDISELINE"===d.type&&null!=e?i.push({path:`$.line_items[${e}]`,amount:n}):"DELIVERYLINE"===d.type&&i.push({path:"$.totals.shipping",amount:n})}const r="code"===n.type&&n.codeHidden,a=s?0:Ce(e.amount);return{title:r?"Discount":n.title,amount:o||a,..."code"===n.type&&!r&&{code:n.title},..."code"!==n.type&&{automatic:!0},..."EACH"===n.allocationMethod&&{method:"each"},..."ACROSS"===n.allocationMethod&&{method:"across"},...i.length>0&&{allocations:i}}}function we(e,{extendedAddressMode:t}){const n=e.address_country?.toUpperCase()??"",i=t.get(n),o=null===i?function(e,t){const n=Ie(t);return{address1:"line"in n?n.line:Oe(e,n),address2:t.extended_address??""}}(n,e):function(e,t,n){const{packedLine2:i,...o}=function(e,t){if("line"in t){const n=r(e,t.line,!0);if(!n?.streetNumber)return{address1:t.line};const i=a({countryCode:e,streetName:n.streetName??"",streetNumber:n.streetNumber});return null==i?{address1:t.line}:{address1:i,packedLine2:n.line2}}const n=a({countryCode:e,...t});return null==n?{address1:xe(t)}:{address1:n,...t}}(e,Ie(t)),{neighborhood:s,...c}=function(e,{extended_address:t="",district:n},i){const o=d(e,t);if(!o)return{address2:Te(t,i)};const s=Te(o.line2??"",i),r=n??o.neighborhood??"";return{address2:Re(e,s,r),line2:s,neighborhood:r}}(e,t,i);return{...o,...c,..."dedicated"===n?void 0!==s&&{district:s,neighborhood:""}:{neighborhood:s}}}(n,e,i);return{...B({...e,street_address:o.address1,extended_address:o.address2}),company:e.company??"",district:void 0,subdistrict:void 0,...o}}function Se(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,...null===i?Ee(n,e):Le(n,e,i),address_locality:e.city,address_regi
1on:e.zoneCode,address_country:e.countryCode,postal_code:e.postalCode}}function Ie({street_address:e="",street_name:t,street_number:n=""}){return t?.trim()?{streetName:t,streetNumber:n}:{line:e}}function Te(e,t){return t&&t!==e.trim()?Ue(e,t):e}function Ee(e,t){return{street_address:Ne(e,t),extended_address:Pe(e,t)}}function Ne(e,{address1:t,streetName:n,streetNumber:i}){return t||!n&&!i?t:Me(e,{streetName:n??"",streetNumber:i??""})}function Pe(e,{address2:t,line2:n,district:i,neighborhood:o}){const s=i||o;return null!=n||s?Re(e,n??"",s??""):t}function Le(e,t,n){const i=function(e,t,n){return"dedicated"!==n||null==t.streetName&&null==t.streetNumber?t.address1?.includes(c)?r(e,t.address1):null:t}(e,t,n);return{...i?.streetName?{street_name:i.streetName,street_number:i.streetNumber??""}:{street_address:Ne(e,t)},...De(e,t,n)}}function De(e,t,n){if("dedicated"===n&&(null!=t.line2||null!=t.district)){const e=t.district??t.neighborhood;return{extended_address:t.line2,...null!=e&&{district:e}}}const i=t.address2?.includes(c)?d(e,t.address2):null;return i?{extended_address:i.line2??"",district:i.neighborhood??""}:{extended_address:t.address2||t.line2,..."concatenated"===n&&null!=t.neighborhood&&{district:t.neighborhood}}}function Me(e,t){return a({countryCode:e,...t})??xe(t)}function Re(e,t,n){return l({countryCode:e,line2:t,neighborhood:n})??Ue(t,n)}function Oe(e,t){return Me(e,t).split(c).join("")}function xe({streetName:e,streetNumber:t}){return[t,e].filter(Boolean).join(" ")}function Ue(e,t){return[e,t].filter(Boolean).join(", ")}function qe(e){return e?.flatMap(e=>(e.lineComponents.length?e.lineComponents:[e]).filter(e=>e.requiresShipping).map(je))??[]}function je(e){return e.stableId}function $e(e){return"presentationLevel"in e&&"CART"===e.presentationLevel}function He(e){return"SHIPPING"===e||"LOCAL"===e||u(e)}function Be(e,t,n){return Boolean(e&&!n&&(t.some(e=>!He(e))||t.some(u)&&t.some(e=>"SHIPPING"===e||"LOCAL"===e)))}function Fe(e,t){switch(t){case"phone_number":return Boolean(e.phoneRequired);case"instructions":return Boolean(e.acceptsInstructions)}}function Ge(e,t){if(!e?.length||!t?.length)return!1;const n=new Set(t),i=e.filter(e=>e.requiresShipping).map(e=>je(e));return i.length===n.size&&i.every(e=>n.has(e))}const Ye="pickup";function We(e){const t=e.methods.find(({handle:t})=>t===e.selectedDeliveryMethodHandle),n=e.proposedLine?t?.methodType??e.proposedLine.deliveryMethodTypes[0]:(t??e.methods[0])?.methodType;if(n)return u(n)?"pickup":"shipping"}function ze(e){const[t,...n]=e.filter(e=>"pickup"===We(e)).map(e=>({line:e,methods:Xe(e)}));if(!t)return[];const i=[];for(const[o,s]of t.methods){const e=[{line:t.line,method:s}];for(const{line:t,methods:i}of n){const n=i.get(o);if(!n)break;e.push({line:t,method:n})}e.length===n.length+1&&i.push({id:s.handle,selections:e})}return i}function Xe(e){const t=new Map;for(const n of e.methods){if(!n.pickupLocation)continue;const i=Ve(n.pickupLocation);t.has(i)&&n.handle!==e.selectedDeliveryMethodHandle||t.set(i,n)}return t}function Ve(e){if("PickupPointLocation"===e.type&&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??""])}const Ke=Se;function Je(e,t){const n=new Set(t.flatMap(e=>e.targetMerchandiseLines?.map(je)??[])),i=new Map,o=new Set;for(const s of e.merchandiseLines??[]){if("proposed"!==e.readMode&&!s.requiresShipping)continue;const t=je(s);if(n.has(t)||o.has(t))continue;o.add(t);const r=new Set((s.lineComponents.length?s.lineComponents:[s]).filter(e=>e.requiresShipping&&!n.has(je(e))).map(je));if(!r.size)continue;const a=e.proposedDeliveryLines?.filter(e=>e.targetMerchandiseLines.some(e=>je(e)===t||r.has(je(e)))).flatMap(e=>e.deliveryMethodTypes),d=a?.length&&a.every(u)?"pickup":"shipping",c=i.get(d)??[];c.push(..."proposed"===e.readMode?r:[t]),i.set(d,c)}return i}function Ze(e){return[...Je(e,[])].map(([t,n])=>({id:t,type:t,line_item_ids:n,destinations:[],..."shipping"===t?nt(e):{},groups:[]}))}function Qe(e){const t=new Set;for(const n of e){const e=We(n);e&&t.add(e)}return Array.from(t)}function et(e){return"SHIPPING"===e||"LOCAL"===e||u(e)}function tt(e,t,n){if("shipping"===e)return nt(n);const i=ze(t);if(!i.length)return{};const o=i.find(({selections:e})=>e.every(({line:e,method:t})=>e.selectedDeliveryMethodHandle===t.handle));return{destinations:i.flatMap(({id:e,selections:[t]})=>{const i=function(e,t){const{pickupLocation:n}=e;return n?{id:e.handle,type:"business_location",name:n.name??"",pickup_location_address:Ke(n.address,t)}:void 0}(t.method,n.addressContext);return i?[{...i,id:e}]:[]}),...o&&{selected_destination_id:o.id}}}function nt({savedDestinations:e,shippingAddress:t,addressContext:n}){if(void 0===e)return t&&m(t)?{destinations:[it(t,n)]}:{};const{destinations:i,selectedDestinationId:o}=function(e,t){const n=new Map;for(const s of e)n.has(s.id)||n.set(s.id,s);const i=[...n.values()],o=t?i.find(({address:e})=>p(e,t)):void 0;return{destinations:i,selectedDestinationId:o?.id}}(e,t);return i.length?{destinations:i.map(({id:e,address:t})=>({id:e,type:"shipping_address",...Ke(t,n)}
1)),...o&&{selected_destination_id:o}}:{}}function it(e,t){return{...Ke(e,t),id:ot(e),type:"shipping_address"}}function ot(e){return["shipping",e.countryCode,e.postalCode].filter(Boolean).join("-").replace(/\s+/g,"")}function st(e,t){const n=rt(e),i=h(e),o=e.proposedLine?e.selectedDeliveryMethodHandle:i?.handle,s=o?function(e,t,n){const i=function(e,t,n=rt(e)){return t?.find(t=>Boolean(e.id)&&t.id===e.id)??t?.find(e=>Ge(e.targetMerchandiseLines,n))}(e,n,t);if(!i||!e.selectedDeliveryMethodHandle||i.deliveryMethodHandle!==e.selectedDeliveryMethodHandle)return;const o=i.deliveryMethodOptions;if(!o)return;const s=h(e),r=s&&!Fe(s,"phone_number")?void 0:o.phone,a=s&&!Fe(s,"instructions")?void 0:o.instructions;return void 0===r&&void 0===a?void 0:{...void 0!==r&&{phone_number:r},...void 0!==a&&{instructions:a}}}(e,n,t):void 0,r="pickup"===We(e),a=r?[{...i?at(i):{totals:[]},id:Ye,title:"Pickup"}]:e.methods.filter(({methodType:e})=>"SHIPPING"===e||"LOCAL"===e).map(at);return{id:e.id??"",line_item_ids:n,options:a,...o&&{selected_option_id:r?Ye:o},...s&&{selected_option_details:s}}}function rt(e){return e.targetMerchandiseLines?.filter(e=>e.requiresShipping).map(e=>je(e))??[]}function at(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:Ce(e.costAfterDiscounts)}]}}function dt(e){return"available"===e.status}const ct=new Map([["terms-of-service","terms_of_service"],["privacy-policy","privacy_policy"],["refund-policy","refund_policy"],["shipping-policy","shipping_policy"]]);function lt(e){const t=[];for(const{handle:n,url:i}of e){const e=ct.get(n);e&&t.push({type:e,url:i})}return t}const ut={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 pt(e){return ut[e]}const ht=new Set(["AcceptNewTermViolation","RequiredArtifactsUnavailableViolation"]),mt=new Set(["PendingTermViolation"]),ft
1=new Set(["PAYMENTS_UNACCEPTABLE_PAYMENT_AMOUNT"]),yt={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 _t(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 gt({subtotal:e,itemsDiscountAmount:t,cartLevelDiscountAmount:n,discountLines:i,fulfillmentTotal:o,tax:s,duty:r,dutiesIncluded:a,runningTotal:d}){const c=[];return null!=e&&(c.push({type:"subtotal",display_text:"Subtotal",amount:Ce(e)}),c.push(...function({currencyCode:e,discountLines:t,itemsDiscountAmount:n,cartLevelDiscountAmount:i}){let o=i;for(const r of t?.lines??[])if($(r))for(const e of r.allocations)"DELIVERYLINE"===e.target.type&&(o+=e.target.amount.amount);const s=[];return n>0&&s.push({type:"items_discount",display_text:"Discounts",amount:Ce({amount:-n,currencyCode:e})}),o>0&&s.push({type:"discount",display_text:"Discount",amount:Ce({amount:-o,currencyCode:e})}),s}({currencyCode:e.currencyCode,discountLines:i,itemsDiscountAmount:t,cartLevelDiscountAmount:n}))),null!=o&&c.push({type:"fulfillment",display_text:"Shipping",amount:Ce(o)}),null==r||a||c.push({type:"duty",display_text:"Duties",amount:Ce(r)}),null!=s&&c.push({type:"tax",display_text:"Taxes",amount:Ce(s)}),null!=d&&c.push({type:"total",display_text:"Total",amount:Ce(d)}),c}function vt(e){const t=e.merchandiseLines?.lines;if(!t||!function(e){return e.every(e=>null!=e.itemPrice&&null!=e.title)}(t)||null==e.runningTotal)return;const n="proposed"===e.readMode&&0===t.length?{...e.runningTotal,amount:0}:function(e){if(e)return e.reduce((e,t)=>{const{itemPrice:n}=t;if(!n)return e;const i=n.amount*t.quantity;return e?{...e,amount:e.amount+i}:{...n,amount:i}},void 0)}(t)??e.subtotal;if(null==n)return;const{lineItems:i,itemsDiscountAmount:o,cartLevelDiscountAmount:s}=function(e){if(!e?.length)return{lineItems:[],itemsDiscountAmount:0,cartLevelDiscountAmount:0};let t=0,n=0;return{lineItems:e.map(e=>{const{itemPrice:i}=e,o=i?{...i,amount:i.amount*e.quantity}:void 0,{lineLevel:s,cartLevel:r}=function(e){let t=0,n=0;for(const i of e)for(const{discountDetails:e,amount:o}of i.allocations)$e(e.discount)?n+=o.amount:t+=o.amount;return{lineLevel:t,cartLevel:n}}(e.lineAllocations),a=[];n+=r,o&&a.push({type:"subtotal",amount:Ce(o)}),0!==s&&o&&(t+=s,a.push({type:"items_discount",amount:Ce({...o,amount:-s})}));const d=o?{...o,amount:o.amount-s}:e.totalPrice;return a.push({type:"total",amount:Ce(d)}),{id:je(e),...e.parentRelationship?.parent?.stableId?{parent_id:e.parentRelationship.parent.stableId}:{},quantity:e.quantity,item:{id:e.variantId??e.stableId,title:e.title,price:Ce(i),...e.image?.url?{image_url:e.image.url}:{}},totals:a}}),itemsDiscountAmount:t,cartLevelDiscountAmount:n}}(t),r=function(e){const{deliveryNext:t}=e;if("filled"!==t?.status||!t.lines)return;const n=[];let i;for(const s of t.lines){if("available"!==s.status||!s.selectedDeliveryMethodHandle)continue;const t=h(s);t?.cost&&(n.push({cost:t.costAfterDiscounts.amount,costBeforeDiscounts:t.cost.amount,rateGroupKey:"SHIPPING"===t.methodType?H({line:s,method:t,localShopId:e.shopId,marketDrivenShippingEnabled:e.marketDrivenShippingEnabled,remoteShopsConfigMap:e.remoteShopsConfigMap,remoteMerchandiseDetails:e.remoteMerchandiseDetails}):void 0}),i??=t.cost.currencyCode)}if(null==i)return;const{priceBeforeDiscounts:o}=j(n,({rateGroupKey:e})=>e);return{amount:o,currencyCode:i}}(e),a="processed"===e.receipt?.status&&e.receipt.isRedacted?void 0:function(e){const{email:t,phone:n}=e??{};if(t||n)return{...t?{email:t}:{},...n?{phone_number:n}:{}}}(e.contactInfo),d=function(e,t){if(!e?.lines.length)return;const n=t?new Map(t.map(({id:e},t)=>[e,t])):void 0,i=new Map,o=[];for(const s of e.lines){const{discount:e}=s;if("code"===e.type||"discountCodeTrigger"===e.type){const t=e.title.toUpperCase();i.has(t)||i.set(t,e.title)}if("allocations"in s){const e=Ae(s,n);e.amount>0&&o.push(e)}}return{codes:[...i.values()],applied:o}}(e.discountLines,"proposed"===e.readMode?i:void 0),c=function(e){const t=function(e){const{deliveryNext:t}=e;if("proposed"!==e.readMode&&("filled"!==t?.status&&"partial"!==t?.status||!t.lines))return Ze(e);const n="filled"!==t?.status&&"partial"!==t?.status||!t.lines?[]:t.lines.filter(dt),i=("proposed"===e.readMode?function(e,t,n){const i=new Map;for(const o of n??[]){i.set(je(o),qe([o]).length>0);for(const e of o.lineComponents)i.set(je(e),e.requiresShipping)}return(t??[]).map(t=>{const n=t.targetMerchandiseLines.filter(e=>e.requiresShipping).map(e=>je(e)),o=e.find(e=>void 0!==t.id&&e.id===t.id)??e.find(e=>e.type===t.type&&Ge(e.targetMerchandiseLines,n));return{...o,status:"available",id:t.id,type:t.type,targetMerchandiseLines:t.targetMerchandiseLines.flatMap(e=>{const t=i.get(je(e));return void 0===t?[]:[{...e,requiresShipping:t}]}),selectedDeliveryMethodHandle:t.deliveryMethodHandle,methods:o?.methods.filter(e=>t.deliveryMethodTypes.includes(e.methodType))??[],proposedLine:t}})}(n,e.proposedDeliveryLines,e.merchandiseLines):n).filter(e=>(e.proposedLine?e.proposedLine.deliveryMethodTypes.some(et):e.methods.some(e=>et(e.methodType)))&&e.targetMerchandiseLines?.some(e=>e.requiresShipping));if("proposed"===e.readMode&&!i.length)return Ze(e);const o="partial"===t?.status?Je(e,i):new Map,s=new Set([...Qe(i),...o.keys()]),r=[];for(const a of s){const t=i.filter(e=>We(e)===a),n=t.map(t=>st(t,t.proposedLine?[t.proposedLine]:e.proposedDeliveryLines)),s=[...new Set([...n.flatMap(e=>e.line_item_ids),...o.get(a)??[]])];
1r.push({id:a,type:a,line_item_ids:s,destinations:[],...tt(a,t,e),groups:n})}return r}(e);return t.length?{methods:t}:void 0}({readMode:e.readMode,deliveryNext:e.deliveryNext,shippingAddress:e.shippingAddress,merchandiseLines:t,savedDestinations:e.savedDestinations,addressContext:e.addressContext,proposedDeliveryLines:e.proposedDeliveryLines}),{status:l,messages:u}=function(e){const{receipt:t,isShippingRequired:n,hasShippingAddress:i,deliveryNext:o,skipsShippingAddress:s=_(o)}=e,r=function(e){const t=[];for(const n of e.violations??[]){if(ht.has(n.__typename))continue;if(ft.has(n.code))continue;if(e.requiresCaptcha&&g.has(n.code))continue;const i=n.code.startsWith("DISCOUNTS_"),o=i||mt.has(n.__typename),s=pt(n.code)??(o?"checkout_warning":"checkout_error"),r="target"in n?n.target:void 0,a=i?"$.discounts.codes":r;t.push({...o?{type:"warning"}:{type:"error",severity:"recoverable"},code:s,content:_t(n,s,e.i18n),...a?{path:a}:{}})}return"action_required"===e.receipt?.status&&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}(e),a=function({receipt:e,isShippingRequired:t,hasShippingAddress:n,skipsShippingAddress:i,hasUnselectableShippingGroup:o,requiresBuyerReview:s,requiresCaptcha:r}){const a=e?.status;return"processed"===a?"completed":"processing"===a||"processing_remote_checkouts"===a||"polling_for_order"===a?"complete_in_progress":"action_required"===a||r?"incomplete":s?"requires_escalation":!t||n||i?t&&o?"incomplete":"ready_for_complete":"incomplete"}({receipt:t,isShippingRequired:n,hasShippingAddress:i,skipsShippingAddress:s,hasUnselectableShippingGroup:e.hasUnselectableShippingGroup??!1,requiresBuyerReview:e.requiresBuyerReview??!1,requiresCaptcha:e.requiresCaptcha??!1});return"incomplete"===a&&e.requiresCaptcha&&"action_required"!==t?.status&&r.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."}),"requires_escalation"===a&&r.push(yt),{status:a,messages:r}}({i18n:e.i18n,requiresBuyerReview:null!=e.buyerReviewUrl,requiresCaptcha:e.requiresCaptcha,violations:e.violations,receipt:e.receipt,isShippingRequired:"proposed"===e.readMode?qe(t).length>0:e.isShippingRequired,hasShippingAddress:"proposed"===e.readMode?m(e.shippingAddress):null!=e.shippingAddress,deliveryNext:e.deliveryNext,skipsShippingAddress:"proposed"===e.readMode?kt(c,t):void 0,hasUnselectableShippingGroup:bt(c,t,e.readMode)}),p=function(e){if("processed"!==e?.status)return;const t=e.orderIdentity.buyerIdentifier,n=f(e.orderIdentity.id);return{...n?{id:y("Order",n)}:{},...t?{label:t}:{},permalink_url:e.confirmationPage.url}}(e.receipt),v=function(e,t,n){const i=n?.filter(({instrument:e,usable:t})=>e.selected||t).map(({instrument:e})=>e);return i?.length?{instruments:i}:{instruments:e?[{billing_address:Se(e,t)}]:[]}}(e.billingAddress,e.addressContext,e.savedCards),b=(k=e.savedCards??[]).some(({instrument:e,usable:t})=>e.selected&&!t)?[{type:"error",severity:k.some(({usable:e})=>e)?"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."}]:[];var k;const C=[...u,...b];return{...e.id?{id:e.id}:{},...e.continueUrl?{continue_url:e.continueUrl}:{},currency:e.runningTotal.currencyCode,status:"ready_for_complete"===l&&b.length?"incomplete":l,..."requires_escalation"===l&&e.buyerReviewUrl?{continue_url:e.buyerReviewUrl}:{},links:lt(e.merchantPolicies),line_items:i,totals:gt({subtotal:n,itemsDiscountAmount:o,cartLevelDiscountAmount:s,discountLines:e.discountLines,fulfillmentTotal:r,tax:e.tax,duty:e.duty,dutiesIncluded:e.dutiesIncluded,runningTotal:e.runningTotal}),...a&&{buyer:a},...d&&{discounts:d},...c&&{fulfillment:c},payment:v,...C.length?{messages:C}:{},...p&&{order:p}}}function bt(e,t,n){const i=new Set(e?.methods.flatMap(e=>"pickup"===e.type?e.line_item_ids:(e.groups??[]).filter(({options:e})=>Boolean(e?.length)).flatMap(e=>e.line_item_ids)));return t.some(e=>{if("proposed"!==n&&!e.requiresShipping)return!1;const t=qe([e]);return t.length>0&&!i.has(je(e))&&!t.every(e=>i.has(e))})}function kt(e,t){const n=new Set(e?.methods.filter(e=>"pickup"===e.type).flatMap(e=>(e.groups??[]).filter(e=>Boolean(e.selected_option_id)).flatMap(e=>e.line_item_ids))??[]);return t.every(e=>n.has(je(e))||qe([e]).every(e=>n.has(e)))}function Ct(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:"shopify.card"===e.handler_id?"direct"===i:"shopWallet"===i,billing_address:n}}function At(e,t,n,i,o){const{proposed:s,negotiated:r}=e.proposal,a=e.addressManager.shipping.value,d="shopPay"===e.identity.current.value?a:void 0,c=d?[...d.addresses.value,...d.immutableAddresses.value]:void 0,l=r.fields.shippingAddress.value,u=o?.currentUrl.value,p=s.captcha.value;return{i18n:t,readMode:i,requiresCaptcha:Boolean("hcaptcha"===p?.provider&&p.sitekey&&(!p.token||p.violationCode)),buyerReviewUrl:"/review"===u?.normalizedPath?u.href:void 0,id:r.fields.ucp.value?.id,continueUrl:r.fields.ucp.value?.continueUrl,merchantPolicies:n.merchantPolicies,merchandiseLines:"proposed"===i?{lines:s.merchandiseLines.value}:r.fields.merchandiseLines.value,subtotal:r.fields.subtotal.value,discountLines:"proposed"===i?{lines:s.discountLines.value}:r.fields.discountLines.value,tax:e.proposal.facts.tax??(m=r.fields.taxes.value,"available_total"===m?.status?m.totalTax:void 0),duty:e.proposal.facts.duty??(h=r.fields.duties.value,"available_total"===h?.status?h.totalDuty:void 0),dutiesIncluded:Boolean(r.fields.dutiesIncluded.value)||Boolean(e.proposal.facts.dutiesIncluded),runningTotal:r.fields.runningTotal.value,contactInfo:"proposed"===i?{email:s.email.value,phone:s.phone.value}:r.fields.contactInfo.value,deliveryNext:r.fields.deliveryNext.value,shopId:n.id,marketDrivenShippingEnabled:n.marketDrivenShippingEnabled,remoteShopsConfigMap:n.remoteShopsConfigMap,remoteMerchandiseDetails:r.fields.remoteMerchandiseDetails.value,shippingAddress:"proposed"===i?s.shippingAddress.value:l,billingAddress:"shopPay"===e.identity.current.value?void 0:wt(e,n,i),addressContext:e.address,savedDestinations:c,proposedDeliveryLines:s.deliveryLines.value.map(e=>
1e.value),isShippingRequired:Boolean(r.fields.isShippingRequired.value),violations:r.fields.allViolations.value,receipt:e.latestReceipt.value};var h,m}function wt(e,t,n){const i=e.latestReceipt.value;return"processed"===i?.status?i.purchaseOrder.billingAddress:"processing"!==i?.status&&"processing_remote_checkouts"!==i?.status&&"polling_for_order"!==i?.status?"proposed"===n?function(e,t){const{proposed:n,negotiated:i,facts:o}=e.proposal,s=n.paymentLines.value;for(const{method:c}of s)if(c.type===v.CreditCard||c.type===v.PayPal)return c.billingAddress;const r=n.billingAddress.value,a=!r.address1&&o.billingAddress?o.billingAddress:r;if("shipping"!==n.billingAddressOption.value||!i.fields.isShippingRequired.value||!b(s))return a;const d=s[0]?.method;if("wallet"===d?.type){const n=i.fields.runningTotal.value,o=n&&n.amount<=0,s=k(i.fields.merchandiseLines.value?.lines).some(e=>Boolean(e.sellingPlan?.subscriptionDetails));if((!o||s||i.fields.deferredTotal.value?.amount.amount)&&("GOOGLE_PAY"===d.name||"APPLE_PAY"===d.name||"PAYPAL_EXPRESS"===d.name&&C({checkout:e,shop:t,paymentMethods:i.fields.paymentMethods.value})))return a}return o.delivery?.[0]?.deliveryAddress??n.shippingAddress.value}(e,t):e.proposal.negotiated.fields.billingAddress.value:void 0}const St="store_credit";const It="tax_number",Tt=["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 Et(e){const t=e.proposal.proposed.localizationExtensions.value.flatMap(e=>Tt.some(t=>t===e.fields.key.value)?[e]:[]);return 1===t.length?t[0]:void 0}function Nt(e,t){const n=new Map(t.flatMap(({targetMerchandiseLines:e})=>e.map(e=>[e.stableId,e]))),i=new Set;for(const o of e){const e=(o.lineComponents?.length?o.lineComponents:[o]).filter(e=>e.requiresShipping??n.get(e.stableId)?.requiresShipping);for(const{stableId:t}of e)i.add(t);e.length&&o.lineComponents?.length&&i.add(o.stableId)}return i}function Pt(e,t){return[...new Set(e.filter(({targetMerchandiseLines:e})=>e.some(({stableId:e})=>t.has(e))).flatMap(({deliveryMethodTypes:e})=>e).filter(e=>"NONE"!==e))]}function Lt(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 Dt(e,t){return{...e,ucp:Lt(Z(e)?"error":"success",t.proposal.negotiated.fields.ucp.value?.paymentHandlers)}}const Mt={"shopify.card":"shopify.card",shop_pay:"shop_pay_approval_id"};class Rt{#n;#i;#o;#s=!1;#r=!1;#a=!1;#d=!1;#c;constructor({observability:e,checkout:t}){this.#n=e,this.#i=t,this.#o="processed"===t.latestReceipt.peek()?.status}log({name:e,message:t,attributes:n}
1){this.#n.log(e,t,n)}error({error:e,...t}){this.#n.error(e,t)}histogram(e){this.#n.histogram(e)}initialized(){this.#l("web_mcp_initialized")}toolCalled(e){this.#s||(this.#s=!0,this.#l("web_mcp_tool_called",{tool:e})),this.#r||"update_checkout"!==e&&"complete_checkout"!==e||(this.#r=!0,this.#l("web_mcp_write_tool_called",{tool:e})),this.#a||"complete_checkout"!==e||(this.#a=!0,this.#l("web_mcp_complete_checkout_called"))}submitForCompletion({accepted:e,submittedAt:t,receiptId:n,agenticInstrument:i}){if(this.#o)return;const o={payment:i?Mt[i.handler_id]:"unknown",identity:this.#i.identity.current.peek()};this.#n.histogram({name:"web_mcp_submit_for_completion",value:Ot(t),unit:"ms",attributes:{...o,result:e?"accepted":"failed"}}),e&&void 0!==n&&(this.#c={receiptId:n,submittedAt:t,labels:o,actionRequired:!1},this.#u(this.#i.latestReceipt.peek()))}paymentCredentialSupplied(e){!this.#d&&F(e)&&(this.#d=!0,this.#l("web_mcp_payment_credential_update_called",{payment:Mt[e.handler_id]}))}updateCheckoutPartialInput(e){(e.buyer||e.fulfillment||e.payment)&&this.#l("web_mcp_update_checkout_partial_input",{missingBuyer:e.buyer,missingFulfillment:e.fulfillment,missingPayment:e.payment})}watchReceipts(e){if(this.#o||e.aborted)return;const n=t(()=>{const e=this.#i.latestReceipt.value;i(()=>this.#u(e))});e.addEventListener("abort",n,{once:!0})}#u(e){const t=this.#c;if(!t||e?.id!==t.receiptId)return;if("action_required"===e.status)return void(t.actionRequired=!0);if("processed"!==e.status&&"failed"!==e.status)return;this.#c=void 0;const n=Ot(t.submittedAt),i="failed"===e.status?e.failure:void 0,o={...t.labels,result:e.status,...i&&{failure:"payment"===i.type?"payment":"other"}};this.#n.histogram({name:"web_mcp_submission_receipt",value:n,unit:"ms",attributes:o}),this.#n.log("web_mcp_submission_receipt_settled","[WebMcp] submission receipt settled",{...o,...i&&{failureType:i.type},..."payment"===i?.type&&{paymentErrorCode:i.code},actionRequired:t.actionRequired,durationMs:n,receiptId:e.id})}#l(e,t={}){this.#o||this.#n.counter({name:e,value:1,attributes:{...t,identity:this.#i.identity.current.peek()}})}}function Ot(e){return Math.round(performance.now()-e)}function xt(e,{checkout:t},n){const i=e.fulfillmentMethods.methods;if(i.length>1)return me("At most one fulfillment method is supported.");const o=i[0];if(void 0!==o?.id&&o.id!==o.type)return me("Method id must match its shipping or pickup type; omit id when requesting a new method.");const{proposed:s,negotiated:r}=t.proposal,a=s.deliveryLines.value.map(e=>e.value),d=Nt(s.merchandiseLines.value,a),c=Pt(a,d);if(c.some(u)&&c.some(Ut)){const e=r.fields.deliveryNext.value,t="filled"===e?.status||"partial"===e?.status?e.lines.filter(e=>"available"===e.status):[],n=Pt(a.map(e=>{const n=t.find(({id:t})=>Boolean(e.id)&&t===e.id)??t.find(t=>Ge(t.targetMerchandiseLines,e.targetMerchandiseLines.filter(e=>e.requiresShipping).map(je))),i=n?.methods.find(({handle:t,methodType:n})=>t===e.deliveryMethodHandle&&e.deliveryMethodTypes.includes(n)),o=i?.methodType??(e.deliveryMethodHandle?void 0:e.deliveryMethodTypes[0]);return o?{...e,deliveryMethodTypes:[o]}:e}),d);if(n.some(u)&&n.some(Ut))return me("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),p=Boolean(e.context&&!qt(s.locationAddress.value,e.context));if(p&&"pickup"!==l)return me("Changing context locality requires a pickup method.");if(!o&&"pickup"!==l)return;const h=e=>"pickup"===l?u(e):Ut(e);if(o&&(void 0!==o.selected_destination_id||o.groups.length))return p||c.length&&!c.some(h)?me("Change the method/search origin first, then select a destination or option returned by that update."):void 0;if("pickup"===l&&c.length&&c.every(e=>"PICKUP_POINT"===e))return p?me("Pickup-point locality discovery is not supported. Select an existing destination instead."):void 0;if(!d.size)return me("This checkout has no physical items to fulfill.");if("pickup"===l&&e.context){const t=s.shippingAddress.value?.countryCode||s.locationAddress.value?.countryCode;if(!t)return me("Pickup search requires an established checkout country. Ask the buyer to choose a country in checkout.");if(e.context.address_country!==t)return me("Pickup search must remain in the checkout country.")}if(!n&&!p&&c.every(h)&&c.length)return;const m=!c.length||!c.every(h);if(!n&&m)return me("The delivery selector is not ready.");const f=n?n.getAvailableMethodTypes().find(e=>"pickup"===l?e.includes("PICK_UP"):e.some(h)):c;if(!f)return me(`The checkout does not offer ${l}.`);const y=r.fields;return(m||p)&&(y.mustSelectProvidedShippingRate.value||y.mustSelectProvidedAddress.value||!1===y.canUpdateDeliveryAddress.value)?me("The checkout locks its delivery method or address."):{methodTypes:f,needsLocalityLookup:p,changesMo
1de:m}}function Ut(e){return"SHIPPING"===e||"LOCAL"===e}function qt(e,t){return X(e,{countryCode:t.address_country,zoneCode:t.address_region,postalCode:t.postal_code})}const jt={status:"written"};const $t=({shippingAddress:e},t)=>{if("saved_address_id"in e)return function(e,t){const{checkout:n,clearShippingAddressErrors:i}=t;if("shopPay"!==n.identity.current.value)return{status:"rejected",field:"shippingAddress"};const o=n.addressManager.shipping.value,s=[...o.addresses.value,...o.immutableAddresses.value].find(t=>t.id===e);if(!s||s.disabled)return{status:"rejected",field:"shippingAddress"};const r=o.applyAddressChangeBlockReason("ucp").value;if(r&&"MUST_SELECT_PROVIDED_ADDRESS"!==r)return;return en(s.address.countryCode,"fulfillment.methods[0].selected_destination_id",t.shop)||{status:"ready",negotiation:{include:["shippingAddress","deliveryNext"],loading:["deliveryNext"],fieldsToResolve:["shippingAddress","deliveryNext"]},apply:async()=>await o.selectAddress(e)?(i(),jt):{status:"failed"}}}(e.saved_address_id,t);const{checkout:n,observability:i,clearShippingAddressErrors:o}=t,s=n.addressManager.shipping.value;if(s.applyAddressChangeBlockReason("ucp").value)return;const r=en(e.address_country,"fulfillment.methods[0].destinations[0].address_country",t.shop);if(r)return r;const a=we(e,n.address);return{status:"ready",negotiation:{include:["shippingAddress","deliveryNext"],loading:["deliveryNext"],fieldsToResolve:["shippingAddress","deliveryNext"]},async apply(){const e=await s.applyAddressChange({source:"ucp",address:a});return"success"!==e.type?(i.log({name:"web_mcp_address_change_declined",message:"[WebMcp] address manager declined an admitted address",attributes:{reason:e.reason}}),{status:"failed"}):(o(),jt)}}};function Ht(e,{readSavedCards:t,getSavedCardSelector:n}){const i=t()?.find(({instrument:t})=>t.id===e);return i?.usable?{status:"ready",negotiation:{include:["paymentLines","billingAddress"],loading:["paymentLines"],fieldsToResolve:["paymentLines"]},async apply(){const t=n?.();return t&&await t(e)?jt:{status:"failed"}}}:{status:"rejected",field:"payment"}}function Bt({fulfillmentMethods:e},{checkout:t},n=!1){const{proposed:i,negotiated:o}=t.proposal,s=o.fields.deliveryNext.peek(),r="filled"===s?.status||"partial"===s?.status?s.lines.filter(sn):[],a=new Map;for(const l of i.deliveryLines.peek()){const{id:e,targetMerchandiseLines:t,deliveryMethodTypes:n,deliveryMethodHandle:i}=l.peek();if(0===n.filter(He).length)continue;const o=r.find(t=>Boolean(e)&&t.id===e)??r.find(e=>Ge(e.targetMerchandiseLines,t.filter(e=>e.requiresShipping).map(je))),s=o?.methods.find(e=>e.handle===i);if(s){if(!He(s.methodType))continue}else if(Be(i,n,s))return{status:"rejected",field:"fulfillmentMethods"};a.set(l,{deliveryLine:l,selectedOptionId:void 0,selectedOptionDetails:void 0})}try{for(const t of function(e,t,n){return e.methods.flatMap(e=>"pickup"===e.type?function(e,t,n){const i=void 0===e.selected_destination_id?void 0:ze(n).find(({id:t})=>t===e.selected_destination_id);if(void 0!==e.selected_destination_id&&!i)throw new Jt("unknown_pickup_destination");const o=new Map;for(const s of e.groups){if(s.selected_option_id!==Ye)throw new Jt("unknown_fulfillment_option");const e=tn(s,n);if("pickup"!==We(e)||i&&!i.selections.some(t=>t.line===e)||o.has(e))throw new Jt("unknown_fulfillment_group");o.set(e,s)}return i?i.selections.map(({line:e,method:n})=>nn(e,n,o.get(e)?.selected_option_details,t)):[...o].map(([e,n])=>{const i=e.methods.find(t=>t.handle===e.selectedDeliveryMethodHandle&&u(t.methodType)&&t.pickupLocation);if(!i)throw new Jt("unknown_pickup_destination");return nn(e,i,n.selected_option_details,t)})}(e,t,n):e.groups.map(e=>{const i=tn(e,n,Boolean(e.id)&&t.some(({value:t})=>t.id===e.id)?"unselectable_fulfillment_group":"unknown_fulfillment_group"),o=i.methods.find(({handle:t,methodType:n})=>t===e.selected_option_id&&("SHIPPING"===n||"LOCAL"===n));if(!o||"shipping"!==We(i))throw new Jt("unknown_fulfillment_option");return nn(i,o,e.selected_option_details,t)}))}(e,i.deliveryLines.peek(),r))a.set(t.deliveryLine,t)}catch(c){if(!(c instanceof Jt))throw c;return{status:"rejected",field:"fulfillmentMethods",reason:c.reason}}const d=o.fields.mustSelectProvidedShippingRate.peek();return[...a.values()].some(({deliveryLine:e,selectedOptionId:t})=>!function(e,t,n){return!n||e===t}(e.peek().deliveryMethodHandle,t,d))?{status:"rejected",field:"fulfillmentMethods"}:{status:"ready",negotiation:{include:["deliveryNext"],loading:["deliveryNext"],fieldsToResolve:["deliveryNext"]},async apply(){for(const e of i.deliveryLines.value){const t=a.get(e);if(!(t||n&&e.value.deliveryMethodTypes.some(He)))continue;
1const{selectedOptionId:i,selectedOptionDetails:o}=t??{};e.value={...e.peek(),deliveryMethodHandle:i,deliveryMethodOptions:on(o),...void 0===i&&{isCustomRate:void 0,customDeliveryStrategy:void 0}}}return jt}}}const Ft=[({buyer:e},{checkout:t,shopPay:n})=>{const i=Y({identity:t.identity,proposal:t.proposal,shopPay:n});if(i&&"shopPay"===t.identity.current.value)return;const{proposed:o}=t.proposal;return{status:"ready",negotiation:{include:["contactInfo"],loading:["contactInfo"],fieldsToResolve:["contactInfo"]},apply:async()=>(i||(o.email.value=e.email),o.phone.value=e.phone_number,jt)}},({discountCodes:e=[]},t)=>{const{proposed:i,negotiated:o}=t.checkout.proposal,s=new Map,r=[];for(const n of i.discountLines.value){const{discount:e}=n;if("code"===e.type||"discountCodeTrigger"===e.type){const t=e.title.toUpperCase(),i=s.get(t);i?i.push(n):s.set(t,[n])}else r.push(n)}if(!1===o.fields.canUpdateDiscountCodes.value){const t=new Set(e.map(e=>e.toUpperCase()));if(t.size===s.size&&[...t].every(e=>s.has(e)))return;return{status:"rejected",field:"discountCodes"}}return{status:"ready",negotiation:{include:["discountLines","deliveryNext"],loading:["discountLines","deliveryNext"],fieldsToResolve:["discountLines","totalSavings","merchandiseLines","deliveryNext"]},async apply(){const o=new Set;for(const t of e){const e=t.toUpperCase();if(o.has(e))continue;o.add(e);const n=s.get(e);n?r.push(...n):r.push({title:t,discount:{type:"discountCodeTrigger",title:t}})}return n(()=>{i.discountLines.value=r,i.reduction.value=void 0;const{discountCodeWarningSignal:e,currentDiscountCodeAttemptSignal:n}=t.negotiator.context;e.value=null,n.value=null}),jt}}},$t,Bt];function Gt(e,t,{fulfillmentRequest:n,fulfillment:i,locationAddress:o}={}){const s=[];for(const r of Ft){if(r===$t&&n){const{methodTypes:e}=n,{proposed:r}=t.checkout.proposal;s.push({status:"ready",negotiation:{include:["deliveryNext"],loading:["deliveryNext"],fieldsToResolve:["deliveryNext"]},apply:async()=>(i?i.setDesiredMethod(e,o):o&&(r.locationAddress.value=o),jt)})}const a=r===Bt?Bt(e,t,void 0!==n):r(e,t);if(void 0!==a){if("rejected"===a.status)return Kt(a.field,a.reason);s.push(a)}}return s}class Yt{#p;constructor(e){this.#p=e}writePayment({payment:e,billingAddress:t=e?.billing_address,applyBilling:i=!0}){const o=i?this.#h(t):void 0,s=this.#m(e);return Z(s)?s:(n(()=>{s?.apply(),o?.apply()}),{status:"applied"})}#h(e){const{checkout:t}=this.#p;if(!G(t))return;const i=void 0===e?void 0:we(e,t.address);return{apply({replacement:e=!1}={}){if(!G(t))return!1;const{proposed:o,negotiated:s,facts:r}=t.proposal,a=!1===s.fields.isShippingRequired.value;if(i&&!T(i)&&(a||!function(e,t){const n=Se(t.proposal.proposed.shippingAddress.value,t.address);return R(e,we(n,t.address))}(i,t)))return n(()=>{o.billingAddress.value=i,o.billingAddressOption.value="custom"}),!0;if(e&&a)return!r.billingAddress&&!function(e){return e.paymentLines.value.some(e=>e.method.type===v.CreditCard||e.method.type===v.PayPal||function(e){if("wallet"!==e.method.type)return!1;switch(e.method.name){case"APPLE_PAY":return U(e);case"GOOGLE_PAY":return x(e);case"PAYPAL_EXPRESS":return O(e);default:return!1}}(e))}(o)&&(n(()=>{o.billingAddress.value=we({address_country:o.billingAddress.value.countryCode},t.address),o.billingAddressOption.value="custom"}),!0);const d=o.billingAddressOption.value;return o.billingAddressOption.value="shipping",void 0!==i||"shipping"!==d}}}#m(e){const{checkout:t,shop:i,paymentInstrument:o}=this.#p;if(!G(t))return;if(!e&&!o.value)return;const{proposed:s,negotiated:r}=t.proposal,a=r.fields.paymentMethods.value,d=s.paymentLines.value.find(e=>!e.due&&"direct"===e.method.type),c=E(a??[],"direct"===d?.method.type&&Boolean(d.method.alternative));return!e||("shopify.card"===e.handler_id?c:i.hasFlagEnabled(N)&&P(a))?{apply(){G(t)&&n(()=>{const t=o.value;if("shop_pay"===t?.handler_id&&t.credential?.approval_id&&(s.paymentLines.value=s.paymentLines.value.map(e=>"shopWallet"===e.method.type&&e.method.shopPayApprovalId===t.credential?.approval_id?{...e,method:{...e.method,shopPayApprovalId:void 0}}:e)),o.value=e,e){"shopify.card"===e.handler_id&&e.credential?.token&&c?"direct"===d?.method.type&&d.method.paymentMethodIdentifier===c.paymentMethodIdentifier||(s.paymentLines.value=L(s.paymentLines.value,{method:{type:"direct",paymentMethodIdentifier:c.paymentMethodIdentifier,alternative:c.alternative}},D(i))):"shop_pay"===e.handler_id&&e.credential?.approval_id&&(s.paymentLines.value=L(s.paymentLines.value,{method:{type:"shopWallet",shopPayApprovalId:e.credential.approval_id}}
1,D(i)));for(const e of Object.values(s.directPaymentErrors))e.value=void 0;s.generalPaymentError.value=void 0,s.generalPaymentErrorCode.value=void 0}})}}:te("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"})}async applyUpdate(e,{isExpired:t}={}){const{shippingAddress:i}=e,o=e.payment&&"billing_address"in e.payment?e.payment.billing_address:void 0;if(await this.loadAddressMetadata(["saved_address_id"in i?void 0:i,G(this.#p.checkout)?o:void 0]),t?.())return ue();if(this.#p.isSubmitting.value)return ye();const s=e.payment&&"instrument_id"in e.payment?e.payment.instrument_id:void 0;if(void 0!==s&&(await this.#p.waitForPendingNegotiations(),t?.()))return ue();let r=ke(e.declaredFields,this.#p.declaredFields);if(Z(r))return r;if(r.some(({changed:e})=>e)){if(await this.#p.waitForPendingNegotiations(),t?.())return ue();if(this.#p.isSubmitting.value)return ye();if(r=ke(e.declaredFields,this.#p.declaredFields),Z(r))return r}let a,d=this.#p.getFulfillmentController?.(),c=xt(e,this.#p,d);if(Z(c))return c;if(c?.needsLocalityLookup&&e.context){try{const t=this.#p.resolvePickupLocality;if(!t)throw new Wt;a=await t(e.context)}catch(C){return this.#p.observability.error({error:C instanceof Wt?C:new Wt(C)}),t?.()?ue():de("update_failed","context","Pickup locality lookup is unavailable.",`Call get_checkout and retry with the latest checkout. ${ne("update the checkout")}`)}if(t?.())return ue();if(!a)return de("rejected","context","Could not resolve a unique postal locality.","Check address_country, address_region and postal_code, then retry.");if(r=ke(e.declaredFields,this.#p.declaredFields),Z(r))return r}if(e.context){const t=this.#p.checkout.proposal.proposed.locationAddress.value;qt(t,e.context)&&(a=t)}if(d=this.#p.getFulfillmentController?.(),c=xt(e,this.#p,d),Z(c))return c;let l=this.#h(o);const p=e.payment&&"handler_id"in e.payment?e.payment:void 0;let h=this.#m(p);if(Z(h))return h;let m=void 0===s?void 0:Ht(s,this.#p);if("rejected"===m?.status)return Kt(m.field);let f=Gt(e,this.#p,{fulfillmentRequest:c,fulfillment:d,locationAddress:a});if(Z(f))return f;if(t?.())return ue();const y=[];let _=!1;for(const n of["negotiate","stage"]){if("stage"===n&&_&&(r=ke(e.declaredFields,this.#p.declaredFields),Z(r)))return ue();for(const i of r)if(i.phase===n&&i.changed){if(t?.())return ue();try{if(!(await i.apply())||t?.())return ue()}catch{return ue()}if("stage"===i.phase)y.push(i.negotiation);else{if(_=!0,d=this.#p.getFulfillmentController?.(),c=xt(e,this.#p,d),Z(c))return ue();if(f=Gt(e,this.#p,{fulfillmentRequest:c,fulfillment:d,locationAddress:a}),Z(f))return ue();if(l=this.#h(o),h=this.#m(p),Z(h))return ue();if(m=void 0===s?void 0:Ht(s,this.#p),"rejected"===m?.status)return ue()}}}if(h){const e=h;f.push({status:"ready",negotiation:{include:["paymentLines"],loading:["paymentLines"],fieldsToResolve:["paymentLines"]},apply:async()=>(e.apply(),jt)})}if(!m&&0===f.length&&0===y.length&&!l)return{status:"applied"};if(t?.())return ue();if(this.#p.isSubmitting.value)return ye();if((await Promise.all(n(()=>f.map(e=>e.apply())))).find(e=>"failed"===e.status)||t?.())return ue();if(this.#p.isSubmitting.value)return ye();if(m){if("failed"===(await m.apply()).status||t?.())return ue();if(await this.#p.waitForPendingNegotiations(),t?.())return ue();if(this.#p.isSubmitting.value)return ye()}const g=l?.apply({replacement:!0})??!1;if(!m&&0===f.length&&0===y.length&&!g)return{status:"applied"};const v=await this.#f((b=[...f.map(e=>e.negotiation),...y,...m?[m.negotiation]:[],...g?[{include:["billingAddress"],loading:["billingAddress"],fieldsToResolve:["billingAddress"]}]:[]],{include:Xt(b,"include"),loading:Xt(b,"loading"),fieldsToResolve:Xt(b,"fieldsToResolve")}));var b;await this.#p.waitForPendingNegotiations();const k=function(e){return"success"===e?.status||"error"===e?.status?{status:"applied"}:ue()}(v);if(void 0!==s&&!function(e,{readSavedCards:t}){return Boolean(t()?.some(({instrument:t,usable:n})=>t.id===e&&t.selected&&n))}(s,this.#p))return ue();
1if(!Z(k)&&!t?.()&&c?.needsLocalityLookup&&a&&e.context&&qt(this.#p.checkout.proposal.proposed.locationAddress.value,e.context)){const{proposed:e}=this.#p.checkout.proposal,t=e.deliveryLines.value.map(e=>e.value),n=Pt(t,Nt(e.merchandiseLines.value,t));n.length&&n.every(u)&&this.#p.announcePickupLocality?.(a)}return t?.()?ue():k}async loadAddressMetadata(e){const t=new Set;for(const i of e){const e=i?.address_country?.toUpperCase();i&&e&&zt(e,i)&&t.add(e)}const{countryDetails:n}=this.#p.checkout.address;for(const i of t){const e=n.get(i);e&&!e.isFallback||await n.fetch(i)}}async#f(e){let t;const{include:n,...i}=e;return await this.#p.journey.negotiate({...i,silenceViolations:M(n),runListenersOnError:n.includes("shippingAddress")||n.includes("discountLines"),onComplete:e=>{t=e}}),t}}class Wt extends Error{constructor(e){super("WebMCP pickup locality lookup failed",{cause:e}),this.name="WebMcpLocalityLookupError"}}function zt(e,t){const n=Boolean(t.street_address||t.street_name||t.street_number),i=Boolean(t.extended_address||t.district),o=null!==r(e,""),s=null!==d(e,"");return n&&o||i&&s}function Xt(e,t){return[...new Set(e.flatMap(e=>e[t]))]}const Vt={context:"context",buyer:"buyer",discountCodes:"discounts",declaredFields:"declared_fields",shippingAddress:"fulfillment",fulfillmentMethods:"fulfillment",payment:"payment"};function Kt(e,t){return t instanceof Qt?function(e,t,n){const i=n?` Supported countries: ${n.join(", ")}.`:"";return te("rejected",`${e} ${t} is not a country this shop ships to. ${se}${i} Tell the buyer. ${ne("update the checkout")}`)}(t.path,t.countryCode,t.listedCountryCodes):"unsupported_option_instructions"===t?pe("instructions"):"unsupported_option_phone"===t?pe("phone_number"):"unknown_fulfillment_group"===t?te("rejected",`fulfillment.methods[].groups[] does not match a delivery group in the current checkout. ${he}`):"unselectable_fulfillment_group"===t?te("rejected",`fulfillment.methods[].groups[] has no selectable delivery option in the current checkout. ${se} Send the update without groups, then choose an option from the next get_checkout. ${ne("update the checkout")}`):"unknown_fulfillment_option"===t?te("rejected",`fulfillment.methods[].groups[].selected_option_id is not an option for this group in the current checkout. ${he}`):te("update_failed",`Unable to update ${Vt[e]}. Call get_checkout to review the checkout and its messages before retrying. ${ne("update the checkout")}`)}class Jt extends Error{constructor(e){super(e),this.name="WebMcpFulfillmentMethodUpdateError",this.reason=e}}const Zt=20;class Qt extends Error{constructor(e,t,n){super(`${e} is not a shipping country`),this.name="UnsupportedShippingCountryError",this.countryCode=e,this.path=t,this.listedCountryCodes=n}}function en(e,t,{shippingCountries:n}){const i=e?.trim().toUpperCase();if(i&&0!==n.length&&!n.some(({value:e})=>e===i))return{status:"rejected",field:"shippingAddress",reason:new Qt(i,t,n.length<=Zt?n.map(({value:e})=>e):void 0)}}function tn(e,t,n="unknown_fulfillment_group"){const i=t.find(t=>Boolean(e.id)&&t.id===e.id)??t.find(t=>Ge(t.targetMerchandiseLines,e.line_item_ids));if(!i)throw new Jt(n);return i}function nn(e,t,n,i){const o=i.find(t=>Boolean(e.id)&&t.value.id===e.id)??i.find(t=>Ge(t.value.targetMerchandiseLines,e.targetMerchandiseLines?.filter(e=>e.requiresShipping).map(je)));if(!o)throw new Jt("unknown_fulfillment_group");if(!o.value.deliveryMethodTypes.includes(t.methodType))throw new Jt("unsupported_fulfillment_transition");return function(e,t){if(t){if(void 0!==t.instructions&&!Fe(e,"instructions"))throw new Jt("unsupported_option_instructions");
1if(void 0!==t.phone_number&&!Fe(e,"phone_number"))throw new Jt("unsupported_option_phone")}}(t,n),{deliveryLine:o,selectedOptionId:t.handle,selectedOptionDetails:n}}function on(e){return{phone:e?.phone_number,instructions:e?.instructions}}function sn(e){return"available"===e.status}const rn=s()(["shipping","pickup"]);class an extends Error{constructor(e,t,n,{loggablePath:i=e}={}){super(`${e}: expected ${t}, got ${n} instead.`),this.name="WebMcpInputError",this.expected=t,this.loggablePath=i}}const dn='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.',cn={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)."}},ln={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:{type:"object",description:`Replacement address. Include all fields to retain; omitted fields are cleared. Use PUT semantics, not PATCH. ${dn}`,properties:cn}}}}}};function un(e,{path:t,requireCredential:n=!1,savedPaymentMethodsOnly:i=!1}){const o=Sn(e,t);if(!n&&(void 0===o.instruments||Array.isArray(o.instruments)&&0===o.instruments.length))return;const s=`${t}.instruments[0]`,r=function(e,t){if(!Array.isArray(e))throw new an(t,"an array",Nn(e));if(1!==e.length)throw new an(t,"1 item",`${e.length} items`);return Sn(e[0],`${t}[0]`)}(o.instruments,`${t}.instruments`);if(!n&&i)return function(e,t){for(const n of Object.keys(e))if(!["id","type","selected","display"].includes(n))throw new an(`${t}.${n}`,"a saved instrument id from get_checkout, not new payment data","an unsupported field",{loggablePath:t});return{instrument_id:pn(e.id,`${t}.id`)}}(r,s);const a=r.handler_id;if(!n&&void 0===a&&void 0===r.credential){const e=hn(r,s);return void 0===e?void 0:{billing_address:e}}if("shopify.card"!==a&&"shop_pay"!==a)throw new an(`${s}.handler_id`,"shopify.card or shop_pay","an unsupported handler");const d=Tn(r,{id:void 0,type:void 0},s),c="shopify.card"===a?"card":"shop_pay";if(void 0!==d.type&&d.type!==c)throw new an(`${s}.type`,c,"an unsupported instrument type");const l=hn(r,s),u={id:d.id??V(),...void 0===l?{}:{billing_address:l}},p=`${s}.credential`,h=n||void 0!==r.credential?Sn(r.credential,p):void 0;if("shopify.card"===a){if(void 0===h)return{...u,handler_id:a,type:"card"};if(mn({object:h,allowedFields:["type","token"],path:p}),void 0!==h.type&&"shopify_token"!==h.type)throw new an(`${p}.type`,"shopify_token","an unsupported credential type");return{...u,handler_id:a,type:"card",credential:{type:"shopify_token",...n||void 0!==h.token?{token:pn(h.token,`${p}.token`)}:{}}}}if(void 0===h)return{...u,handler_id:a,type:"shop_pay"};if(mn({object:h,allowedFields:["type","approval_id"],path:p}),void 0!==h.type&&"shop_token"!==h.type)throw new an(`${p}.type`,"shop_token","an unsupported credential type");return{...u,handler_id:a,type:"shop_pay",credential:{type:"shop_token",...n||void 0!==h.approval_id?{approval_id:pn(h.approval_id,`${p}.approval_id`).trim()}:{}}}}function pn(e,t){if("string"!=typeof e||0===e.trim().length)throw new an(t,"a non-empty string",Nn(e));return e}function hn(e,t){if(void 0!==e.billing_address)return Tn(e.billing_address,_n,`${t}.billing_address`)}function mn({object:e,allowedFields:t,path:n}){if(Object.keys(e).some(e=>!t.includes(e)))throw new an(n,"only supported fields","extra properties")}
1const fn={email:"",phone_number:""},yn={first_name:"",last_name:"",phone_number:"",street_address:void 0,extended_address:void 0,address_locality:"",address_region:"",address_country:"",postal_code:""},_n={...yn,company:void 0,street_name:void 0,street_number:void 0,district:void 0},gn={phone_number:void 0,instructions:void 0};const vn=new Set(["purpose","title","description","value_schema","presentation","required"]);function bn(e,t){const n=rn.find(t=>t===e);if(void 0!==n)return n;throw new an(t,rn.map(e=>JSON.stringify(e)).join(" or "),"string"==typeof e?JSON.stringify(e):Nn(e))}function kn(e,t){if(void 0!==e){if(!Array.isArray(e))throw new an(t,"an array",Nn(e));for(const[n,i]of e.entries()){const e=Sn(i,`${t}[${n}]`);if("business_location"!==e.type)throw new an(`${t}[${n}].type`,'a read-only "business_location" from get_checkout; select pickup through selected_destination_id',Nn(e.type))}}}function Cn(e,t){if(null===e.selected_destination_id)return;const{selected_destination_id:n}=Tn(e,{selected_destination_id:void 0},t);if(""===n)throw new an(`${t}.selected_destination_id`,"a non-empty string or null","an empty string");return n}function An(e,t){const n=`${t}.destinations[0]`,i=`${t}.destinations`,{destinations:o}=e;if(void 0===o)return{...yn};if(!Array.isArray(o))throw new an(i,"an array",Nn(o));if(0===o.length)return{...yn};if(1!==o.length)throw new an(i,"1 item",`${o.length} items`);const s=Sn(o[0],n);if(void 0!==s.pickup_location_address||"business_location"===s.type)throw new an(n,"a flat shipping address","a pickup location");const r=Tn(s,_n,n);return{...yn,...r,address_country:(r.address_country??"").trim()}}function wn(e,t){if(!Array.isArray(e))throw new an(t,"an array",Nn(e));return e.flatMap((e,n)=>{const i=`${t}[${n}]`,o=Sn(e,i),s=o.selected_option_id,r=o.selected_option_details;if(void 0===s){if(void 0!==r)throw new an(`${i}.selected_option_details`,"selected_option_id to also be present","selected_option_details without selected_option_id");return[]}if("string"!=typeof s)throw new an(`${i}.selected_option_id`,"a string",Nn(s));const a=o.id;if("string"!=typeof a)throw new an(`${i}.id`,"a string",Nn(a));const d=o.line_item_ids;if(void 0!==d&&!En(d))throw new an(`${i}.line_item_ids`,"an array of strings",Nn(d));return[{id:a,line_item_ids:d,selected_option_id:s,selected_option_details:{...gn,...Tn(void 0===r?{}:r,gn,`${i}.selected_option_details`)}}]})}function Sn(e,t){if(!In(e))throw new an(t,"an object",Nn(e));return e}function In(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function Tn(e,t,n){const i=Sn(e,n),o={};for(const s in t){if(!Object.hasOwn(i,s))continue;const e=i[s];if("string"!=typeof e)throw new an(`${n}.${s}`,"a string",Nn(e));o[s]=e}return o}function En(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)}function Nn(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"an array":"object"==typeof e?"an object":"a "+typeof e}const Pn="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.",Ln={type:"object",additionalProperties:!1,properties:{payment:{...ln,required:["instruments"],properties:{instruments:{...ln.properties.instruments,minItems:1,items:{...ln.properties.instruments.items,required:["handler_id","credential"]}}}}}};class Dn extends Error{constructor(){super("WebMCP complete_checkout failed"),this.name="WebMcpCompleteCheckoutError"}}function Mn({isSubmitting:e,paymentInstrument:t,signal:n,checkout:i,shop:o,readCheckout:s,readSavedCards:r,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. ${Pn}`,inputSchema:Ln,annotations:{consequentialHint:!0,readOnlyHint:!1,untrustedContentHint:!0},execute:async p=>Dt(await async function(p){if(u||e.value)return te("completion_in_progress","A checkout completion is already in progress. Wait for it to finish, then call get_checkout before retrying.");u=!0;try{if(!o.hasFlagEnabled(q))return te("buyer_action_required","The buyer must manually complete checkout on the page. Do not attempt to complete checkout on their behalf.");const{payment:u}=function(e,{ignorePayment:t=!1}={}){const n=Sn(e,"input");return mn({object:n,allowedFields:["payment"],path:"input"}),t||void 0===n.payment?{}:{payment:un(n.payment,{path:"input.payment",requireCredential:!0})}}(p,{ignorePayment:!G(i)});u&&d.paymentCredentialSupplied(u);const h=i.latestReceipt.value?.status;if("processing"===h||"processing_remote_checkouts"===h||"polling_for_order"===h||"processed"===h||"action_required"===h)return s()??ge();const m=c();if(!m||n?.aborted)return _e();if(G(i)&&(u||t.value)){if(await m.waitForPendingNegotiations(),n?.aborted)return _e();const s=G(i)?u??t.value:void 0;if(s&&u&&!i.isPaymentRequired.value)return te("invalid_request","This checkout requires no payment. Retry complete_checkout without the payment field.",{invalidInputPath:"input.payment",invalidInputExpected:"no payment"});if(s&&F(s)&&i.isPaymentRequired.value){const c=new Yt({isSubmitting:e,paymentInstrument:t,checkout:i,shop:o,shopPay:a,observability:d,declaredFields:l,...m,readSavedCards:r});if(u&&(await c.loadAddressMetadata([u.billing_address]),n?.aborted))return _e();const p=c.writePayment({payment:s,applyBilling:void 0!==u});if(Z(p))return p}}let f,y,_=!1,g=!1,v={progressionStatus:"none"};const b=G(i)&&i.isPaymentRequired.value&&F(t.value),k=b?t.value:void 0;try{e.value=b,await m.journey.progress("web-mcp-complete-checkout",e=>{v=function(e){const t=function(e){return"invalid"===e.status?e.reasons:"violations"in e?[...e.violations,...e.errors].map(({code:e})=>e):[]}(e);return{progressionStatus:e.status,...t.length>0&&{progressionReasons:[...new Set(t)].sort().join(",")}}}(e),_="success"===e.status||"alreadyCompleted"===e.status,g||="negotiated"in e||"receipt"in e,"receipt"in e&&(y=e.receipt.id)},{onValidationSuccess:()=>{f=performance.now()}})}finally{void 0!==f&&d.submitForCompletion({accepted:_,submittedAt:f,receiptId:y,agenticInstrument:k}),e.value&&g&&(t.value=void 0),e.value=!1}const C=s();return _||C?.messages?.some(e=>"error"===e.type&&"requires_buyer_input"===e.severity)?C??ge("completion_failed",v):ge("completion_failed",v)}catch(h){return h instanceof an?ce(h,"complete the checkout"):(d.error({error:new Dn}),ge("internal_error"))}finally{u=!1}}(p),i)}}
1class Rn extends Error{constructor(){super("WebMCP get_checkout failed to read the checkout"),this.name="WebMcpGetCheckoutError"}}class On extends Error{constructor(e){super("WebMCP navigate_to_storefront failed",{cause:e}),this.name="WebMcpStorefrontNavigationError"}}function xn({shop:e,url:t}){if(e.hasStorefront)try{const n=new URL(e.previewReturnUrl??e.partnerStorefrontUrl??t.storefront());if("https:"!==n.protocol&&"http:"!==n.protocol)return;if(n.username||n.password)return;return n.href}catch{return}}function Un({checkout:e,shop:t,url:n,observability:i,signal:o,getPreactContext:s}){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(a,d)=>Dt(await async function(e,a){let d;try{if(null===e||"object"!=typeof e||Array.isArray(e)||Object.keys(e).length>0)return te("invalid_request","navigate_to_storefront takes no input. Retry with an empty object.",{invalidInputPath:"input",invalidInputExpected:"an empty object"});if(a.aborted||o.aborted)return ve();const c=s();if(!c)return te("internal_error",oe);if(r(c))return be();const l=xn({shop:t,url:n});if(!l)return te("navigation_failed","A supported storefront destination is not available. Stay on the current checkout.");const u=new Promise(e=>{d=setTimeout(()=>e("timeout"),3e4)}),p=await Promise.race([c.waitForPendingNegotiations(),u]);return a.aborted||o.aborted?ve():"timeout"===p?(i.log({name:"web_mcp_storefront_navigation_timed_out",message:"Storefront navigation timed out waiting for pending checkout updates"}),te("navigation_failed","Checkout updates are still pending. Navigation was not started. Retry after updates finish.")):r(c)?be():(window.location.assign(l),{status:"navigation_started",destination_url:l,message:"Refresh the available tools after the storefront loads."})}catch(c){return i.error({error:new On(c)}),te("navigation_failed","Unable to navigate to the storefront. Refresh the available tools and check the current page before retrying.")}finally{clearTimeout(d)}}(a,d?.signal??o),e)};function r({journey:t}){const n=e.latestReceipt.value;return t.completing.value||t.progressing.value||null!=n&&!["processed","failed","abandoned"].includes(n.status)}}const qn={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."},address_region:{type:"string",description:"Province or region code."},postal_code:{type:"string"}}},payment:{...ln,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. ${dn}`,properties:cn}},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"}}}}}}}}}}}}}}};
1class jn extends Error{constructor(){super("WebMCP update_checkout failed to apply"),this.name="WebMcpUpdateCheckoutError"}}function $n({isSubmitting:e,paymentInstrument:t,signal:n,checkout:i,shop:s,shopPay:r,router:a,getSavedCardSelector:d,readCheckout:c,readSavedCards:l,observability:u,getPreactContext:p,declaredFields:h,getFulfillmentController:m}){return{name:"update_checkout",title:"Update checkout",description:`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. ${Pn}`,inputSchema:qn,annotations:{consequentialHint:!1,readOnlyHint:!1,untrustedContentHint:!0},execute:async f=>Dt(await async function(f){let y;try{if(e.value)return ye();const _="shopPay"===i.identity.current.value,g=function(e,t={}){const n=function(e,t){const n=Sn(Sn(e,"input").checkout,"input.checkout"),i={};if(void 0!==n.context){const e="input.checkout.context",t=Tn(n.context,{address_country:void 0,address_region:void 0,postal_code:void 0},e);if(!t.address_country?.trim()||!t.postal_code?.trim())throw new an(e,"address_country and postal_code for a pickup search","incomplete locality");i.context={address_country:t.address_country.trim().toUpperCase(),postal_code:t.postal_code.trim(),...t.address_region?.trim()&&{address_region:t.address_region.trim().toUpperCase()}}}return void 0!==n.buyer&&(i.buyer=Tn(n.buyer,fn,"input.checkout.buyer")),void 0!==n.discounts&&(i.discountCodes=function(e){const t="input.checkout.discounts",{codes:n}=Sn(e,t);if(void 0!==n){if(!En(n))throw new an(`${t}.codes`,"an array of strings",Nn(n));return n}}(n.discounts)??[]),void 0!==n.declared_fields&&(i.declaredFields=function(e){const t="input.checkout.declared_fields";if(!Array.isArray(e))throw new an(t,"an array",Nn(e));const n=new Set;return e.map((e,i)=>{const o=`${t}[${i}]`,s=Sn(e,o);for(const t of Object.keys(s))if(!["key","value"].includes(t)&&!vn.has(t))throw new an(`${o}.${t}`,"a declared field key or value","an unknown field",{loggablePath:o});if("string"!=typeof s.key||0===s.key.length)throw new an(`${o}.key`,"a non-empty string",Nn(s.key));if(n.has(s.key))throw new an(`${o}.key`,"a unique declared field key",`duplicate ${JSON.stringify(s.key)}`);if(n.add(s.key),!Object.hasOwn(s,"value")||void 0===s.value)throw new an(`${o}.value`,"a value","undefined");return{key:s.key,value:s.value}})}(n.declared_fields)),void 0!==n.fulfillment&&Object.assign(i,function(e){const t="input.checkout.fulfillment",n=Sn(e,t);if(!Array.isArray(n.methods))throw new an(`${t}.methods`,"an array",Nn(n.methods));if(n.methods.length>1)throw new an(`${t}.methods`,"at most 1 fulfillment method",`${n.methods.length} methods`);let i={...yn};const s=[];for(const[r,a]of n.methods.entries()){const e=`${t}.methods[${r}]`,n=Sn(a,e),d=bn(n.type??"shipping",`${e}.type`),{id:c}=Tn(n,{id:void 0},e),l={...void 0!==c&&{id:c}},u=void 0===n.groups?[]:wn(n.groups,`${e}.groups`),p=Cn(n,e);switch(d){case"pickup":void 0===p&&kn(n.destinations,`${e}.destinations`),s.push({...l,type:d,...void 0!==p&&{selected_destination_id:p},groups:u});break;case"shipping":i=void 0===p?An(n,e):{saved_address_id:p},s.push({...l,type:d,groups:u});break;default:o(d)}}return{shippingAddress:i,fulfillmentMethods:{methods:s}}}(n.fulfillment)),t.ignorePayment||void 0===n.payment||(i.payment=un(n.payment,{path:"input.checkout.payment",savedPaymentMethodsOnly:t.savedPaymentMethodsOnly})),i}(e,t);return function(e,t){return{...e,...t,buyer:{...e.buyer,...t.buyer}}}({buyer:{...fn},discountCodes:[],declaredFields:[],shippingAddress:{...yn},fulfillmentMethods:{methods:[]},payment:void 0},n)}(f,{savedPaymentMethodsOnly:_,ignorePayment:_?!i.isPaymentRequired.value:!G(i)});g.payment&&"handler_id"in g.payment&&u.paymentCredentialSupplied(g.payment),u.updateCheckoutPartialInput(function(e,{checkout:t,paymentInstrument:n}){const i=In(e)&&In(e.checkout)?e.checkout:{},o="shopPay"===t.identity.current.value,s=Boolean(t.proposal.negotiated.fields.isS
1hippingRequired.value);return{buyer:!o&&void 0===i.buyer,fulfillment:s&&void 0===i.fulfillment,payment:G(t)&&F(n.value)&&void 0===i.payment}}(f,{checkout:i,paymentInstrument:t}));const v=p();if(!v||n?.aborted)return le();if("/review"===a.currentUrl.value.normalizedPath&&a.navigate("/"),g.payment&&"instrument_id"in g.payment&&!d())return le();const{loadPickupLocalityServices:b}=v;let k;const C=new Yt({isSubmitting:e,paymentInstrument:t,checkout:i,shop:s,shopPay:r,getSavedCardSelector:d,observability:u,declaredFields:h,...v,readSavedCards:l,getFulfillmentController:m,resolvePickupLocality:b?async e=>(k=await b(),k.resolvePickupLocality(e)):void 0,announcePickupLocality:e=>k?.announcePickupLocality(e),get negotiator(){return v.negotiator}});let A=!1;const w=new Promise(e=>{y=setTimeout(()=>{A=!0,e("timeout")},3e4)}),S=await Promise.race([C.applyUpdate(g,{isExpired:()=>A||Boolean(n?.aborted)}),w]);return"timeout"===S?(u.log({name:"web_mcp_update_timed_out",message:"[WebMcp] Update did not finish in time; update outcome is unknown",attributes:{timeoutMs:3e4}}),ue()):Z(S)?S:c()??ue()}catch(_){return _ instanceof an?ce(_,"update the checkout"):(u.error({error:new jn}),ue("internal_error"))}finally{clearTimeout(y)}}(f),i)}}function Hn(e){if("object"!=typeof e||null===e||!("error"in e))return"unknown";const{error:t}=e;return"object"==typeof t&&null!==t&&"code"in t?(n=t.code,J.includes(n)?t.code:"unknown"):"unknown";var n}function Bn(e,t,n,i){const o=Math.round(performance.now()-i),s=function(e){return"object"==typeof e&&null!==e&&"error"in e&&"object"==typeof e.error}(n),r={tool:t,outcome:s?"error":"success",...s&&{errorCode:Hn(n)}};e.log({name:"web_mcp_tool_executed",message:"[WebMcp] tool executed",attributes:{...r,...ee(n),durationMs:o}}),e.histogram({name:"web_mcp_tool_execution",value:o,unit:"ms",attributes:r})}function Fn(e,{activeTool:t,observability:n,checkout:i}){const o=e.name;return{...e,execute:async(...s)=>{const r=performance.now();if("navigate_to_storefront"===t.current||"navigate_to_storefront"===o&&void 0!==t.current){const e=Dt(te("checkout_busy","Another checkout tool is running. Wait for it to finish before retrying."),i);return Bn(n,o,e,r),e}return t.during(o,async()=>{const t=await e.execute(...s);return Bn(n,o,t,r),t})}}}performance.mark("checkout:web-mcp-runtime-loaded",{detail:{url:import.meta.url}});class Gn extends Error{constructor(e,t){super(`WebMCP tool registration failed for ${e}: ${String(t)}`),this.name="WebMcpRegistrationError",t instanceof Error&&(this.cause=t)}}function Yn({modelContext:e,signal:i,isSubmitting:o,paymentInstrument:s,checkout:r,i18n:a,shop:d,shopPay:c,url:l,router:u,observability:p,activeTool:h,onActiveToolCreated:m,getPreactContext:f,markToolCallStarted:y,getSavedCardSelector:_,declaredFields:g,getFulfillmentProvider:v,getStoreCreditProvider:b,unregisterInitializingTool:k}){if(i.aborted)return;const C=new Rt({observability:p,checkout:r}),T=function({checkout:e,shopPay:t}){const n=z({identity:e.identity,shopPay:t,negotiatedFields:e.proposal.negotiated.fields},{isApplePayAvailable:t.user.isApplePayAvailable}),i=e.proposal.negotiated.fields.paymentMethods,o=t.session.isInstallmentsSelected,s=e.installments.paymentMethodMustSupportInterestBearingLoans;return()=>{if("shopPay"!==e.identity.current.value||t.session.isLoading.value)return;const r=t.user.paymentMethods.value.filter(A).filter(({id:e})=>e!==w).sort(S),a=I(r,n.value),d=t.session.selectedPaymentMethod.value,c=e.proposal.proposed.paymentLines.value.some(({method:e})=>"wallet"===e.type&&"SHOP_PAY"===e.name);return r.map(e=>{const t=e.paymentAttributes;return{instrument:{id:e.id,type:"card",selected:c&&"CREDIT_CARD"===d?.paymentMethod&&d.id===e.id,display:{brand:t.brand,last_digits:t.lastDigits}},usable:!t.expired&&t.verified&&a.includes(e)&&!W(t,i,o,s)}})}}({checkout:r,shopPay:c}),E=e=>function({checkout:e,i18n:t,shop:n,router:i,readMode:o="negotiated",savedCards:s,declaredFields:r=new Map,paymentInstrument:a}){const d=vt({...At(e,t,n,o,i),savedCards:e.isPaymentRequired.value?s:void 0});if(!d)return;const c=(l=r,Array.from(l.values()).flatMap(e=>{const t=e.read();return t?[t]:[]}).sort((e,t)=>
1function(e,t){return e===t?0:e<t?-1:1}(e.key,t.key)));var l;const u=d.payment.instruments[0],p={...d,...a?{payment:{instruments:[Ct(a,e,u&&"billing_address"in u?u.billing_address:{})]}}:{},...c.length>0?{declared_fields:c}:{}},h=e.proposal.proposed.locationAddress.value,m=p.fulfillment?.methods,[f]=m??[];return 1===m?.length&&"pickup"===f?.type&&h?.countryCode&&h.postalCode&&h.coordinates?{...p,context:{address_country:h.countryCode,...h.zoneCode&&{address_region:h.zoneCode},postal_code:h.postalCode}}:p}({checkout:r,i18n:a,shop:d,router:u,readMode:e,savedCards:T(),declaredFields:g,paymentInstrument:s.value}),N=function(e){const t={key:It,read(){const t=Et(e);if(!t)return;const{title:n,value:i,required:o}=t.fields;return{key:It,purpose:"dev.shopify.shopping.declared_fields.generic",title:n.value,description:`Enter the buyer's ${n.value} tax number for this checkout.`,value_schema:{type:"string"},value:i.value||null,required:o.value??!1}},prepare:n=>null!==n&&"string"!=typeof n?{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 t=Et(e);if(!t)return!1;const{value:i}=t.fields;return i.value=n??"",!0}}};return t}(r);g.set(N.key,N);const P=function(e){const n=(e,t)=>e.hasGiftCard.value?"cannot change while the cart contains a gift card":e.hasFixedSellingPlan.value?"cannot change while the cart contains a fixed-date subscription":e.settling.value?"is still updating from a previous change; retry shortly":t&&0===e.paymentDue.value?.amount&&!e.applied.value?"cannot be applied when nothing is left to pay":void 0;return{key:St,read(){const t=e();if(t?.available.value)return{key:St,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:t.redeeming.value,required:!1}},prepare(i){if(null!==i&&"boolean"!=typeof i)return{requirement:"must be a boolean or null"};const o=i??void 0,s=e();if(!s)return{requirement:"is no longer offered on this checkout"};if(void 0!==o&&o!==s.redeeming.value){const e=n(s,o);if(e)return{requirement:e}}return{phase:"negotiate",get changed(){if(void 0===o)return!1;const t=e();return!!t&&(o!==t.redeeming.value||t.settling.value)},async apply(){if(void 0===o)return!1;const i=e();return!(!i||(await(e=>{if(!e.settling.peek())return Promise.resolve();let n,i=()=>{};return new Promise(o=>{n=setTimeout(o,1e4),i=t(()=>{e.settling.value||o()})}).then(()=>{clearTimeout(n),i()})})(i),e()!==i||!i.available.value||void 0!==n(i,o)||(await i.setRedeeming(o),i.applied.peek()!==o)))}}}}}(()=>b?.());g.set(P.key,P);const L=h??new K;m?.(L);const D=function(e,t){const n=e.name;return{...e,execute:(...i)=>{const o=performance.now(),s=e.execute(...i);return Bn(t,n,s,o),s}}}(function({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. ${Pn}`,inputSchema:{type:"object",properties:{}},annotations:{consequentialHint:!1,readOnlyHint:!0,untrustedContentHint:!0},execute:()=>Dt(function(){try{return t("processed"===e.latestReceipt.value?.status?"negotiated":"proposed")||te("internal_error",`Checkout data is not available yet. ${ie} ${ne("read checkout state")}`)}catch{return n.error({error:new Rn}),te("internal_error",`Unable to read the checkout. ${ne("read checkout state")}`)}}(),e)}}({checkout:r,readCheckout:E,observability:C}),C),M=[{tool:D,signal:i}],R=function(e,n){const i=new AbortController,o=t(function(){"processed"===e.latestReceipt.value?.status&&(this.dispose(),i.abort())});return n.addEventListener("abort",()=>{o(),i.abort()},{once:!0,signal:i.signal}),i.signal}(r,i);R.aborted||M.push(...[$n({isSubmitting:o,paymentInstrument:s,signal:i,checkout:r,shop:d,shopPay:c,router:u,getSavedCardSelector:_,readCheckout:E,readSavedCards:T,observability:C,getPreactContext:f,declaredFields:g,getFulfillmentController:()=>{const e=v?.();return e?function(e,{proposed:t}){return{getAvailableMethodTypes:()=>e.getAvailableMethodTypes().filter(e=>!e.includes("PICKUP_POINT")),setDesiredMethod(i,o){const s=e.getSelectedMethodTypes();e.markBuyerSelection();const r=t.deliveryLines.value.map(e=>e.value),a=Nt(t.merchandiseLines.value,r);var d,c;c=i,(d=s).length>0&&d.every(e=>"SHIPPING"===e||"LOCAL"===e?c.includes("SHIPPING")||c.includes("LOCAL"):c.includes(e))?n(()=>{for(const e of t.deliveryLines.value){const t=e.value;t.targetMerchandiseLines.some(({stableId:e})=>a.has(e))&&(t.deliveryMethodTypes.length!==i.length||t.deliveryMethodTypes.some(e=>!i.includes(e)))&&(e.value={...t,deliveryMethodTypes:i})}if(e.reconcileSameMethod(i),o){if(o!==t.locationAddress.value)for(const e of t.deliveryLines.value)e.value={...e.value,deliveryMethodHandle:void 0};t.locationAddress.value=o}}):e.applyMethodChange(i,s,o)}}}(e,r.proposal):void 0}}),Mn({isSubmitting:o,paymentInstrument:s,signal:i,checkout:r,shop:d,shopPay:c,readCheckout:E,readSavedCards:T,observability:C,getPreactContext:f,declaredFields:g})].map(e=>({tool:Fn(e,{activeTool:L,observability:C,checkout:r}),signal:R}))),xn({shop:d,url:l})&&M.push({tool:Fn(Un({checkout:r,shop:d,url:l,observability:C,signal:i,getPreactContext:f}),{activeTool:L,observability:C,checkout:r}),signal:i}),k?.(),C.watchReceipts(i);const O=M.map(async({tool:t,signal:n})=>{try{return await e.registerTool({...t,execute:(e,n)=>(y(),C.toolCalled(t.name),t.execute(e,n))},{signal:n}),"registered"}catch(i){return n.aborted?"withdrawn":(C.error({error:new Gn(t.name,i)}),"failed")}});return Promise.all(O).then(e=>{if(i.aborted)return;const t=e.filter(e=>"registered"===e).length;C.log({name:"web_mcp_tools_registered",message:"[WebMcp] tools registered",attributes:{registered:t,failed:e.filter(e=>"failed"===e).length}}),t>0&&C.initialized()}).catch(()=>{}),L}export{Yn as registerWebMcpTools};
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.