"use strict";(()=>{var De=null;function yn(){return De??=new AbortController().signal,De}function X(e){let t=e?.signal;return gn(t)?t:yn()}function gn(e){return typeof e=="object"&&e!==null&&typeof Reflect.get(e,"aborted")=="boolean"&&typeof Reflect.get(e,"addEventListener")=="function"}function de(e){return e.reason??mn()}function mn(){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 Ne(e){if(e.aborted)throw de(e)}function Z(e){return typeof e=="object"&&e!==null&&Reflect.get(e,"name")==="AbortError"}function Ue(e,t){return e.aborted?(t(),()=>{}):(e.addEventListener("abort",t,{once:!0}),()=>e.removeEventListener("abort",t))}var hn=[["analyticsProcessingAllowed","USER_CONSENT_TYPE_ANALYTICS"],["marketingAllowed","USER_CONSENT_TYPE_MARKETING"],["preferencesProcessingAllowed","USER_CONSENT_TYPE_PREFERENCES"],["saleOfDataAllowed","USER_CONSENT_TYPE_SALE_OF_DATA"]];function bn(e){return hn.filter(([t])=>e[t]).map(([,t])=>({consentType:t}))}function $e(e){let{send:t,context:n,dataOriginator:r="DATA_ORIGINATOR_MERCHANT",flushDelayMs:o=5e3,registerLifecycle:i=!1}=e,a=[],s;function c(){s!==void 0||typeof setTimeout!="function"||(s=setTimeout(()=>{s=void 0,l()},o))}function u(y){let _=n.consent();_.analyticsProcessingAllowed&&(a.length>=50&&a.shift(),a.push({eventClass:"EVENT_CLASS_EVENT",source:"EVENT_APP_STOREFRONT",dataOriginator:r,user:{type:"USER_TYPE_BUYER",...n.browserId===void 0?{}:{domainScopedBrowserId:{value:n.browserId}}},...n.shopId===void 0?{}:{shop:{id:{lowid:n.shopId}}},...n.sessionToken===void 0?{}:{session:{clientSessionToken:n.sessionToken}},userConsents:bn(_),client:{browser:{href:Sn(n.pageUrl())}},payload:y}),c())}function l(){if(s!==void 0&&(clearTimeout(s),s=void 0),a.length===0)return;if(!n.consent().analyticsProcessingAllowed){a.length=0;return}let y=JSON.stringify({events:a});a.length=0;try{t(y,!0)}catch{}}return i&&typeof document<"u"&&typeof window<"u"&&typeof window.addEventListener=="function"&&(document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&l()}),window.addEventListener("pagehide",()=>l())),{produce:u,flush:l}}var _n="/.well-known/shopify/fec/produce";function ke(e=_n){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 Sn(e){let t;try{t=new URL(e)}catch{return""}return t.pathname=t.pathname.replace(/(\/account\/(?:reset|activate)\/[^/]+\/)[^/]+/,"$1[redacted]"),t.toString()}var vn=[5,10,25,50,100,250,500,1e3,2500,5e3,1e4],Tn=5e3,qe=1;function Fe(e){return Object.keys(e).sort().map(t=>`${t}\0${String(e[t])}`).join("")}function Cn(e){return Object.entries(e).map(([t,n])=>({key:t,value:{stringValue:String(n)}}))}function wn(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 An={info:{number:9,text:"INFO"},warn:{number:13,text:"WARN"},error:{number:17,text:"ERROR"}};function Rn(e,t){for(let n=0;n({timeUnixNano:r.timeUnixNano,observedTimeUnixNano:r.timeUnixNano,severityNumber:r.severityNumber,severityText:r.severityText,body:{stringValue:r.body},attributes:wn(r.attributes)}))}]}]}}var On=100;function We(e){let{serviceName:t,send:n,sendLogs:r,scopeName:o="@shopify/webmcp",scopeVersion:i="0.0.0",flushDelayMs:a=Tn,now:s=Date.now,registerLifecycle:c=!1}=e,u={name:o,version:i},l=new Map,y=[],_=s(),d;function x(){d!==void 0||typeof setTimeout!="function"||(d=setTimeout(()=>{d=void 0,J()},a))}function v(R,b,E={},C="1"){if(!Number.isFinite(b))return;let U=`c${R}${C}${Fe(E)}`,$=l.get(U);$&&$.kind==="counter"?$.value+=b:l.set(U,{kind:"counter",name:R,unit:C,attributes:E,value:b}),x()}function pn(R,b,E={},C="1",U=vn){if(!Number.isFinite(b))return;let $=`h${R}${C}${Fe(E)}`,ue=l.get($),w;ue&&ue.kind==="histogram"?w=ue:(w={kind:"histogram",name:R,unit:C,attributes:E,bounds:U,count:0,sum:0,min:b,max:b,bucketCounts:Array.from({length:U.length+1},()=>0)},l.set($,w)),w.count+=1,w.sum+=b,w.min=Math.min(w.min,b),w.max=Math.max(w.max,b),w.bucketCounts[Rn(w.bounds,b)]+=1,x()}function fn(R,b={},E="info"){if(!r)return;y.length>=On&&y.shift();let{number:C,text:U}=An[E];y.push({timeUnixNano:pe(s()),severityNumber:C,severityText:U,body:R,attributes:b}),x()}function J(){d!==void 0&&(clearTimeout(d),d=void 0);let R=l.size>0,b=y.length>0;if(!R&&!b)return;let E=s();if(R){let C=En(t,u,l.values(),pe(E),pe(_));l.clear();try{n(JSON.stringify(C),!0)}catch{}}if(b&&r){let C=Pn(t,u,y);y.length=0;try{r(JSON.stringify(C),!0)}catch{}}_=E}return c&&typeof document<"u"&&typeof window<"u"&&typeof window.addEventListener=="function"&&(document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&J()}),window.addEventListener("pagehide",()=>J())),{counter:v,histogram:pn,log:fn,flush:J}}function fe(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 q={analyticsProcessingAllowed:!1,marketingAllowed:!1,preferencesProcessingAllowed:!1,saleOfDataAllowed:!1},Mn=/\/(\d+)(?:\?.*)?$/;function Be(e){return typeof e=="number"?Number.isSafeInteger(e)?String(e):void 0:e===void 0||e===""?void 0:/^\d+$/.test(e)?e:Mn.exec(e)?.[1]}function In(e){try{return decodeURIComponent(e)}catch{return e}}function xn(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:In(r)}}var Ln="00000000-0000-0000-0000-000000000000",je="00000000-0000-0000-5000-000000000000";function ye(e){if(!(typeof e!="string"||e==="")&&!(e===Ln||e===je))return e}var ee={token:void 0,denied:!1};function Dn(e){try{if(typeof document>"u")return ee;let t=document.querySelector(`meta[name="${e}"]`);if(!t)return ee;let n=Number(t.getAttribute("data-expiration"));if(!Number.isFinite(n)||n<=Date.now())return ee;let r=t.getAttribute("content");return r===je?{token:void 0,denied:!0}:{token:ye(r),denied:!1}}catch{return ee}}function Ve(e,t,n){try{let o=window.Shopify?.customerPrivacy?.__internal,i=o?.[n];if(typeof i=="function")return ye(i.call(o,{generateFallback:!1,tag:"webmcp_storefront_context"}))}catch{return}let r=Dn(e);if(!r.denied)return r.token!==void 0?r.token:ye(xn(t))}function te(e){try{return e?.()===!0}catch{return!1}}function ge(e){return typeof e=="object"&&e!==null}function Nn(e){return!ge(e)||e.analytics===""&&e.marketing===""&&e.preferences===""}function Un(){try{if(!ge(window.privacyBanner))return!1;let e=window.Shopify?.customerPrivacy,t=e?.shouldShowBanner;return typeof t!="function"?!0:t()&&Nn(e?.currentVisitorConsent?.())}catch{return!0}}function me(){let e=window.Shopify?.customerPrivacy;if(!e||Un())return q;try{if(e.consentStatus!=="loaded")return q;let t=e.currentVisitorConsent?.();if(ge(t)&&t.analytics==="no")return q}catch{return q}return{analyticsProcessingAllowed:te(e.analyticsProcessingAllowed),marketingAllowed:te(e.marketingAllowed),preferencesProcessingAllowed:te(e.preferencesProcessingAllowed),saleOfDataAllowed:te(e.saleOfDataAllowed)}}function $n(){try{return Be(window.Shopify?.analytics?.getConfig().shop?.shopId)}catch{return}}function kn(){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"?Be(r):void 0}catch{return}}function qn(){return $n()??kn()}function Fn(){return window.location?.href??""}function He(){return{shopId:qn(),browserId:Ve("shopify-y","_shopify_y","uniqueToken"),sessionToken:Ve("shopify-s","_shopify_s","visitToken"),pageUrl:Fn,consent:me}}var Wn="https://otlp-http-production.shopifysvc.com/v1/metrics",Vn="https://otlp-http-production.shopifysvc.com/v1/logs",Bn="storefront_webmcp",jn=!0,Hn={localhost:!0,"127.0.0.1":!0,"0.0.0.0":!0,"[::1]":!0,"localtest.me":!0};function Ke(){if(!jn||typeof window>"u"||typeof document>"u")return!1;let e=window.location?.host??"";return e!==""&&!Hn[e]&&!e.includes(":")}var he=null,Qe=!1;function ze(){return Qe||(Qe=!0,Ke()&&(he=We({serviceName:Bn,send:fe(Wn),sendLogs:fe(Vn),registerLifecycle:!0}))),he}var be=null,Ye=!1;function Je(){return Ye||(Ye=!0,Ke()&&(be=$e({send:ke(),context:He(),registerLifecycle:!0}))),be}var Qn="type.googleapis.com/shopify.buyer_activity.agent.WebMcpToolCallEvent";function Yn(e){return e.aborted===!0?"OUTCOME_ABORTED":e.isError?e.errorClass==="tool_error"?"OUTCOME_TOOL_ERROR":"OUTCOME_EXCEPTION":"OUTCOME_SUCCESS"}function Gn(e){let t=e.aborted===!0;return{"@type":Qn,eventType:"EVENT_TYPE_WEB_MCP_TOOL_CALL_COMPLETED",surface:"AGENT_SURFACE_STOREFRONT_WEBMCP",toolName:e.tool,outcome:Yn(e),durationMs:Math.max(0,Math.round(e.durationMs)),occurredAt:new Date().toISOString(),...e.errorClass===void 0?{}:{errorClass:e.errorClass},...t?{resultDiscarded:e.resultDiscarded===!0}:{}}}function Kn(e,t=ze(),n=Je()){if(zn(e,n),!t)return;let{tool:r,durationMs:o,isError:i,errorClass:a,errorMessage:s,aborted:c,resultDiscarded:u}=e;try{Jn(e,t),t.log(`webmcp ${r} ${c?"aborted":i?"error":"ok"}`,{tool_name:r,duration_ms:Math.round(o),is_error:i,error_class:a??"none",...c?{aborted:!0,result_discarded:u===!0}:{},...s===void 0||!me().analyticsProcessingAllowed?{}:{error_message:s}},i?"error":"info")}catch{}}function zn(e,t){if(t)try{t.produce(Gn(e))}catch{}}function Jn(e,t){let{tool:n,durationMs:r,isError:o,errorClass:i,aborted:a,resultDiscarded:s}=e,c={tool_name:n,is_error:o,error_class:i??"none"};a?t.counter("webmcp_tool_call_aborted_total",1,{tool_name:n,result_discarded:s===!0}):t.histogram("webmcp_tool_call_duration_ms",r,c,"ms"),t.counter("webmcp_tool_call_total",1,c),o&&t.counter("webmcp_tool_call_errors_total",1,{tool_name:n,error_class:i??"unknown"})}function Xn(e){return typeof e=="object"&&e!==null&&typeof Reflect.get(e,"then")=="function"}function Zn(e){return e instanceof Error&&typeof e.name=="string"&&e.name.length>0?e.name:"Error"}function er(e){return typeof e=="object"&&e!==null&&Reflect.get(e,"isError")===!0}var Ge=300;function Xe(e){return e.length>Ge?`${e.slice(0,Ge)}\u2026`:e}function tr(e){if(e instanceof Error&&typeof e.message=="string"&&e.message.length>0)return Xe(e.message)}function nr(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?Xe(n):void 0}function Ze(e,t,n=ze(),r=Je()){return(o,i)=>{let a=X(i),s=performance.now(),c=d=>{Kn({tool:e,durationMs:performance.now()-s,...d},n,r)},u=d=>c({isError:!1,errorClass:"aborted",aborted:!0,resultDiscarded:d}),l=d=>{if(a.aborted)throw u(!0),de(a);let x=er(d);return c({isError:x,errorClass:x?"tool_error":void 0,errorMessage:x?nr(d):void 0}),d},y=d=>{throw a.aborted||Z(d)?u(!1):c({isError:!0,errorClass:Zn(d),errorMessage:tr(d)}),d},_;try{_=t(o,i)}catch(d){return y(d)}return Xn(_)?_.then(l,y):l(_)}}var et={checkout:()=>F("/checkout"),accountOrders:()=>F("/account/orders"),product:e=>F(`/products/${e}`),collection:e=>F(`/collections/${e}`),search:e=>F(`/search?q=${encodeURIComponent(e)}`)};function F(e){let t=rr(),n=e.startsWith("/")?e.slice(1):e;return t+n}function L(e){let n=tt()?.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]?or(r[1]):""}function rr(){if(typeof window>"u")return"/";let t=tt()?.root;return typeof t!="string"?"/":t}function tt(){if(!(typeof window>"u"))return window.Shopify?.routes}function or(e){try{return decodeURIComponent(e)}catch{return""}}var ir={type:"object",properties:{amount:{type:"integer"},currency:{type:"string"}}},P={type:["object","null"],properties:ir.properties},it={type:"object",properties:{name:{type:"string"},values:{type:"array",items:{type:"string"}}}},W={type:"object",properties:{name:{type:"string"},value:{type:"string"}}},nt={type:"object",properties:{id:{type:"string",description:"Storefront API Product GID. Pass as catalog.id to get_product."},title:{type:"string"},handle:{type:"string",description:"Product handle. Can be passed to add_to_cart as line_items[].handle."},url:{type:"string"},price_range:P,image:{type:"string"},available:{type:"boolean"},variant_count:{type:"integer"},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:it},product_type:{type:"string"},vendor:{type:"string"}}},at={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. Pass to add_to_cart as line_items[].item.id to add this variant."},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:P}},ar={type:"object",properties:{id:{type:"string",description:"Cart line GID from get_cart. Pass back to update_cart_lines as line_items[].id to update or remove this line."},item:at,quantity:{type:"integer"},line_price:{...P,description:"Total price for the line (quantity \xD7 unit_price)."}}},rt={type:"object",properties:{item:at,quantity:{type:"integer",description:"Actual quantity on the cart line after the mutation. May differ from requested_quantity if the line merged with an existing entry or availability capped the add."},requested_quantity:{type:"integer",description:"Quantity the caller asked to add."}}},ot={type:"object",properties:{updated:{type:"boolean"},deduped:{type:"boolean",description:"True when this exact add was applied moments ago and was skipped to avoid a duplicate. When true, nothing changed on this call and updated is false."},item_count:{type:"integer"},total_price:P,line_items:{type:"array",description:"Items affected by this mutation, with product/variant details filled in from the post-mutation cart.",items:rt},unresolved_items:{type:"array"},resolved_items:{type:"array",description:"Present only on the clarification-needed path (nothing was applied). Items that could have been added, with pre-mutation lookup titles when available.",items:rt},warnings:{type:"array",items:{type:"string"}}}},st={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 add_to_cart for cart changes. If the user asks for a specific product variant, call get_product after search_catalog to inspect available variants, then show_variant to display one.",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:nt},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 add_to_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 then confirms the destination and instructs you not to navigate again \u2014 follow 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:nt},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 an add_to_cart call \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 add_to_cart for that. For a specific variant (color/size/etc.), use show_variant instead \u2014 it accepts partial option selections like "purple" without needing every option. With catalog.navigate=true this MOVES the browser to the product page; the tool result then confirms the destination and instructs you not to navigate again \u2014 follow 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:P,max:P}},available:{type:"boolean"},options:{type:"array",description:"All product option names and possible values. Use available_options to identify purchasable combinations.",items:it},variants:{type:"array",description:"Resolved variant records. When catalog.selected_options contains a complete option combination, this contains the matching variant. Pass an available variant id to add_to_cart as line_items[].item.id.",items:{type:"object",properties:{id:{type:"string",description:"Storefront API ProductVariant GID. Pass to show_variant as catalog.variant_id to display it, or add_to_cart as line_items[].item.id to add it."},title:{type:"string"},options:{type:"array",items:W},price:P,list_price:P,availability:{type:"object",properties:{available:{type:"boolean"}}},sku:{type:"string"}}}},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:W}},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:W},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 add_to_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 then confirms the destination and instructs you not to navigate again \u2014 follow 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:W}}}}},outputSchema:{type:"object",properties:{handle:{type:"string"},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:W}}}},getCart:{name:"get_cart",annotations:{readOnlyHint:!0,untrustedContentHint:!0},description:"Get the current shopping cart contents \u2014 line items with product titles, variant titles, handles, URLs, images, unit prices, quantities, and totals. Everything needed to describe the cart to the user in natural language, without a follow-up get_product call per line. Works from any page.",inputSchema:{type:"object",properties:{}},outputSchema:{type:"object",properties:{id:{type:"string",description:"Cart GID."},item_count:{type:"integer"},total_price:P,currency:{type:"string"},line_items:{type:"array",items:ar}}}},addToCart:{name:"add_to_cart",annotations:{readOnlyHint:!1,untrustedContentHint:!0},description:`Add products to the cart. Call this as soon as the user asks to ADD items (triggers: "add ... to my cart", "buy", "I'll take", "put ... in my basket") \u2014 in ONE call listing every item they named, up to the 10-entry limit. That request IS the authorization: do NOT ask the user to confirm before calling, and do NOT stop after search_catalog or get_product merely to report the variant you found \u2014 make the change, then tell the user it is done. Batch every item for ONE request into a SINGLE call \u2014 line_items accepts up to 10 entries; do NOT call add_to_cart once per item. Batching applies WITHIN a single request: each new thing the user asks for later is its own call. If one request names more than 10 items, split just that request into as few calls as possible. Do NOT retry a call that already returned a result: adds are cumulative, so repeating a call adds duplicate items. Use line_items[].item.id with a ProductVariant GID when the exact variant is known. Use handle or query only when adding the selected or first available variant. To change a quantity or remove something already in the cart, use update_cart_lines instead \u2014 this tool can only add.`,inputSchema:{type:"object",required:["cart"],properties:{cart:{type:"object",required:["line_items"],properties:{line_items:{type:"array",description:"Items to add (1-10).",minItems:1,maxItems:10,items:{type:"object",properties:{item:{type:"object",description:"The merchandise to add.",properties:{id:{type:"string",description:'ProductVariant GID from get_product variants[].id, e.g. "gid://shopify/ProductVariant/123".'}}},handle:{type:"string",description:"Product handle. Adds the selected or first available variant; call get_product first if the user requested specific options."},query:{type:"string",description:"Search query to find and add the selected or first available variant. For specific variants, call search_catalog/get_product first and pass item.id."},quantity:{type:"integer",description:"How many to add. Defaults to 1.",minimum:1,default:1}}}}}}}},outputSchema:ot},updateCartLines:{name:"update_cart_lines",annotations:{readOnlyHint:!1,untrustedContentHint:!0},description:"Change the quantity of items already in the cart, or remove them. Every change here addresses an existing cart line by its id, so call get_cart first unless you already have line_items[].id from an earlier get_cart in this conversation. Pass the ABSOLUTE target quantity, not a delta \u2014 quantity 2 means the line ends up at 2 regardless of what it was. Use quantity 0 to remove the line entirely. Batch every change for ONE request into a SINGLE call \u2014 line_items accepts up to 10 entries; do NOT call update_cart_lines once per line. Batching applies WITHIN a single request: each new thing the user asks for later is its own call. This tool cannot add new merchandise. To add something not already in the cart, use add_to_cart. To empty the whole cart at once, use cancel_cart.",inputSchema:{type:"object",required:["cart"],properties:{cart:{type:"object",required:["line_items"],properties:{line_items:{type:"array",description:"Existing cart lines to update or remove (1-10).",minItems:1,maxItems:10,items:{type:"object",required:["id","quantity"],properties:{id:{type:"string",description:"Existing cart line id from get_cart line_items[].id. Required \u2014 this tool cannot resolve products by name."},quantity:{type:"integer",description:"Absolute target quantity for this line (not a delta). 0 removes the line.",minimum:0}}}}}}}},outputSchema:ot},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 then confirms the destination and instructs you not to navigate again \u2014 follow it.",inputSchema:{type:"object",properties:{}},outputSchema:{type:"object",properties:{navigating_to:{type:"string"},item_count:{type:"integer"},total_price:P}}},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 then confirms the destination and instructs you not to navigate again \u2014 follow it.",inputSchema:{type:"object",properties:{}}},searchShopPoliciesAndFaqs:{name:"search_shop_policies_and_faqs",annotations:{readOnlyHint:!0,untrustedContentHint:!0},description:`Used to get facts about the store's policies, FAQ, or contact details. When the question is about specific policy kinds, set policy_types to those kinds; leave it unset for general FAQ questions. Some examples of questions you can ask are: - What is your return policy? (policy_types: ["refund"]) - What is your shipping policy? (policy_types: ["shipping"]) - What is your phone number? (policy_types: ["contact"]) - What are your hours of operation? (policy_types: ["contact"]) - Do you offer gift wrapping? (general FAQ, no specific policy kind \u2014 leave policy_types unset) `,inputSchema:{type:"object",properties:{query:{type:"string",description:"A natural language query. Searches FAQ pages and articles, and routes policies by keyword when policy_types is omitted."},policy_types:{type:"array",description:`Policy kinds to fetch, chosen from the user's question \u2014 e.g. ["refund"] for returns/exchanges, ["contact"] for phone/hours/address. Include every kind the question touches. Omit when no specific policy is relevant (e.g. a general FAQ question).`,items:{type:"string",enum:["refund","shipping","privacy","terms_of_service","terms_of_sale","subscription","legal_notice","contact"]}}},required:["query"]},outputSchema:{type:"object",properties:{policies:{type:"array",description:"Store policies and contact information matching the query.",items:{type:"object",properties:{type:{type:"string",description:"Policy kind: refund, shipping, privacy, terms_of_service, terms_of_sale, subscription, legal_notice, or contact."},title:{type:"string"},url:{type:"string"},body:{type:"string",description:"The policy text (may contain HTML)."}}}},pages:{type:"array",description:"Store pages (e.g. FAQ, help) matching the query.",items:{type:"object",properties:{title:{type:"string"},handle:{type:"string"},url:{type:"string"},body:{type:"string",description:"The page body (may contain HTML) for the top matched pages."}}}},articles:{type:"array",description:"Blog articles matching the query.",items:{type:"object",properties:{title:{type:"string"},handle:{type:"string"},url:{type:"string"},excerpt:{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 g=((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 ct="2026-04";function lt(e){return e?e.startsWith("v1_")?sr(e.replace(/^v1_/,"")):(typeof console<"u"&&console.warn(`[webmcp] Unsupported variant encoding: "${e}"`),[]):[]}function sr(e){let t=/[ :,-]/g,n={currentOptionValue:[],decodedOptions:[],depth:0,index:0,rangeStart:null},r;for(;r=t.exec(e);)cr(e,n,r,t);return dr(e,n),n.decodedOptions}function cr(e,t,n,r){let o=n[0],i=Number.parseInt(e.slice(t.index,n.index),10)||0;ut(t,i),t.currentOptionValue[t.depth]=i,o==="-"?t.rangeStart=i:o===":"?t.depth++:lr(e,t,n,o),t.index=r.lastIndex}function lr(e,t,n,r){ur(e,n,r)&&t.decodedOptions.push([...t.currentOptionValue]),r===","&&(t.currentOptionValue.pop(),t.depth--)}function ur(e,t,n){return n===" "||n===","&&e[t.index-1]!==","}function dr(e,t){let n=e.match(/\d+$/g)?.[0];if(n===void 0)return;let r=Number.parseInt(n,10);if(t.rangeStart!==null){ut(t,r+1);return}t.currentOptionValue[t.depth]=r,t.decodedOptions.push([...t.currentOptionValue])}function ut(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}},ft="This add has ALREADY been applied \u2014 the item_count and total in this result are the authoritative post-update cart state. Do NOT call add_to_cart again for these items: adds are cumulative, so repeating the call adds duplicates. If you need to confirm, read the values in this result instead of re-running the mutation. If the same request also asked you to change or remove a line already in the cart, continue with update_cart_lines.",yt="This change has ALREADY been applied \u2014 the item_count and total in this result are the authoritative post-update cart state, so read them from here rather than re-running the mutation. If the same request also asked you to add something that was not already in the cart, continue with add_to_cart.",gt="The cart has ALREADY been emptied \u2014 this result is the authoritative state. Do NOT call cancel_cart again for this request. If the shopper also asked for something to be added, continue with add_to_cart.",V=(e,t,n)=>{let r=n?` ${n}`:"";return{content:[{type:"text",text:`Suggested response: ${e}${r} Now respond to the user with a friendly message. If you completed multiple steps, recap the full journey.`}],structuredContent:t}},O=(e,t)=>{let{summary:n,navigated:r,destination:o,keyFields:i}=e,a=o?`the ${o} page`:"the requested page",u=`${r?`Navigation is complete: the browser is ALREADY on ${a} and the user is looking at it now.`:`The browser is ALREADY on ${a} and the user is looking at it now \u2014 no navigation was needed.`} Do NOT navigate again by ANY means for this request: not with another webmcp tool (browse_store, get_product navigate=true, show_variant, proceed_to_checkout, manage_orders), not with any host tool that changes the page URL / opens / loads / fetches a page (whatever its name), and not by constructing, guessing, or retyping a URL yourself. Do NOT tell the user to click a link or button or open a URL \u2014 they are already there. The destination is confirmed; just reply, referring to the page by name. Suggested reply: ${n}`;return i&&(u+=` ${i}`),{content:[{type:"text",text:u}],structuredContent:t}},p=(e,t)=>{let n=`Error: ${e}`;return t&&(n+=` Recovery: ${t}`),{content:[{type:"text",text:n}],structuredContent:{error:e},isError:!0}},f=(e,t,n,r)=>{if(t.aborted||Z(e))throw e;return p(e instanceof Error?e.message:n,r)},B=()=>{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},D=async(e,t=B())=>(await t.getCart(void 0,{signal:e})).cart??{},ne=e=>{Ne(e)},re=e=>{let t=e.userErrors?.map(n=>n.message).filter(Boolean);if(t?.length)throw new Error(t.join(", "))},oe=e=>e.warnings?.map(t=>t.message).filter(_e)??[],mt=e=>e.lines?.nodes??[],N=e=>e.totalQuantity??0,dt=new Map,ht=e=>{let t=String(e??"").toUpperCase();if(!t)return 2;let n=dt.get(t);if(n!=null)return n;try{let r=new Intl.NumberFormat("en",{style:"currency",currency:t}).resolvedOptions().maximumFractionDigits??2;return dt.set(t,r),r}catch{return 2}},h=e=>{if(e?.amount==null||!e.currencyCode)return null;let t=Number(e.amount);return Number.isFinite(t)?{amount:Math.round(t*10**ht(e.currencyCode)),currency:e.currencyCode}:null},S=e=>{if(!e)return"";let t=ht(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}`}},_e=e=>typeof e=="string"&&e.length>0,M=e=>{if(typeof window>"u")return!1;let t=new URL(window.location.href);return t.pathname+t.search===e},I=(e,t,n=0)=>{let{signal:r}=e;if(r.aborted)return;let o=setTimeout(()=>{r.aborted||e.navigate(t),i()},n),i=Ue(r,()=>clearTimeout(o))},pt="gid://shopify/ProductVariant/";function T(e){if(e===void 0)return"";let t=String(e).trim(),n=t.startsWith(pt)?t.slice(pt.length):t;return/^\d+$/.test(n)?n:""}var pr=`/api/${ct}/graphql.json`,Se=30,fr=50,bt=50,yr="gid://shopify/Product/",ve=g("fragment WebMcpMoney on MoneyV2{amount currencyCode}"),Te=g("fragment WebMcpProductCard on Product{id title handle vendor productType availableForSale onlineStoreUrl featuredImage{url altText}priceRange{minVariantPrice{...WebMcpMoney}}variantsCount{count}options{name optionValues{name}}}",[ve]),Tt=g("fragment WebMcpProductForCart on Product{title handle selectedOrFirstAvailableVariant{id title availableForSale}}"),gr=g("fragment WebMcpCartDetails on Cart{id totalQuantity cost{totalAmount{...WebMcpMoney}}lines(first:250){nodes{id quantity cost{totalAmount{...WebMcpMoney}}merchandise{__typename ...on ProductVariant{id title image{url altText}price{...WebMcpMoney}product{id title handle onlineStoreUrl}}}}}}",[ve]),mr=g("fragment WebMcpProductVariant on ProductVariant{id title availableForSale sku price{...WebMcpMoney}compareAtPrice{...WebMcpMoney}selectedOptions{name value}}",[ve]),Ct=g("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}}}",[mr]),hr=g("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}}}",[Te]),br=g("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}}}"),_r=3,Sr=g("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}}"),vr=g("query WebMcpListCollections($first:Int!){collections(first:$first){nodes{title handle description onlineStoreUrl}}}"),Tr=g("query WebMcpBrowseProducts($first:Int!$sortKey:ProductSortKeys$reverse:Boolean!){products(first:$first sortKey:$sortKey reverse:$reverse){nodes{...WebMcpProductCard}}}",[Te]),Cr=g("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}}}}",[Te]),wr=g("query WebMcpProductByHandle($handle:String!$selectedOptions:[SelectedOptionInput!]!$hasSelectedOptions:Boolean!){product(handle:$handle){...WebMcpProductDetails variantBySelectedOptions(selectedOptions:$selectedOptions caseInsensitiveMatch:true)@include(if:$hasSelectedOptions){...WebMcpProductVariant}}}",[Ct]),Ar=g("query WebMcpProductById($id:ID!$selectedOptions:[SelectedOptionInput!]!$hasSelectedOptions:Boolean!){node(id:$id){__typename ...on Product{...WebMcpProductDetails variantBySelectedOptions(selectedOptions:$selectedOptions caseInsensitiveMatch:true)@include(if:$hasSelectedOptions){...WebMcpProductVariant}}}}",[Ct]),Rr=g("query WebMcpProductForCartByHandle($handle:String!){product(handle:$handle){...WebMcpProductForCart}}",[Tt]),Er=g("query WebMcpCartDetails($id:ID!){cart(id:$id){...WebMcpCartDetails}}",[gr]),Pr=g("query WebMcpSearchProductForCart($query:String!){predictiveSearch(query:$query types:[PRODUCT]limit:1){products{...WebMcpProductForCart}}}",[Tt]);async function wt(e,t,n){let r=await A(hr,{query:e,types:["PRODUCT","COLLECTION","ARTICLE","PAGE"],limit:t},n);return{predictiveSearch:Lr(r.predictiveSearch)}}var At=[{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"}],Ce=At.map(e=>e.type);async function Rt(e,t,n,r){let o=new Set(n),i=await A(br,{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(Re),s=(i.predictiveSearch?.articles??[]).map(Ae);return{policies:Or(i.shop),articles:s,pages:await Mr(a,r)}}function Or(e){return e?At.flatMap(({type:t,field:n})=>{let r=e[n];return r?[{type:t,title:r.title??"",url:r.url??"",body:r.body??""}]:[]}):[]}async function Mr(e,t){let n=e.filter(s=>s.handle).slice(0,_r);if(!n.length)return e;let r=n.map(s=>s.handle),o=await A(Sr,{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((s,c)=>{let u=i[c]?.body;u&&a.set(s.handle,u)}),e.map(s=>{let c=a.get(s.handle);return c?{...s,body:c}:s})}async function Et(e){return{collections:{nodes:(await A(vr,{first:fr},e)).collections?.nodes?.map(we)??[]}}}async function Pt(e){let t=await A(Tr,{first:It(e.page),...Ir(e.sortBy)},e.signal);return{products:xt(t.products?.nodes??[],e.page).map(j),title:"All products"}}async function Ot(e){let t=e.handle.trim(),n=await A(Cr,{handle:t,first:It(e.page),...xr(e.sortBy)},e.signal),r=n.collection?we(n.collection):null;return{collection:r,products:xt(n.collection?.products?.nodes??[],e.page).map(j),title:r?.title??t}}async function H(e,t){let n=Ee(e);if(!n)return null;let r=Lt(t.selected_options),o=r.length>0;if(Xr(n)){let s=(await A(Ar,{id:n,selectedOptions:r,hasSelectedOptions:o},t.signal)).node;return s?.__typename==="Product"?vt(j(s),t):null}let i=await A(wr,{handle:n,selectedOptions:r,hasSelectedOptions:o},t.signal);return i.product?vt(j(i.product),t):null}async function Q(e,t,n){let r=e.trim();if(!r)return null;let i=(await A(Er,{id:r},n)).cart;return i?{id:i.id??r,item_count:i.totalQuantity??0,total_price:h(i.cost?.totalAmount),currency:i.cost?.totalAmount?.currencyCode??"",line_items:(i.lines?.nodes??[]).map(a=>Dr(a,t))}:null}async function Mt(e){if(e.handle?.trim()){let t=await A(Rr,{handle:e.handle.trim()},e.signal);return t.product?_t(t.product):null}if(e.query?.trim()){let n=(await A(Pr,{query:e.query.trim()},e.signal)).predictiveSearch?.products?.[0];return n?_t(n):null}return null}async function A(e,t,n){let r=await fetch(pr,{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 It(e){return Math.min(Math.max(1,e)*Se,250)}function xt(e,t){let n=(Math.max(1,t)-1)*Se;return e.slice(n,n+Se)}function Ir(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 xr(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 Lr(e){return{products:(e?.products??[]).map(j),collections:(e?.collections??[]).map(we),articles:(e?.articles??[]).map(Br),pages:(e?.pages??[]).map(jr)}}function j(e){let t=e.selectedOrFirstAvailableVariant?St(e.selectedOrFirstAvailableVariant):null,n=e.variantBySelectedOptions?St(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:qr(e.options),images:Wr(e.images?.nodes)}}function Dr(e,t){return{id:e.id??"",quantity:e.quantity??0,line_price:h(e.cost?.totalAmount),item:Nr(e,t)}}function Nr(e,t){let n=Ur(e),r=n.product;return{id:n.id,title:r.title,variant_title:n.title,handle:r.handle,url:kr({handle:r.handle,onlineStoreUrl:r.onlineStoreUrl},n.id,t),image:n.image,unit_price:h(n.price)}}function Ur(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:$r(n?.product)}}function $r(e){return{id:e?.id??"",title:e?.title??"",handle:e?.handle??"",onlineStoreUrl:e?.onlineStoreUrl}}function kr(e,t,n){let r=G(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 _t(e){let t=e.selectedOrFirstAvailableVariant;return!t?.id||!t.availableForSale?null:{product:{title:e.title,handle:e.handle},variant:{merchandise_id:t.id,title:t.title}}}function qr(e){return e?.map(t=>({name:t.name??"",values:t.optionValues?.map(n=>n.name)??[]}))??[]}function Fr(e){return e?.map(t=>({name:t.name??"",value:t.value??""}))??[]}function Wr(e){return e?.filter(Vr)??[]}function St(e){return{id:e.id??"",title:e.title??"",availableForSale:!!e.availableForSale,price:e.price,compareAtPrice:e.compareAtPrice,sku:e.sku,selectedOptions:Fr(e.selectedOptions)}}function Vr(e){return e!=null}function we(e){return{title:e.title,handle:e.handle,description:e.description,onlineStoreUrl:e.onlineStoreUrl}}function Br(e){return{title:e.title,handle:e.handle,excerpt:e.excerpt,onlineStoreUrl:e.onlineStoreUrl}}function jr(e){return{title:e.title,handle:e.handle,onlineStoreUrl:e.onlineStoreUrl}}function Y(e,t){let n=Zr(e);return{id:e.id??"",title:e.title??"",handle:n,url:Hr(e,n,t),price_range:h(e.priceRange?.minVariantPrice),image:Nt(e.featuredImage),available:!!e.availableForSale,variant_count:e.variantCount??0,options:e.options??[],product_type:e.productType??"",vendor:e.vendor??""}}function Hr(e,t,n){return G({handle:t,onlineStoreUrl:e.onlineStoreUrl},r=>n.product(r))}function vt(e,t){let n=Y(e,t.routes),r=e.options??[],o=Lt(t.selected_options),i=Yr(r,e,o),a=Qr(e,o);return{...n,description:{html:e.descriptionHtml??""},type:e.productType??"",tags:e.tags??[],price_range:{min:h(e.priceRange?.minVariantPrice),max:h(e.priceRange?.maxVariantPrice)},variants:a.map(Jr),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(Nt).filter(_e)??[]}}function Qr(e,t){return t.length?e.variantBySelectedOptions?[e.variantBySelectedOptions]:[]:e.selectedOrFirstAvailableVariant?[e.selectedOrFirstAvailableVariant]:[]}function Yr(e,t,n){let r=lt(t.encodedVariantAvailability),o=[];for(let s of r){let c=Gr(e,s);c&&Kr(c,n)&&o.push(c)}let a=n.length>0||o.length<=bt?o.slice(0,bt):[];return{options:a,count:o.length,truncated:o.length>a.length}}function Gr(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 Kr(e,t){return t.every(n=>e.some(r=>zr(r,n)))}function zr(e,t){return ie(e.name)===ie(t.name)&&ie(e.value)===ie(t.value)}function Lt(e){return e?.map(t=>({name:t.name?.trim()??"",value:t.value?.trim()??""})).filter(t=>t.name&&t.value)??[]}function ie(e){return e?.trim().toLowerCase()??""}function Jr(e){return{id:e.id??"",title:e.title??"",options:e.selectedOptions??[],price:h(e.price),list_price:h(e.compareAtPrice),availability:{available:!!e.availableForSale},sku:e.sku??void 0}}function ae(e,t){let n=e.handle??"";return{title:e.title??"",handle:n,url:G(e,r=>t.collection(r)),description:e.description??""}}function Ae(e){return{title:e.title??"",handle:e.handle??"",url:G(e),excerpt:e.excerpt??""}}function Re(e){return{title:e.title??"",handle:e.handle??"",url:G(e)}}function G(e,t){let n=Dt(e.onlineStoreUrl);if(n)return n;let r=e.handle?.trim();return r?t?.(r)??"":""}function Ee(e){let t=e?.trim();return t?L(t)||t:""}function Xr(e){return e.startsWith(yr)}function Zr(e){return e.handle??L(Dt(e.onlineStoreUrl))}function Dt(e){if(!e)return"";if(e.startsWith("/"))return e;try{let t=new URL(e);return e.replace(t.origin,"")}catch{return e}}function Nt(e){return e?.url??""}var eo=new Set(["best-selling","price-ascending","price-descending","title-ascending","title-descending","created-ascending","created-descending"]),$t=async(e,t)=>{try{let n=e.collection?.trim(),r=e.navigate===!0;if(!n)return no(await Et(t.signal),t.routes,r);let o=Math.max(1,Number(e.page)||1),i=oo(e.sort_by),a=await to(n,i,o,t.signal);return ro(n,a,i,o,t,r)}catch(n){return f(n,t.signal,"Failed to browse store","Try browsing without a collection to list available collections.")}};async function to(e,t,n,r){return e==="all"?Pt({page:n,sortBy:t,signal:r}):Ot({handle:e,page:n,sortBy:t,signal:r})}function no(e,t,n){let r=e.collections?.nodes?.map(i=>ae(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 m(`Found ${r.length} collection${r.length!==1?"s":""}.`,{collections:r,products:[],navigated:!1},io(r),o)}function ro(e,t,n,r,o,i){let{routes:a}=o;if(e!=="all"&&!t.collection)return p(`Collection "${e}" was not found.`,"Call browse_store without a collection to list available collections.");let s=t.products.map(l=>Y(l,a)),c=a.collection(e),u={collections:[],products:s,collection_title:t.title,page:r,sort_by:n,url:c};if(i){let l=!M(c);return l&&I(o,c),O({summary:l?`Showing the ${t.title} collection.`:`Already showing the ${t.title} collection.`,navigated:l,destination:`${t.title} collection`,keyFields:Ut(s)},{...u,navigated:l})}return m(`Showing ${s.length} product${s.length!==1?"s":""} from ${t.title}.`,{...u,navigated:!1},Ut(s),"If the user asked to be taken to this collection, call browse_store again with navigate=true. If the user wants the selected or first available variant, call add_to_cart with cart.line_items using the product handle. 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 with add_to_cart, OR call show_variant with selected_options to just navigate to that variant.")}function oo(e){return e&&eo.has(e)?e:"best-selling"}function io(e){return e.length?`Collections: ${e.map(t=>`- ${t.title} (${t.handle})`).join(` `)}`:null}function Ut(e){return e.length?`Products: ${e.map(t=>`- ${t.title} (id: ${t.id}, handle: ${t.handle}) - ${S(t.price_range)||"price unavailable"}`).join(` `)}`:null}var kt=10,qt=async(e,t)=>{let n=e.cart?.line_items;if(!Array.isArray(n)||n.length===0)return p("No line_items provided.","Call add_to_cart with cart.line_items.");let r=n.slice(0,kt);try{let o=await Promise.all(r.map((a,s)=>so(a??{},s,t.signal))),i=o.filter(jt);return i.length?Vt(i,o,r.length):await Wt(o.filter(Ht),t,ft)}catch(o){return f(o,t.signal,"Cart update failed","Call get_cart to verify cart state, then retry add_to_cart with an explicit line_items[].item.id.")}},Ft=async(e,t)=>{let n=e.cart?.line_items;if(!Array.isArray(n)||n.length===0)return p("No line_items provided.","Call get_cart, then call update_cart_lines with cart.line_items[].id and the target quantity.");let r=n.slice(0,kt),o=r.map((a,s)=>ao(a??{},s)),i=o.filter(jt);if(i.length)return Vt(i,o,r.length);try{return await Wt(o.filter(Ht),t,yt)}catch(a){return f(a,t.signal,"Cart update failed","Call get_cart to verify cart state, then retry update_cart_lines with the current line_items[].id.")}};async function Wt(e,t,n){let r=e.filter(se),o=await Co(r,t),i=new Set(o.map(({add:v})=>T(v.merchandiseId))),a=e.filter(v=>!(v.type==="add"&&i.has(T(v.merchandiseId))));if(k("decision",{requested:e.length,skippedAsDuplicate:o.length,willWrite:a.length}),a.length===0)return Ao(o);ne(t.signal);let c=await B().updateCart({lines:a.map(v=>v.type==="update"?{id:v.id,quantity:v.quantity}:{merchandiseId:v.merchandiseId,quantity:v.quantity})});re(c);let u=a.filter(se);u.length?vo(u):Me();let l=oe(c),y=c.cart??{},_=h(y.cost?.totalAmount),d=await fo(u,y.id,t),x=V([yo(a,N(y),_,l),Ro(o)].filter(Boolean).join(" "),{updated:!0,...o.length?{deduped:!0}:{},item_count:N(y),total_price:_,line_items:d,warnings:l.length?l:void 0},n);return u.length&&!t.signal.aborted&&To(u),x}function ao(e,t){if(!e.id)return{type:"unresolved",item:t+1,kind:"needs-cart-line",reason:"update_cart_lines needs the cart line's id. Call get_cart and pass line_items[].id, or use add_to_cart if this item is not in the cart yet."};let n=Oe(e.quantity);return n===null?{type:"unresolved",item:t+1,kind:"needs-cart-line",reason:`line_items[${t}] is missing a readable quantity. update_cart_lines needs the ABSOLUTE target quantity for the line (0 removes it); it cannot assume one.`}:n<0?{type:"unresolved",item:t+1,kind:"needs-cart-line",reason:`line_items[${t}] has a negative quantity (${n}). update_cart_lines takes the ABSOLUTE target quantity, not a delta \u2014 pass the quantity the line should end up at, or 0 to remove it.`}:{type:"update",id:e.id,quantity:n}}async function so(e,t,n){let r=lo(e.quantity),o=co(e);if(o)return{type:"unresolved",item:t+1,kind:"needs-cart-line",reason:`line_items[${t}] has a cart line id ("${o}"), so it is already in the cart. add_to_cart only adds new merchandise \u2014 call update_cart_lines with that id to change its quantity or remove it.`,query:e.query,handle:e.handle};if(uo(e.quantity))return{type:"unresolved",item:t+1,kind:"needs-cart-line",reason:"add_to_cart can only add. To remove an item or set its quantity to 0, call get_cart for the line id and then update_cart_lines.",query:e.query,handle:e.handle};if(e.item?.id)return{type:"add",merchandiseId:e.item.id,quantity:r};let i=await Mt({handle:e.handle,query:e.query,signal:n});return i?{type:"add",merchandiseId:i.variant.merchandise_id,quantity:r,productTitle:i.product.title,variantTitle:i.variant.title}:{type:"unresolved",item:t+1,kind:"lookup-failed",reason:e.handle?`Could not resolve product handle "${e.handle}".`:e.query?`Could not find a product for query "${e.query}".`:"Missing item.id, handle, or query.",query:e.query,handle:e.handle}}function co(e){let t=e.id;return typeof t=="string"&&t.trim()!==""?t:void 0}function Oe(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 lo(e){let t=Oe(e);return t===null?1:Math.max(1,t)}function uo(e){let t=Oe(e);return t!==null&&t<=0}function Vt(e,t,n){let r=t.filter(se),o=e.map(i=>`- Item ${i.item}: ${i.reason}`).join(` `);return m(`Need clarification for ${e.length} of ${n} line_item${n===1?"":"s"}. Nothing changed.`,{updated:!1,unresolved_items:e,resolved_items:r.map(Bt)},o,po(e))}function po(e){let t=[];return e.some(({kind:n})=>n==="lookup-failed")&&t.push("NOTHING was added \u2014 not even the line items that resolved. Resolve the problem above (search_catalog or get_product for an explicit product or variant id), then call add_to_cart again with the COMPLETE set of line items for this request, including the ones listed as resolved: re-sending only the failed one would drop the rest. For specific variant requests prefer line_items[].item.id from get_product variants[].id."),e.some(({kind:n})=>n==="needs-cart-line")&&t.push("To change or remove something already in the cart, call get_cart and pass that line's line_items[].id to update_cart_lines with the ABSOLUTE target quantity (0 removes the line). A handle or query can never remove or reduce a line."),t.join(" ")}async function fo(e,t,n){let r=e.map(Bt);if(!t||e.length===0)return r;let o;try{o=await Q(t,n.routes,n.signal)}catch{return r}if(!o)return r;let i=new Map;for(let a of o.line_items){let s=T(a.item.id);s&&i.set(s,a)}return e.map((a,s)=>{let c=i.get(T(a.merchandiseId));return c?{item:c.item,quantity:c.quantity,requested_quantity:a.quantity}:r[s]})}function Bt(e){return{item:{id:e.merchandiseId,title:e.productTitle??"",variant_title:e.variantTitle??"",handle:"",url:"",image:"",unit_price:null},quantity:e.quantity,requested_quantity:e.quantity}}function yo(e,t,n,r){let o=e.filter(se),i=e.filter(go),a=o.reduce((l,y)=>l+y.quantity,0),s=[];o.length&&s.push(`Added ${a} item${a===1?"":"s"} across ${o.length} product${o.length===1?"":"s"}`),i.length&&s.push(`updated ${i.length} line${i.length===1?"":"s"}`);let c=`Cart now has ${t} item${t===1?"":"s"}${n?` totaling ${S(n)}`:""}.`,u=r.length?` Warnings: ${r.join("; ")}.`:"";return`${s.join(" and ")}. ${c}${u}`}function jt(e){return e.type==="unresolved"}function Ht(e){return e.type==="add"||e.type==="update"}function se(e){return e.type==="add"}function go(e){return e.type==="update"}var mo=6e4,Qt="shopify.webmcp.recentAdds",Pe=new Map;function ho(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.merchandiseId=="string"&&typeof t.quantity=="number"&&typeof t.at=="number"&&typeof t.confirmed=="boolean"}function K(){let e=bo();return e&&e.size>0?e:new Map(Pe)}function bo(){try{let e=window.sessionStorage.getItem(Qt);if(!e)return;let t=JSON.parse(e);if(typeof t!="object"||t===null)return;let n=new Map;for(let[r,o]of Object.entries(t)){if(!ho(o))continue;let i=T(r);i&&n.set(i,o)}return n}catch{return}}function z(e){Pe.clear();for(let[t,n]of e)Pe.set(t,n);try{window.sessionStorage.setItem(Qt,JSON.stringify(Object.fromEntries(e)))}catch{}}function Me(){z(new Map)}function _o(e){let t=K(),n=t.get(e);if(n){if(Date.now()-n.at>=mo){t.delete(e),z(t);return}return n}}function So(e){let t=K();t.delete(e)&&z(t)}function vo(e){let t=K(),n=Date.now();for(let r of e)t.set(T(r.merchandiseId),{merchandiseId:r.merchandiseId,quantity:r.quantity,at:n,confirmed:!1});z(t),k("remember",{merchandiseIds:e.map(r=>r.merchandiseId)})}function To(e){let t=K(),n=!1;for(let r of e){let o=t.get(T(r.merchandiseId));o&&(o.confirmed=!0,n=!0)}n&&z(t)}function k(e,t){try{if(typeof window>"u"||!Reflect.get(window,"__WEBMCP_CART_DEBUG__"))return;console.warn(`[webmcp:cart-guard] ${e}`,t)}catch{}}async function Co(e,t){let n=e.flatMap(o=>{let i=_o(T(o.merchandiseId));return i?[{add:o,remembered:i}]:[]});if(k("requested",{requested:e.map(o=>o.merchandiseId),remembered:[...K().keys()],suspected:n.map(({add:o})=>o.merchandiseId)}),n.length===0)return[];let r=await wo(t);return k("cart-lookup",{conclusive:r!==void 0,merchandiseInCart:r?[...r.keys()]:null}),r?n.flatMap(({add:o,remembered:i})=>{let a=r.get(T(o.merchandiseId));return a?(k("duplicate",{merchandiseId:o.merchandiseId,cartLineId:a.cartLineId}),[{add:o,remembered:i,cartLineId:a.cartLineId,cartQuantity:a.quantity}]):(k("released",{merchandiseId:o.merchandiseId,reason:"positively absent from a conclusive cart lookup"}),So(T(o.merchandiseId)),[])}):n.map(({add:o,remembered:i})=>({add:o,remembered:i,cartLineId:void 0,cartQuantity:i.quantity}))}async function wo(e){try{let t=await D(e.signal);if(!t.id)return;let n=await Q(t.id,e.routes,e.signal);if(!n)return;let r=new Map,o=0;for(let i of n.line_items){let a=T(i.item.id);if(!a){o+=1;continue}let s=r.get(a);r.set(a,s?{cartLineId:void 0,quantity:s.quantity+i.quantity}:{cartLineId:i.id,quantity:i.quantity})}return o>0||r.size===0&&N(t)>0?void 0:r}catch{return}}function Ao(e){let n=e.some(({remembered:r})=>!r.confirmed)?"These items are ALREADY in the cart. The earlier add_to_cart call was cancelled, but the cart update had already been applied before the cancellation, so it was never reported back. I did not add them again (that would duplicate them).":"An identical add was just applied \u2014 the cart already includes these items, so I did not add them again (this prevents accidental duplicates).";return m(n,{updated:!1,deduped:!0},Yt(e)||null,`Call get_cart if you need the authoritative post-update cart contents. ${Gt(e)} Otherwise do NOT repeat this call \u2014 the previous update already succeeded.`)}function Ro(e){return e.length===0?"":`Skipped ${e.length} line item${e.length===1?"":"s"} already added to this cart, to avoid duplicating ${e.length===1?"it":"them"}: ${Yt(e)} ${Gt(e)}`}function Yt(e){return e.map(({add:t,cartLineId:n,cartQuantity:r})=>{let o=t.productTitle?`${t.productTitle}${t.variantTitle?` (${t.variantTitle})`:""}`:t.merchandiseId,i=n?`, cart line id ${n}`:"";return`- ${o}: already in the cart with quantity ${r}${i}`}).join(` `)}function Gt(e){return e.every(({cartLineId:n})=>n)?"If the shopper truly wants MORE of the same item, call update_cart_lines with the cart line id above and the ABSOLUTE total quantity they want (not the number to add).":"If the shopper truly wants MORE of the same item, call get_cart and set that line's ABSOLUTE total quantity with update_cart_lines."}var Kt=async(e,t)=>{try{let n=B(),r=await D(t.signal,n),o=N(r);if(o===0)return V("Cart is already empty.",{cleared:!0,previous_item_count:0});let i=mt(r).filter(u=>u.id).map(u=>({id:u.id,quantity:0}));ne(t.signal);let a=await n.updateCart({lines:i});re(a),Me();let s=oe(a),c=s.length?` Warnings: ${s.join("; ")}.`:"";return V(`Cart cleared. Removed ${o} item${o!==1?"s":""}.${c}`,{cleared:!0,previous_item_count:o,...s.length&&{warnings:s}},gt)}catch(n){return f(n,t.signal,"Failed to clear cart","Try update_cart_lines with each line_items[].id and quantity 0 to remove items individually.")}};var zt=async(e,t)=>{try{let n=await D(t.signal),r=N(n);if(r===0)return p("Cart is empty. Add items before checking out.","Use search_catalog or add_to_cart to add products first.");let o=h(n.cost?.totalAmount),i=t.routes.checkout(),a=!M(i);a&&I(t,i);let s=o?` totaling ${S(o)}`:"",c=a?`Taken you to checkout with ${r} item${r!==1?"s":""}${s}.`:`Already on the checkout page with ${r} item${r!==1?"s":""}${s}.`;return O({summary:c,navigated:a,destination:"checkout"},{navigating_to:i,item_count:r,total_price:o})}catch(n){return f(n,t.signal,"Failed to initiate checkout","Call get_cart to verify cart contents, then retry.")}};var Xt=async(e,t)=>{try{let n=await D(t.signal);if((n.totalQuantity??0)===0||!n.id)return Eo(n);let o=await Q(n.id,t.routes,t.signal);return Jt(o||Io(n,t.routes))}catch(n){return f(n,t.signal,"Failed to fetch cart","Try again - this is usually a transient error.")}},Eo=e=>{let t={id:e.id??"",item_count:0,total_price:h(e.cost?.totalAmount),currency:e.cost?.totalAmount?.currencyCode??"",line_items:[]};return m("Cart is empty.",t,null,"Use search_catalog or browse_store to help the user find products to add. Then call add_to_cart with cart.line_items.")},Jt=e=>m(Po(e),e,Oo(e.line_items),"To modify quantities, call update_cart_lines with the line_items[].id from this response and the new quantity. To remove an item, call update_cart_lines with quantity 0. To proceed, use proceed_to_checkout."),Po=e=>{let t=e.line_items.slice(0,3).map(Zt).join(", "),n=e.line_items.length>3?` and ${e.line_items.length-3} more`:"",r=e.item_count===1?"":"s",o=S(e.total_price)||"unknown total";return`Cart has ${e.item_count} item${r} totaling ${o}: ${t}${n}.`},Oo=e=>`Cart line items: `+e.map(Mo).join(` `),Mo=e=>{let t=S(e.line_price)||"price unavailable";return`- ${e.id}: "${Zt(e)}" - ${t}`},Zt=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 Io(e,t){return{id:e.id??"",item_count:e.totalQuantity??0,total_price:h(e.cost?.totalAmount),currency:e.cost?.totalAmount?.currencyCode??"",line_items:(e.lines?.nodes??[]).map(n=>({id:n.id??"",quantity:n.quantity??0,line_price:h(n.cost?.totalAmount),item:{id:"",title:"",variant_title:"",handle:"",url:"",image:"",unit_price:null}}))}}var en=async(e,t)=>{let n=e.catalog,r=Ee(n?.id)||Uo();if(!r)return p("Product catalog.id is required.","Call search_catalog or browse_store to find a product id or handle first.");try{return await xo(r,n,t)}catch(o){return f(o,t.signal,"Failed to load product details","Try again with a product id or handle from search_catalog or browse_store.")}};async function xo(e,t,n){let r=t?.selected_options,o=r?.length?[...r]:void 0,i=await H(e,{selected_options:o,routes:n.routes,signal:n.signal});return i?t?.navigate===!0?Do(i,n):No(i,!!o?.length):Lo(e)}function Lo(e){return p(`Product "${e}" was not found.`,"Call search_catalog or browse_store to find an available product.")}function Do(e,t){let n=e.url,r=!M(n);return r&&I(t,n),O({summary:r?`Showing ${e.title}.`:`Already showing ${e.title}.`,navigated:r,destination:e.title},e)}function No(e,t){return m(`${e.title} has ${e.variant_count} variant${e.variant_count!==1?"s":""}.`,e,$o(e),ko(e,t))}function Uo(){return typeof window>"u"?"":L(window.location.href)}function $o(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(s=>`${s.name}: ${s.value}`).join(", "),i=S(r.price)||"price unavailable",a=r.availability.available?"available":"unavailable";return`- ${r.title} (id: ${r.id}) - ${o||"no options"} - ${i} - ${a}`}).join(` `)}function ko(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: use the matching variants[].id from this result with add_to_cart line_items[].item.id.`;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, use variants[0].id or the product handle with add_to_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 qo="/.well-known/ucp",tn=async(e,t)=>{try{let n=await fetch(qo,{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=Fo(r);if(!o)throw new Error("UCP profile response did not include a ucp object.");return m(Wo(o),{ucp:o},Vo(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 f(n,t.signal,"Failed to fetch UCP profile","Try again - this is usually a transient error.")}};function Fo(e){return!ce(e)||!ce(e.ucp)?null:e.ucp}function Wo(e){let t=typeof e.version=="string"?` (version ${e.version})`:"",n=Object.keys(Ie(e.services)),r=Object.keys(Ie(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 Vo(e){let t=Object.entries(Ie(e.services)).flatMap(([n,r])=>Bo(r).filter(o=>o.endpoint).map(o=>`- ${n} (${o.transport??"unknown"}): ${o.endpoint}`));return t.length?`UCP service endpoints: ${t.join(` `)}`:null}function Bo(e){return Array.isArray(e)?e.filter(ce).map(t=>({transport:typeof t.transport=="string"?t.transport:void 0,endpoint:typeof t.endpoint=="string"?t.endpoint:void 0})):[]}function Ie(e){return ce(e)?e:{}}function ce(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var nn=(e,t)=>{let n=t.routes.accountOrders(),r=!M(n);return r&&I(t,n,10),O({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 rn=async(e,t)=>{let n=e.catalog?.query?.trim();if(!n)return p("Search query is required.","Call search_catalog with catalog.query.");try{let r=zo(Number(e.catalog?.pagination?.limit)||5,1,10),o=await wt(n,r,t.signal);return Ho(n,jo(o.predictiveSearch,t.routes),t.routes)}catch(r){return f(r,t.signal,"Search failed","Try again with a simpler catalog.query, or use browse_store to inspect collections.")}};function jo(e,t){return{products:e.products.map(n=>Y(n,t)),collections:e.collections.map(n=>ae(n,t)),articles:e.articles.map(Ae),pages:e.pages.map(Re)}}function Ho(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?m(`No search results found for "${e}".`,o,null,"Try browse_store to inspect collections or search_catalog with a broader catalog.query."):m(`Found ${Qo(t).join(", ")} for "${e}".`,o,Go(t),Yo(t))}function Qo(e){return[le("product",e.products.length),le("collection",e.collections.length),le("article",e.articles.length),le("page",e.pages.length)].filter(Boolean)}function le(e,t){return t?`${t} ${e}${t===1?"":"s"}`:""}function Yo(e){return e.products.length?"If the user wants the selected or first available variant, call add_to_cart with cart.line_items using the product handle or query. 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 with add_to_cart.":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 Go(e){let t=[Ko(e.products),xe("Collections",e.collections),xe("Articles",e.articles),xe("Pages",e.pages)].filter(Boolean);return t.length?t.join(` `):null}function Ko(e){return e.length?`Products: `+e.map(t=>`- ${t.title} (id: ${t.id}, handle: ${t.handle}) - ${S(t.price_range)||"price unavailable"}`).join(` `):null}function xe(e,t){return t.length?`${e}: `+t.map(n=>`- ${n.title}${n.handle?` (${n.handle})`:""}: ${n.url}`).join(` `):null}function zo(e,t,n){return Math.min(n,Math.max(t,e))}var Jo=5,Xo=[{type:"refund",patterns:[/\brefund/i,/\breturn/i,/\bmoney\s+back/i,/\bexchange/i,/\breimburse/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]}],on=async(e,t)=>{let n=e.query?.trim();if(!n)return p("A search query is required.","Call search_shop_policies_and_faqs with a query, e.g. 'return policy' or 'shipping'.");try{let r=Zo(e.policy_types,n),o=await Rt(n,Jo,r,t.signal);return ti(n,o.policies,o.articles,o.pages)}catch(r){return f(r,t.signal,"Policy and FAQ search failed","Rephrase the query (e.g. 'return policy', 'shipping', 'contact') and try again.")}};function Zo(e,t){let n=new Set(Ce),o=(Array.isArray(e)?e:[]).filter(i=>typeof i=="string"&&n.has(i));return o.length?o:ei(t)}function ei(e){let t=Xo.flatMap(({type:n,patterns:r})=>r.some(o=>o.test(e))?[n]:[]);return t.length?t:/\bpolic(?:y|ies)\b/i.test(e)?[...Ce]:[]}function ti(e,t,n,r){let o={policies:t,articles:n,pages:r};return t.length+n.length+r.length===0?m(`No policies or FAQ content found for "${e}".`,o,null,"The store may not have published this content. Ask the user to rephrase, or share the store's contact page if one exists."):m(ni(e,t,n,r),o,ri(t,n,r),oi(t,n,r))}function ni(e,t,n,r){return`Found ${[t.length?`${t.length} polic${t.length===1?"y":"ies"}`:null,r.length?`${r.length} page${r.length===1?"":"s"}`:null,n.length?`${n.length} article${n.length===1?"":"s"}`:null].filter(Boolean).join(", ")||"no results"} for "${e}".`}function ri(e,t,n){let r=[e.length?`Policies: `+e.map(o=>`- ${o.title}: ${o.url}`).join(` `):null,n.length?`Pages: `+n.map(o=>`- ${o.title}: ${o.url}`).join(` `):null,t.length?`Articles: `+t.map(o=>`- ${o.title}: ${o.url}`).join(` `):null].filter(Boolean);return r.length?r.join(` `):null}function oi(e,t,n){return e.length?"Answer the user's question directly from the policy body text in the structured content. The body is the authoritative policy text \u2014 do not invent details that are not present.":n.length||t.length?"The store has no matching policy. Share the relevant page or article URL, and answer from any page body or article excerpt in the structured content.":"No matching policy or FAQ content was found. Ask the user to rephrase the question."}var an="gid://shopify/ProductVariant/",sn=async(e,t)=>{let n=ii(e);if("error"in n)return n.error;let{handle:r,rawVariantId:o,selectedOptions:i}=n,a=await ai(r,o,i,t);if("error"in a)return a.error;let{variantId:s,resolvedOptions:c}=a,u=hi(t.routes.product(r),r,s),l=!M(u);return l&&I(t,u),si({handle:r,variantId:s,url:u,navigated:l,resolvedOptions:c})};function ii(e){let t=e.catalog.variant_id,n=pi(e.catalog.selected_options);if(t==null&&!n.length)return{error:p("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=fi(e.catalog.handle);return r?gi(r)?{handle:r,rawVariantId:t??void 0,selectedOptions:n}:{error:p(`Product handle "${r}" is not valid.`,"Use a product handle from search_catalog, browse_store, or get_product.")}:{error:p("Product handle is required.","Pass catalog.handle, or call show_variant from a product page.")}}async function ai(e,t,n,r){let o=t!=null?Le(t):"";if(o)return{variantId:o,resolvedOptions:void 0};if(n.length){let i=await ci(e,n,r);return"error"in i?i:{variantId:i.variantId,resolvedOptions:i.options}}return{error:p("Product variant_id could not be resolved.","Call get_product to find an available variants[].id, then retry show_variant.")}}function si(e){let{handle:t,variantId:n,url:r,navigated:o,resolvedOptions:i}=e,a=i?.length?` (${i.map(s=>`${s.name}: ${s.value}`).join(", ")})`:"";return O({summary:o?`Showing the selected variant${a}.`:`Already showing the selected variant${a}.`,navigated:o,destination:t,keyFields:`Variant id: ${n}`},{handle:t,variant_id:n,url:r,navigated:o,selected_options:i})}async function ci(e,t,n){try{let r=await H(e,{selected_options:t,routes:n.routes,signal:n.signal});if(!r)return{error:di(e)};let o=li(r);if(o)return o;let i=await ui(r,e,n);return i||{error:p("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:f(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 li(e){let n=e.variants.filter(r=>r.availability.available)[0]??e.variants[0];return n?.id?{variantId:Le(n.id),options:n.options}:null}async function ui(e,t,n){let r=e.available_options?.[0];if(!r?.length)return null;let o=await H(t,{selected_options:r,routes:n.routes,signal:n.signal}),i=o?.variants?.find(a=>a.availability.available)??o?.variants?.[0];return i?.id?{variantId:Le(i.id),options:i.options}:null}function di(e){return p(`Product "${e}" was not found.`,"Call search_catalog or browse_store to find an available product.")}function pi(e){return e?.length?e.map(t=>({name:String(t?.name??"").trim(),value:String(t?.value??"").trim()})).filter(t=>t.name&&t.value):[]}function Le(e){let t=String(e).trim();if(!t)return"";let n=t.startsWith(an)?t.slice(an.length):t;return/^\d+$/.test(n)?n:""}function fi(e){return e?.trim()?yi(e):cn()}function yi(e){let t=e?.trim();return t?L(t)||mi(t):""}function cn(){return typeof window>"u"?"":L(window.location.href)}function gi(e){return!!e&&!/[/?#\\]/.test(e)&&e!=="."&&e!==".."}function mi(e){try{return decodeURIComponent(e)}catch{return""}}function hi(e,t,n){let r=new URL(e,_i());if(r.searchParams.set("variant",n),cn()===t){let o=bi().searchParams.get("selling_plan");o&&r.searchParams.set("selling_plan",o)}return r.pathname+r.search}function bi(){return typeof window>"u"?new URL("https://shopify.local/"):new URL(window.location.href)}function _i(){return typeof window>"u"?"https://shopify.local":window.location.origin}var ln={add_to_cart:qt,browse_store:$t,cancel_cart:Kt,proceed_to_checkout:zt,get_cart:Xt,get_product:en,get_ucp_profile:tn,manage_orders:nn,search_catalog:rn,search_shop_policies_and_faqs:on,show_variant:sn,update_cart_lines:Ft};var un=Symbol.for("shopify.webmcp.registered"),Si=Object.values(st).map(e=>({...e,execute:ln[e.name]}));function dn(){let e=Ti();if(!e||Ci())return!1;let t=[];for(let n of Si){let r=Ai(n);t.push(e.registerTool(r))}return wi(),Promise.allSettled(t),!0}function vi(e){let t=window.Shopify?.routes?.navigate;if(typeof t=="function")return t(e);window.location.href=e}function Ti(){return typeof document<"u"&&"modelContext"in document?document.modelContext??null:typeof navigator<"u"&&"modelContext"in navigator?navigator.modelContext??null:null}function Ci(){return typeof window>"u"?!1:Reflect.get(window,un)===!0}function wi(){typeof window>"u"||Reflect.set(window,un,!0)}function Ai(e){let{execute:t,...n}=e;return{...n,execute:Ze(e.name,(r,o)=>t(r,{routes:et,navigate:vi,signal:X(o)}))}}(function(){typeof window>"u"||dn()})();})();