"use strict";(()=>{var Et=null;function Or(){return Et??=new AbortController().signal,Et}function Ae(e){let t=e?.signal;return Mr(t)?t:Or()}function Mr(e){return typeof e=="object"&&e!==null&&typeof Reflect.get(e,"aborted")=="boolean"&&typeof Reflect.get(e,"addEventListener")=="function"}function He(e){return e.reason??Ir()}function Ir(){if(typeof DOMException=="function")return new DOMException("Tool execution was aborted.","AbortError");let e=new Error("Tool execution was aborted.");return e.name="AbortError",e}function At(e){if(e.aborted)throw He(e)}function Pe(e){return typeof e=="object"&&e!==null&&Reflect.get(e,"name")==="AbortError"}function Re(e,t){return e.aborted?(t(),()=>{}):(e.addEventListener("abort",t,{once:!0}),()=>e.removeEventListener("abort",t))}var xr=[["analyticsProcessingAllowed","USER_CONSENT_TYPE_ANALYTICS"],["marketingAllowed","USER_CONSENT_TYPE_MARKETING"],["preferencesProcessingAllowed","USER_CONSENT_TYPE_PREFERENCES"],["saleOfDataAllowed","USER_CONSENT_TYPE_SALE_OF_DATA"]];function kr(e){return xr.filter(([t])=>e[t]).map(([,t])=>({consentType:t}))}function Pt(e){let{send:t,context:n,dataOriginator:r="DATA_ORIGINATOR_MERCHANT",flushDelayMs:o=5e3,registerLifecycle:i=!1}=e,a=[],c;function l(){c!==void 0||typeof setTimeout!="function"||(c=setTimeout(()=>{c=void 0,s()},o))}function f(u){let p=n.consent();if(!p.analyticsProcessingAllowed)return;let d=n.browserId();if(d===void 0||r==="DATA_ORIGINATOR_MERCHANT"&&n.shopId===void 0)return;let g=n.sessionToken(),y=Nr();a.length>=50&&a.shift(),a.push({eventClass:"EVENT_CLASS_EVENT",severity:"EVENT_SEVERITY_EVENT",source:"EVENT_APP_STOREFRONT",dataOriginator:r,user:{type:"USER_TYPE_BUYER",domainScopedBrowserId:{value:d}},...n.shopId===void 0?{}:{shop:{id:{lowid:n.shopId}}},...g===void 0?{}:{session:{clientSessionToken:g}},userConsents:kr(p),client:{message:{...y===void 0?{}:{id:y},createdAt:new Date().toISOString()},browser:{href:Lr(n.pageUrl())}},payload:u}),l()}function s(){if(c!==void 0&&(clearTimeout(c),c=void 0),a.length===0)return;if(!n.consent().analyticsProcessingAllowed){a.length=0;return}let u=new Date().toISOString();for(let d of a)d.client.message.sentAt=u;let p=JSON.stringify({events:a});a.length=0;try{t(p,!0)}catch{}}return i&&typeof document<"u"&&typeof window<"u"&&typeof window.addEventListener=="function"&&(document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&s()}),window.addEventListener("pagehide",()=>s())),{produce:f,flush:s}}function Nr(){try{if(typeof crypto>"u"||typeof crypto.randomUUID!="function")return;let e=crypto.randomUUID().replaceAll("-","");return{lowid:BigInt(`0x${e.slice(16)}`).toString(),highid:BigInt(`0x${e.slice(0,16)}`).toString()}}catch{return}}var Dr="/.well-known/shopify/fec/produce";function Rt(e=Dr){return(t,n)=>{try{if(typeof fetch!="function")return;fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:t,keepalive:n}).catch(()=>{})}catch{}}}function Lr(e){let t;try{t=new URL(e)}catch{return""}return t.pathname=t.pathname.replace(/(\/(?:account\/(?:reset|activate)|gift_cards)\/[^/]+\/)[^/]+/,"$1[redacted]"),t.toString()}var Ur=[5,10,25,50,100,250,500,1e3,2500,5e3,1e4],$r=5e3,Ot=1;function Mt(e){return Object.keys(e).sort().map(t=>`${t}\0${String(e[t])}`).join("")}function Vr(e){return Object.entries(e).map(([t,n])=>({key:t,value:{stringValue:String(n)}}))}function Fr(e){return Object.entries(e).map(([t,n])=>typeof n=="boolean"?{key:t,value:{boolValue:n}}:typeof n=="number"?{key:t,value:{doubleValue:n}}:{key:t,value:{stringValue:String(n)}})}var Wr={info:{number:9,text:"INFO"},warn:{number:13,text:"WARN"},error:{number:17,text:"ERROR"}};function qr(e,t){for(let n=0;n({timeUnixNano:r.timeUnixNano,observedTimeUnixNano:r.timeUnixNano,severityNumber:r.severityNumber,severityText:r.severityText,body:{stringValue:r.body},attributes:Fr(r.attributes)}))}]}]}}var Hr=100;function It(e){let{serviceName:t,send:n,sendLogs:r,scopeName:o="@shopify/webmcp",scopeVersion:i="0.0.0",flushDelayMs:a=$r,now:c=Date.now,registerLifecycle:l=!1}=e,f={name:o,version:i},s=new Map,u=[],p=c(),d;function g(){d!==void 0||typeof setTimeout!="function"||(d=setTimeout(()=>{d=void 0,C()},a))}function y(T,w,$={},k="1"){if(!Number.isFinite(w))return;let J=`c${T}${k}${Mt($)}`,ne=s.get(J);ne&&ne.kind==="counter"?ne.value+=w:s.set(J,{kind:"counter",name:T,unit:k,attributes:$,value:w}),g()}function m(T,w,$={},k="1",J=Ur){if(!Number.isFinite(w))return;let ne=`h${T}${k}${Mt($)}`,Be=s.get(ne),N;Be&&Be.kind==="histogram"?N=Be:(N={kind:"histogram",name:T,unit:k,attributes:$,bounds:J,count:0,sum:0,min:w,max:w,bucketCounts:Array.from({length:J.length+1},()=>0)},s.set(ne,N)),N.count+=1,N.sum+=w,N.min=Math.min(N.min,w),N.max=Math.max(N.max,w),N.bucketCounts[qr(N.bounds,w)]+=1,g()}function Q(T,w={},$="info"){if(!r)return;u.length>=Hr&&u.shift();let{number:k,text:J}=Wr[$];u.push({timeUnixNano:Ke(c()),severityNumber:k,severityText:J,body:T,attributes:w}),g()}function C(){d!==void 0&&(clearTimeout(d),d=void 0);let T=s.size>0,w=u.length>0;if(!T&&!w)return;let $=c();if(T){let k=jr(t,f,s.values(),Ke($),Ke(p));s.clear();try{n(JSON.stringify(k),!0)}catch{}}if(w&&r){let k=Br(t,f,u);u.length=0;try{r(JSON.stringify(k),!0)}catch{}}p=$}return l&&typeof document<"u"&&typeof window<"u"&&typeof window.addEventListener=="function"&&(document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&C()}),window.addEventListener("pagehide",()=>C())),{counter:y,histogram:m,log:Q,flush:C}}function Ge(e){return(t,n)=>{try{if(typeof fetch!="function")return;fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:t,keepalive:n}).catch(()=>{})}catch{}}}var xt="2.1",kt="3",re={ACCEPTED:"yes",DECLINED:"no",NO_INTERACTION:"no_interaction",NO_VALUE:""},M={NO_VALUE:"",ACCEPTED:"1",DECLINED:"0"},P={PREFERENCES:"p",ANALYTICS:"a",MARKETING:"m",SALE_OF_DATA:"t"},_={MARKETING:"m",ANALYTICS:"a",PREFERENCES:"p",SALE_OF_DATA:"s"},D={MARKETING:"marketing",ANALYTICS:"analytics",PREFERENCES:"preferences",SALE_OF_DATA:"sale_of_data",EMAIL:"email"},j={HEADLESS_STOREFRONT:"headlessStorefront",ROOT_DOMAIN:"rootDomain",CHECKOUT_ROOT_DOMAIN:"checkoutRootDomain",STOREFRONT_ROOT_DOMAIN:"storefrontRootDomain",STOREFRONT_ACCESS_TOKEN:"storefrontAccessToken",IS_EXTENSION_TOKEN:"isExtensionToken",METAFIELDS:"metafields",CUSTOMER_ACCOUNT_REQUEST_INFO:"customerAccountRequestInfo"};var G=()=>typeof window>"u";function X(e){try{return decodeURIComponent(e)}catch{return""}}var Kr="_shopify_cmp";function Gr(){try{return document.cookie}catch{return!1}}function Yr(e){let t=Gr()?document.cookie.split("; "):[];for(let n=0;nXr(e)),!t){if(e!==ue)return;let n;try{n=sessionStorage.getItem(Lt)}catch{}return n||void 0}try{t=decodeURIComponent(t)}catch{}return t}function Jr(e){try{return e()}catch{return}}function Xr(e=ue){var t,n;let r=(t=performance)===null||t===void 0||(n=t.getEntriesByType)===null||n===void 0?void 0:n.call(t,"navigation");if(!r)return;let i=r.map(a=>zr(a,e)).find(a=>a);return i&&e===ue&&Qr(i),i}function zr(e,t=ue){var n,r;if(e)return(n=e.serverTiming)===null||n===void 0||(r=n.find(o=>o.name==t))===null||r===void 0?void 0:r.description}function $t(){return new URLSearchParams(window.location.search).get("_cs")||void 0}function Vt(){var e,t;let n=(e=window.Shopify)===null||e===void 0||(t=e.customerPrivacy)===null||t===void 0?void 0:t.cachedConsent;return n?X(n):void 0}var eo;function Ye(){if(G())return eo;{var e,t;let n=((e=window.Shopify)===null||e===void 0||(t=e.customerPrivacy)===null||t===void 0?void 0:t.injectedConsent)||le().injectedConsent;return n?X(n):void 0}}function to(){let e;if(G()?e=Ye():e=Vt()||Ye()||$t()||Nt()||Ut(),e!==void 0)return no(e)}function oe(){try{let e=to();return e||void 0}catch{return}}function Ft(){return{m:z(_.MARKETING),a:z(_.ANALYTICS),p:z(_.PREFERENCES),s:z(_.SALE_OF_DATA)}}function Wt(e=null){return e===null&&(e=oe()),e===void 0}function no(e){if(e.slice(0,1)=="%")try{e=decodeURIComponent(e)}catch{}let t=e.slice(0,1);if(t=="{")return ro(e);if(t=="3")return oo(e)}function ro(e){var t;let n;try{n=JSON.parse(e)}catch{return}if(n.v===xt&&(t=n.con)!==null&&t!==void 0&&t.CMP)return n}function oo(e){let{base:t}=Dt(e);e=t;let n=e.slice(1).split("_"),[r,o,i,a,c]=n,l;try{l=n[5]?JSON.parse(n.slice(5).join("_")):void 0}catch{}let f;if(c){let p=c.replace(/\*/g,"/").replace(/-/g,"+"),d=atob(p),g="";for(let y=0;yy.slice(0,m)+"-"+y.slice(m),g)}function s(p){let d=r.split(".")[0];return d.includes(p.toLowerCase())?M.DECLINED:d.includes(p.toUpperCase())?M.ACCEPTED:M.NO_VALUE}function u(p){return r.includes(p.replace("t","s").toUpperCase())}return{v:kt,con:{CMP:{[_.ANALYTICS]:s(_.ANALYTICS),[_.PREFERENCES]:s(_.PREFERENCES),[_.MARKETING]:s(_.MARKETING),[_.SALE_OF_DATA]:s(_.SALE_OF_DATA)}},region:o||"",cus:l,purposes:{[P.ANALYTICS]:u(P.ANALYTICS),[P.PREFERENCES]:u(P.PREFERENCES),[P.MARKETING]:u(P.MARKETING),[P.SALE_OF_DATA]:u(P.SALE_OF_DATA)},sale_of_data_region:a=="t",display_banner:i=="t",consent_id:f}}function qt(e){switch(e){case M.ACCEPTED:return re.ACCEPTED;case M.DECLINED:return re.DECLINED;default:return re.NO_VALUE}}function jt(e){switch(e){case _.ANALYTICS:return D.ANALYTICS;case _.MARKETING:return D.MARKETING;case _.PREFERENCES:return D.PREFERENCES;case _.SALE_OF_DATA:return D.SALE_OF_DATA}}function z(e){let t=oe();if(!t)return M.NO_VALUE;let n=t.con.CMP;return n?n[e]:M.NO_VALUE}function Bt(){let e=oe();return Wt(e)?"":e.region||""}function Oe(e){let t=oe();if(!t||!t.purposes)return!0;let n=t.purposes[e];return typeof n=="boolean"?n:!0}function Ht(){return Oe(P.PREFERENCES)}function Kt(){return Oe(P.ANALYTICS)}function Gt(){return Oe(P.MARKETING)}function Yt(){return Oe(P.SALE_OF_DATA)}function Me(){let e=oe();return e&&typeof e.display_banner=="boolean"?e.display_banner:!1}function Qt(){let e=oe();return e&&e.consent_id||""}var Jt=[D.MARKETING,D.ANALYTICS,D.PREFERENCES,D.SALE_OF_DATA],Hs=[...Jt,D.EMAIL,j.ROOT_DOMAIN,j.CHECKOUT_ROOT_DOMAIN,j.STOREFRONT_ROOT_DOMAIN,j.STOREFRONT_ACCESS_TOKEN,j.HEADLESS_STOREFRONT,j.IS_EXTENSION_TOKEN,j.METAFIELDS,j.CUSTOMER_ACCOUNT_REQUEST_INFO],Ks=Jt.map(e=>`"${e}"`).join(", ");function Ie(){return Bt()}function Xt(){return Kt()}function zt(){return Ht()}function Zt(){return Gt()}function en(){return Yt()}function de(){let e={},t=Ft();for(let n of Object.keys(t))e[jt(n)]=qt(t[n]);return e}function xe(){return Qt()}function Qe(){return Zt()}function Je(){return Xt()}function Xe(){return zt()}function ze(){return en()}var pe={analyticsProcessingAllowed:!1,marketingAllowed:!1,preferencesProcessingAllowed:!1,saleOfDataAllowed:!1},uo=/\/(\d+)(?:\?.*)?$/;function nn(e){return typeof e=="number"?Number.isSafeInteger(e)?String(e):void 0:e===void 0||e===""?void 0:/^\d+$/.test(e)?e:uo.exec(e)?.[1]}function po(e){try{return decodeURIComponent(e)}catch{return e}}function fo(e){if(!(typeof document>"u"||typeof document.cookie!="string"))for(let t of document.cookie.split("; ")){let n=t.indexOf("=");if(n===-1||t.slice(0,n)!==e)continue;let r=t.slice(n+1);return r===""?void 0:po(r)}}var go="00000000-0000-0000-0000-000000000000",rn="00000000-0000-0000-5000-000000000000";function Ze(e){if(!(typeof e!="string"||e==="")&&!(e===go||e===rn))return e}var ke={token:void 0,denied:!1};function mo(e){try{if(typeof document>"u")return ke;let t=document.querySelector(`meta[name="${e}"]`);if(!t)return ke;let n=Number(t.getAttribute("data-expiration"));if(!Number.isFinite(n)||n<=Date.now())return ke;let r=t.getAttribute("content");return r===rn?{token:void 0,denied:!0}:{token:Ze(r),denied:!1}}catch{return ke}}function tn(e,t,n){try{let o=window.Shopify?.customerPrivacy?.__internal,i=o?.[n];if(typeof i=="function")return Ze(i.call(o,{generateFallback:!1,tag:"webmcp_storefront_context"}))}catch{return}let r=mo(e);if(!r.denied)return r.token!==void 0?r.token:Ze(fo(t))}function Ne(e){try{return e?.()===!0}catch{return!1}}function De(e){return typeof e=="object"&&e!==null}function ho(e){return!De(e)||e.analytics===""&&e.marketing===""&&e.preferences===""}var yo="scb4127";function bo(){try{if(typeof document>"u"||De(window.privacyBanner))return;let e=document.getElementById(yo);return e instanceof HTMLScriptElement?e:void 0}catch{return}}function _o(){try{return bo()?!0:De(window.privacyBanner)?Me()&&ho(de()):!1}catch{return!0}}function So(){let e=window.Shopify?.customerPrivacy?.consentStatus;return e==="loading"?!0:le().asyncConsent===!0&&e!=="loaded"}function Co(){return Ie()!==""||xe()!==""?!0:Object.values(_).some(e=>z(e)!==M.NO_VALUE)}function et(){try{if(So()||!Co()||_o())return pe;let e=de();if(De(e)&&e.analytics==="no")return pe}catch{return pe}return{analyticsProcessingAllowed:Ne(Je),marketingAllowed:Ne(Qe),preferencesProcessingAllowed:Ne(Xe),saleOfDataAllowed:Ne(ze)}}function vo(){try{return nn(window.Shopify?.analytics?.getConfig().shop?.shopId)}catch{return}}function To(){try{if(typeof document>"u")return;let t=document.getElementById("shopify-features")?.textContent;if(typeof t!="string"||t==="")return;let n=JSON.parse(t);if(typeof n!="object"||n===null)return;let r=Reflect.get(n,"shopId");return typeof r=="string"||typeof r=="number"?nn(r):void 0}catch{return}}function wo(){return vo()??To()}function Eo(){return window.location?.href??""}function on(){return{shopId:wo(),browserId:()=>tn("shopify-y","_shopify_y","uniqueToken"),sessionToken:()=>tn("shopify-s","_shopify_s","visitToken"),pageUrl:Eo,consent:et}}var Ao="https://otlp-http-production.shopifysvc.com/v1/metrics",Po="https://otlp-http-production.shopifysvc.com/v1/logs",Ro="storefront_webmcp",Oo=!0,Mo={localhost:!0,"127.0.0.1":!0,"0.0.0.0":!0,"[::1]":!0,"localtest.me":!0};function ln(){if(!Oo||typeof window>"u"||typeof document>"u")return!1;let e=window.location?.host??"";return e!==""&&!Mo[e]&&!e.includes(":")}var tt=null,an=!1;function un(){return an||(an=!0,ln()&&(tt=It({serviceName:Ro,send:Ge(Ao),sendLogs:Ge(Po),registerLifecycle:!0}))),tt}var nt=null,sn=!1;function dn(){return sn||(sn=!0,ln()&&(nt=Pt({send:Rt(),context:on(),registerLifecycle:!0}))),nt}var Io="type.googleapis.com/shopify.buyer_activity.agent.WebMcpToolCallEvent";function xo(e){return e.aborted===!0?"OUTCOME_ABORTED":e.isError?e.errorClass==="tool_error"?"OUTCOME_TOOL_ERROR":"OUTCOME_EXCEPTION":"OUTCOME_SUCCESS"}var ko=255;function No(e){let t=e.aborted===!0;return{"@type":Io,eventType:"EVENT_TYPE_WEB_MCP_TOOL_CALL_COMPLETED",surface:"AGENT_SURFACE_STOREFRONT_WEBMCP",toolName:e.tool,outcome:xo(e),durationMs:Math.max(0,Math.round(e.durationMs)),...e.errorClass===void 0?{}:{errorClass:e.errorClass.slice(0,ko)},...t?{resultDiscarded:e.resultDiscarded===!0}:{}}}function Do(e,t=un(),n=dn()){if(Lo(e,n),!t)return;let{tool:r,durationMs:o,isError:i,errorClass:a,errorMessage:c,aborted:l,resultDiscarded:f}=e;try{Uo(e,t),t.log(`webmcp ${r} ${l?"aborted":i?"error":"ok"}`,{tool_name:r,duration_ms:Math.round(o),is_error:i,error_class:a??"none",...l?{aborted:!0,result_discarded:f===!0}:{},...c===void 0||!et().analyticsProcessingAllowed?{}:{error_message:c}},i?"error":"info")}catch{}}function Lo(e,t){if(t)try{t.produce(No(e))}catch{}}function Uo(e,t){let{tool:n,durationMs:r,isError:o,errorClass:i,aborted:a,resultDiscarded:c}=e,l={tool_name:n,is_error:o,error_class:i??"none"};a?t.counter("webmcp_tool_call_aborted_total",1,{tool_name:n,result_discarded:c===!0}):t.histogram("webmcp_tool_call_duration_ms",r,l,"ms"),t.counter("webmcp_tool_call_total",1,l),o&&t.counter("webmcp_tool_call_errors_total",1,{tool_name:n,error_class:i??"unknown"})}function $o(e){return typeof e=="object"&&e!==null&&typeof Reflect.get(e,"then")=="function"}function Vo(e){return e instanceof Error&&typeof e.name=="string"&&e.name.length>0?e.name:"Error"}function Fo(e){return typeof e=="object"&&e!==null&&Reflect.get(e,"isError")===!0}var cn=300;function pn(e){return e.length>cn?`${e.slice(0,cn)}\u2026`:e}function Wo(e){if(e instanceof Error&&typeof e.message=="string"&&e.message.length>0)return pn(e.message)}function qo(e){if(typeof e!="object"||e===null)return;let t=Reflect.get(e,"structuredContent");if(typeof t!="object"||t===null)return;let n=Reflect.get(t,"error");return typeof n=="string"&&n.length>0?pn(n):void 0}function fn(e,t,n=un(),r=dn()){return(o,i)=>{let a=Ae(i),c=performance.now(),l=d=>{Do({tool:e,durationMs:performance.now()-c,...d},n,r)},f=d=>l({isError:!1,errorClass:"aborted",aborted:!0,resultDiscarded:d}),s=d=>{if(a.aborted)throw f(!0),He(a);let g=Fo(d);return l({isError:g,errorClass:g?"tool_error":void 0,errorMessage:g?qo(d):void 0}),d},u=d=>{throw a.aborted||Pe(d)?f(!1):l({isError:!0,errorClass:Vo(d),errorMessage:Wo(d)}),d},p;try{p=t(o,i)}catch(d){return u(d)}return $o(p)?p.then(s,u):s(p)}}var gn={checkout:()=>fe("/checkout"),accountOrders:()=>fe("/account/orders"),product:e=>fe(`/products/${e}`),collection:e=>fe(`/collections/${e}`),search:e=>fe(`/search?q=${encodeURIComponent(e)}`)};function fe(e){let t=jo(),n=e.startsWith("/")?e.slice(1):e;return t+n}function Y(e){let n=mn()?.match?.(e);if(n?.route==="product"||n?.route==="productInCollection"){let o=n.params?.productHandle;if(o)return o}let r=e.match(/\/products\/([^/?#]+)/);return r?.[1]?Bo(r[1]):""}function jo(){if(typeof window>"u")return"/";let t=mn()?.root;return typeof t!="string"?"/":t}function mn(){if(!(typeof window>"u"))return window.Shopify?.routes}function Bo(e){try{return decodeURIComponent(e)}catch{return""}}var hn={type:"object",description:`A price. amount is in the currency's minor units (e.g. cents), NOT whole units: {"amount": 39800, "currency": "USD"} is $398.00. Use display for a human-readable price.`,properties:{amount:{type:"integer",description:"Price in the currency's minor units (cents for USD, so 39800 means 398.00). Not whole currency units."},currency:{type:"string",description:"ISO 4217 currency code."},display:{type:"string",description:'The price formatted for display, e.g. "$398.00".'}}},B={type:["object","null"],description:hn.description,properties:hn.properties},Cn={type:"object",properties:{name:{type:"string"},values:{type:"array",items:{type:"string"}}}},ge={type:"object",properties:{name:{type:"string"},value:{type:"string"}}},yn={type:"object",properties:{id:{type:"string",description:"Storefront API Product GID. Pass as catalog.id to get_product."},title:{type:"string"},handle:{type:"string"},variant_id:{type:"string",description:"ProductVariant GID of the product's selected or first available variant: the line_items[].item.id that create_cart and update_cart take when no specific option was requested. Empty when no variant is available."},url:{type:"string"},price_range:B,image:{type:"string"},available:{type:"boolean"},variant_count:{type:"integer",description:"Number of variants on this product record. Some stores split one item across several linked products (e.g. one product per color), so options can list more values than variant_count suggests; use get_product to see where each option value lives."},options:{type:"array",description:"Product option names and possible values. These values do not guarantee every combination is purchasable; call get_product for available variants.",items:Cn},product_type:{type:"string"},vendor:{type:"string"}}},Ho={type:"object",description:"Product + variant information for the line, sufficient to name and link to the item without an extra get_product call.",properties:{id:{type:"string",description:"Storefront API ProductVariant GID: the line's line_items[].item.id in create_cart and update_cart."},title:{type:"string",description:'Product title (e.g. "Classic Hoodie").'},variant_title:{type:"string",description:'Variant title (e.g. "Large / Black"). Empty or "Default Title" for single-variant products.'},handle:{type:"string"},url:{type:"string",description:"Direct URL to the product page with the variant preselected."},image:{type:"string"},unit_price:B}},vn={type:"array",description:`Monetary totals in the currency's minor units (cents for USD), NOT whole units: {"type": "total", "amount": 39800} is $398.00.`,items:{type:"object",required:["type","amount"],properties:{type:{type:"string",description:"Cost category: subtotal or total."},amount:{type:"integer",description:"The amount in minor currency units."}}}},Ko={type:"array",description:"What the tool has to say about this call. type error: the request was not applied (the cart above is unchanged). warning: applied, with a caveat. info: a fact about the cart or the tools.",items:{type:"object",required:["type"],properties:{type:{type:"string",enum:["error","warning","info"]},code:{type:"string"},content:{type:"string"},path:{type:"string",description:"JSONPath of the input the message is about, e.g. $.cart.line_items[1]."},severity:{type:"string",enum:["recoverable","requires_buyer_input","requires_buyer_review","unrecoverable"]}}}},Go={type:"object",properties:{id:{type:"string",description:"Cart line GID: the line's line_items[].id in update_cart. A line listed there with this id keeps its place in the cart."},item:Ho,quantity:{type:"integer"},line_price:{...B,description:"Total price for the line (quantity \xD7 unit_price)."},totals:vn}},Tn={id:{type:"string",description:"Cart GID: the id update_cart takes."},item_count:{type:"integer"},total_price:B,currency:{type:"string"},totals:vn,line_items:{type:"array",description:"Every line in the cart.",items:Go},messages:Ko},bn={type:"object",properties:Tn},_n={item:{type:"object",required:["id"],properties:{id:{type:"string",description:'ProductVariant GID, e.g. "gid://shopify/ProductVariant/123": variant_id from search_catalog or browse_store, variants[].id from get_product, or line_items[].item.id from a cart result.'}}},quantity:{type:"integer",description:"How many of this item the line holds.",minimum:1}},Sn=100,wn={searchCatalog:{name:"search_catalog",annotations:{readOnlyHint:!0,untrustedContentHint:!0},description:"Search the store catalog for products, collections, articles, and pages. Does NOT add anything to the cart; use create_cart or update_cart for cart changes. Each product carries variant_id, its selected or first available variant. If the user asks for a specific product variant, call get_product after search_catalog to get that variant's id, or use show_variant to display it.",inputSchema:{type:"object",required:["catalog"],properties:{catalog:{type:"object",required:["query"],properties:{query:{type:"string",description:"Search query string."},pagination:{type:"object",properties:{limit:{type:"integer",description:"Max results per type (1-10). Defaults to 5.",default:5,minimum:1,maximum:10}}}}}}},outputSchema:{type:"object",properties:{products:{type:"array",items:yn},collections:{type:"array"},articles:{type:"array"},pages:{type:"array"},search_url:{type:"string",description:"Full search results page URL."}}}},browseStore:{name:"browse_store",annotations:{readOnlyHint:!1,untrustedContentHint:!0},description:'Browse OR navigate to store collections. Set navigate=true whenever the user wants to be taken to a collection page in the browser (triggers: "browse to", "go to", "show me", "open", "take me to", "navigate to" a collection or category). With navigate=false (default), returns collection or product data without changing the page \u2014 use this only when the user is asking a question about the catalog, not asking to view it. Without a collection handle, lists all collections. With a handle, returns products from that collection; use "all" to browse everything. Does NOT add anything to the cart; use create_cart or update_cart for cart changes. Prefer this over search_catalog when the user names a category, collection, or wants to explore. With navigate=true this MOVES the browser to the collection page; the tool result confirms the destination, and no further navigation is needed to show it.',inputSchema:{type:"object",properties:{collection:{type:"string",description:'Collection handle to browse (e.g. "best-sellers", "new-arrivals"). Omit to list all collections. Use "all" to browse every product.'},navigate:{type:"boolean",description:'When true, navigate the browser to the collection page after loading data. Set true for user intents like "browse to", "go to", "show me", "open", "take me to" a collection. Requires a collection handle. Defaults to false.'},sort_by:{type:"string",description:"Sort order. Options: best-selling (default), price-ascending, price-descending, title-ascending, title-descending, created-descending, created-ascending."},page:{type:"number",description:"Page number for pagination (starts at 1). Each page returns up to 30 products."}}},outputSchema:{type:"object",properties:{collections:{type:"array",items:{type:"object",properties:{title:{type:"string"},handle:{type:"string"},url:{type:"string"},description:{type:"string"}}}},products:{type:"array",items:yn},collection_title:{type:"string"},page:{type:"number"},sort_by:{type:"string"},navigated:{type:"boolean"},url:{type:"string"}}}},getProduct:{name:"get_product",annotations:{readOnlyHint:!1,untrustedContentHint:!0},description:`Get product details, OR navigate the browser to the product page. Set catalog.navigate=true whenever the user wants to see/view the product in the browser (triggers: "show me", "open", "view", "go to", "take me to", "navigate to" a product). Set catalog.navigate=false (default) only when you need data (description, options, variants, prices, availability) to answer a question or to prepare a cart change \u2014 the browser stays on the current page. Defaults to the current page's product if no catalog.id is provided. Does NOT add anything to the cart; use create_cart or update_cart for that. To view a specific variant (color/size/etc.) in the browser, use show_variant instead \u2014 it accepts partial option selections like "purple" without needing every option. To add a specific variant to the cart, call get_product with catalog.selected_options to get its variant id. With catalog.navigate=true this MOVES the browser to the product page; the tool result confirms the destination, and no further navigation is needed to show it.`,inputSchema:{type:"object",properties:{catalog:{type:"object",description:"Product detail parameters.",properties:{id:{type:"string",description:"Storefront API Product GID, product handle, or product URL path. Custom app product paths and Shopify standard /products/ paths are supported. The id field from search_catalog or browse_store can be passed directly. If omitted, uses the current page's product."},navigate:{type:"boolean",description:'When true, navigate the browser to the product page after fetching details. Set true for user intents like "show me", "open", "view", "go to", "take me to" a product. Defaults to false. If the user specified partial options (e.g. only a color), prefer show_variant with selected_options instead.'},selected_options:{type:"array",description:"Known product option selections to filter available_options. Use exact option names and values from search_catalog options or a prior get_product available_options entry.",items:{type:"object",properties:{name:{type:"string",description:'Option name, e.g. "Size" or "Color".'},value:{type:"string",description:'Option value, e.g. "160cm" or "Fiberglass".'}},required:["name","value"]}}}}}},outputSchema:{type:"object",properties:{id:{type:"string",description:"Storefront API Product GID."},title:{type:"string"},handle:{type:"string"},description:{type:"object",properties:{html:{type:"string"}}},vendor:{type:"string"},type:{type:"string"},tags:{type:"array",items:{type:"string"}},url:{type:"string"},price_range:{type:"object",properties:{min:B,max:B}},available:{type:"boolean"},options:{type:"array",description:"All product option names and possible values. Use available_options to identify purchasable combinations.",items:Cn},variants:{type:"array",description:"Resolved variant records. When catalog.selected_options contains a complete option combination, this contains the matching variant. An available variant's id is the line_items[].item.id that create_cart and update_cart take.",items:{type:"object",properties:{id:{type:"string",description:"Storefront API ProductVariant GID. Pass to show_variant as catalog.variant_id to display it, or to create_cart or update_cart as line_items[].item.id to put it in the cart."},title:{type:"string"},options:{type:"array",items:ge},price:B,list_price:B,availability:{type:"object",properties:{available:{type:"boolean"}}},sku:{type:"string"},product_handle:{type:"string",description:"Present only when this variant belongs to a different product than the one requested \u2014 some stores sell each option value (e.g. each color) as its own product, linked as options. Pass it to show_variant as catalog.handle to display the variant."}}}},available_options:{type:"array",description:"Available option combinations, optionally filtered by catalog.selected_options. Use one full combination to call get_product again when variants[] is empty.",items:{type:"array",items:ge}},available_options_count:{type:"integer",description:"Total available option combinations matching catalog.selected_options."},available_options_truncated:{type:"boolean",description:"True when more available option combinations exist than were returned."},available_options_filter:{type:"array",description:"The selected_options filter applied to available_options, when provided.",items:ge},images:{type:"array",items:{type:"string"}}}}},showVariant:{name:"show_variant",annotations:{readOnlyHint:!1,untrustedContentHint:!0},description:'Navigate the browser to a product page, with a specific variant OR a partial option filter selected. Use for view intents: "show me", "open", "view", "go to", "take me to" a specific product configuration. Accepts EITHER variant_id (fully specified variant) OR selected_options (partial, e.g. only Color=Purple) \u2014 with partial options the first matching available variant is picked automatically, so DO NOT ask the user for missing options when their intent is to view. Does NOT add anything to the cart; use create_cart or update_cart for cart changes. For cart operations you still need a full variant_id \u2014 call get_product with the full option combination first. This MOVES the browser to the exact variant page with the variant pre-selected; the tool result confirms the destination, and no further navigation is needed to show it.',inputSchema:{type:"object",required:["catalog"],properties:{catalog:{type:"object",description:"Provide EITHER variant_id OR selected_options. Handle is required unless the user is already on the product page.",properties:{handle:{type:"string",description:"Product handle. If omitted, uses the current product page's handle."},variant_id:{type:["string","number"],description:'ProductVariant ID from get_product variants[].id, e.g. "gid://shopify/ProductVariant/123", or the numeric variant ID. Use when the user picked a specific fully-specified variant. Omit when using selected_options.'},selected_options:{type:"array",description:'Partial (or full) option selections, e.g. [{"name":"Color","value":"Purple"}]. Use when the user names some options but not all (e.g. "show me the purple shoe" \u2014 pass only Color). The first matching available variant will be selected automatically. Use exact option names and values from get_product available_options or search_catalog options.',items:ge}}}}},outputSchema:{type:"object",properties:{handle:{type:"string",description:"Handle of the product page that was shown. Can differ from the requested handle when the variant is sold as a separate, linked product (e.g. one product per color)."},variant_id:{type:"string"},url:{type:"string"},navigated:{type:"boolean"},selected_options:{type:"array",description:"The option selections that were resolved to a variant, if provided.",items:ge}}}},getCart:{name:"get_cart",annotations:{readOnlyHint:!0,untrustedContentHint:!0},description:"Get the shopper's current cart: its id, every line (line id, product and variant titles, variant id, handle, URL, image, unit price, quantity, line price) and the totals. Everything needed to describe the cart to the user in natural language, without a follow-up get_product call per line. It is also where a change to an existing cart starts from: update_cart takes the cart's id and the complete set of lines the cart should hold, and create_cart applies only to a cart with no items. Works from any page.",inputSchema:{type:"object",properties:{}},outputSchema:{type:"object",properties:Tn}},createCart:{name:"create_cart",annotations:{readOnlyHint:!1,idempotentHint:!0,untrustedContentHint:!0},description:"Create the shopper's cart with the given items, for a shopper whose cart has no items yet. It is the tool for a shopper asking to add or buy something when the cart is empty, and that request is all the authorization it needs. Each line item names a ProductVariant GID in item.id (variant_id from search_catalog or browse_store, or variants[].id from get_product for specific options) and a quantity; every item from one request fits in one call. When the cart already has items, nothing is created or changed: the result is that existing cart with an error message, and update_cart can extend it with its current lines plus the new ones. Returns the whole resulting cart, including its id and line ids. Repeating a call with the same items leaves the cart as it is.",inputSchema:{type:"object",required:["cart"],properties:{cart:{type:"object",required:["line_items"],properties:{line_items:{type:"array",description:"The items the new cart holds.",minItems:1,maxItems:Sn,items:{type:"object",required:["item","quantity"],properties:_n}}}}}},outputSchema:bn},updateCart:{name:"update_cart",annotations:{readOnlyHint:!1,idempotentHint:!0,untrustedContentHint:!0},description:`Set the shopper's cart to exactly the given line items. This is a full replacement, not a patch: afterwards the cart holds these lines and only these. - A listed line with its line_items[].id keeps its place and is set to the given quantity, which is absolute (2 means 2, not 2 more). - A listed item without a line id is added, or, when that variant is already on one line of the cart, sets that line's quantity. - A line in the cart that is not listed is removed. It takes the cart's lines as most recently returned by get_cart, create_cart or update_cart. When the cart has changed since then (for example, the shopper edited it on the page, or a new cart replaced it), or an id is given that is not the shopper's current cart, nothing changes and the result is the current cart with an error message. Since the outcome depends only on the lines sent, repeating a call leaves the cart as it is. An empty line_items list empties the cart; leaving line_items out leaves the lines as they are. Returns the whole resulting cart, including its line ids, and messages about the call.`,inputSchema:{type:"object",required:["cart"],properties:{id:{type:"string",description:"Optional: the page has one cart, the shopper's, and update_cart always acts on it. When given (the id from a cart result), it is compared with the current cart, and a mismatch changes nothing."},cart:{type:"object",properties:{line_items:{type:"array",description:"The complete set of lines the cart holds afterwards. Empty empties the cart; absent leaves the lines as they are.",maxItems:Sn,items:{type:"object",required:["item","quantity"],properties:{id:{type:"string",description:"Existing cart line id (line_items[].id from a cart result). Absent for an item that is not in the cart yet."},..._n}}}}}}},outputSchema:bn},cancelCart:{name:"cancel_cart",annotations:{readOnlyHint:!1},description:"Remove all items from the cart in one step. Use when the user wants to empty their cart or start over.",inputSchema:{type:"object",properties:{}},outputSchema:{type:"object",properties:{cleared:{type:"boolean"},previous_item_count:{type:"number"}}}},createCheckout:{name:"proceed_to_checkout",annotations:{readOnlyHint:!1},description:"Proceed to checkout. Verifies the cart is not empty, then MOVES the browser to the checkout page. The tool result confirms the destination, and no further navigation is needed to show it.",inputSchema:{type:"object",properties:{}},outputSchema:{type:"object",properties:{navigating_to:{type:"string"},item_count:{type:"integer"},total_price:B}}},manageOrders:{name:"manage_orders",annotations:{readOnlyHint:!1},description:"Navigate to the customer's order history page. Use when the user asks about past orders, order status, tracking, or returns. The user will be prompted to log in if not already authenticated. This MOVES the browser to the order history page; the tool result confirms the destination, and no further navigation is needed to show it.",inputSchema:{type:"object",properties:{}}},askBusiness:{name:"ask_business",annotations:{readOnlyHint:!0,untrustedContentHint:!0},description:`Ask the store a question about its policies and services: returns, refunds and exchanges, shipping and delivery, privacy, terms, subscriptions, contact details and opening hours, or FAQ topics such as gift wrapping. The store answers it: from its own knowledge base when the store offers Ask, otherwise from its published policies, FAQ pages and articles. Put the shopper's question in ask.query in their own words, one question per call; name the topic when the shopper only implies it (e.g. a question about sending back a gift is a returns question). Read-only: it does not change the cart, place orders, or start returns. For products, prices and availability, use search_catalog or get_product. Examples of questions: - What is your return policy? - How long does shipping to Canada take? - What is your phone number? - What are your hours of operation? - Do you offer gift wrapping? `,inputSchema:{type:"object",required:["ask"],properties:{ask:{type:"object",description:"The question and optional buyer context.",required:["query"],properties:{query:{type:"string",maxLength:1e4,description:"The shopper's question, in natural language."},context:{type:"object",description:"Optional buyer context, such as the shopper's country or language. Send only what the question needs.",additionalProperties:!0,properties:{intent:{type:"string",description:'What the shopper is trying to do, when it adds to the question (e.g. "returning a gift they received").'},address_country:{type:"string",description:`The buyer's country, e.g. "US".`},address_region:{type:"string",description:`The buyer's state or region, e.g. "CA".`},language:{type:"string",description:'The preferred language, e.g. "en".'}}}}}}},outputSchema:{type:"object",required:["answer"],properties:{answer:{type:"object",required:["plain"],properties:{plain:{type:"string",description:"The answer as plain text. Either the store's own answer, or the store's policy, page and article text that matches the question, one labelled section per source with its URL. When the store has no information for the question, the answer says so."}}},links:{type:"array",description:"Pages related to the answer, such as the policies, FAQ pages and articles it draws on.",items:{type:"object",required:["type","url"],properties:{type:{type:"string",description:"The kind of page, e.g. refund_policy, shipping_policy, privacy_policy, terms_of_service, faq, page or article."},url:{type:"string"},title:{type:"string"},id:{type:"string",description:"The linked resource's GID, when it is a product or other store resource."}}}},messages:{type:"array",description:"Notes about the answer or its sources, e.g. a policy that only links to other pages. A warning is store information the shopper must be shown, such as an allergen or safety disclosure.",items:{type:"object",required:["type","content"],properties:{type:{type:"string",description:"info, warning or error."},code:{type:"string"},content:{type:"string"}}}}}}},getUcpProfile:{name:"get_ucp_profile",annotations:{readOnlyHint:!0,untrustedContentHint:!0},description:"Get this store's Universal Commerce Protocol (UCP) profile, as served at /.well-known/ucp: the UCP version, the services the store offers with their endpoints (e.g. the store's UCP MCP server), its capabilities, and its payment handlers. Use it to discover how to continue a purchase with this store over UCP, or to check which platform operates the store. Read-only; works from any page.",inputSchema:{type:"object",properties:{}},outputSchema:{type:"object",properties:{ucp:{type:"object",description:"The UCP profile exactly as served. Keys include version, supported_versions (older versions keyed to their profile URLs), services (keyed by service name, e.g. dev.ucp.shopping; each a list of bindings with version, spec, transport, endpoint and schema), capabilities (keyed by capability name), and payment_handlers (keyed by handler name)."}}}}};var v=((e,t)=>{let n=e;if(t){let r=new Set;for(let o of t)r.has(o)||(r.add(o),n+=` `+o)}return n});var En="2026-04";function An(e){return e?e.startsWith("v1_")?Yo(e.replace(/^v1_/,"")):(typeof console<"u"&&console.warn(`[webmcp] Unsupported variant encoding: "${e}"`),[]):[]}function Yo(e){let t=/[ :,-]/g,n={currentOptionValue:[],decodedOptions:[],depth:0,index:0,rangeStart:null},r;for(;r=t.exec(e);)Qo(e,n,r,t);return zo(e,n),n.decodedOptions}function Qo(e,t,n,r){let o=n[0],i=Number.parseInt(e.slice(t.index,n.index),10)||0;Pn(t,i),t.currentOptionValue[t.depth]=i,o==="-"?t.rangeStart=i:o===":"?t.depth++:Jo(e,t,n,o),t.index=r.lastIndex}function Jo(e,t,n,r){Xo(e,n,r)&&t.decodedOptions.push([...t.currentOptionValue]),r===","&&(t.currentOptionValue.pop(),t.depth--)}function Xo(e,t,n){return n===" "||n===","&&e[t.index-1]!==","}function zo(e,t){let n=e.match(/\d+$/g)?.[0];if(n===void 0)return;let r=Number.parseInt(n,10);if(t.rangeStart!==null){Pn(t,r+1);return}t.currentOptionValue[t.depth]=r,t.decodedOptions.push([...t.currentOptionValue])}function Pn(e,t){let n=e.rangeStart;if(n!==null){for(let r=n;r{let o=e;return n&&(o+=` ${n}`),r&&(o+=` Next steps: ${r}`),{content:[{type:"text",text:o}],structuredContent:t}},Mn="The cart has been emptied: this result reflects its current state, so calling cancel_cart again would have no effect. With no items in the cart, create_cart is the tool that adds new ones.",rt=(e,t,n)=>{let r=n?` ${n}`:"";return{content:[{type:"text",text:`${e}${r}`}],structuredContent:t}},V=(e,t)=>{let{summary:n,navigated:r,destination:o,keyFields:i}=e,a=o?`the ${o} page`:"the requested page",l=`${r?`This tool has navigated the browser to ${a}, so the shopper will be looking at it without any further navigation. Navigating to the same page again would only reload it.`:`The browser was already on ${a}, so no navigation was needed.`} ${n}`;return i&&(l+=` ${i}`),{content:[{type:"text",text:l}],structuredContent:t}},h=(e,t)=>{let n=`Error: ${e}`;return t&&(n+=` Recovery: ${t}`),{content:[{type:"text",text:n}],structuredContent:{error:e},isError:!0}},b=(e,t,n,r)=>{if(t.aborted||Pe(e))throw e;return h(e instanceof Error?e.message:n,r)},Z=()=>{let e=window.Shopify?.actions;if(!e?.getCart||!e.updateCart)throw new Error("Standard Actions are not available. Ensure Shopify Standard Actions are available before calling cart tools.");return e},L=async(e,t=Z())=>(await t.getCart(void 0,{signal:e})).cart??{},ie=e=>{At(e)},ae=e=>{let t=e.userErrors?.map(n=>n.message).filter(Boolean);if(t?.length)throw new Error(t.join(", "))},ee=e=>e.warnings?.map(t=>t.message).filter(ot)??[],me=e=>e.lines?.nodes??[],H=e=>e.totalQuantity??0,Rn=new Map,In=e=>{let t=String(e??"").toUpperCase();if(!t)return 2;let n=Rn.get(t);if(n!=null)return n;try{let r=new Intl.NumberFormat("en",{style:"currency",currency:t}).resolvedOptions().maximumFractionDigits??2;return Rn.set(t,r),r}catch{return 2}},E=e=>{if(e?.amount==null||!e.currencyCode)return null;let t=Number(e.amount);if(!Number.isFinite(t))return null;let n={amount:Math.round(t*10**In(e.currencyCode)),currency:e.currencyCode},r=x(n);return r?{...n,display:r}:n},x=e=>{if(!e)return"";let t=In(e.currency),n=e.amount/10**t;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e.currency}).format(n)}catch{return`${n.toFixed(t)} ${e.currency}`}},ot=e=>typeof e=="string"&&e.length>0,F=e=>{if(typeof window>"u")return!1;let t=new URL(window.location.href);return t.pathname+t.search===e},W=(e,t,n=0)=>{let{signal:r}=e;if(r.aborted)return;let o=setTimeout(()=>{r.aborted||e.navigate(t),i()},n),i=Re(r,()=>clearTimeout(o))},On="gid://shopify/ProductVariant/";function U(e){if(e===void 0)return"";let t=String(e).trim(),n=t.startsWith(On)?t.slice(On.length):t;return/^\d+$/.test(n)?n:""}function ye(e){let t=[],n=E(e.subtotal),r=E(e.total);return n&&t.push({type:"subtotal",amount:n.amount}),r&&t.push({type:"total",amount:r.amount}),t}var Zo=`/api/${En}/graphql.json`,it=30,ei=50,xn=50,ti="gid://shopify/Product/",at=v("fragment WebMcpMoney on MoneyV2{amount currencyCode}"),st=v("fragment WebMcpProductCard on Product{id title handle vendor productType availableForSale onlineStoreUrl featuredImage{url altText}priceRange{minVariantPrice{...WebMcpMoney}}variantsCount{count}selectedOrFirstAvailableVariant{id availableForSale}options{name optionValues{name}}}",[at]),ni=v("fragment WebMcpCartDetails on Cart{id totalQuantity cost{subtotalAmount{...WebMcpMoney}totalAmount{...WebMcpMoney}}lines(first:250){nodes{id quantity cost{subtotalAmount{...WebMcpMoney}totalAmount{...WebMcpMoney}}merchandise{__typename ...on ProductVariant{id title image{url altText}price{...WebMcpMoney}product{id title handle onlineStoreUrl}}}}}}",[at]),ri=v("fragment WebMcpProductVariant on ProductVariant{id title availableForSale sku price{...WebMcpMoney}compareAtPrice{...WebMcpMoney}selectedOptions{name value}product{handle}}",[at]),Dn=v("fragment WebMcpProductDetails on Product{id title handle descriptionHtml vendor productType tags availableForSale onlineStoreUrl featuredImage{url altText}priceRange{minVariantPrice{...WebMcpMoney}maxVariantPrice{...WebMcpMoney}}variantsCount{count}encodedVariantAvailability selectedOrFirstAvailableVariant{...WebMcpProductVariant}options{name optionValues{name}}images(first:20){nodes{url altText}}}",[ri]),oi=v("query WebMcpSearchCatalog($query:String!$types:[PredictiveSearchType!]$limit:Int!){predictiveSearch(query:$query types:$types limit:$limit){products{...WebMcpProductCard}collections{title handle description onlineStoreUrl}articles{title handle excerpt onlineStoreUrl}pages{title handle onlineStoreUrl}}}",[st]),ii=v("query WebMcpSearchPoliciesAndFaqs($query:String!$types:[PredictiveSearchType!]$limit:Int!$includeRefund:Boolean!$includeShipping:Boolean!$includePrivacy:Boolean!$includeTermsOfService:Boolean!$includeTermsOfSale:Boolean!$includeSubscription:Boolean!$includeLegalNotice:Boolean!$includeContact:Boolean!){shop{refundPolicy@include(if:$includeRefund){title body url}shippingPolicy@include(if:$includeShipping){title body url}privacyPolicy@include(if:$includePrivacy){title body url}termsOfService@include(if:$includeTermsOfService){title body url}termsOfSale@include(if:$includeTermsOfSale){title body url}subscriptionPolicy@include(if:$includeSubscription){title body url}legalNotice@include(if:$includeLegalNotice){title body url}contactInformation@include(if:$includeContact){title body url}}predictiveSearch(query:$query types:$types limit:$limit){articles{title handle excerpt onlineStoreUrl}pages{title handle onlineStoreUrl}}}"),ai=3,si=v("query WebMcpPageBodies($h1:String$h2:String$h3:String){p1:page(handle:$h1){title body}p2:page(handle:$h2){title body}p3:page(handle:$h3){title body}}"),ci=v("query WebMcpListCollections($first:Int!){collections(first:$first){nodes{title handle description onlineStoreUrl}}}"),li=v("query WebMcpBrowseProducts($first:Int!$sortKey:ProductSortKeys$reverse:Boolean!){products(first:$first sortKey:$sortKey reverse:$reverse){nodes{...WebMcpProductCard}}}",[st]),ui=v("query WebMcpBrowseCollectionProducts($handle:String!$first:Int!$sortKey:ProductCollectionSortKeys$reverse:Boolean!){collection(handle:$handle){title handle description onlineStoreUrl products(first:$first sortKey:$sortKey reverse:$reverse){nodes{...WebMcpProductCard}}}}",[st]),di=v("query WebMcpProductByHandle($handle:String!$selectedOptions:[SelectedOptionInput!]!$hasSelectedOptions:Boolean!){product(handle:$handle){...WebMcpProductDetails variantBySelectedOptions(selectedOptions:$selectedOptions caseInsensitiveMatch:true)@include(if:$hasSelectedOptions){...WebMcpProductVariant}}}",[Dn]),pi=v("query WebMcpProductById($id:ID!$selectedOptions:[SelectedOptionInput!]!$hasSelectedOptions:Boolean!){node(id:$id){__typename ...on Product{...WebMcpProductDetails variantBySelectedOptions(selectedOptions:$selectedOptions caseInsensitiveMatch:true)@include(if:$hasSelectedOptions){...WebMcpProductVariant}}}}",[Dn]),fi=v("query WebMcpVariantProductHandle($id:ID!$handle:String!){node(id:$id){__typename ...on ProductVariant{product{id handle}}}requested:product(handle:$handle){id}}"),gi=v("query WebMcpCartDetails($id:ID!){cart(id:$id){...WebMcpCartDetails}}",[ni]);async function Ln(e,t,n){let r=await q(oi,{query:e,types:["PRODUCT","COLLECTION","ARTICLE","PAGE"],limit:t},n);return{predictiveSearch:_i(r.predictiveSearch)}}var Un=[{type:"refund",field:"refundPolicy",include:"includeRefund"},{type:"shipping",field:"shippingPolicy",include:"includeShipping"},{type:"privacy",field:"privacyPolicy",include:"includePrivacy"},{type:"terms_of_service",field:"termsOfService",include:"includeTermsOfService"},{type:"terms_of_sale",field:"termsOfSale",include:"includeTermsOfSale"},{type:"subscription",field:"subscriptionPolicy",include:"includeSubscription"},{type:"legal_notice",field:"legalNotice",include:"includeLegalNotice"},{type:"contact",field:"contactInformation",include:"includeContact"}],Ue=Un.map(e=>e.type);async function ct(e,t,n,r){let o=new Set(n),i=await q(ii,{query:e,types:["ARTICLE","PAGE"],limit:t,includeRefund:o.has("refund"),includeShipping:o.has("shipping"),includePrivacy:o.has("privacy"),includeTermsOfService:o.has("terms_of_service"),includeTermsOfSale:o.has("terms_of_sale"),includeSubscription:o.has("subscription"),includeLegalNotice:o.has("legal_notice"),includeContact:o.has("contact")},r),a=(i.predictiveSearch?.pages??[]).map(dt),c=(i.predictiveSearch?.articles??[]).map(ut);return{policies:mi(i.shop),articles:c,pages:await hi(a,r)}}function mi(e){return e?Un.flatMap(({type:t,field:n})=>{let r=e[n];return r?[{type:t,title:r.title??"",url:r.url??"",body:r.body??""}]:[]}):[]}async function hi(e,t){let n=e.filter(c=>c.handle).slice(0,ai);if(!n.length)return e;let r=n.map(c=>c.handle),o=await q(si,{h1:r[0]??null,h2:r[1]??null,h3:r[2]??null},t),i=[o.p1,o.p2,o.p3],a=new Map;return n.forEach((c,l)=>{let f=i[l]?.body;f&&a.set(c.handle,f)}),e.map(c=>{let l=a.get(c.handle);return l?{...c,body:l}:c})}async function $n(e){return{collections:{nodes:(await q(ci,{first:ei},e)).collections?.nodes?.map(lt)??[]}}}async function Vn(e){let t=await q(li,{first:jn(e.page),...yi(e.sortBy)},e.signal);return{products:Bn(t.products?.nodes??[],e.page).map(he),title:"All products"}}async function Fn(e){let t=e.handle.trim(),n=await q(ui,{handle:t,first:jn(e.page),...bi(e.sortBy)},e.signal),r=n.collection?lt(n.collection):null;return{collection:r,products:Bn(n.collection?.products?.nodes??[],e.page).map(he),title:r?.title??t}}async function be(e,t){let n=pt(e);if(!n)return null;let r=Hn(t.selected_options),o=r.length>0;if($i(n)){let c=(await q(pi,{id:n,selectedOptions:r,hasSelectedOptions:o},t.signal)).node;return c?.__typename==="Product"?Nn(he(c),t):null}let i=await q(di,{handle:n,selectedOptions:r,hasSelectedOptions:o},t.signal);return i.product?Nn(he(i.product),t):null}async function Wn(e,t,n){let r=await q(fi,{id:e,handle:t},n),o=r.node;if(o?.__typename!=="ProductVariant")return null;let i=o.product;if(!i?.handle)return null;let a=!!i.id&&i.id===r.requested?.id;return{handle:i.handle,sameProduct:a}}async function qn(e,t,n){let r=e.trim();if(!r)return null;let i=(await q(gi,{id:r},n)).cart;return i?{id:i.id??r,item_count:i.totalQuantity??0,total_price:E(i.cost?.totalAmount),currency:i.cost?.totalAmount?.currencyCode??"",totals:ye({subtotal:i.cost?.subtotalAmount,total:i.cost?.totalAmount}),line_items:(i.lines?.nodes??[]).map(a=>Si(a,t))}:null}async function q(e,t,n){let r=await fetch(Zo,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({query:e,variables:t}),signal:n});if(!r.ok)throw new Error(`Storefront API request failed (${r.status})`);let o=await r.json();if(o.errors?.length)throw new Error(o.errors.map(i=>i.message).filter(Boolean).join(", "));if(!o.data)throw new Error("Storefront API response did not include data.");return o.data}function jn(e){return Math.min(Math.max(1,e)*it,250)}function Bn(e,t){let n=(Math.max(1,t)-1)*it;return e.slice(n,n+it)}function yi(e){switch(e){case"price-ascending":return{sortKey:"PRICE",reverse:!1};case"price-descending":return{sortKey:"PRICE",reverse:!0};case"title-ascending":return{sortKey:"TITLE",reverse:!1};case"title-descending":return{sortKey:"TITLE",reverse:!0};case"created-ascending":return{sortKey:"CREATED_AT",reverse:!1};case"created-descending":return{sortKey:"CREATED_AT",reverse:!0};case"best-selling":default:return{sortKey:"BEST_SELLING",reverse:!1}}}function bi(e){switch(e){case"price-ascending":return{sortKey:"PRICE",reverse:!1};case"price-descending":return{sortKey:"PRICE",reverse:!0};case"title-ascending":return{sortKey:"TITLE",reverse:!1};case"title-descending":return{sortKey:"TITLE",reverse:!0};case"created-ascending":return{sortKey:"CREATED",reverse:!1};case"created-descending":return{sortKey:"CREATED",reverse:!0};case"best-selling":default:return{sortKey:"BEST_SELLING",reverse:!1}}}function _i(e){return{products:(e?.products??[]).map(he),collections:(e?.collections??[]).map(lt),articles:(e?.articles??[]).map(Oi),pages:(e?.pages??[]).map(Mi)}}function he(e){let t=e.selectedOrFirstAvailableVariant?kn(e.selectedOrFirstAvailableVariant):null,n=e.variantBySelectedOptions?kn(e.variantBySelectedOptions):null;return{id:e.id,title:e.title,handle:e.handle,descriptionHtml:e.descriptionHtml,vendor:e.vendor,productType:e.productType,tags:e.tags,availableForSale:e.availableForSale,onlineStoreUrl:e.onlineStoreUrl,featuredImage:e.featuredImage??null,priceRange:e.priceRange,variantCount:e.variantsCount?.count??0,selectedOrFirstAvailableVariant:t,variantBySelectedOptions:n,encodedVariantAvailability:e.encodedVariantAvailability,options:Ei(e.options),images:Pi(e.images?.nodes)}}function Si(e,t){return{id:e.id??"",quantity:e.quantity??0,line_price:E(e.cost?.totalAmount),totals:ye({subtotal:e.cost?.subtotalAmount,total:e.cost?.totalAmount}),item:Ci(e,t)}}function Ci(e,t){let n=vi(e),r=n.product;return{id:n.id,title:r.title,variant_title:n.title,handle:r.handle,url:wi({handle:r.handle,onlineStoreUrl:r.onlineStoreUrl},n.id,t),image:n.image,unit_price:E(n.price)}}function vi(e){let t=e.merchandise,n=t?.__typename==="ProductVariant"?t:null;return{id:n?.id??"",title:n?.title??"",image:n?.image?.url??"",price:n?.price,product:Ti(n?.product)}}function Ti(e){return{id:e?.id??"",title:e?.title??"",handle:e?.handle??"",onlineStoreUrl:e?.onlineStoreUrl}}function wi(e,t,n){let r=Se(e,a=>n.product(a));if(!r)return"";let o=t.split("/").pop();if(!o)return r;let i=r.includes("?")?"&":"?";return`${r}${i}variant=${encodeURIComponent(o)}`}function Ei(e){return e?.map(t=>({name:t.name??"",values:t.optionValues?.map(n=>n.name)??[]}))??[]}function Ai(e){return e?.map(t=>({name:t.name??"",value:t.value??""}))??[]}function Pi(e){return e?.filter(Ri)??[]}function kn(e){return{id:e.id??"",title:e.title??"",availableForSale:!!e.availableForSale,price:e.price,compareAtPrice:e.compareAtPrice,sku:e.sku,selectedOptions:Ai(e.selectedOptions),productHandle:e.product?.handle??void 0}}function Ri(e){return e!=null}function lt(e){return{title:e.title,handle:e.handle,description:e.description,onlineStoreUrl:e.onlineStoreUrl}}function Oi(e){return{title:e.title,handle:e.handle,excerpt:e.excerpt,onlineStoreUrl:e.onlineStoreUrl}}function Mi(e){return{title:e.title,handle:e.handle,onlineStoreUrl:e.onlineStoreUrl}}function _e(e,t){let n=Vi(e);return{id:e.id??"",title:e.title??"",handle:n,variant_id:e.selectedOrFirstAvailableVariant?.availableForSale?e.selectedOrFirstAvailableVariant.id??"":"",url:Ii(e,n,t),price_range:E(e.priceRange?.minVariantPrice),image:Gn(e.featuredImage),available:!!e.availableForSale,variant_count:e.variantCount??0,options:e.options??[],product_type:e.productType??"",vendor:e.vendor??""}}function Ii(e,t,n){return Se({handle:t,onlineStoreUrl:e.onlineStoreUrl},r=>n.product(r))}function Nn(e,t){let n=_e(e,t.routes),r=e.options??[],o=Hn(t.selected_options),i=ki(r,e,o),a=xi(e,o);return{...n,description:{html:e.descriptionHtml??""},type:e.productType??"",tags:e.tags??[],price_range:{min:E(e.priceRange?.minVariantPrice),max:E(e.priceRange?.maxVariantPrice)},variants:a.map(c=>Ui(c,n.handle)),available_options:i.options,available_options_count:i.count,available_options_truncated:i.truncated,available_options_filter:o.length?o:void 0,images:e.images?.map(Gn).filter(ot)??[]}}function xi(e,t){return t.length?e.variantBySelectedOptions?[e.variantBySelectedOptions]:[]:e.selectedOrFirstAvailableVariant?[e.selectedOrFirstAvailableVariant]:[]}function ki(e,t,n){let r=An(t.encodedVariantAvailability),o=[];for(let c of r){let l=Ni(e,c);l&&Di(l,n)&&o.push(l)}let a=n.length>0||o.length<=xn?o.slice(0,xn):[];return{options:a,count:o.length,truncated:o.length>a.length}}function Ni(e,t){if(!e.length||t.length!==e.length)return null;let n=[];for(let[r,o]of e.entries()){let i=o.values[t[r]];if(!i)return null;n.push({name:o.name,value:i})}return n}function Di(e,t){return t.every(n=>e.some(r=>Li(r,n)))}function Li(e,t){return Le(e.name)===Le(t.name)&&Le(e.value)===Le(t.value)}function Hn(e){return e?.map(t=>({name:t.name?.trim()??"",value:t.value?.trim()??""})).filter(t=>t.name&&t.value)??[]}function Le(e){return e?.trim().toLowerCase()??""}function Ui(e,t){let n=e.productHandle&&e.productHandle!==t?e.productHandle:void 0;return{id:e.id??"",title:e.title??"",options:e.selectedOptions??[],price:E(e.price),list_price:E(e.compareAtPrice),availability:{available:!!e.availableForSale},sku:e.sku??void 0,...n?{product_handle:n}:{}}}function $e(e,t){let n=e.handle??"";return{title:e.title??"",handle:n,url:Se(e,r=>t.collection(r)),description:e.description??""}}function ut(e){return{title:e.title??"",handle:e.handle??"",url:Se(e),excerpt:e.excerpt??""}}function dt(e){return{title:e.title??"",handle:e.handle??"",url:Se(e)}}function Se(e,t){let n=Kn(e.onlineStoreUrl);if(n)return n;let r=e.handle?.trim();return r?t?.(r)??"":""}function pt(e){let t=e?.trim();return t?Y(t)||t:""}function $i(e){return e.startsWith(ti)}function Vi(e){return e.handle??Y(Kn(e.onlineStoreUrl))}function Kn(e){if(!e)return"";if(e.startsWith("/"))return e;try{let t=new URL(e);return e.replace(t.origin,"")}catch{return e}}function Gn(e){return e?.url??""}var Fi="/api/ucp/mcp",Wi="https://shopify.dev/ucp/agent-profiles/2026-08-25/storefront-webmcp.json",qi=12e3,ji=new Set([404,405,422]),Bi=new Set([-32601,-32602]),Hi=new Set(["This question can't be answered right now."]),ft=null;function gt(e){ft=e}var Ki=0;async function Yn(e,t){if(ft)return{kind:"unavailable",reason:ft};let n=new AbortController,r=!1,o=setTimeout(()=>{r=!0,n.abort()},qi),i=Re(t,()=>n.abort(t.reason));try{let a=await fetch(Fi,{method:"POST",credentials:"omit",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:++Ki,method:"tools/call",params:{name:"ask_business",arguments:{meta:{"ucp-agent":{profile:Wi}},ask:e.context===void 0?{query:e.query}:e}}}),signal:n.signal});if(!a.ok){let c=`HTTP ${a.status}`;return ji.has(a.status)&>(c),{kind:"unavailable",reason:c}}return Gi(await a.json())}catch(a){if(t.aborted)throw a;return{kind:"unavailable",reason:r?"timeout":"request failed"}}finally{clearTimeout(o),i()}}function Gi(e){if(!te(e))return{kind:"unavailable",reason:"malformed response"};if(te(e.error)){let a=e.error.code,c=`JSON-RPC error ${typeof a=="number"?a:"unknown"}`;return typeof a=="number"&&Bi.has(a)&>(c),{kind:"unavailable",reason:c}}let t=e.result;if(!te(t)||t.isError===!0)return{kind:"unavailable",reason:"tool error"};let n=t.structuredContent;if(!te(n)||!te(n.answer))return{kind:"unavailable",reason:"no answer"};let r=n.answer.plain;if(typeof r!="string"||!r.trim())return{kind:"unavailable",reason:"no answer"};let o=Array.isArray(n.messages)?n.messages.flatMap(Qi):[];if(o.some(a=>a.code==="ask_unavailable"))return{kind:"unavailable",reason:"ask_unavailable"};if(Hi.has(r.trim()))return gt("not_available"),{kind:"unavailable",reason:"not_available"};let i=Array.isArray(n.links)?n.links.flatMap(Yi):[];return{kind:"answered",result:{answer:{plain:r},...i.length?{links:i}:{},...o.length?{messages:o}:{}}}}function Yi(e){return!te(e)||typeof e.type!="string"||typeof e.url!="string"?[]:[{type:e.type,url:e.url,...typeof e.title=="string"?{title:e.title}:{},...typeof e.id=="string"?{id:e.id}:{}}]}function Qi(e){return!te(e)||typeof e.type!="string"||typeof e.content!="string"?[]:[{type:e.type,...typeof e.code=="string"?{code:e.code}:{},content:e.content}]}function te(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Qn=1e4,Jn=8192,Xn=5,Ji=300,Xi=5,zi={refund:"refund_policy",shipping:"shipping_policy",privacy:"privacy_policy",terms_of_service:"terms_of_service",terms_of_sale:"terms_of_sale",subscription:"subscription_policy",legal_notice:"legal_notice",contact:"contact_information"},Zi=[{type:"refund",patterns:[/\brefund/i,/\breturn/i,/\bmoney\s+back/i,/\bexchange/i,/\breimburse/i,/\b(?:send|mail|post|bring|take|give)\w*\s+(?:\w+\s+){0,2}?back\b/i]},{type:"shipping",patterns:[/\bship/i,/\bdeliver/i,/\bdispatch/i,/\bfulfil/i,/\bfulfill/i,/\bpostage/i,/\btracking/i,/\bcourier/i]},{type:"privacy",patterns:[/\bprivacy/i,/\bdata/i,/\bcookie/i,/\bgdpr/i,/\bpersonal\s+information/i,/\bpersonal\s+data/i]},{type:"terms_of_service",patterns:[/\bterms\s+of\s+service/i,/\bterms\s+of\s+use/i,/\btos/i,/\bterms/i]},{type:"terms_of_sale",patterns:[/\bterms\s+of\s+sale/i,/\bpurchase\s+terms/i]},{type:"subscription",patterns:[/\bsubscription/i,/\bsubscribe/i,/\brecurring/i]},{type:"legal_notice",patterns:[/\blegal\s+notice/i,/\bimprint/i,/\bcompany\s+info/i]},{type:"contact",patterns:[/\bphone/i,/\bcall/i,/\bcontact/i,/\bemail/i,/\baddress/i,/\bhours/i,/\bopening/i,/\blocation/i,/\breach/i,/\bsupport/i]}],tr=async(e,t)=>{let n=e?.ask;if(!er(n))return h("Missing required 'ask' object.",`Call ask_business with { "ask": { "query": "" } }.`);let r=typeof n.query=="string"?n.query.trim():"";if(!r)return Ve(ea);if(r.length>Qn)return h(`Query exceeds the ${Qn}-character limit.`,"Ask a shorter question.");let o=n.context;if(o!==void 0&&aa(o)>Jn)return h(`Context exceeds the ${Jn}-byte limit.`,"Send only the context needed to answer the question.");let i=er(o)&&typeof o.intent=="string"?o.intent:"",a=await Yn(o===void 0?{query:r}:{query:r,context:o},t.signal);if(a.kind==="answered")return Ve(a.result);try{let c=ta([r,i].filter(Boolean).join(" ")),l=await ct(r,Xn,c,t.signal);if(l.policies.length||l.pages.length||l.articles.length||c.length===Ue.length)return Ve(zn(r,l.policies,l.articles,l.pages));let s=await ct(r,Xn,Ue,t.signal);return Ve(zn(r,s.policies,s.articles,s.pages,{unmatched:!0}))}catch(c){return b(c,t.signal,"Ask failed","Rephrase the question (e.g. 'What is your return policy?') and try again.")}},ea={answer:{plain:"Please ask a question about this store, such as its return policy, shipping options, or contact details."}};function ta(e){let t=Zi.flatMap(({type:n,patterns:r})=>r.some(o=>o.test(e))?[n]:[]);return t.length?t:/\bpolic(?:y|ies)\b/i.test(e)?[...Ue]:[]}function zn(e,t,n,r,{unmatched:o=!1}={}){let i=[...t.map(s=>mt(s.title,s.url,yt(s.body)||"(This policy is empty.)")),...r.map(s=>mt(`Page "${s.title}"`,s.url,s.body?yt(s.body):"")),...n.map(s=>mt(`Article "${s.title}"`,s.url,yt(s.excerpt)))],a=[...t.map(s=>ht(zi[s.type]??s.type,s.url,s.title)),...r.map(s=>ht("page",s.url,s.title)),...n.map(s=>ht("article",s.url,s.title))].filter(s=>s!==null),c=t.flatMap(na),l=o?"No policy, page, or article matched this question directly, so these are all of the store's published policies:":"The store's published content that matches this question:";return{answer:{plain:i.length?`${l} ${i.join(` `)}`:`This store has not published a policy, page, or article that answers "${e}". The store may still be able to help if contacted directly.`},...a.length?{links:a}:{},...c.length?{messages:c}:{}}}function mt(e,t,n){let r=t?`${e} (${t}):`:`${e}:`;return n?`${r} ${n}`:r}function ht(e,t,n){return t?n?{type:e,url:t,title:n}:{type:e,url:t}:null}function na(e){let t=ra(e.body);return t?t.kind==="empty"?[{type:"info",code:"policy_empty",content:`${e.title} has an empty policy body.`}]:[{type:"info",code:"policy_links_elsewhere",content:`${e.title} is short and links to other pages (${t.links.join(", ")}); the full details may be on those pages.`}]:[]}function Ve(e){let t=e.messages?.length?`Notes: ${e.messages.map(n=>`- ${n.content}`).join(` `)}`:null;return I(e.answer.plain,e,t)}function ra(e){let t=[...new Set([...e.matchAll(/]*\bhref\s*=\s*["']([^"']+)["']/gi)].map(r=>Ce(r[1]??"").trim()).filter(r=>r&&!r.startsWith("#")&&!/^(?:javascript|mailto|tel):/i.test(r)))],n=Ce(e.replace(/<[^>]*>/g," ")).replace(/https?:\/\/\S+/g," ").replace(/\s+/g," ").trim();return!n&&t.length===0?{kind:"empty"}:t.length>0&&n.length]*>[\s\S]*?<\/\1\s*>/gi," ").replace(//g," ").replace(/]*\bhref\s*=\s*["']([^"']*)["'][^>]*>([\s\S]*?)<\/a\s*>/gi,(n,r,o)=>oa(r,o)).replace(//gi,` `).replace(/]*>/gi,` - `).replace(/<\/t[dh]\s*>/gi," | ").replace(/<\/(?:p|div|ul|ol|h[1-6]|table|section|article|blockquote)\s*>/gi,` `).replace(/<(?:p|div|h[1-6]|tr|table|section|article|blockquote)\b[^>]*>/gi,` `).replace(/<[^>]*>/g,"");return Ce(t).split(` `).map(n=>n.replace(/[ \t\f\v\u00a0]+/g," ").replace(/(?:\s*\|)+\s*$/,"").trim()).join(` `).replace(/\n{3,}/g,` `).trim()}function oa(e,t){let n=Ce(t.replace(/<[^>]*>/g," ")).replace(/\s+/g," ").trim(),r=Ce(e).trim();if(!r||r.startsWith("#")||/^javascript:/i.test(r))return n;let o=r.replace(/^(?:mailto|tel):/i,""),i=ia(o);return!n||n===o||n===i||i.startsWith(n)?i:`${n} (${i})`}function ia(e){if(!e.startsWith("/")||typeof window>"u")return e;try{return new URL(e,window.location.origin).toString()}catch{return e}}function Ce(e){return e.replace(/&#(\d+);/g,(t,n)=>Zn(Number(n))).replace(/&#x([0-9a-f]+);/gi,(t,n)=>Zn(parseInt(n,16))).replace(/ /gi," ").replace(/"/gi,'"').replace(/'|'/gi,"'").replace(/</gi,"<").replace(/>/gi,">").replace(/–/gi,"\u2013").replace(/—/gi,"\u2014").replace(/’|‘/gi,"'").replace(/”|“/gi,'"').replace(/&/gi,"&")}function Zn(e){try{return Number.isFinite(e)?String.fromCodePoint(e):""}catch{return""}}function aa(e){try{return new TextEncoder().encode(JSON.stringify(e)??"").length}catch{return Number.POSITIVE_INFINITY}}function er(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var sa=new Set(["best-selling","price-ascending","price-descending","title-ascending","title-descending","created-ascending","created-descending"]),rr=async(e,t)=>{try{let n=e.collection?.trim(),r=e.navigate===!0;if(!n)return la(await $n(t.signal),t.routes,r);let o=Math.max(1,Number(e.page)||1),i=da(e.sort_by),a=await ca(n,i,o,t.signal);return ua(n,a,i,o,t,r)}catch(n){return b(n,t.signal,"Failed to browse store","Try browsing without a collection to list available collections.")}};async function ca(e,t,n,r){return e==="all"?Vn({page:n,sortBy:t,signal:r}):Fn({handle:e,page:n,sortBy:t,signal:r})}function la(e,t,n){let r=e.collections?.nodes?.map(i=>$e(i,t))??[],o=n?'A collection handle is required to navigate. Ask the user which collection, or call browse_store again with a specific collection handle (or "all") and navigate=true.':'Call browse_store with a collection handle, or with collection "all" to browse products. Set navigate=true to take the user to the collection page.';return I(`Found ${r.length} collection${r.length!==1?"s":""}.`,{collections:r,products:[],navigated:!1},pa(r),o)}function ua(e,t,n,r,o,i){let{routes:a}=o;if(e!=="all"&&!t.collection)return h(`Collection "${e}" was not found.`,"Call browse_store without a collection to list available collections.");let c=t.products.map(s=>_e(s,a)),l=a.collection(e),f={collections:[],products:c,collection_title:t.title,page:r,sort_by:n,url:l};if(i){let s=!F(l);return s&&W(o,l),V({summary:s?`Showing the ${t.title} collection.`:`Already showing the ${t.title} collection.`,navigated:s,destination:`${t.title} collection`,keyFields:nr(c)},{...f,navigated:s})}return I(`Showing ${c.length} product${c.length!==1?"s":""} from ${t.title}.`,{...f,navigated:!1},nr(c),"If the user asked to be taken to this collection, call browse_store again with navigate=true. Each product's variant_id is its selected or first available variant, the line_items[].item.id that create_cart (empty cart) and update_cart take. If the user requested a specific color, size, material, or other option, call get_product with catalog.id and any known catalog.selected_options, then use the matching variants[].id instead, OR call show_variant with selected_options to just navigate to that variant.")}function da(e){return e&&sa.has(e)?e:"best-selling"}function pa(e){return e.length?`Collections: ${e.map(t=>`- ${t.title} (${t.handle})`).join(` `)}`:null}function nr(e){return e.length?`Products: ${e.map(t=>`- ${t.title} (id: ${t.id}, handle: ${t.handle}${t.variant_id?`, variant_id: ${t.variant_id}`:""}) - ${x(t.price_range)||"price unavailable"}`).join(` `)}`:null}function R(e){return typeof e=="string"?e.split("?")[0]?.trim()??"":""}var or="gid://shopify/Cart/";function ve(e){let t=R(e);return t.startsWith(or)?t.slice(or.length):t}async function K(e,t){return!e.id||(e.totalQuantity??0)===0?bt(e):await qn(e.id,t.routes,t.signal)??bt(e)}async function se(e,t){try{return await K(e,t)}catch{return bt(e)}}function bt(e){return{id:e.id??"",item_count:e.totalQuantity??0,total_price:E(e.cost?.totalAmount),currency:e.cost?.totalAmount?.currencyCode??"",totals:ye({total:e.cost?.totalAmount}),line_items:me(e).map(t=>({id:t.id??"",quantity:t.quantity??0,line_price:E(t.cost?.totalAmount),totals:ye({total:t.cost?.totalAmount}),item:{id:t.merchandise?.id??"",title:t.merchandise?.product?.title??"",variant_title:t.merchandise?.title??"",handle:t.merchandise?.product?.handle??"",url:"",image:t.merchandise?.image?.url??"",unit_price:null}}))}}var ir="shopify.webmcp.cartSnapshot",ar;function _t(e){let t={};for(let n of me(e)){let r=R(n.id);r&&(t[r]=(t[r]??0)+(n.quantity??0))}return{cart:ve(e.id),lines:t}}function S(e,t){let n=_t(e);if(t&&St(t,e)){let r=lr(t);Object.keys(r).length&&(n.variants=r)}ar=n;try{window.sessionStorage.setItem(ir,JSON.stringify(n))}catch{}}function fa(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.cart!="string"||typeof t.lines!="object"||t.lines===null||!Object.values(t.lines).every(n=>typeof n=="number")?!1:t.variants===void 0?!0:typeof t.variants=="object"&&t.variants!==null&&Object.values(t.variants).every(n=>typeof n=="string")}function sr(){try{let e=window.sessionStorage.getItem(ir);if(e){let t=JSON.parse(e);if(fa(t))return t}}catch{}return ar}function cr(e){let t=sr(),n=_t(e);if(!t)return!1;if(t.cart!==n.cart)return!0;let r=Object.entries(t.lines);return r.length!==Object.keys(n.lines).length?!0:r.some(([o,i])=>n.lines[o]!==i)}function lr(e){let t={};for(let n of e.line_items){let r=R(n.id),o=U(n.item.id);r&&o&&(t[r]=o)}return t}function ur(e){let t=sr()?.variants;if(!t)return!1;let n=lr(e);return Object.entries(t).some(([r,o])=>n[r]!==void 0&&n[r]!==o)}function St(e,t){let n=_t(t).lines,r={};for(let i of e.line_items){let a=R(i.id);a&&(r[a]=(r[a]??0)+i.quantity)}let o=Object.keys(n);return o.length===Object.keys(r).length&&o.every(i=>r[i]===n[i])}function A(e,t,n=[]){let r=[e];return t.line_items.length&&r.push(ma(t)),n.length&&r.push(n.map(ga).join(` `)),{content:[{type:"text",text:r.join(` `)}],structuredContent:n.length?{...t,messages:n}:t}}function ga({type:e,content:t,path:n}){let r=n?` (${n})`:"";return e==="error"?`Error${r}: ${t}`:e==="warning"?`Warning${r}: ${t}`:t}function ce(e){return e.map(t=>({type:"warning",code:"cart_warning",content:t}))}function O(e){if(e.item_count===0||e.line_items.length===0)return"The cart is empty.";let t=e.line_items.slice(0,3).map(dr).join(", "),n=e.line_items.length>3?` and ${e.line_items.length-3} more`:"",r=e.item_count===1?"":"s",o=x(e.total_price)||"unknown total";return`Cart has ${e.item_count} item${r} totaling ${o}: ${t}${n}.`}function ma(e){return`Cart id: ${e.id} Cart line items: `+e.line_items.map(ha).join(` `)}function ha(e){let t=x(e.line_price)||"price unavailable",n=e.item.id?`, item.id ${e.item.id}`:"";return`- ${e.id}: "${dr(e)}" (quantity ${e.quantity}${n}) - ${t}`}function dr(e){let t=e.item.title||e.item.handle||e.item.id||"item",n=e.item.variant_title,r=n&&n!=="Default Title"?` (${n})`:"";return`${t}${r} x${e.quantity}`}function Te(e){let t=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):Number.NaN;return Number.isFinite(t)?Math.floor(t):null}function Fe(e){if(typeof e!="object"||e===null)return null;let t=Reflect.get(e,"cart");if(typeof t!="object"||t===null)return null;let n=Reflect.get(t,"line_items");return Array.isArray(n)?n.map(r=>typeof r=="object"&&r!==null?r:{}):null}function We(e){return e.map(({item:t,reason:n})=>({type:"error",code:"invalid_line_item",content:n,path:`$.cart.line_items[${t-1}]`,severity:"recoverable"}))}var pr=async(e,t)=>{try{let n=Z(),r=await L(t.signal,n),o=H(r);if(o===0)return S(r),rt("Cart is already empty.",{cleared:!0,previous_item_count:0});let i=me(r).filter(f=>f.id).map(f=>({id:f.id,quantity:0}));ie(t.signal);let a=await n.updateCart({lines:i});ae(a),S(a.cart);let c=ee(a),l=c.length?` Warnings: ${c.join("; ")}.`:"";return rt(`Cart cleared. Removed ${o} item${o!==1?"s":""}.${l}`,{cleared:!0,previous_item_count:o,...c.length&&{warnings:c}},Mn)}catch(n){return b(n,t.signal,"Failed to clear cart","get_cart returns the cart's current contents.")}};var we=100,fr=async(e,t)=>{let n=Fe(e);if(!n?.length)return h("No cart.line_items provided.","create_cart takes cart.line_items, each with item.id (a ProductVariant GID) and quantity.");if(n.length>we)return h(`create_cart takes at most ${we} line_items; ${n.length} were sent. Nothing changed.`);try{let r=Z(),o=await L(t.signal,r);if(H(o)>0){let s=await K(o,t);return S(o,s),A(gr(s,n).summary,s,ba(s,n))}let{lines:i,unresolved:a}=ya(n);if(a.length){let s=await K(o,t);return S(o,s),_a(a,n.length,s)}ie(t.signal);let c=await r.updateCart({lines:i});ae(c),S(c.cart);let l=await se(c.cart,t);S(c.cart,l);let f=ee(c);return A(`Created the cart. ${O(l)}`,l,[...ce(f),{type:"info",code:"applied",content:"This is the cart as it now stands, after the change."}])}catch(r){return b(r,t.signal,"Cart creation failed","get_cart returns the cart's current contents.")}};function ya(e){let t=[],n=new Map;return e.forEach((r,o)=>{let i=o+1,a=typeof r.item?.id=="string"?r.item.id.trim():"",c=U(a);if(!c){t.push({item:i,reason:a?`item.id "${a}" is not a ProductVariant GID (gid://shopify/ProductVariant/...). A Product GID names the product, not one of its variants.`:"item.id is missing. Each line item needs a ProductVariant GID."});return}let l=Te(r.quantity)??1;if(l<1){t.push({item:i,reason:`quantity ${l} cannot be created; a new cart line holds at least 1.`});return}let f=n.get(c);f?f.quantity+=l:n.set(c,{merchandiseId:a,quantity:l})}),{lines:[...n.values()],unresolved:t}}function gr(e,t){let n=new Map;for(let i of t){let a=U(typeof i.item?.id=="string"?i.item.id:void 0);a&&n.set(a,(n.get(a)??0)+(Te(i.quantity)??1))}let r=new Map;for(let i of e.line_items){let a=U(i.item.id);a&&r.set(a,(r.get(a)??0)+i.quantity)}return n.size>0&&n.size===r.size&&[...n].every(([i,a])=>r.get(i)===a)?{summary:`The cart already holds exactly these items, so nothing was added. ${O(e)}`,repeat:!0}:{summary:`The shopper already has a cart with items, so no cart was created. ${O(e)}`,repeat:!1}}function ba(e,t){return gr(e,t).repeat?[{type:"info",code:"no_change",content:"These items are already in the cart, so it was left as it is."}]:[{type:"error",code:"cart_not_empty",content:"create_cart only fills a cart with no items, so this cart was left as it is. update_cart sets this cart to exactly the lines it is given, so its current lines plus new ones add to it.",severity:"recoverable"}]}function _a(e,t,n){return A(`${e.length} of ${t} line item${t===1?"":"s"} could not be used, so nothing was added.`,n,[...We(e),{type:"info",code:"variant_ids",content:"search_catalog and browse_store return each product's variant_id, and get_product returns the id of every variant."}])}var mr=async(e,t)=>{try{let n=await L(t.signal),r=H(n);if(r===0)return h("Cart is empty. Add items before checking out.","search_catalog finds products, and create_cart adds them to an empty cart.");let o=E(n.cost?.totalAmount),i=t.routes.checkout(),a=!F(i);a&&W(t,i);let c=o?` totaling ${x(o)}`:"",l=a?`Taken you to checkout with ${r} item${r!==1?"s":""}${c}.`:`Already on the checkout page with ${r} item${r!==1?"s":""}${c}.`;return V({summary:l,navigated:a,destination:"checkout"},{navigating_to:i,item_count:r,total_price:o})}catch(n){return b(n,t.signal,"Failed to initiate checkout","Call get_cart to verify cart contents, then retry.")}};var hr=async(e,t)=>{try{let n=await L(t.signal),r=await K(n,t);return S(n,r),r.line_items.length===0?A("Cart is empty.",r,[{type:"info",code:"empty_cart",content:"With no items in the cart, create_cart is the tool that adds the first ones."}]):A(O(r),r,[{type:"info",code:"full_replacement",content:"update_cart sets the cart to exactly the lines it is given, identified by the line ids above. proceed_to_checkout moves to checkout."}])}catch(n){return b(n,t.signal,"Failed to fetch cart","This is usually a transient error.")}};var yr=async(e,t)=>{let n=e.catalog,r=pt(n?.id)||wa();if(!r)return h("Product catalog.id is required.","Call search_catalog or browse_store to find a product id or handle first.");try{return await Sa(r,n,t)}catch(o){return b(o,t.signal,"Failed to load product details","Try again with a product id or handle from search_catalog or browse_store.")}};async function Sa(e,t,n){let r=t?.selected_options,o=r?.length?[...r]:void 0,i=await be(e,{selected_options:o,routes:n.routes,signal:n.signal});return i?t?.navigate===!0?va(i,n):Ta(i,!!o?.length):Ca(e)}function Ca(e){return h(`Product "${e}" was not found.`,"Call search_catalog or browse_store to find an available product.")}function va(e,t){let n=e.url,r=!F(n);return r&&W(t,n),V({summary:r?`Showing ${e.title}.`:`Already showing ${e.title}.`,navigated:r,destination:e.title},e)}function Ta(e,t){return I(`${e.title} has ${e.variant_count} variant${e.variant_count!==1?"s":""}.`,e,Ea(e),Aa(e,t))}function wa(){return typeof window>"u"?"":Y(window.location.href)}function Ea(e){if(!e.variants.length)return null;let t=e.variants.filter(r=>r.availability.available);return`Variants: `+(t.length?t:e.variants.slice(0,10)).map(r=>{let o=r.options.map(c=>`${c.name}: ${c.value}`).join(", "),i=x(r.price)||"price unavailable",a=r.availability.available?"available":"unavailable";return`- ${r.title} (id: ${r.id}) - ${o||"no options"} - ${i} - ${a}`}).join(` `)}function Aa(e,t){let n=e.variants.filter(o=>o.availability.available),r="TO VIEW (show/open/go to): call show_variant with catalog.selected_options set to whatever options the user specified (even partial like just Color) \u2014 do NOT ask for missing options.";if(n.length&&t)return`${r} TO ADD TO CART: the matching variants[].id from this result is the line_items[].item.id that create_cart (empty cart) and update_cart take.`;if(n.length){let o=e.available_options_truncated?" (available_options is truncated \u2014 narrow with catalog.selected_options if needed).":"";return`${r}${o} TO ADD TO CART: if the user did not request specific options, variants[0].id is the line_items[].item.id for create_cart (empty cart) or update_cart. If they requested specific options, pick one complete available_options entry (or call get_product again with catalog.selected_options) to get the exact variants[].id.`}return e.available_options_count>0?`${r} TO ADD TO CART: you need a full option combination \u2014 pick one complete available_options entry, or ask the user for missing options, then call get_product again with catalog.selected_options set to that full combination to get the exact variants[].id.`:e.available_options_truncated?"Available option combinations were truncated. Call get_product again with catalog.selected_options for any options the user already specified to narrow the result before choosing a variant.":"No available option combinations matched. Ask the user to choose different product options or search for another product."}var Pa="/.well-known/ucp",br=async(e,t)=>{try{let n=await fetch(Pa,{headers:{accept:"application/json"},signal:t.signal});if(!n.ok)throw new Error(`UCP profile request failed (${n.status})`);let r=await n.json(),o=Ra(r);if(!o)throw new Error("UCP profile response did not include a ucp object.");return I(Oa(o),{ucp:o},Ma(o),"Use the UCP service endpoints in this profile to continue the purchase over UCP. Call get_cart for the current cart id.")}catch(n){return b(n,t.signal,"Failed to fetch UCP profile","Try again - this is usually a transient error.")}};function Ra(e){return!qe(e)||!qe(e.ucp)?null:e.ucp}function Oa(e){let t=typeof e.version=="string"?` (version ${e.version})`:"",n=Object.keys(Ct(e.services)),r=Object.keys(Ct(e.capabilities)),o=n.length?n.join(", "):"none",i=r.length?r.join(", "):"none";return`Fetched this store's UCP profile${t}. Services: ${o}. Capabilities: ${i}.`}function Ma(e){let t=Object.entries(Ct(e.services)).flatMap(([n,r])=>Ia(r).filter(o=>o.endpoint).map(o=>`- ${n} (${o.transport??"unknown"}): ${o.endpoint}`));return t.length?`UCP service endpoints: ${t.join(` `)}`:null}function Ia(e){return Array.isArray(e)?e.filter(qe).map(t=>({transport:typeof t.transport=="string"?t.transport:void 0,endpoint:typeof t.endpoint=="string"?t.endpoint:void 0})):[]}function Ct(e){return qe(e)?e:{}}function qe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var _r=(e,t)=>{let n=t.routes.accountOrders(),r=!F(n);return r&&W(t,n,10),V({summary:r?"Taken you to your order history. You may need to log in if not already authenticated.":"Already on your order history page. You may need to log in if not already authenticated.",navigated:r,destination:"order history"},{navigating_to:n})};var Sr=async(e,t)=>{let n=e.catalog?.query?.trim();if(!n)return h("Search query is required.","Call search_catalog with catalog.query.");try{let r=$a(Number(e.catalog?.pagination?.limit)||5,1,10),o=await Ln(n,r,t.signal);return ka(n,xa(o.predictiveSearch,t.routes),t.routes)}catch(r){return b(r,t.signal,"Search failed","Try again with a simpler catalog.query, or use browse_store to inspect collections.")}};function xa(e,t){return{products:e.products.map(n=>_e(n,t)),collections:e.collections.map(n=>$e(n,t)),articles:e.articles.map(ut),pages:e.pages.map(dt)}}function ka(e,t,n){let r=t.products.length+t.collections.length+t.articles.length+t.pages.length,o={...t,search_url:n.search(e)};return r===0?I(`No search results found for "${e}".`,o,null,"Try browse_store to inspect collections or search_catalog with a broader catalog.query."):I(`Found ${Na(t).join(", ")} for "${e}".`,o,La(t),Da(t))}function Na(e){return[je("product",e.products.length),je("collection",e.collections.length),je("article",e.articles.length),je("page",e.pages.length)].filter(Boolean)}function je(e,t){return t?`${t} ${e}${t===1?"":"s"}`:""}function Da(e){return e.products.length?"Each product's variant_id is its selected or first available variant, the line_items[].item.id that create_cart (empty cart) and update_cart take. If the user requested a specific color, size, material, or other option, call get_product with catalog.id and any known catalog.selected_options to filter available_options, then use the matching variants[].id instead.":e.collections.length||e.articles.length||e.pages.length?"No products matched, but other catalog results were found. Share the relevant collection, article, or page URL with the user, or call browse_store for product collections.":"Use browse_store to inspect products by collection."}function La(e){let t=[Ua(e.products),vt("Collections",e.collections),vt("Articles",e.articles),vt("Pages",e.pages)].filter(Boolean);return t.length?t.join(` `):null}function Ua(e){return e.length?`Products: `+e.map(t=>`- ${t.title} (id: ${t.id}, handle: ${t.handle}${t.variant_id?`, variant_id: ${t.variant_id}`:""}) - ${x(t.price_range)||"price unavailable"}`).join(` `):null}function vt(e,t){return t.length?`${e}: `+t.map(n=>`- ${n.title}${n.handle?` (${n.handle})`:""}: ${n.url}`).join(` `):null}function $a(e,t,n){return Math.min(n,Math.max(t,e))}var Tt="gid://shopify/ProductVariant/",Cr=async(e,t)=>{let n=Va(e);if("error"in n)return n.error;let{handle:r,rawVariantId:o,selectedOptions:i}=n,a=await Fa(r,o,i,t);if("error"in a)return a.error;let{variantId:c,resolvedOptions:l}=a,f=a.productHandle||r,s=l?[f,r]:[f],u=za(t.routes.product(f),c,s),p=!F(u);return p&&W(t,u),qa({handle:f,requestedHandle:r,variantId:c,url:u,navigated:p,resolvedOptions:l})};function Va(e){let t=e.catalog.variant_id,n=Ga(e.catalog.selected_options);if(t==null&&!n.length)return{error:h("Provide either catalog.variant_id or catalog.selected_options.","For a specific variant, pass variant_id from get_product variants[].id. For a partial match like a color only, pass selected_options.")};let r=Ya(e.catalog.handle);return r?Ja(r)?{handle:r,rawVariantId:t??void 0,selectedOptions:n}:{error:h(`Product handle "${r}" is not valid.`,"Use a product handle from search_catalog, browse_store, or get_product.")}:{error:h("Product handle is required.","Pass catalog.handle, or call show_variant from a product page.")}}async function Fa(e,t,n,r){let o=t!=null?Tr(t):"";if(o){let i=await Wa(o,e,r);return"error"in i?i:{variantId:o,resolvedOptions:void 0,productHandle:i.sameProduct?void 0:i.handle}}if(n.length){let i=await ja(e,n,r);return"error"in i?i:{variantId:i.variantId,resolvedOptions:i.options,productHandle:i.productHandle}}return{error:h("Product variant_id could not be resolved.","Call get_product to find an available variants[].id, then retry show_variant.")}}async function Wa(e,t,n){try{let r=await Wn(`${Tt}${e}`,t,n.signal);return r||{error:h(`Product variant ${e} was not found on this store.`,"Call get_product to find an available variants[].id, then retry show_variant.")}}catch(r){return{error:b(r,n.signal,"Failed to look up the product variant.","Call get_product to find an available variants[].id, then retry show_variant.")}}}function qa(e){let{handle:t,requestedHandle:n,variantId:r,url:o,navigated:i,resolvedOptions:a}=e,c=a?.length?` (${a.map(f=>`${f.name}: ${f.value}`).join(", ")})`:"",l=t===n?"":a?` This variant is sold as a separate product (${t}), linked to ${n} as an option, so its own product page is shown.`:` This variant belongs to a different product (${t}), so that product's page is shown.`;return V({summary:i?`Showing the selected variant${c}.${l}`:`Already showing the selected variant${c}.${l}`,navigated:i,destination:t,keyFields:`Variant id: ${r}`},{handle:t,variant_id:r,url:o,navigated:i,selected_options:a})}async function ja(e,t,n){try{let r=await be(e,{selected_options:t,routes:n.routes,signal:n.signal});if(!r)return{error:Ka(e)};let o=Ba(r);if(o)return o;let i=await Ha(r,e,n);return i||{error:h("No available variant matched the selected options.","Call get_product with the same selected_options to see available_options, then pick one and retry.")}}catch(r){return{error:b(r,n.signal,"Failed to resolve variant from selected_options.","Call get_product first to inspect available variants, then retry show_variant with a variant_id.")}}}function Ba(e){let t=e.variants.filter(n=>n.availability.available);return vr(t[0]??e.variants[0])}function vr(e){return e?.id?{variantId:Tr(e.id),options:e.options,...e.product_handle?{productHandle:e.product_handle}:{}}:null}async function Ha(e,t,n){let r=e.available_options?.[0];if(!r?.length)return null;let o=await be(t,{selected_options:r,routes:n.routes,signal:n.signal});return vr(o?.variants?.find(i=>i.availability.available)??o?.variants?.[0])}function Ka(e){return h(`Product "${e}" was not found.`,"Call search_catalog or browse_store to find an available product.")}function Ga(e){return e?.length?e.map(t=>({name:String(t?.name??"").trim(),value:String(t?.value??"").trim()})).filter(t=>t.name&&t.value):[]}function Tr(e){let t=String(e).trim();if(!t)return"";let n=t.startsWith(Tt)?t.slice(Tt.length):t;return/^\d+$/.test(n)?n:""}function Ya(e){return e?.trim()?Qa(e):wr()}function Qa(e){let t=e?.trim();return t?Y(t)||Xa(t):""}function wr(){return typeof window>"u"?"":Y(window.location.href)}function Ja(e){return!!e&&!/[/?#\\]/.test(e)&&e!=="."&&e!==".."}function Xa(e){try{return decodeURIComponent(e)}catch{return""}}function za(e,t,n){let r=new URL(e,es());if(r.searchParams.set("variant",t),n.includes(wr())){let o=Za().searchParams.get("selling_plan");o&&r.searchParams.set("selling_plan",o)}return r.pathname+r.search}function Za(){return typeof window>"u"?new URL("https://shopify.local/"):new URL(window.location.href)}function es(){return typeof window>"u"?"https://shopify.local":window.location.origin}var Er=async(e,t)=>{let n=Fe(e);if(n&&n.length>we)return h(`update_cart takes at most ${we} line_items; ${n.length} were sent. Nothing changed.`);try{let r=Z(),o=await L(t.signal,r),i=ts(e.id,o);if(i)return await Ee(i,o,t);if(!n)return await Ee({type:"info",code:"no_change",content:"No line_items were given, so the cart's lines were left as they are."},o,t);if(cr(o))return await Ee(wt,o,t);let a=await K(o,t);if(!St(a,o))return await Ee({...wt,content:"The cart changed while this update was being prepared (for example, the shopper edited it on the page), so nothing was changed."},await L(t.signal,r),t);if(ur(a))return await Ee({...wt,content:"The cart has changed since it was last returned (a line now holds a different variant, for example because the shopper changed it on the page), so nothing was changed."},o,t);let{lines:c,unresolved:l}=ns(n,a.line_items);if(l.length)return S(o,a),A(`${l.length} of ${n.length} line item${n.length===1?"":"s"} could not be used, so nothing was changed.`,a,We(l));if(c.length===0)return S(o,a),A(`The cart already holds exactly these lines, so nothing changed. ${O(a)}`,a,[{type:"info",code:"no_change",content:"The cart was left as it is."}]);let f=c.filter(g=>!g.id),s=c.filter(g=>g.id);ie(t.signal);let u=await r.updateCart({lines:f.length?f:s});ae(u),S(u.cart);let p=ee(u);if(f.length&&s.length){let g=f.reduce((C,T)=>C+T.quantity,0),y=H(u.cart)-H(o);if(p.length||yC.message).filter(Boolean)??[];if(p.push(...ee(m)),Q.length){let C=m.cart??u.cart,T=await se(C,t);return S(C,T),A(`The new items were added, but some of the other changes failed. ${O(T)}`,T,[...ce(p),{type:"warning",code:"partial_update",content:`Some changes to existing lines failed (${Q.join(", ")}). The cart above is as it now stands; update_cart with the complete set of lines plans only what is still different.`}])}u=m,S(u.cart)}let d=await se(u.cart,t);return S(u.cart,d),A(`Updated the cart. ${O(d)}`,d,[...ce(p),{type:"info",code:"applied",content:"This is the cart as it now stands, after the change."}])}catch(r){return b(r,t.signal,"Cart update failed","get_cart returns the cart's current contents.")}};function ts(e,t){return t.id?typeof e!="string"||!ve(e)?null:ve(e)!==ve(t.id)?{type:"error",code:"cart_not_found",content:"That id is not the shopper's current cart, so nothing was changed.",severity:"recoverable",path:"$.id"}:null:{type:"error",code:"cart_not_found",content:"The shopper has no cart yet, so there is nothing to update. create_cart creates one.",severity:"recoverable"}}var wt={type:"error",code:"cart_changed",content:"The cart has changed since it was last returned (for example, the shopper edited it on the page, or a new cart replaced it), so nothing was changed.",severity:"recoverable"};async function Ee(e,t,n){let r=await K(t,n);S(t,r);let o=e.type==="info"?O(r):`Nothing was changed. ${O(r)}`;return A(o,r,[e])}function ns(e,t){let n=[],r=new Map(t.map(s=>[R(s.id),s])),o=new Map,i=new Map,a=new Map,c=(s,u,p,d)=>{let g=a.get(u);g?g.quantity+=p:a.set(u,{merchandiseId:s,quantity:p,position:d})};if(e.forEach((s,u)=>{let p=u+1,d=Te(s.quantity);if(d===null){n.push({item:p,reason:"quantity is missing or not a number. update_cart takes each line's absolute quantity and has no default to fall back on."});return}if(d<0){n.push({item:p,reason:`quantity ${d} is negative. Quantities here are absolute, not changes; a line left out of line_items is removed.`});return}let g=typeof s.item?.id=="string"?s.item.id.trim():"",y=U(g),m=R(s.id);if(m){let Q=r.get(m);if(!Q){n.push({item:p,reason:`line id "${String(s.id)}" is not a line of the current cart.`});return}if(o.has(m)){n.push({item:p,reason:`line id "${String(s.id)}" is listed more than once.`});return}if(g&&!y){n.push({item:p,reason:`item.id "${g}" is not a ProductVariant GID (gid://shopify/ProductVariant/...).`});return}let C=U(Q.item.id);if(y&&C&&y!==C){o.set(m,d),d>0&&i.set(m,{merchandiseId:g,merchandiseKey:y,position:p});return}o.set(m,d);return}if(!y){n.push({item:p,reason:g?`item.id "${g}" is not a ProductVariant GID (gid://shopify/ProductVariant/...), and the entry has no line id.`:"the entry has neither a line id nor an item.id."});return}c(g,y,d,p)}),n.length)return{lines:[],unresolved:n};for(let[s,u]of i){let p=t.find(g=>R(g.id)!==s&&U(g.item.id)===u.merchandiseKey),d=[...i].some(([g,y])=>g!==s&&y.merchandiseKey===u.merchandiseKey);(p||d||a.has(u.merchandiseKey))&&n.push({item:u.position,reason:p?`item.id "${u.merchandiseId}" is already on line ${p.id}. That line's quantity can carry the total, with this line left out.`:`item.id "${u.merchandiseId}" is named by more than one entry, so it is unclear which line should carry it.`})}if(n.length)return{lines:[],unresolved:n};let l=[];for(let[s,u]of a){let p=t.filter(m=>U(m.item.id)===s),d=p.filter(m=>!o.has(R(m.id)));if(d.length>1){n.push({item:u.position,reason:`item.id "${u.merchandiseId}" is on ${d.length} lines of the cart (${d.map(m=>m.id).join(", ")}), so it is unclear which one this entry means. Each of those lines can be listed by its line id.`});continue}let g=d[0];if(g){o.set(R(g.id),u.quantity);continue}if(u.quantity===0)continue;let y=p.find(m=>i.has(R(m.id))||o.get(R(m.id))!==m.quantity);if(y){n.push({item:u.position,reason:`item.id "${u.merchandiseId}" is already on line ${y.id}, which this request also changes, so adding it again would collide with that line. That line's quantity can carry the total instead.`});continue}l.push({merchandiseId:u.merchandiseId,quantity:u.quantity})}if(n.length)return{lines:[],unresolved:n};let f=[];for(let s of t){if(!s.id)continue;let u=R(s.id),p=o.get(u)??0,d=i.get(u);d?f.push({id:s.id,merchandiseId:d.merchandiseId,quantity:p}):p!==s.quantity&&f.push({id:s.id,quantity:p})}for(let{merchandiseId:s,quantity:u}of l)f.push({merchandiseId:s,quantity:u});return{lines:f,unresolved:n}}var Ar={ask_business:tr,browse_store:rr,cancel_cart:pr,create_cart:fr,proceed_to_checkout:mr,get_cart:hr,get_product:yr,get_ucp_profile:br,manage_orders:_r,search_catalog:Sr,show_variant:Cr,update_cart:Er};var Pr=Symbol.for("shopify.webmcp.registered"),rs=Object.values(wn).map(e=>({...e,execute:Ar[e.name]}));function Rr(){let e=is();if(!e||as())return!1;let t=[];for(let n of rs){let r=cs(n);t.push(e.registerTool(r))}return ss(),Promise.allSettled(t),!0}function os(e){let t=window.Shopify?.routes?.navigate;if(typeof t=="function")return t(e);window.location.href=e}function is(){return typeof document<"u"&&"modelContext"in document?document.modelContext??null:typeof navigator<"u"&&"modelContext"in navigator?navigator.modelContext??null:null}function as(){return typeof window>"u"?!1:Reflect.get(window,Pr)===!0}function ss(){typeof window>"u"||Reflect.set(window,Pr,!0)}function cs(e){let{execute:t,...n}=e;return{...n,execute:fn(e.name,(r,o)=>t(r,{routes:gn,navigate:os,signal:Ae(o)}))}}(function(){typeof window>"u"||Rr()})();})();