1import{c as e,j as t,n,f as i,a as o,b as s}from"./2c1ab0fe.GMbxnz74.js";import{c as r,s as a,a as d,b as c,R as l,d as u,i as p,e as h,n as m,r as f,f as y,g as _,h as g,j as v,C as b,V as k,p as C,k as A,l as w,U as S,m as I,o as T,q as E,t as P,u as N,F as L,v as D,w as M,x as R,y as O,z as x,A as U,B as q,D as $,E as j,G as H}from"./4c290a1e.C6TDJ9Fn.js";import{i as B}from"./5fda1420.KYpufQ--.js";import{c as F,i as G}from"./0a7dffce.DfUtZWCu.js";import{h as Y,a as W,i as z}from"./6a2fc6d6.Cw2cQrl7.js";import{s as X}from"./08a3b809.BxtDOfoo.js";class V{#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 K=["buyer_action_required","checkout_busy","completion_failed","completion_in_progress","internal_error","invalid_request","navigation_failed","rejected","update_failed"];function J(e){return"object"==typeof e&&null!==e&&"error"in e}const Q=Symbol("WebMcpFailureDetails");function Z(e){if(!J(e))return;const t=e.error;return"object"==typeof t&&null!==t&&Q in t?t[Q]:void 0}function ee(e,t,n){const i={code:e,message:t};return n&&Object.defineProperty(i,Q,{value:n}),{error:i}}function te(e){return`Do not attempt to ${e} by interacting with the page.`}const ne="Retry shortly.",ie=`Checkout is still initializing. ${ne}`,oe="Nothing was applied.",se=`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. ${te("update the checkout")}`,re=`Checkout completion could not be confirmed. Call get_checkout for the current state and its messages before retrying. ${te("complete the checkout")}`;function ae(e,t,n,i="Call get_checkout before retrying."){return ee(e,`${t}: ${n} ${oe} ${i}`)}function de(e,t){return ee("invalid_request",`${e.message} Correct the input and retry. ${te(t)}`,{invalidInputPath:e.loggablePath.replace(/\[\d+\]/g,"[]"),invalidInputExpected:e.expected})}function ce(){return ee("internal_error",`Checkout is not available for updates. ${ne} ${te("update the checkout")}`)}function le(e="update_failed"){return ee(e,se)}function ue(e){return ee("rejected",`The selected delivery option does not support selected_option_details.${e}. ${oe} Remove ${e} from selected_option_details or choose an option that supports it, then retry. ${te("update the checkout")}`)}const pe=`${oe} 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. ${te("update the checkout")}`;function he(e){return ae("rejected","fulfillment",e)}function me(e,t){return ae("rejected",e,`${t}.`)}function fe(){return ee("completion_in_progress","A credentialed completion is in progress. Wait for it to finish before updating payment.")}function ye(){return ee("internal_error",`${ie} ${te("complete the checkout")}`)}function _e(e="completion_failed",t){return ee(e,re,t)}function ge(){return ee("navigation_failed","Navigation was cancelled. The tool did not leave checkout.")}function ve(){return ee("checkout_busy","Checkout submission or payment is in progress. Wait for it to finish and call get_checkout before navigating away.")}function be(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 me(`${e}.key`,"must identify a declared field available in the current checkout");const o=n.prepare(a);if("requirement"in o)return me(`${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 me("$.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 ke(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 Ce(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=ke(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:ke(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 Ae(e,{extendedAddressMode:t}){const n=e.address_country?.toUpperCase()??"",i=t.get(n),o=null===i?function(e,t){const n=Se(t);return{address1:"line"in n?n.line:Re(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=a(e,t.line,!0);if(!n?.streetNumber)return{address1:t.line};const i=d({countryCode:e,streetName:n.streetName??"",streetNumber:n.streetNumber});return null==i?{address1:t.line}:{address1:i,packedLine2:n.line2}}const n=d({countryCode:e,...t});return null==n?{address1:Oe(t)}:{address1:n,...t}}(e,Se(t)),{neighborhood:s,...r}=function(e,{extended_address:t="",district:n},i){const o=c(e,t);if(!o)return{address2:Ie(t,i)};const s=Ie(o.line2??"",i),r=n??o.neighborhood??"";return{address2:Me(e,s,r),line2:s,neighborhood:r}}(e,t,i);return{...o,...r,..."dedicated"===n?void 0!==s&&{district:s,neighborhood:""}:{neighborhood:s}}}(n,e,i);return{...r({...e,street_address:o.address1,extended_address:o.address2}),company:e.company??"",district:void 0,subdistrict:void 0,...o}}function we(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?Te(n,e):Ne(n,e,i),address_locality:e.city,address_regi
1on:e.zoneCode,address_country:e.countryCode,postal_code:e.postalCode}}function Se({street_address:e="",street_name:t,street_number:n=""}){return t?.trim()?{streetName:t,streetNumber:n}:{line:e}}function Ie(e,t){return t&&t!==e.trim()?xe(e,t):e}function Te(e,t){return{street_address:Ee(e,t),extended_address:Pe(e,t)}}function Ee(e,{address1:t,streetName:n,streetNumber:i}){return t||!n&&!i?t:De(e,{streetName:n??"",streetNumber:i??""})}function Pe(e,{address2:t,line2:n,district:i,neighborhood:o}){const s=i||o;return null!=n||s?Me(e,n??"",s??""):t}function Ne(e,t,n){const i=function(e,t,n){return"dedicated"!==n||null==t.streetName&&null==t.streetNumber?t.address1?.includes(l)?a(e,t.address1):null:t}(e,t,n);return{...i?.streetName?{street_name:i.streetName,street_number:i.streetNumber??""}:{street_address:Ee(e,t)},...Le(e,t,n)}}function Le(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(l)?c(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 De(e,t){return d({countryCode:e,...t})??Oe(t)}function Me(e,t,n){return u({countryCode:e,line2:t,neighborhood:n})??xe(t,n)}function Re(e,t){return De(e,t).split(l).join("")}function Oe({streetName:e,streetNumber:t}){return[t,e].filter(Boolean).join(" ")}function xe(e,t){return[e,t].filter(Boolean).join(", ")}function Ue(e){return e?.flatMap(e=>(e.lineComponents.length?e.lineComponents:[e]).filter(e=>e.requiresShipping).map(qe))??[]}function qe(e){return e.stableId}function $e(e){return"presentationLevel"in e&&"CART"===e.presentationLevel}function je(e){return"SHIPPING"===e||"LOCAL"===e||p(e)}function He(e,t,n){return Boolean(e&&!n&&(t.some(e=>!je(e))||t.some(p)&&t.some(e=>"SHIPPING"===e||"LOCAL"===e)))}function Be(e,t){switch(t){case"phone_number":return Boolean(e.phoneRequired);case"instructions":return Boolean(e.acceptsInstructions)}}function Fe(e,t){if(!e?.length||!t?.length)return!1;const n=new Set(t),i=e.filter(e=>e.requiresShipping).map(e=>qe(e));return i.length===n.size&&i.every(e=>n.has(e))}const Ge="pickup";function Ye(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 p(n)?"pickup":"shipping"}function We(e){const t=e.filter(e=>"pickup"===Ye(e)),n=t.map(e=>{const t=new Map;for(const n of e.methods){if(!n.pickupLocation)continue;const i=ze(n.pickupLocation);t.has(i)&&n.handle!==e.selectedDeliveryMethodHandle||t.set(i,n)}return t}),i=n[0];if(!i)return[];const o=[];for(const[s,r]of i){const e=[];for(const[i,o]of t.entries()){const t=n[i].get(s);if(!t)break;e.push({line:o,method:t})}e.length===t.length&&o.push({id:r.handle,selections:e})}return o}function ze(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 Xe=we;function Ve(e,t){const n=new Set(t.flatMap(e=>e.targetMerchandiseLines?.map(qe)??[])),i=new Map,o=new Set;for(const s of e.merchandiseLines??[]){if("proposed"!==e.readMode&&!s.requiresShipping)continue;const t=qe(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(qe(e))).map(qe));if(!r.size)continue;const a=e.proposedDeliveryLines?.filter(e=>e.targetMerchandiseLines.some(e=>qe(e)===t||r.has(qe(e)))).flatMap(e=>e.deliveryMethodTypes),d=a?.length&&a.every(p)?"pickup":"shipping",c=i.get(d)??[];c.push(..."proposed"===e.readMode?r:[t]),i.set(d,c)}return i}function Ke(e){return[...Ve(e,[])].map(([t,n])=>({id:t,type:t,line_item_ids:n,destinations:[],..."shipping"===t?et(e):{},groups:[]}))}function Je(e){const t=new Set;for(const n of e){const e=Ye(n);e&&t.add(e)}return Array.from(t)}function Qe(e){return"SHIPPING"===e||"LOCAL"===e||p(e)}function Ze(e,t,n){if("shipping"===e)return et(n);const i=We(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:Xe(n.address,t)}:void 0}(t[0].method,n.addressContext);return i?[{...i,id:e}]:[]}),...o&&{selected_destination_id:o.id}}}function et({savedDestinations:e,shippingAddress:t,addressContext:n}){if(void 0===e)return t&&y(t)?{destinations:[tt(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})=>h(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",...Xe(t,n)}
1)),...o&&{selected_destination_id:o}}:{}}function tt(e,t){return{...Xe(e,t),id:nt(e),type:"shipping_address"}}function nt(e){return["shipping",e.countryCode,e.postalCode].filter(Boolean).join("-").replace(/\s+/g,"")}function it(e,t){const n=ot(e),i=m(e),o=e.proposedLine?e.selectedDeliveryMethodHandle:i?.handle,s=o?function(e,t,n){const i=function(e,t,n=ot(e)){return t?.find(t=>Boolean(e.id)&&t.id===e.id)??t?.find(e=>Fe(e.targetMerchandiseLines,n))}(e,n,t);if(!i||!e.selectedDeliveryMethodHandle||i.deliveryMethodHandle!==e.selectedDeliveryMethodHandle)return;const o=i.deliveryMethodOptions;if(!o)return;const s=m(e),r=s&&!Be(s,"phone_number")?void 0:o.phone,a=s&&!Be(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"===Ye(e),a=r?[{...i?st(i):{totals:[]},id:Ge,title:"Pickup"}]:e.methods.filter(({methodType:e})=>"SHIPPING"===e||"LOCAL"===e).map(st);return{id:e.id??"",line_item_ids:n,options:a,...o&&{selected_option_id:r?Ge:o},...s&&{selected_option_details:s}}}function ot(e){return e.targetMerchandiseLines?.filter(e=>e.requiresShipping).map(e=>qe(e))??[]}function st(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:p(e.methodType)?"Pickup":"Shipping",amount:ke(e.costAfterDiscounts)}]}}function rt(e){return"available"===e.status}const at=new Map([["terms-of-service","terms_of_service"],["privacy-policy","privacy_policy"],["refund-policy","refund_policy"],["shipping-policy","shipping_policy"]]);function dt(e){const t=[];for(const{handle:n,url:i}of e){const e=at.get(n);e&&t.push({type:e,url:i})}return t}const ct={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 lt(e){return ct[e]}const ut=new Set(["AcceptNewTermViolation","RequiredArtifactsUnavailableViolation"]),pt=new Set(["PendingTermViolation"]),ht=new Set(["PAYMENTS_UNACCEPTABLE_PAYMENT_AMOUNT"]),mt={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 ft(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 yt({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:ke(e)}),c.push(...function({currencyCode:e,discountLines:t,itemsDiscountAmount:n,cartLevelDiscountAmount:i}){let o=i;for(const r of t?.lines??[])if(G(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:ke({amount:-n,currencyCode:e})}),o>0&&s.push({type:"discount",display_text:"Discount",amount:ke({amount:-o,currencyCode:e})}),s}({currencyCode:e.currencyCode,discountLines:i,itemsDiscountAmount:t,cartLevelDiscountAmount:n}))),null!=o&&c.push({type:"fulfillment",display_text:"Shipping",amount:ke(o)}),null==r||a||c.push({type:"duty",display_text:"Duties",amount:ke(r)}),null!=s&&c.push({type:"tax",display_text:"Taxes",amount:ke(s)}),null!=d&&c.push({type:"total",display_text:"Total",amount:ke(d)}),c}function _t(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)=>
1{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:ke(o)}),0!==s&&o&&(t+=s,a.push({type:"items_discount",amount:ke({...o,amount:-s})}));const d=o?{...o,amount:o.amount-s}:e.totalPrice;return a.push({type:"total",amount:ke(d)}),{id:qe(e),...e.parentRelationship?.parent?.stableId?{parent_id:e.parentRelationship.parent.stableId}:{},quantity:e.quantity,item:{id:e.variantId??e.stableId,title:e.title,price:ke(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=m(s);t?.cost&&(n.push({cost:t.costAfterDiscounts.amount,costBeforeDiscounts:t.cost.amount,rateGroupKey:"SHIPPING"===t.methodType?f({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}=F(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=Ce(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 Ke(e);const n="filled"!==t?.status&&"partial"!==t?.status||!t.lines?[]:t.lines.filter(rt),i=("proposed"===e.readMode?function(e,t,n){const i=new Map;for(const o of n??[]){i.set(qe(o),Ue([o]).length>0);for(const e of o.lineComponents)i.set(qe(e),e.requiresShipping)}return(t??[]).map(t=>{const n=t.targetMerchandiseLines.filter(e=>e.requiresShipping).map(e=>qe(e)),o=e.find(e=>void 0!==t.id&&e.id===t.id)??e.find(e=>e.type===t.type&&Fe(e.targetMerchandiseLines,n));return{...o,status:"available",id:t.id,type:t.type,targetMerchandiseLines:t.targetMerchandiseLines.flatMap(e=>{const t=i.get(qe(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(Qe):e.methods.some(e=>Qe(e.methodType)))&&e.targetMerchandiseLines?.some(e=>e.requiresShipping));if("proposed"===e.readMode&&!i.length)return Ke(e);const o="partial"===t?.status?Ve(e,i):new Map,s=new Set([...Je(i),...o.keys()]),r=[];for(const a of s){const t=i.filter(e=>Ye(e)===a),n=t.map(t=>it(t,t.proposedLine?[t.proposedLine]:e.proposedDeliveryLines)),s=[...new Set([...n.flatMap(e=>e.line_item_ids),...o.get(a)??[]])];r.push({id:a,type:a,line_item_ids:s,destinations:[],...Ze(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=v(o)}=e,r=function(e){const t=[];for(const n of e.violations??[]){if(ut.has(n.__typename))continue;if(ht.has(n.code))continue;if(e.requiresCaptcha&&b.has(n.code))continue;const i=n.code.startsWith("DISCOUNTS_"),o=i||pt.has(n.__typename),s=lt(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:ft(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(mt),{status:a,messages:r}}({i18n:e.i18n,requiresBuyerReview:null!=e.buyerReviewUrl,requiresCaptcha:e.requiresCaptcha,violations:e.violations,receipt:e.receipt,isShippingRequired:"proposed"===e.readMode?Ue(t).length>0:e.isShippingRequired,hasShippingAddress:"proposed"===e.readMode?y(e.shippingAddress):null!=e.shippingAddress,deliveryNext:e.deliveryNext,skipsShippingAddress:"proposed"===e.readMode?vt(c,t):void 0,hasUnselectableShippingGroup:gt(c,t,e.readMode)}),p=function(e){if("processed"!==e?.status)return;const t=e.orderIdentity.buyerIdentifier,n=_(e.orderIdentity.id);return{...n?{id:g("Order",n)}:{},...t?{label:t}:{},permalink_url:e.confirmationPage.url}}(e.receipt),h=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:we(e,t)}]:[]}}(e.billingAddress,e.addressContext,e.savedCards),k=(C=e.savedCards??[]).some(({instrument:e,usable:t})=>e.selected&&!t)?[{type:"error",severity:C.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 C;const A=[...u,...k];return{...e.id?{id:e.id}:{},...e.continueUrl?{continue_url:e.continueUrl}:{},currency:e.runningTotal.currencyCode,status:"ready_for_complete"===l&&k.length?"incomplete":l,..."requires_escalation"===l&&e.buyerReviewUrl?{continue_url:e.buyerReviewUrl}:{},links:dt(e.merchantPolicies),line_items:i,totals:yt({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:h,...A.length?{messages:A}:{},...p&&{order:p}}}function gt(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=Ue([e]);return t.length>0&&!i.has(qe(e))&&!t.every(e=>i.has(e))})}function vt(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(qe(e))||Ue([e]).every(e=>n.has(e)))}function bt(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 kt(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:Ct(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 Ct(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===k.CreditCard||c.type===k.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||!C(s))return a;const d=s[0]?.method;if("wallet"===d?.type){const n=i.fields.runningTotal.value,o=n&&n.amount<=0,s=A(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&&B({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 At="store_credit";const wt="tax_number",St=["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 It(e){const t=e.proposal.proposed.localizationExtensions.value.flatMap(e=>St.some(t=>t===e.fields.key.value)?[e]:[]);return 1===t.length?t[0]:void 0}function Tt(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 Et(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 Pt(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 Nt(e,t){return{...e,ucp:Pt(J(e)?"error":"success",t.proposal.negotiated.fields.ucp.value?.paymentHandlers)}}const Lt={"shopify.card":"shopify.card",shop_pay:"shop_pay_approval_id"};class Dt{#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?Lt[i.handler_id]:"unknown",identity:this.#i.identity.current.peek()};this.#n.histogram({name:"web_mcp_submit_for_completion",value:Mt(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&&Y(e)&&(this.#d=!0,this.#l("web_mcp_payment_credential_update_called",{payment:Lt[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=Mt(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 Mt(e){return Math.round(performance.now()-e)}function Rt(e){return e?.replace(/[\s-]/g,"").toUpperCase()}function Ot(e,{checkout:t},n){const i=e.fulfillmentMethods.methods;if(i.length>1)return he("At most one fulfillment method is supported.");const o=i[0];if(void 0!==o?.id&&o.id!==o.type)return he("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=Tt(s.merchandiseLines.value,a),c=Et(a,d);if(c.some(p)&&c.some(xt)){const e=r.fields.deliveryNext.value,t="filled"===e?.status||"partial"===e?.status?e.lines.filter(e=>"available"===e.status):[],n=Et(a.map(e=>{const n=t.find(({id:t})=>Boolean(e.id)&&t===e.id)??t.find(t=>Fe(t.targetMerchandiseLines,e.targetMerchandiseLines.filter(e=>e.requiresShipping).map(qe))),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(p)&&n.some(xt))return he("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(p)?"pickup":void 0),u=Boolean(e.context&&!Ut(s.locationAddress.value,e.context));if(u&&"pickup"!==l)return he("Changing context locality requires a pickup method.");if(!o&&"pickup"!==l)return;const h=e=>"pickup"===l?p(e):xt(e);if(o&&(void 0!==o.selected_destination_id||o.groups.length))return u||c.length&&!c.some(h)?he("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 u?he("Pickup-point locality discovery is not supported. Select an existing destination instead."):void 0;if(!d.size)return he("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 he("Pickup search requires an established checkout country. Ask the buyer to choose a country in checkout.");if(e.context.address_country!==t)return he("Pickup search must remain in the checkout country.")}if(!n&&!u&&c.every(h)&&c.length)return;const m=!c.length||!c.every(h);if(!n&&m)return he("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 he(`The checkout does not offer ${l}.`);const y=r.fields;return(m||u)&&(y.mustSelectProvidedShippingRate.value||y.mustSelectProvidedAddress.value||!1===y.canUpdateDeliveryAddress.value)?he("The checkout locks its delivery method or address."):{methodTypes:f,needsLocalityLookup:u,changesMo
1de:m}}function xt(e){return"SHIPPING"===e||"LOCAL"===e}function Ut(e,t){return function(e,t){return Boolean(e?.coordinates)&&e?.countryCode===t.countryCode&&(!t.zoneCode||e.zoneCode===t.zoneCode)&&Rt(e.postalCode)===Rt(t.postalCode)}(e,{countryCode:t.address_country,zoneCode:t.address_region,postalCode:t.postal_code})}const qt={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 Zt(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(),qt):{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=Zt(e.address_country,"fulfillment.methods[0].destinations[0].address_country",t.shop);if(r)return r;const a=Ae(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(),qt)}}};function jt(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)?qt:{status:"failed"}}}:{status:"rejected",field:"payment"}}function Ht({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(on):[],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(je).length)continue;const o=r.find(t=>Boolean(e)&&t.id===e)??r.find(e=>Fe(e.targetMerchandiseLines,t.filter(e=>e.requiresShipping).map(qe))),s=o?.methods.find(e=>e.handle===i);if(s){if(!je(s.methodType))continue}else if(He(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:We(n).find(({id:t})=>t===e.selected_destination_id);if(void 0!==e.selected_destination_id&&!i)throw new Kt("unknown_pickup_destination");const o=new Map;for(const s of e.groups){if(s.selected_option_id!==Ge)throw new Kt("unknown_fulfillment_option");const e=en(s,n);if("pickup"!==Ye(e)||i&&!i.selections.some(t=>t.line===e)||o.has(e))throw new Kt("unknown_fulfillment_group");o.set(e,s)}return i?i.selections.map(({line:e,method:n})=>tn(e,n,o.get(e)?.selected_option_details,t)):[...o].map(([e,n])=>{const i=e.methods.find(t=>t.handle===e.selectedDeliveryMethodHandle&&p(t.methodType)&&t.pickupLocation);if(!i)throw new Kt("unknown_pickup_destination");return tn(e,i,n.selected_option_details,t)})}(e,t,n):e.groups.map(e=>{const i=en(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"!==Ye(i))throw new Kt("unknown_fulfillment_option");return tn(i,o,e.selected_option_details,t)}))}(e,i.deliveryLines.peek(),r))a.set(t.deliveryLine,t)}catch(c){if(!(c instanceof Kt))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(je)))continue;
1const{selectedOptionId:i,selectedOptionDetails:o}=t??{};e.value={...e.peek(),deliveryMethodHandle:i,deliveryMethodOptions:nn(o),...void 0===i&&{isCustomRate:void 0,customDeliveryStrategy:void 0}}}return qt}}}const Bt=[({buyer:e},{checkout:t,shopPay:n})=>{const i=z({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,qt)}},({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}),qt}}},$t,Ht];function Ft(e,t,{fulfillmentRequest:n,fulfillment:i,locationAddress:o}={}){const s=[];for(const r of Bt){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),qt)})}const a=r===Ht?Ht(e,t,void 0!==n):r(e,t);if(void 0!==a){if("rejected"===a.status)return Vt(a.field,a.reason);s.push(a)}}return s}class Gt{#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 J(s)?s:(n(()=>{s?.apply(),o?.apply()}),{status:"applied"})}#h(e){const{checkout:t}=this.#p;if(!W(t))return;const i=void 0===e?void 0:Ae(e,t.address);return{apply({replacement:e=!1}={}){if(!W(t))return!1;const{proposed:o,negotiated:s,facts:r}=t.proposal,a=!1===s.fields.isShippingRequired.value;if(i&&!P(i)&&(a||!function(e,t){const n=we(t.proposal.proposed.shippingAddress.value,t.address);return x(e,Ae(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===k.CreditCard||e.method.type===k.PayPal||function(e){if("wallet"!==e.method.type)return!1;switch(e.method.name){case"APPLE_PAY":return $(e);case"GOOGLE_PAY":return q(e);case"PAYPAL_EXPRESS":return U(e);default:return!1}}(e))}(o)&&(n(()=>{o.billingAddress.value=Ae({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(!W(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=N(a??[],"direct"===d?.method.type&&Boolean(d.method.alternative));return!e||("shopify.card"===e.handler_id?c:i.hasFlagEnabled(L)&&D(a))?{apply(){W(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=M(s.paymentLines.value,{method:{type:"direct",paymentMethodIdentifier:c.paymentMethodIdentifier,alternative:c.alternative}},R(i))):"shop_pay"===e.handler_id&&e.credential?.approval_id&&(s.paymentLines.value=M(s.paymentLines.value,{method:{type:"shopWallet",shopPayApprovalId:e.credential.approval_id}},R(i)));for(const e of Object.values(s.directPaymentErrors))e.value=void 0;s.generalPaymentError.value=void 0,s.generalPaymentErrorCode.value=void 0}})}}:ee("invalid_request","This checkout does not accept the supplied payment handler. Call get_checkout for the current checkout state.",{invalidInputPath:"payment.instruments[].handler_id",invali
1dInputExpected:"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,W(this.#p.checkout)?o:void 0]),t?.())return le();if(this.#p.isSubmitting.value)return fe();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 le();let r=be(e.declaredFields,this.#p.declaredFields);if(J(r))return r;if(r.some(({changed:e})=>e)){if(await this.#p.waitForPendingNegotiations(),t?.())return le();if(this.#p.isSubmitting.value)return fe();if(r=be(e.declaredFields,this.#p.declaredFields),J(r))return r}let a,d=this.#p.getFulfillmentController?.(),c=Ot(e,this.#p,d);if(J(c))return c;if(c?.needsLocalityLookup&&e.context){try{const t=this.#p.resolvePickupLocality;if(!t)throw new Yt;a=await t(e.context)}catch(C){return this.#p.observability.error({error:C instanceof Yt?C:new Yt(C)}),t?.()?le():ae("update_failed","context","Pickup locality lookup is unavailable.",`Call get_checkout and retry with the latest checkout. ${te("update the checkout")}`)}if(t?.())return le();if(!a)return ae("rejected","context","Could not resolve a unique postal locality.","Check address_country, address_region and postal_code, then retry.");if(r=be(e.declaredFields,this.#p.declaredFields),J(r))return r}if(e.context){const t=this.#p.checkout.proposal.proposed.locationAddress.value;Ut(t,e.context)&&(a=t)}if(d=this.#p.getFulfillmentController?.(),c=Ot(e,this.#p,d),J(c))return c;let l=this.#h(o);const u=e.payment&&"handler_id"in e.payment?e.payment:void 0;let h=this.#m(u);if(J(h))return h;let m=void 0===s?void 0:jt(s,this.#p);if("rejected"===m?.status)return Vt(m.field);let f=Ft(e,this.#p,{fulfillmentRequest:c,fulfillment:d,locationAddress:a});if(J(f))return f;if(t?.())return le();const y=[];let _=!1;for(const n of["negotiate","stage"]){if("stage"===n&&_&&(r=be(e.declaredFields,this.#p.declaredFields),J(r)))return le();for(const i of r)if(i.phase===n&&i.changed){if(t?.())return le();try{if(!(await i.apply())||t?.())return le()}catch{return le()}if("stage"===i.phase)y.push(i.negotiation);else{if(_=!0,d=this.#p.getFulfillmentController?.(),c=Ot(e,this.#p,d),J(c))return le();if(f=Ft(e,this.#p,{fulfillmentRequest:c,fulfillment:d,locationAddress:a}),J(f))return le();if(l=this.#h(o),h=this.#m(u),J(h))return le();if(m=void 0===s?void 0:jt(s,this.#p),"rejected"===m?.status)return le()}}}if(h){const e=h;f.push({status:"ready",negotiation:{include:["paymentLines"],loading:["paymentLines"],fieldsToResolve:["paymentLines"]},apply:async()=>(e.apply(),qt)})}if(!m&&0===f.length&&0===y.length&&!l)return{status:"applied"};if(t?.())return le();if(this.#p.isSubmitting.value)return fe();if((await Promise.all(n(()=>f.map(e=>e.apply())))).find(e=>"failed"===e.status)||t?.())return le();if(this.#p.isSubmitting.value)return fe();if(m){if("failed"===(await m.apply()).status||t?.())return le();if(await this.#p.waitForPendingNegotiations(),t?.())return le();if(this.#p.isSubmitting.value)return fe()}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:zt(b,"include"),loading:zt(b,"loading"),fieldsToResolve:zt(b,"fieldsToResolve")}));var b;await this.#p.waitForPendingNegotiations();const k=function(e){return"success"===e?.status||"error"===e?.status?{status:"applied"}:le()}(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 le();if(!J(k)&&!t?.()&&c?.needsLocalityLookup&&a&&e.context&&Ut(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=Et(t,Tt(e.merchandiseLines.value,t));n.length&&n.every(p)&&this.#p.announcePickupLocality?.(a)}return t?.()?le():k}async loadAddressMetadata(e){const t=new Set;for(const i of e){const e=i?.address_country?.toUpperCase();i&&e&&Wt(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({legacyFiltering:{include:n},...i,silenceViolations:O(n),runListenersOnError:n.includes("shippingAddress")||n.includes("discountLines"),onComplete:e=>{t=e}}),t}}
1class Yt extends Error{constructor(e){super("WebMCP pickup locality lookup failed",{cause:e}),this.name="WebMcpLocalityLookupError"}}function Wt(e,t){const n=Boolean(t.street_address||t.street_name||t.street_number),i=Boolean(t.extended_address||t.district),o=null!==a(e,""),s=null!==c(e,"");return n&&o||i&&s}function zt(e,t){return[...new Set(e.flatMap(e=>e[t]))]}const Xt={context:"context",buyer:"buyer",discountCodes:"discounts",declaredFields:"declared_fields",shippingAddress:"fulfillment",fulfillmentMethods:"fulfillment",payment:"payment"};function Vt(e,t){return t instanceof Qt?function(e,t,n){const i=n?` Supported countries: ${n.join(", ")}.`:"";return ee("rejected",`${e} ${t} is not a country this shop ships to. ${oe}${i} Tell the buyer. ${te("update the checkout")}`)}(t.path,t.countryCode,t.listedCountryCodes):"unsupported_option_instructions"===t?ue("instructions"):"unsupported_option_phone"===t?ue("phone_number"):"unknown_fulfillment_group"===t?ee("rejected",`fulfillment.methods[].groups[] does not match a delivery group in the current checkout. ${pe}`):"unselectable_fulfillment_group"===t?ee("rejected",`fulfillment.methods[].groups[] has no selectable delivery option in the current checkout. ${oe} Send the update without groups, then choose an option from the next get_checkout. ${te("update the checkout")}`):"unknown_fulfillment_option"===t?ee("rejected",`fulfillment.methods[].groups[].selected_option_id is not an option for this group in the current checkout. ${pe}`):ee("update_failed",`Unable to update ${Xt[e]}. Call get_checkout to review the checkout and its messages before retrying. ${te("update the checkout")}`)}class Kt extends Error{constructor(e){super(e),this.name="WebMcpFulfillmentMethodUpdateError",this.reason=e}}const Jt=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 Zt(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<=Jt?n.map(({value:e})=>e):void 0)}}function en(e,t,n="unknown_fulfillment_group"){const i=t.find(t=>Boolean(e.id)&&t.id===e.id)??t.find(t=>Fe(t.targetMerchandiseLines,e.line_item_ids));if(!i)throw new Kt(n);return i}function tn(e,t,n,i){const o=i.find(t=>Boolean(e.id)&&t.value.id===e.id)??i.find(t=>Fe(t.value.targetMerchandiseLines,e.targetMerchandiseLines?.filter(e=>e.requiresShipping).map(qe)));if(!o)throw new Kt("unknown_fulfillment_group");if(!o.value.deliveryMethodTypes.includes(t.methodType))throw new Kt("unsupported_fulfillment_transition");return function(e,t){if(t){if(void 0!==t.instructions&&!Be(e,"instructions"))throw new Kt("unsupported_option_instructions");
1if(void 0!==t.phone_number&&!Be(e,"phone_number"))throw new Kt("unsupported_option_phone")}}(t,n),{deliveryLine:o,selectedOptionId:t.handle,selectedOptionDetails:n}}function nn(e){return{phone:e?.phone_number,instructions:e?.instructions}}function on(e){return"available"===e.status}const sn=s()(["shipping","pickup"]);class rn 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 an='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.',dn={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)."}},cn={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. ${an}`,properties:dn}}}}}};function ln(e,{path:t,requireCredential:n=!1,savedPaymentMethodsOnly:i=!1}){const o=wn(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 rn(t,"an array",En(e));if(1!==e.length)throw new rn(t,"1 item",`${e.length} items`);return wn(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 rn(`${t}.${n}`,"a saved instrument id from get_checkout, not new payment data","an unsupported field",{loggablePath:t});return{instrument_id:un(e.id,`${t}.id`)}}(r,s);const a=r.handler_id;if(!n&&void 0===a&&void 0===r.credential){const e=pn(r,s);return void 0===e?void 0:{billing_address:e}}if("shopify.card"!==a&&"shop_pay"!==a)throw new rn(`${s}.handler_id`,"shopify.card or shop_pay","an unsupported handler");const d=In(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 rn(`${s}.type`,c,"an unsupported instrument type");const l=pn(r,s),u={id:d.id??j(),...void 0===l?{}:{billing_address:l}},p=`${s}.credential`,h=n||void 0!==r.credential?wn(r.credential,p):void 0;if("shopify.card"===a){if(void 0===h)return{...u,handler_id:a,type:"card"};if(hn({object:h,allowedFields:["type","token"],path:p}),void 0!==h.type&&"shopify_token"!==h.type)throw new rn(`${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:un(h.token,`${p}.token`)}:{}}}}if(void 0===h)return{...u,handler_id:a,type:"shop_pay"};if(hn({object:h,allowedFields:["type","approval_id"],path:p}),void 0!==h.type&&"shop_token"!==h.type)throw new rn(`${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:un(h.approval_id,`${p}.approval_id`).trim()}:{}}}}function un(e,t){if("string"!=typeof e||0===e.trim().length)throw new rn(t,"a non-empty string",En(e));return e}function pn(e,t){if(void 0!==e.billing_address)return In(e.billing_address,yn,`${t}.billing_address`)}function hn({object:e,allowedFields:t,path:n}){if(Object.keys(e).some(e=>!t.includes(e)))throw new rn(n,"only supported fields","extra properties")}
1const mn={email:"",phone_number:""},fn={first_name:"",last_name:"",phone_number:"",street_address:void 0,extended_address:void 0,address_locality:"",address_region:"",address_country:"",postal_code:""},yn={...fn,company:void 0,street_name:void 0,street_number:void 0,district:void 0},_n={phone_number:void 0,instructions:void 0};const gn=new Set(["purpose","title","description","value_schema","presentation","required"]);function vn(e,t){const n=sn.find(t=>t===e);if(void 0!==n)return n;throw new rn(t,sn.map(e=>JSON.stringify(e)).join(" or "),"string"==typeof e?JSON.stringify(e):En(e))}function bn(e,t){if(void 0!==e){if(!Array.isArray(e))throw new rn(t,"an array",En(e));for(const[n,i]of e.entries()){const e=wn(i,`${t}[${n}]`);if("business_location"!==e.type)throw new rn(`${t}[${n}].type`,'a read-only "business_location" from get_checkout; select pickup through selected_destination_id',En(e.type))}}}function kn(e,t){if(null===e.selected_destination_id)return;const{selected_destination_id:n}=In(e,{selected_destination_id:void 0},t);if(""===n)throw new rn(`${t}.selected_destination_id`,"a non-empty string or null","an empty string");return n}function Cn(e,t){const n=`${t}.destinations[0]`,i=`${t}.destinations`,{destinations:o}=e;if(void 0===o)return{...fn};if(!Array.isArray(o))throw new rn(i,"an array",En(o));if(0===o.length)return{...fn};if(1!==o.length)throw new rn(i,"1 item",`${o.length} items`);const s=wn(o[0],n);if(void 0!==s.pickup_location_address||"business_location"===s.type)throw new rn(n,"a flat shipping address","a pickup location");const r=In(s,yn,n);return{...fn,...r,address_country:(r.address_country??"").trim()}}function An(e,t){if(!Array.isArray(e))throw new rn(t,"an array",En(e));return e.flatMap((e,n)=>{const i=`${t}[${n}]`,o=wn(e,i),s=o.selected_option_id,r=o.selected_option_details;if(void 0===s){if(void 0!==r)throw new rn(`${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 rn(`${i}.selected_option_id`,"a string",En(s));const a=o.id;if("string"!=typeof a)throw new rn(`${i}.id`,"a string",En(a));const d=o.line_item_ids;if(void 0!==d&&!Tn(d))throw new rn(`${i}.line_item_ids`,"an array of strings",En(d));return[{id:a,line_item_ids:d,selected_option_id:s,selected_option_details:{..._n,...In(void 0===r?{}:r,_n,`${i}.selected_option_details`)}}]})}function wn(e,t){if(!Sn(e))throw new rn(t,"an object",En(e));return e}function Sn(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function In(e,t,n){const i=wn(e,n),o={};for(const s in t){if(!Object.hasOwn(i,s))continue;const e=i[s];if("string"!=typeof e)throw new rn(`${n}.${s}`,"a string",En(e));o[s]=e}return o}function Tn(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)}function En(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.",Nn={type:"object",additionalProperties:!1,properties:{payment:{...cn,required:["instruments"],properties:{instruments:{...cn.properties.instruments,minItems:1,items:{...cn.properties.instruments.items,required:["handler_id","credential"]}}}}}};
1class Ln extends Error{constructor(){super("WebMCP complete_checkout failed"),this.name="WebMcpCompleteCheckoutError"}}function Dn({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:Nn,annotations:{consequentialHint:!0,readOnlyHint:!1,untrustedContentHint:!0},execute:async p=>Nt(await async function(p){if(u||e.value)return ee("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(H))return ee("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=wn(e,"input");return hn({object:n,allowedFields:["payment"],path:"input"}),t||void 0===n.payment?{}:{payment:ln(n.payment,{path:"input.payment",requireCredential:!0})}}(p,{ignorePayment:!W(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()??_e();const m=c();if(!m||n?.aborted)return ye();if(W(i)&&(u||t.value)){if(await m.waitForPendingNegotiations(),n?.aborted)return ye();const s=W(i)?u??t.value:void 0;if(s&&u&&!i.isPaymentRequired.value)return ee("invalid_request","This checkout requires no payment. Retry complete_checkout without the payment field.",{invalidInputPath:"input.payment",invalidInputExpected:"no payment"});if(s&&Y(s)&&i.isPaymentRequired.value){const c=new Gt({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 ye();const p=c.writePayment({payment:s,applyBilling:void 0!==u});if(J(p))return p}}let f,y,_=!1,g=!1,v={progressionStatus:"none"};const b=W(i)&&i.isPaymentRequired.value&&Y(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??_e("completion_failed",v):_e("completion_failed",v)}catch(h){return h instanceof rn?de(h,"complete the checkout"):(d.error({error:new Ln}),_e("internal_error"))}finally{u=!1}}(p),i)}}class Mn extends Error{constructor(){super("WebMCP get_checkout failed to read the checkout"),this.name="WebMcpGetCheckoutError"}}function Rn({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:()=>Nt(function(){try{return t("processed"===e.latestReceipt.value?.status?"negotiated":"proposed")||ee("internal_error",`Checkout data is not available yet. ${ne} ${te("read checkout state")}`)}catch{return n.error({error:new Mn}),ee("internal_error",`Unable to read the checkout. ${te("read checkout state")}`)}}(),e)}}
1class 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??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)=>Nt(await async function(e,a){let d;try{if(null===e||"object"!=typeof e||Array.isArray(e)||Object.keys(e).length>0)return ee("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 ge();const c=s();if(!c)return ee("internal_error",ie);if(r(c))return ve();const l=xn({shop:t,url:n});if(!l)return ee("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?ge():"timeout"===p?(i.log({name:"web_mcp_storefront_navigation_timed_out",message:"Storefront navigation timed out waiting for pending checkout updates"}),ee("navigation_failed","Checkout updates are still pending. Navigation was not started. Retry after updates finish.")):r(c)?ve():(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)}),ee("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:{...cn,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. ${an}`,properties:dn}},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 $n extends Error{constructor(){super("WebMCP update_checkout failed to apply"),this.name="WebMcpUpdateCheckoutError"}}function jn({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=>Nt(await async function(f){let y;try{if(e.value)return fe();const _="shopPay"===i.identity.current.value,g=function(e,t={}){const n=function(e,t){const n=wn(wn(e,"input").checkout,"input.checkout"),i={};if(void 0!==n.context){const e="input.checkout.context",t=In(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 rn(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=In(n.buyer,mn,"input.checkout.buyer")),void 0!==n.discounts&&(i.discountCodes=function(e){const t="input.checkout.discounts",{codes:n}=wn(e,t);if(void 0!==n){if(!Tn(n))throw new rn(`${t}.codes`,"an array of strings",En(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 rn(t,"an array",En(e));const n=new Set;return e.map((e,i)=>{const o=`${t}[${i}]`,s=wn(e,o);for(const t of Object.keys(s))if(!["key","value"].includes(t)&&!gn.has(t))throw new rn(`${o}.${t}`,"a declared field key or value","an unknown field",{loggablePath:o});if("string"!=typeof s.key||0===s.key.length)throw new rn(`${o}.key`,"a non-empty string",En(s.key));if(n.has(s.key))throw new rn(`${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 rn(`${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=wn(e,t);if(!Array.isArray(n.methods))throw new rn(`${t}.methods`,"an array",En(n.methods));if(n.methods.length>1)throw new rn(`${t}.methods`,"at most 1 fulfillment method",`${n.methods.length} methods`);let i={...fn};const s=[];for(const[r,a]of n.methods.entries()){const e=`${t}.methods[${r}]`,n=wn(a,e),d=vn(n.type??"shipping",`${e}.type`),{id:c}=In(n,{id:void 0},e),l={...void 0!==c&&{id:c}},u=void 0===n.groups?[]:An(n.groups,`${e}.groups`),p=kn(n,e);switch(d){case"pickup":void 0===p&&bn(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?Cn(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=ln(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:{...mn},discountCodes:[],declaredFields:[],shippingAddress:{...fn},fulfillmentMethods:{methods:[]},payment:void 0},n)}(f,{savedPaymentMethodsOnly:_,ignorePayment:_?!i.isPaymentRequired.value:!W(i)});g.payment&&"handler_id"in g.payment&&u.paymentCredentialSupplied(g.payment),u.updateCheckoutPartialInput(function(e,{checkout:t,paymentInstrument:n}){const i=Sn(e)&&Sn(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:W(t)&&Y(n.value)&&void 0===i.payment}}(f,{checkout:i,paymentInstrument:t}));const v=p();if(!v||n?.aborted)return ce();if("/review"===a.currentUrl.value.normalizedPath&&a.navigate("/"),g.payment&&"instrument_id"in g.payment&&!d())return ce();const{loadPickupLocalityServices:b}=v;let k;const C=new Gt({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}}),le()):J(S)?S:c()??le()}catch(_){return _ instanceof rn?de(_,"update the checkout"):(u.error({error:new $n}),le("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,K.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,...Z(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=Nt(ee("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})}}}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)}}const Yn=Object.freeze(Object.defineProperty({__proto__:null,registerWebMcpTools:function({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 Dt({observability:p,checkout:r}),A=function({checkout:e,shopPay:t}){const n=X({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(w).filter(({id:e})=>e!==S).sort(I),a=T(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)&&!E(t,i,o,s)}})}}({checkout:r,shopPay:c}),P=e=>function({checkout:e,i18n:t,shop:n,router:i,readMode:o="negotiated",savedCards:s,declaredFields:r=new Map,paymentInstrument:a}){const d=_t({...kt(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:[bt(a,e,u&&"billing_address"in u?u.billing_address:{})]}}:{},...c.length>0?{declared_fields:c}:{}},h=e.proposal.proposed.locationAddress.value;return 1===p.fulfillment?.methods.length&&"pickup"===p.fulfillment.methods[0].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:A(),declaredFields:g,paymentInstrument:s.value}),N=function(e){const t={key:wt,read(){const t=It(e);if(!t)return;const{title:n,value:i,required:o}=t.fields;return{key:wt,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=It(e);if(!t)return!1;const{value:i}=t.fields;return i.value=n??"",!0}}};return t}(r);g.set(N.key,N);const L=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:At,read(){const t=e();if(t?.available.value)return{key:At,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(L.key,L);const D=h??new V;m?.(D);const M=[{tool: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}}}(Rn({checkout:r,readCheckout:P,observability:C}),C),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(...[jn({isSubmitting:o,paymentInstrument:s,signal:i,checkout:r,shop:d,shopPay:c,router:u,getSavedCardSelector:_,readCheckout:P,readSavedCards:A,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=Tt(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}}),Dn({isSubmitting:o,paymentInstrument:s,signal:i,checkout:r,shop:d,shopPay:c,readCheckout:P,readSavedCards:A,observability:C,getPreactContext:f,declaredFields:g})].map(e=>({tool:Fn(e,{activeTool:D,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:D,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(()=>{}),D}},Symbol.toStringTag,{value:"Module"}));
1export{Rt as n,Yn 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.