@swishapp/sdk 0.120.0 → 0.121.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/dom/dom-utils.d.ts +1 -0
- package/dist/events/event-bus.d.ts +1 -1
- package/dist/intents/handlers/edit-item-lists-handler.d.ts +3 -3
- package/dist/intents/handlers/edit-item-variant-handler.d.ts +3 -3
- package/dist/intents/handlers/{open-quick-buy-handler.d.ts → initiate-quick-buy-handler.d.ts} +5 -5
- package/dist/intents/handlers/save-item-handler.d.ts +3 -3
- package/dist/intents/handlers/view-home-handler.d.ts +6 -0
- package/dist/intents/handlers/view-list-detail-page-menu-handler.d.ts +11 -0
- package/dist/intents/handlers/{open-list-handler.d.ts → view-list-handler.d.ts} +5 -5
- package/dist/intents/handlers/{open-list-menu-handler.d.ts → view-list-menu-handler.d.ts} +5 -5
- package/dist/intents/handlers/view-lists-handler.d.ts +6 -0
- package/dist/intents/handlers/view-notifications-handler.d.ts +6 -0
- package/dist/intents/handlers/{open-order-handler.d.ts → view-order-handler.d.ts} +5 -5
- package/dist/intents/handlers/view-order-menu-handler.d.ts +11 -0
- package/dist/intents/handlers/view-orders-handler.d.ts +6 -0
- package/dist/intents/handlers/{open-product-handler.d.ts → view-product-handler.d.ts} +5 -5
- package/dist/intents/handlers/view-profile-handler.d.ts +6 -0
- package/dist/intents/handlers/view-saves-handler.d.ts +6 -0
- package/dist/intents/hooks/after-view-home-hook.d.ts +5 -0
- package/dist/intents/intents.d.ts +16 -1
- package/dist/intents/types.d.ts +41 -45
- package/dist/options/swish-options.d.ts +2 -1
- package/dist/options/types.d.ts +36 -2
- package/dist/query/client.d.ts +2 -0
- package/dist/query/index.d.ts +18 -0
- package/dist/query/invalidation.d.ts +6 -0
- package/dist/query/keys.d.ts +16 -0
- package/dist/query/persistence.d.ts +13 -0
- package/dist/query/storage-key.d.ts +4 -0
- package/dist/state/declarative-state.d.ts +2 -0
- package/dist/state/item-context-signal.d.ts +1 -1
- package/dist/state/item-context-source.d.ts +2 -0
- package/dist/state/item-state-signal.d.ts +1 -0
- package/dist/state/swish-query-signals.d.ts +1 -1
- package/dist/state/tanstack-query-signal.d.ts +14 -0
- package/dist/storefront-api/queries/fragments.d.ts +0 -1
- package/dist/storefront-api/queries/index.d.ts +0 -2
- package/dist/storefront-api/storefront-api-client.d.ts +0 -5
- package/dist/storefront-api/types/storefront.generated.d.ts +0 -50
- package/dist/swish-api/swish-api-auth.d.ts +2 -1
- package/dist/swish-api/swish-api-client.d.ts +1 -1
- package/dist/swish-ui/swish-ui.d.ts +5 -3
- package/dist/swish-ui/types.d.ts +1 -0
- package/dist/swish.d.ts +6 -2
- package/dist/swish.js +24 -77
- package/package.json +2 -1
- package/dist/intents/handlers/open-home-handler.d.ts +0 -6
- package/dist/intents/handlers/open-list-detail-page-menu-handler.d.ts +0 -11
- package/dist/intents/handlers/open-lists-handler.d.ts +0 -6
- package/dist/intents/handlers/open-notifications-handler.d.ts +0 -6
- package/dist/intents/handlers/open-order-menu-handler.d.ts +0 -11
- package/dist/intents/handlers/open-orders-handler.d.ts +0 -6
- package/dist/intents/handlers/open-profile-handler.d.ts +0 -6
- package/dist/intents/handlers/open-saves-handler.d.ts +0 -6
- package/dist/intents/handlers/open-sign-in-handler.d.ts +0 -11
- package/dist/intents/hooks/after-open-home-hook.d.ts +0 -5
- package/dist/storefront-api/load-save-intent-data.d.ts +0 -13
package/dist/swish.js
CHANGED
|
@@ -1,43 +1,18 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Wi=Object.create;var Yt=Object.defineProperty;var Xi=Object.getOwnPropertyDescriptor;var Ji=Object.getOwnPropertyNames;var Yi=Object.getPrototypeOf,Zi=Object.prototype.hasOwnProperty;var r=(t,e)=>Yt(t,"name",{value:e,configurable:!0});var er=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var tr=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ji(e))!Zi.call(t,i)&&i!==n&&Yt(t,i,{get:()=>e[i],enumerable:!(s=Xi(e,i))||s.enumerable});return t};var nr=(t,e,n)=>(n=t!=null?Wi(Yi(t)):{},tr(e||!t||!t.__esModule?Yt(n,"default",{value:t,enumerable:!0}):n,t));var Gi=er((dy,Qi)=>{"use strict";var Ya=(function(){function t(n,s){if(typeof n!="function")throw new TypeError("DataLoader must be constructed with a function which accepts "+("Array<key> and returns Promise<Array<value>>, but got: "+n+"."));this._batchLoadFn=n,this._maxBatchSize=nu(s),this._batchScheduleFn=su(s),this._cacheKeyFn=iu(s),this._cacheMap=ru(s),this._batch=null,this.name=ou(s)}r(t,"DataLoader");var e=t.prototype;return e.load=r(function(s){if(s==null)throw new TypeError("The loader.load() function must be called with a value, "+("but got: "+String(s)+"."));var i=eu(this),o=this._cacheMap,a;if(o){a=this._cacheKeyFn(s);var u=o.get(a);if(u){var c=i.cacheHits||(i.cacheHits=[]);return new Promise(function(l){c.push(function(){l(u)})})}}i.keys.push(s);var p=new Promise(function(l,y){i.callbacks.push({resolve:l,reject:y})});return o&&o.set(a,p),p},"load"),e.loadMany=r(function(s){if(!Hi(s))throw new TypeError("The loader.loadMany() function must be called with Array<key> "+("but got: "+s+"."));for(var i=[],o=0;o<s.length;o++)i.push(this.load(s[o]).catch(function(a){return a}));return Promise.all(i)},"loadMany"),e.clear=r(function(s){var i=this._cacheMap;if(i){var o=this._cacheKeyFn(s);i.delete(o)}return this},"clear"),e.clearAll=r(function(){var s=this._cacheMap;return s&&s.clear(),this},"clearAll"),e.prime=r(function(s,i){var o=this._cacheMap;if(o){var a=this._cacheKeyFn(s);if(o.get(a)===void 0){var u;i instanceof Error?(u=Promise.reject(i),u.catch(function(){})):u=Promise.resolve(i),o.set(a,u)}}return this},"prime"),t})(),Za=typeof process=="object"&&typeof process.nextTick=="function"?function(t){Hn||(Hn=Promise.resolve()),Hn.then(function(){process.nextTick(t)})}:typeof setImmediate=="function"?function(t){setImmediate(t)}:function(t){setTimeout(t)},Hn;function eu(t){var e=t._batch;if(e!==null&&!e.hasDispatched&&e.keys.length<t._maxBatchSize)return e;var n={hasDispatched:!1,keys:[],callbacks:[]};return t._batch=n,t._batchScheduleFn(function(){tu(t,n)}),n}r(eu,"getCurrentBatch");function tu(t,e){if(e.hasDispatched=!0,e.keys.length===0){Gn(e);return}var n;try{n=t._batchLoadFn(e.keys)}catch(s){return Qn(t,e,new TypeError("DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function "+("errored synchronously: "+String(s)+".")))}if(!n||typeof n.then!="function")return Qn(t,e,new TypeError("DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did "+("not return a Promise: "+String(n)+".")));n.then(function(s){if(!Hi(s))throw new TypeError("DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did "+("not return a Promise of an Array: "+String(s)+"."));if(s.length!==e.keys.length)throw new TypeError("DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise of an Array of the same length as the Array of keys."+(`
|
|
2
2
|
|
|
3
3
|
Keys:
|
|
4
4
|
`+String(e.keys))+(`
|
|
5
5
|
|
|
6
6
|
Values:
|
|
7
|
-
`+String(s)));rn(e);for(var i=0;i<e.callbacks.length;i++){var a=s[i];a instanceof Error?e.callbacks[i].reject(a):e.callbacks[i].resolve(a)}}).catch(function(s){sn(t,e,s)})}r(po,"dispatchBatch");function sn(t,e,n){rn(e);for(var s=0;s<e.keys.length;s++)t.clear(e.keys[s]),e.callbacks[s].reject(n)}r(sn,"failedDispatch");function rn(t){if(t.cacheHits)for(var e=0;e<t.cacheHits.length;e++)t.cacheHits[e]()}r(rn,"resolveCacheHits");function ho(t){var e=!t||t.batch!==!1;if(!e)return 1;var n=t&&t.maxBatchSize;if(n===void 0)return 1/0;if(typeof n!="number"||n<1)throw new TypeError("maxBatchSize must be a positive number: "+n);return n}r(ho,"getValidMaxBatchSize");function fo(t){var e=t&&t.batchScheduleFn;if(e===void 0)return co;if(typeof e!="function")throw new TypeError("batchScheduleFn must be a function: "+e);return e}r(fo,"getValidBatchScheduleFn");function mo(t){var e=t&&t.cacheKeyFn;if(e===void 0)return function(n){return n};if(typeof e!="function")throw new TypeError("cacheKeyFn must be a function: "+e);return e}r(mo,"getValidCacheKeyFn");function yo(t){var e=!t||t.cache!==!1;if(!e)return null;var n=t&&t.cacheMap;if(n===void 0)return new Map;if(n!==null){var s=["get","set","delete","clear"],i=s.filter(function(a){return n&&typeof n[a]!="function"});if(i.length!==0)throw new TypeError("Custom cacheMap missing methods: "+i.join(", "))}return n}r(yo,"getValidCacheMap");function vo(t){return t&&t.name?t.name:null}r(vo,"getValidName");function xs(t){return typeof t=="object"&&t!==null&&typeof t.length=="number"&&(t.length===0||t.length>0&&Object.prototype.hasOwnProperty.call(t,t.length-1))}r(xs,"isArrayLike");Cs.exports=uo});function pn(t,e="",n=new Map){for(let[s,i]of Object.entries(t)){let a=e?`${e}.${s}`:s;typeof i=="object"&&i!==null?pn(i,a,n):typeof i=="string"&&n.set(a,i)}return n}r(pn,"s");function Us(t,e,n){n?.count!==void 0&&(e=n.count===1?`${e}One`:`${e}Other`);let s=t.get(e)??e;return n&&(n.count!==void 0&&(s=s.replace("{{count}}",n.count.toString())),Object.entries(n).forEach(([i,a])=>{i!=="count"&&typeof a=="string"&&(s=s.replace(`{{${i}}}`,a))})),s}r(Us,"f");var Vs=new Set(["en"]),me="en";function dn(t,e){let n=null;async function s(i){let a=await import(`${t}/locales/${i.toLowerCase()}.js`);return pn(a.default)}return r(s,"o"),{t(i,a){return n?Us(n,i,a):i},async loadLocale(i){let a=i;Vs.has(i)||(console.warn(`[swish] Unsupported language "${i}", falling back to "${me}".`),a=me);let o;try{o=await s(a)}catch(u){if(console.warn(`[swish-i18n] Failed to load locale "${a}".`,u),a!==me)try{o=await s(me)}catch{console.warn(`[swish] Failed to load fallback locale "${me}".`);return}else return}if(e?.[a])for(let[u,c]of Object.entries(e[a]))c!==void 0&&o.set(u,c);n=o}}}r(dn,"p");var P=r(t=>t.split("/").pop()??"","shopifyGidToId"),N=r((t,e)=>`gid://shopify/${t}/${e}`,"shopifyIdToGid"),G=r(t=>t.toLowerCase().replace(".myshopify.com",""),"toShopName");var J=class{constructor(e,n,s=""){this.revalidationPromises=new Map;this.inFlightRequests=new Map;this.clearCachePromise=null;this.cacheName=e,this.defaultCacheControl=n,this.keyPrefix=s}static{r(this,"FetchCache")}async get(e){try{let n=await caches.open(this.cacheName),s=await n.match(e);if(s&&this.isExpired(s)){await n.delete(e);return}return s}catch(n){console.warn("Cache get error:",n);return}}async set(e,n,s){try{if(s?.includes("no-cache"))return;let i=this.createCacheableResponse(n,s);await(await caches.open(this.cacheName)).put(e,i)}catch(i){console.warn("Cache set error:",i)}}async fetchWithCache(e,n,s){let i=await this.getCacheKey(e,n);if(this.clearCachePromise&&await this.clearCachePromise,this.inFlightRequests.has(i))return this.inFlightRequests.get(i).then(o=>o.clone());let a=(async()=>{let o=await this.get(i);if(o)return this.isStaleButRevalidatable(o)&&this.revalidateInBackground(i,e,n,s),o.clone();let u=await fetch(e,n);return u.ok&&await this.set(i,u.clone(),s??this.defaultCacheControl),u})().finally(()=>{this.inFlightRequests.delete(i)});return this.inFlightRequests.set(i,a),a}async delete(e){try{return await(await caches.open(this.cacheName)).delete(e)}catch(n){return console.warn("Cache delete error:",n),!1}}async clear(){return this.clearCachePromise?this.clearCachePromise:(this.clearCachePromise=new Promise(async(e,n)=>{try{let s=await caches.open(this.cacheName),i=await s.keys();await Promise.all(i.map(a=>s.delete(a))),e()}catch(s){console.warn("Cache clear error:",s),n(s)}}),this.clearCachePromise.then(()=>{this.clearCachePromise=null}).catch(e=>{console.warn("Cache clear error:",e)}))}async keys(){try{return(await(await caches.open(this.cacheName)).keys()).map(s=>s.url)}catch(e){return console.warn("Cache keys error:",e),[]}}async has(e){try{let n=await caches.open(this.cacheName),s=await n.match(e);return s&&this.isExpired(s)?(await n.delete(e),!1):s!==void 0}catch(n){return console.warn("Cache has error:",n),!1}}async getStats(){try{return{total:(await(await caches.open(this.cacheName)).keys()).length}}catch(e){return console.warn("Cache stats error:",e),{total:0}}}async cleanupExpiredEntries(){try{let e=await caches.open(this.cacheName),n=await e.keys(),s=0;for(let a of n){let o=await e.match(a);o&&this.isExpired(o)&&(await e.delete(a),s++)}let i=n.length-s;return{removed:s,remaining:i}}catch(e){return console.warn("Cache cleanup error:",e),{removed:0,remaining:0}}}async getCacheKey(e,n){let s=this.getInputUrl(e),i=`${this.keyPrefix}${s}/${JSON.stringify(n)}`,o=new TextEncoder().encode(i),u=await crypto.subtle.digest("SHA-256",o);return`/${Array.from(new Uint8Array(u)).map(l=>l.toString(16).padStart(2,"0")).join("")}`}getInputUrl(e){return e instanceof URL?e.toString():typeof e=="string"?e:e.url}isExpired(e){let n=e.headers.get("Cache-Control");if(!n)return!1;let s=this.parseMaxAge(n),i=this.parseStaleWhileRevalidate(n);if(s===null)return!1;let a=e.headers.get("Date");if(!a)return!1;let o=new Date(a).getTime(),c=(Date.now()-o)/1e3,p=s+(i??0);return c>p}isStaleButRevalidatable(e){let n=e.headers.get("Cache-Control");if(!n)return!1;let s=this.parseMaxAge(n),i=this.parseStaleWhileRevalidate(n);if(s===null||i===null)return!1;let a=e.headers.get("Date");if(!a)return!1;let o=new Date(a).getTime(),c=(Date.now()-o)/1e3;return c>s&&c<=s+i}async revalidateInBackground(e,n,s,i){if(this.revalidationPromises.has(e))return;let a=(async()=>{try{let o=await fetch(n,s);o.ok&&await this.set(e,o.clone(),i??this.defaultCacheControl)}catch(o){console.warn("Background revalidation error:",o)}finally{this.revalidationPromises.delete(e)}})();this.revalidationPromises.set(e,a)}parseMaxAge(e){let n=new RegExp(/max-age=(\d+)/).exec(e);return n?parseInt(n[1],10):null}parseStaleWhileRevalidate(e){let n=new RegExp(/stale-while-revalidate=(\d+)/).exec(e);return n?parseInt(n[1],10):null}createCacheableResponse(e,n){let s=new Headers(e.headers);return s.set("Cache-Control",n),s.has("Date")||s.set("Date",new Date().toUTCString()),new Response(e.body,{status:e.status,statusText:e.statusText,headers:s})}};var be=class{static{r(this,"AjaxApiClient")}constructor(e){this.config=e;let n=G(e.storeDomain);this.cache=new J(`ajax-api-${n}`,"max-age=60, stale-while-revalidate=3600"),this.cache.cleanupExpiredEntries().catch(s=>{console.warn("Ajax API cache initialization cleanup error:",s)})}patchFetch(){if(!window.fetch||typeof window.fetch!="function")return;let e=window.fetch,n=this.config.responseInterceptor,s=this.getFetchRequest.bind(this);window.fetch=function(...i){let a=e.apply(this,i);if(typeof n=="function"){let o=s(i[0]);a.then(u=>n(u,o))}return a}}getFetchRequest(e){return e instanceof Request?e:new Request(e)}getBaseUrl(){if(!this.config?.storeDomain)throw new Error("Cart API client not initialized - missing store domain");return`https://${this.config.storeDomain}`}fetch(e,n){return(e instanceof Request?e.method:n?.method??"GET")==="GET"?this.cache.fetchWithCache(e,n):fetch(e,n)}async request(e,n={}){let s=`${this.getBaseUrl()}${e}`,i={"Content-Type":"application/json",Accept:"application/json"},a=await this.fetch(s,{...n,headers:{...i,...n.headers}});if(!a.ok){let o;try{o=await a.json()}catch{o={message:`HTTP ${a.status}: ${a.statusText}`,status:a.status.toString(),description:a.statusText}}throw new Error(o.message||o.description)}return a.json()}async fetchCart(){return this.request("/cart.js")}async addToCart(e){let n={...e,items:e.items.map(s=>{let i=Number(P(String(s.id)));if(!Number.isFinite(i)||i<=0)throw new Error(`Invalid Shopify ID: ${s.id}`);return{...s,id:i}})};return this.request("/cart/add.js",{method:"POST",body:JSON.stringify(n)})}async clearCache(){await this.cache.clear()}};var Se=class{constructor(e){this.eventMap={"/cart/add":"cart-add","/cart/update":"cart-update","/cart/change":"cart-change","/cart/clear":"cart-clear"};this.eventBus=e,this.processFetchResponse=this.processFetchResponse.bind(this)}static{r(this,"AjaxApiPublisher")}async processFetchResponse(e,n){try{let s=this.getEventName(n.url);if(s){let i=await e.clone().json();this.eventBus.publish(s,i)}}catch(s){console.warn(s)}}getEventName(e){for(let[n,s]of Object.entries(this.eventMap))if(e.includes(n))return s;return null}};function Fs(){let t=document.body||document.documentElement;return t?Promise.resolve(t):new Promise(e=>{window.addEventListener("DOMContentLoaded",()=>e(t))})}r(Fs,"waitForDOM");function re({onElementFound:t,selector:e,observerOptions:n,mustMatch:s}){let i=new WeakSet,a=new MutationObserver(p=>{let l=!1;for(let h of p)if(h.addedNodes.length>0){l=!0;break}l&&o()}),o=r(()=>{document.querySelectorAll(e).forEach(p=>{i.has(p)||(i.add(p),s?.(p)!==!1&&u(p))})},"locateElements"),u=r(p=>{if(!n){t(p);return}let l=new IntersectionObserver(h=>{for(let y of h)y.isIntersecting&&(l.disconnect(),t(p))},n);l.observe(p)},"observeElement");return r(async()=>{let p=await Fs();o(),a.observe(p,{childList:!0,subtree:!0})},"locateAndObserveElements")(),a}r(re,"createElementLocator");function pe({onLocationChange:t,fireOnInit:e=!1}){let n=r(()=>{t(window.location)},"handleChange");window.addEventListener("popstate",n);let s=history.pushState,i=history.replaceState;return history.pushState=function(...a){s.apply(this,a),n()},history.replaceState=function(...a){i.apply(this,a),n()},e&&n(),()=>{window.removeEventListener("popstate",n),history.pushState=s,history.replaceState=i}}r(pe,"createLocationObserver");function fn({element:t,onHrefChange:e}){let n=r(()=>{e(t.href)},"handleChange"),s=new MutationObserver(()=>{n()});return s.observe(t,{attributes:!0,attributeFilter:["href"]}),()=>{s.disconnect()}}r(fn,"createHrefObserver");function vn(t,e){if(!e.element)throw new Error("Element must be provided");let n=null,s=new Map,i=r(()=>{if(n){console.warn("Placement already mounted. Skipping mount.");return}Hs(e),n=re({selector:e.target.selector,observerOptions:e.target.observerOptions,mustMatch:e.target.mustMatch,onElementFound:r(p=>a(p),"onElementFound")})},"mount"),a=r(p=>{s.has(p)||p.hasAttribute("swish-ignore")||p.getAttribute("swish-placement-target")===e.id||(p.setAttribute("swish-placement-target",e.id),o(p))},"evaluateAndMount"),o=r(async p=>{let l=[],h=e.mount.mode,y=ei(p,e.mount.at);if(!y)return;let f=await(typeof e.element=="function"?e.element(e):ri(t,e.element));if(!f)return;if(f.setAttribute("swish-placement-element",e.id),typeof e.element!="function"){let x=e.element;x.props&&oi(f,x.props),x.classNames&&wn(f,x.classNames)}let E;e.container&&(E=ii(e.id,e.container),E.appendChild(f));let g,_=E??f;if(e.layout?.type==="overlay"){ni(y);let x=e.layout.anchor??"bottom-right";_.setAttribute("swish-placement-overlay",e.id),_.setAttribute("swish-placement-anchor",x)}let B=!1,O;if(e.layout?.type==="inline"){let x=e.layout,te=x.rowSelector?y.closest(x.rowSelector):null;te?g=te:(g=si(e.id,y,x),B=!0),O=g.getAttribute("swish-placement-inline-row"),g.setAttribute("swish-placement-inline-row",e.id)}let H=E??f;if(!ti(y,H,h)){try{H.remove()}catch{}return}let b={targetEl:p,renderTargetEl:y,mountEl:f,containerEl:E,rowEl:g,rowWasCreated:B,rowInlineAttrPrevValue:O,cleanupFns:l,ownsNode:!0};s.set(p,b);let T={id:e.id,targetEl:p,renderTargetEl:y,mountEl:b.mountEl,containerEl:E,rowEl:g,cleanup:r(x=>l.push(x),"cleanup")};e.element?.name==="save-button"&&js(t,T),e.onMount?.(T)},"mountElement"),u=r(p=>{let l=s.get(p);if(l){if(e.onUnmount?.({id:e.id,targetEl:l.targetEl,renderTargetEl:l.renderTargetEl,mountEl:l.mountEl,containerEl:l.containerEl,rowEl:l.rowEl}),l.cleanupFns.forEach(h=>h()),l.targetEl.getAttribute("swish-placement-target")===e.id&&l.targetEl.removeAttribute("swish-placement-target"),l.ownsNode&&(l.containerEl||l.mountEl).remove(),l.rowEl){if(l.rowWasCreated){let h=l.rowEl.parentElement;h&&l.targetEl.parentElement===l.rowEl?l.rowEl.replaceWith(l.targetEl):h?h.removeChild(l.rowEl):l.rowEl.remove()}else if(l.rowInlineAttrPrevValue!==void 0){let h=l.rowInlineAttrPrevValue;h===null?l.rowEl.removeAttribute("swish-placement-inline-row"):l.rowEl.setAttribute("swish-placement-inline-row",h)}}s.delete(p)}},"unmountElement");return{mount:i,unmount:r(()=>{n&&(n.disconnect(),n=null),s.forEach((p,l)=>u(l)),s.clear()},"unmount")}}r(vn,"createPlacement");var js=r((t,{mountEl:e,targetEl:n,cleanup:s})=>{let i=t.state.itemContext(n),a=t.state.effect(()=>{let{loading:o,productId:u,variantId:c}=i.value;o||(e.setAttribute("product-id",u??""),e.setAttribute("variant-id",c??""))});s(()=>a?.())},"saveButtonMount");function Hs(t){let e=Gs(t.id),n=Zs(t),s=document.getElementById(e);if(s){s.textContent=n;return}let i=document.createElement("style");i.id=e,i.setAttribute("swish-placement-style",t.id),i.textContent=n,document.head.appendChild(i)}r(Hs,"ensurePlacementStylesheet");function Gs(t){return`swish-placement-style-${zs(t)}`}r(Gs,"getPlacementStyleId");function zs(t){return t.replace(/[^a-zA-Z0-9\-_]/g,"_")}r(zs,"cssEscapeId");function mn(t){return`--swish-placement-${Ws(String(t))}`}r(mn,"designKeyToCSSVar");function Ws(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z])([A-Z][a-z])/g,"$1-$2").toLowerCase()}r(Ws,"toKebabCase");function Qs(t){return Object.entries(t??{sm:500,lg:700}).map(([s,i])=>({name:s,minWidth:i})).sort((s,i)=>s.minWidth-i.minWidth)}r(Qs,"getBreakpoints");function gn(t,e){if(t==null)return{};if(typeof t=="object"&&!Array.isArray(t)){if(e&&e.size){let n=Object.keys(t);return"base"in t||n.some(i=>e.has(i))?t:{base:t}}return t}return{base:t}}r(gn,"normalizeResponsiveValue");var Ks=new Set(["fontWeight","lineHeight","pressedScale","backgroundAlpha","pressedOpacity","pressedScale"]);function yn(t,e){if(e!=null)return typeof e=="number"&&!Ks.has(t)?`${e}px`:String(e)}r(yn,"formatDesignValue");function Xs(t,e,n){if(!e)return"";let s=new Set(n.map(c=>c.name)),i=[],a={},o=Object.entries(e).map(([c,p])=>[c,p]);for(let[c,p]of o){let l=gn(p,s),h=yn(String(c),l.base);h!==void 0&&i.push(`${mn(c)}:${h};`);for(let y of n){let f=l[y.name],E=yn(String(c),f);E!==void 0&&(a[y.name]||(a[y.name]=[]),a[y.name].push(`${mn(c)}:${E};`))}}let u=[];i.length&&u.push(`[swish-placement-element="${t}"]{${i.join("")}}`);for(let c of n){let p=a[c.name];p?.length&&u.push(`@media(min-width:${c.minWidth}px){[swish-placement-element="${t}"]{${p.join("")}}}`)}return u.join("")}r(Xs,"emitDesignCSS");function Ee(t){return t==null?"0px":typeof t=="number"?`${t}px`:t}r(Ee,"formatOffsetValue");function Js(t){return t==null?"":typeof t=="number"?`${t}`:t}r(Js,"formatZIndexValue");function Ys(t,e,n){let s=new Set(n.map(p=>p.name)),i=gn(e,s),a=i.base??{},o=Ee(a.x),u=Ee(a.y),c=[];c.push(`[swish-placement-overlay="${t}"]{--swish-placement-offset-x:${o};--swish-placement-offset-y:${u};}`);for(let p of n){let l=i[p.name];if(!l)continue;let h=Ee(l.x),y=Ee(l.y);c.push(`@media(min-width:${p.minWidth}px){[swish-placement-overlay="${t}"]{--swish-placement-offset-x:${h};--swish-placement-offset-y:${y};}}`)}return c.join("")}r(Ys,"emitOverlayOffsetCSS");function Zs(t){let e=t.id,n=Qs(t.breakpoints),s=`[swish-placement-inline-row="${e}"]{display:flex;flex-direction:row;align-items:center;gap:var(--swish-placement-inline-gap,8px);width:100%}[swish-placement-inline-row="${e}"]>*:not([swish-placement-element="${e}"]){flex:1;min-width:0}`,i=`[swish-placement-overlay="${e}"]{position:absolute;z-index:var(--swish-placement-overlay-z,10);transform:translate(calc(var(--swish-placement-sign-x,1)*var(--swish-placement-offset-x,0px)),calc(var(--swish-placement-sign-y,1)*var(--swish-placement-offset-y,0px)));}[swish-placement-overlay="${e}"][swish-placement-anchor="top-left"]{top:0;left:0;}[swish-placement-overlay="${e}"][swish-placement-anchor="top-right"]{top:0;right:0;}[swish-placement-overlay="${e}"][swish-placement-anchor="bottom-left"]{bottom:0;left:0;}[swish-placement-overlay="${e}"][swish-placement-anchor="bottom-right"]{bottom:0;right:0;}[swish-placement-overlay="${e}"][swish-placement-anchor$="left"]{--swish-placement-sign-x:1;}[swish-placement-overlay="${e}"][swish-placement-anchor$="right"]{--swish-placement-sign-x:-1;}[swish-placement-overlay="${e}"][swish-placement-anchor^="top"]{--swish-placement-sign-y:1;}[swish-placement-overlay="${e}"][swish-placement-anchor^="bottom"]{--swish-placement-sign-y:-1;}`,a="";if(t.layout?.type==="overlay"){let o=Ys(e,t.layout.offset,n),u=t.layout.zIndex?`[swish-placement-overlay="${e}"]{--swish-placement-overlay-z:${Js(t.layout.zIndex)};}`:"";a+=o+u+i}else t.layout?.type==="inline"&&(a+=s);if(t.design){let o=Xs(e,t.design,n);o&&(a+=o)}return t.css&&(a+=t.css.trim()),a}r(Zs,"buildPlacementCSS");function ei(t,e){if(!e||e==="target")return t;if("closest"in e)return t.closest(e.closest);if("query"in e)return t.querySelector(e.query);if("withinClosest"in e){let n=t.closest(e.withinClosest.root);return n?n.querySelector(e.withinClosest.selector):null}return t}r(ei,"resolveMountTarget");function ti(t,e,n){switch(n){case"before":return t.parentElement?(t.before(e),!0):!1;case"after":{let s=t.parentElement;return s?(s.insertBefore(e,t.nextSibling),!0):!1}case"append":return t.appendChild(e),!0;case"prepend":return t.insertBefore(e,t.firstChild),!0;case"replace":return t.parentElement?(t.replaceWith(e),!0):!1}}r(ti,"insertIntoDOM");function ni(t){let e=t.parentElement;return e?(window.getComputedStyle(e).position==="static"&&(e.style.position="relative"),e):null}r(ni,"ensureRelativeParent");function si(t,e,n){if(!e.parentElement)throw new Error("Cannot inline-wrap: refEl has no parentElement");let i=document.createElement("div");return i.setAttribute("swish-placement-inline-row",t),e.before(i),i.appendChild(e),i}r(si,"wrapWithFlexRow");function ii(t,e){let n=e.tag||"div",s=document.createElement(n);return s.setAttribute("swish-placement-container",t),e.classNames&&wn(s,e.classNames),s}r(ii,"createContainer");function ri(t,e){return t.ui.createElement(e.name,{})}r(ri,"createElement");function oi(t,e){for(let[n,s]of Object.entries(e)){let i=n.replace(/([A-Z])/g,"-$1").toLowerCase();s===!1||s===void 0||s===null||(s===!0?t.setAttribute(i,"true"):t.setAttribute(i,String(s)))}}r(oi,"applyProps");function wn(t,e){t.classList.add(...e)}r(wn,"applyClassNames");var ke=class{constructor(){this.eventBus=new EventTarget}static{r(this,"EventBus")}subscribe(e,n,s){return Array.isArray(e)||(e=[e]),e.forEach(i=>{this.eventBus.addEventListener(i,n,s)}),()=>{e.forEach(i=>{this.eventBus.removeEventListener(i,n,s)})}}unsubscribe(e,n,s){this.eventBus.removeEventListener(e,n,s)}publish(e,n){this.eventBus.dispatchEvent(new CustomEvent(e,{detail:n}))}};var kt;function bn(t){return{lang:t?.lang??kt?.lang,message:t?.message,abortEarly:t?.abortEarly??kt?.abortEarly,abortPipeEarly:t?.abortPipeEarly??kt?.abortPipeEarly}}r(bn,"getGlobalConfig");var ai;function ui(t){return ai?.get(t)}r(ui,"getGlobalMessage");var ci;function li(t){return ci?.get(t)}r(li,"getSchemaMessage");var pi;function di(t,e){return pi?.get(t)?.get(e)}r(di,"getSpecificMessage");function xe(t){let e=typeof t;return e==="string"?`"${t}"`:e==="number"||e==="bigint"||e==="boolean"?`${t}`:e==="object"||e==="function"?(t&&Object.getPrototypeOf(t)?.constructor?.name)??"null":e}r(xe,"_stringify");function Q(t,e,n,s,i){let a=i&&"input"in i?i.input:n.value,o=i?.expected??t.expects??null,u=i?.received??xe(a),c={kind:t.kind,type:t.type,input:a,expected:o,received:u,message:`Invalid ${e}: ${o?`Expected ${o} but r`:"R"}eceived ${u}`,requirement:t.requirement,path:i?.path,issues:i?.issues,lang:s.lang,abortEarly:s.abortEarly,abortPipeEarly:s.abortPipeEarly},p=t.kind==="schema",l=i?.message??t.message??di(t.reference,c.lang)??(p?li(c.lang):null)??s.message??ui(c.lang);l!==void 0&&(c.message=typeof l=="function"?l(c):l),p&&(n.typed=!1),n.issues?n.issues.push(c):n.issues=[c]}r(Q,"_addIssue");function Y(t){return{version:1,vendor:"valibot",validate(e){return t["~run"]({value:e},bn())}}}r(Y,"_getStandardProps");function Sn(t,e){let n=[...new Set(t)];return n.length>1?`(${n.join(` ${e} `)})`:n[0]??"never"}r(Sn,"_joinExpects");function ye(t,e){return{kind:"validation",type:"min_length",reference:ye,async:!1,expects:`>=${t}`,requirement:t,message:e,"~run"(n,s){return n.typed&&n.value.length<this.requirement&&Q(this,"length",n,s,{received:`${n.value.length}`}),n}}}r(ye,"minLength");function K(t,e){return{kind:"validation",type:"min_value",reference:K,async:!1,expects:`>=${t instanceof Date?t.toJSON():xe(t)}`,requirement:t,message:e,"~run"(n,s){return n.typed&&!(n.value>=this.requirement)&&Q(this,"value",n,s,{received:n.value instanceof Date?n.value.toJSON():xe(n.value)}),n}}}r(K,"minValue");function D(t){return{kind:"transformation",type:"transform",reference:D,async:!1,operation:t,"~run"(e){return e.value=this.operation(e.value),e}}}r(D,"transform");function hi(t,e,n){return typeof t.fallback=="function"?t.fallback(e,n):t.fallback}r(hi,"getFallback");function En(t,e,n){return typeof t.default=="function"?t.default(e,n):t.default}r(En,"getDefault");function oe(t,e){return{kind:"schema",type:"array",reference:oe,expects:"Array",async:!1,item:t,message:e,get"~standard"(){return Y(this)},"~run"(n,s){let i=n.value;if(Array.isArray(i)){n.typed=!0,n.value=[];for(let a=0;a<i.length;a++){let o=i[a],u=this.item["~run"]({value:o},s);if(u.issues){let c={type:"array",origin:"value",input:i,key:a,value:o};for(let p of u.issues)p.path?p.path.unshift(c):p.path=[c],n.issues?.push(p);if(n.issues||(n.issues=u.issues),s.abortEarly){n.typed=!1;break}}u.typed||(n.typed=!1),n.value.push(u.value)}}else Q(this,"type",n,s);return n}}}r(oe,"array");function xt(t){return{kind:"schema",type:"boolean",reference:xt,expects:"boolean",async:!1,message:t,get"~standard"(){return Y(this)},"~run"(e,n){return typeof e.value=="boolean"?e.typed=!0:Q(this,"type",e,n),e}}}r(xt,"boolean");function C(t){return{kind:"schema",type:"number",reference:C,expects:"number",async:!1,message:t,get"~standard"(){return Y(this)},"~run"(e,n){return typeof e.value=="number"&&!isNaN(e.value)?e.typed=!0:Q(this,"type",e,n),e}}}r(C,"number");function w(t,e){return{kind:"schema",type:"object",reference:w,expects:"Object",async:!1,entries:t,message:e,get"~standard"(){return Y(this)},"~run"(n,s){let i=n.value;if(i&&typeof i=="object"){n.typed=!0,n.value={};for(let a in this.entries){let o=this.entries[a];if(a in i||(o.type==="exact_optional"||o.type==="optional"||o.type==="nullish")&&o.default!==void 0){let u=a in i?i[a]:En(o),c=o["~run"]({value:u},s);if(c.issues){let p={type:"object",origin:"value",input:i,key:a,value:u};for(let l of c.issues)l.path?l.path.unshift(p):l.path=[p],n.issues?.push(l);if(n.issues||(n.issues=c.issues),s.abortEarly){n.typed=!1;break}}c.typed||(n.typed=!1),n.value[a]=c.value}else if(o.fallback!==void 0)n.value[a]=hi(o);else if(o.type!=="exact_optional"&&o.type!=="optional"&&o.type!=="nullish"&&(Q(this,"key",n,s,{input:void 0,expected:`"${a}"`,path:[{type:"object",origin:"key",input:i,key:a,value:i[a]}]}),s.abortEarly))break}}else Q(this,"type",n,s);return n}}}r(w,"object");function R(t,e){return{kind:"schema",type:"optional",reference:R,expects:`(${t.expects} | undefined)`,async:!1,wrapped:t,default:e,get"~standard"(){return Y(this)},"~run"(n,s){return n.value===void 0&&(this.default!==void 0&&(n.value=En(this,n,s)),n.value===void 0)?(n.typed=!0,n):this.wrapped["~run"](n,s)}}}r(R,"optional");function ae(t,e){return{kind:"schema",type:"picklist",reference:ae,expects:Sn(t.map(xe),"|"),async:!1,options:t,message:e,get"~standard"(){return Y(this)},"~run"(n,s){return this.options.includes(n.value)?n.typed=!0:Q(this,"type",n,s),n}}}r(ae,"picklist");function v(t){return{kind:"schema",type:"string",reference:v,expects:"string",async:!1,message:t,get"~standard"(){return Y(this)},"~run"(e,n){return typeof e.value=="string"?e.typed=!0:Q(this,"type",e,n),e}}}r(v,"string");function In(t){let e;if(t)for(let n of t)e?e.push(...n.issues):e=n.issues;return e}r(In,"_subIssues");function q(t,e){return{kind:"schema",type:"union",reference:q,expects:Sn(t.map(n=>n.expects),"|"),async:!1,options:t,message:e,get"~standard"(){return Y(this)},"~run"(n,s){let i,a,o;for(let u of this.options){let c=u["~run"]({value:n.value},s);if(c.typed)if(c.issues)a?a.push(c):a=[c];else{i=c;break}else o?o.push(c):o=[c]}if(i)return i;if(a){if(a.length===1)return a[0];Q(this,"type",n,s,{issues:In(a)}),n.typed=!0}else{if(o?.length===1)return o[0];Q(this,"type",n,s,{issues:In(o)})}return n}}}r(q,"union");function S(...t){return{...t[0],pipe:t,get"~standard"(){return Y(this)},"~run"(e,n){for(let s of t)if(s.kind!=="metadata"){if(e.issues&&(s.kind==="schema"||s.kind==="transformation")){e.typed=!1;break}(!e.issues||!n.abortEarly&&!n.abortPipeEarly)&&(e=s["~run"](e,n))}return e}}}r(S,"pipe");function k(t,e,n){let s=t["~run"]({value:e},bn(n));return{typed:s.typed,success:!s.issues,output:s.value,issues:s.issues}}r(k,"safeParse");var de=S(q([S(v(),D(P)),C()]),D(t=>Number(t)),S(C(),K(1)));var m=class{constructor(e,n,s,i){this.swish=e;this.ui=n;this.eventBus=s;this.options=i}static{r(this,"IntentHandler")}};var fi=q([w({variantId:de,quantity:R(S(C(),K(1)),1)}),w({items:S(oe(w({variantId:de,quantity:R(S(C(),K(1)),1)})),ye(1))})]),Ce=class extends m{static{r(this,"CreateCartLineHandler")}async invoke(e){let n=k(fi,e);if(!n.success)return{intent:"create:cart-line",code:"error",message:"Invalid intent data",issues:n.issues.map(i=>i.message)};let s=n.output;try{let i="items"in s?s.items.map(o=>({id:o.variantId,quantity:o.quantity})):[{id:s.variantId,quantity:s.quantity}];return{intent:"create:cart-line",code:"ok",data:await this.swish.ajax.addToCart({items:i})}}catch(i){let a=[],o="Failed to add item to cart";return i instanceof Error?(i.message&&(o=i.message,a.push(i.message)),i.stack&&a.push(i.stack)):typeof i=="string"&&i.trim()?(o=i,a.push(i)):i!=null&&a.push(String(i)),{intent:"create:cart-line",code:"error",message:o,issues:a.length?a:["Cart request failed"]}}}};var Re=class extends m{static{r(this,"CreateListHandler")}async invoke(e){let n=await this.ui.showListEditor();if(n.code==="closed")return{intent:"create:list",code:"closed"};let{list:s}=n.data;return{intent:"create:list",code:"ok",data:{list:s}}}};var mi=w({listId:v()}),Ae=class extends m{static{r(this,"DeleteListHandler")}async invoke(e){let n=k(mi,e);if(!n.success)return{intent:"delete:list",code:"error",message:"Invalid intent data",issues:n.issues.map(a=>a.message)};let{listId:s}=n.output;return(await this.ui.showDeleteListAlert({listId:s})).code==="closed"?{intent:"delete:list",code:"closed"}:{intent:"delete:list",code:"ok",data:{listId:s}}}};var yi=w({itemId:v()}),Pe=class extends m{static{r(this,"EditItemListsHandler")}async invoke(e){let n=k(yi,e);if(!n.success)return{intent:"edit:item-lists",code:"error",message:"Invalid intent data",issues:n.issues.map(a=>a.message)};let{itemId:s}=n.output,i=await this.ui.showListSelect({itemId:s});if(i.code==="closed")return{intent:"edit:item-lists",code:"closed"};if(i.data.action==="submit"){let{item:a,product:o,variant:u}=i.data.data;return{intent:"edit:item-lists",code:"ok",data:{item:a,product:o,variant:u}}}return{intent:"unsave:item",code:"ok",data:{itemId:i.data.data.itemId}}}};var vi=w({itemId:S(v()),productId:S(q([S(v(),D(P)),C()]),D(t=>Number(t)),C()),variantId:R(S(q([S(v(),D(P)),C()]),D(t=>Number(t)),C()))}),Te=class extends m{static{r(this,"EditItemVariantHandler")}async invoke(e){let n=k(vi,e);if(!n.success)return{intent:"edit:item-variant",code:"error",message:"Invalid intent data",issues:n.issues.map(y=>y.message)};let{itemId:s,productId:i,variantId:a}=n.output;if(!(!a||this.swish.options.intents.editSavedProduct.promptVariantChange)){let y=await this.swish.api.items.updateById(s,{productId:i,variantId:a});if("error"in y)return{intent:"edit:item-variant",code:"error",message:"Failed to update variant",issues:[y.error.message]};if(!y.data)return{intent:"edit:item-variant",code:"error",message:"Failed to update variant",issues:["No item returned from API"]};let f=await this.swish.storefront.loadSaveIntentData({productId:N("Product",i),variantId:a?N("ProductVariant",a):void 0});if(!f.data?.product)return{intent:"edit:item-variant",code:"error",message:"Failed to load save intent data",issues:[f.errors?.message??"No product data returned from API"]};let E=f.data?.product,g="variant"in f.data?f.data.variant:void 0;return{intent:"edit:item-variant",code:"ok",data:{item:y.data,product:E,variant:g}}}let u=await this.ui.showVariantSelect({itemId:s,productId:i,variantId:a});if(u.code==="closed")return{intent:"edit:item-variant",code:"closed"};let{item:c,product:p,variant:l}=u.data;return{intent:"edit:item-variant",code:"ok",data:{item:c,product:p,variant:l}}}};var gi=w({listId:v(),access:ae(["public","private"])}),De=class extends m{static{r(this,"EditListAccessHandler")}async invoke(e){let n=k(gi,e);if(!n.success)return{intent:"edit:list-access",code:"error",message:"Invalid intent data",issues:n.issues.map(u=>u.message)};let{listId:s,access:i}=n.output;if((await this.ui.showConfirmDialog({titleKey:i==="public"?"listMenu.public.title":"listMenu.private.title",descriptionKey:i==="public"?"listMenu.public.description":"listMenu.private.description",confirmLabelKey:i==="public"?"listMenu.public.text":"listMenu.private.text",cancelLabelKey:"listMenu.cancel",danger:!1})).code==="closed")return{intent:"edit:list-access",code:"closed"};let o=await this.swish.api.lists.updateById(s,{access:i});return"error"in o?{intent:"edit:list-access",code:"error",message:"Failed to update list access",issues:[o.error.message]}:o.data?{intent:"edit:list-access",code:"ok",data:{list:o.data}}:{intent:"edit:list-access",code:"error",message:"Failed to update list access",issues:["API response missing data"]}}};var wi=w({listId:v()}),Le=class extends m{static{r(this,"EditListHandler")}async invoke(e){let n=k(wi,e);if(!n.success)return{intent:"edit:list",code:"error",message:"Invalid intent data",issues:n.issues.map(o=>o.message)};let{listId:s}=n.output,i=await this.ui.showListEditor({listId:s});if(i.code==="closed")return{intent:"edit:list",code:"closed"};let{list:a}=i.data;return{intent:"edit:list",code:"ok",data:{list:a}}}};var Ii=w({variantId:de,quantity:R(S(C(),K(1)),1)}),bi=150,Si=q([w({variantId:de,quantity:R(S(C(),K(1)),1)}),w({items:S(oe(Ii),ye(1))})]),_e=class extends m{static{r(this,"InitiateCheckoutHandler")}async invoke(e){let n=k(Si,e);if(!n.success)return{intent:"initiate:checkout",code:"error",message:"Invalid intent data",issues:n.issues.map(u=>u.message)};let s=n.output,a=("items"in s?s.items:[{variantId:s.variantId,quantity:s.quantity}]).map(u=>`${u.variantId}:${u.quantity}`).join(","),o=new URL(`/cart/${a}`,this.swish.shopUrl);return o.searchParams.set("checkout","1"),typeof window<"u"&&window.setTimeout(()=>window.location.assign(o.href),bi),{intent:"initiate:checkout",code:"ok",data:{checkoutUrl:o.href}}}};var Ei=150,ki=w({returnTo:v()}),Oe=class extends m{static{r(this,"InitiateSignInHandler")}async invoke(e){let n=k(ki,e);if(!n.success)return{intent:"initiate:sign-in",code:"error",message:"Invalid intent data",issues:n.issues.map(a=>a.message)};let s=n.output.returnTo;return(await this.ui.showConfirmDialog({titleKey:"signIn.title",descriptionKey:"signIn.description",confirmLabelKey:"signIn.continue",danger:!1})).code==="closed"?{intent:"initiate:sign-in",code:"closed"}:(this.scheduleRedirect(s),{intent:"initiate:sign-in",code:"ok",data:void 0})}scheduleRedirect(e){window.setTimeout(()=>this.redirectToSignIn(e),Ei)}redirectToSignIn(e){let n=this.swish.storefrontContext.routes.accountUrl,s=new URL(n,window.location.origin);s.searchParams.set("return_url",e),window.location.assign(s.toString())}};var qe=class extends m{static{r(this,"OpenHomeHandler")}async invoke(e){return{intent:"open:home",code:(await this.ui.showDrawer()).code,data:void 0}}};var xi=w({listId:v()}),Me=class extends m{static{r(this,"OpenListDetailPageMenuHandler")}async invoke(e){let n=k(xi,e);if(!n.success)return{intent:"open:list-detail-page-menu",code:"error",message:"Invalid intent data",issues:n.issues.map(a=>a.message)};let{listId:s}=n.output;return{intent:"open:list-detail-page-menu",code:(await this.ui.showListDetailPageMenu({listId:s})).code,data:void 0}}};var Ci=w({listId:v(),listType:R(ae(["user","smart","shared"]),"user")}),$e=class extends m{static{r(this,"OpenListHandler")}async invoke(e){let n=k(Ci,e);if(!n.success)return{intent:"open:list",code:"error",message:"Invalid intent data",issues:n.issues.map(o=>o.message)};let{listId:s,listType:i}=n.output;return{intent:"open:list",code:(await this.ui.showDrawer({view:"list",listId:s,listType:i})).code,data:void 0}}};var Ri=w({listId:v()}),Ne=class extends m{static{r(this,"OpenListMenuHandler")}async invoke(e){let n=k(Ri,e);if(!n.success)return{intent:"open:list-menu",code:"error",message:"Invalid intent data",issues:n.issues.map(a=>a.message)};let{listId:s}=n.output,i=await this.ui.showListMenu({listId:s});if(i.code==="closed")return{intent:"open:list-menu",code:"closed"};if(i.data.action==="edit")return{intent:"edit:list",code:"ok",data:i.data.data};if(i.data.action==="delete")return{intent:"delete:list",code:"ok",data:{listId:s}};if(i.data.action==="edit-access"){let a=i.data.data?.currentListAccess,o=a==="public"?"private":a==="private"?"public":void 0;return o?(await this.swish.intents.invoke("edit:list-access",{listId:s,access:o})).complete:{intent:"open:list-menu",code:"error",message:"Missing list access from UI",issues:["List menu UI did not provide currentListAccess"]}}return i.data.action==="share"?(await this.swish.intents.invoke("initiate:share",{listId:s})).complete:i.data.action==="add-items"?{intent:"open:list-menu",code:"ok",data:{listId:s}}:{intent:"open:list-menu",code:"error",message:"Unknown list menu action",issues:["Unknown action returned from list menu UI"]}}};var Be=class extends m{static{r(this,"OpenListsHandler")}async invoke(e){return{intent:"open:lists",code:(await this.ui.showDrawer({view:"lists"})).code,data:void 0}}};var Ue=class extends m{static{r(this,"OpenNotificationsHandler")}async invoke(e){return{intent:"open:notifications",code:(await this.ui.showDrawer({view:"notifications"})).code,data:void 0}}};var Ai=w({orderId:S(q([S(v(),D(P)),C()]),D(t=>Number(t)),C())}),Ve=class extends m{static{r(this,"OpenOrderHandler")}async invoke(e){let n=k(Ai,e);if(!n.success)return{intent:"open:order",code:"error",message:"Invalid intent data",issues:n.issues.map(a=>a.message)};let{orderId:s}=n.output;return{intent:"open:order",code:(await this.ui.showDrawer({view:"order",orderId:s.toString()})).code,data:void 0}}};var Pi=w({orderId:v()}),Fe=class extends m{static{r(this,"OpenOrderMenuHandler")}async invoke(e){let n=k(Pi,e);if(!n.success)return{intent:"open:order-menu",code:"error",message:"Invalid intent data",issues:n.issues.map(a=>a.message)};let{orderId:s}=n.output;return{intent:"open:order-menu",code:(await this.ui.showOrderMenu({orderId:s})).code,data:void 0}}};var je=class extends m{static{r(this,"OpenOrdersHandler")}async invoke(e){return{intent:"open:orders",code:(await this.ui.showDrawer({view:"orders"})).code,data:void 0}}};var Ti=w({productId:S(q([S(v(),D(P)),C()]),D(t=>Number(t)),C()),variantId:R(S(q([S(v(),D(P)),C()]),D(Number),C()))}),He=class extends m{static{r(this,"OpenProductHandler")}async invoke(e){let n=k(Ti,e);if(!n.success)return{intent:"open:product",code:"error",message:"Invalid intent data",issues:n.issues.map(o=>o.message)};let{productId:s,variantId:i}=n.output;return{intent:"open:product",code:(await this.ui.showDrawer({view:"product",productId:s.toString(),variantId:i?.toString()})).code,data:void 0}}};var Ge=class extends m{static{r(this,"OpenProfileHandler")}async invoke(e){return{intent:"open:profile",code:(await this.ui.showDrawer({view:"profile"})).code,data:void 0}}};var Di=w({productId:S(q([S(v(),D(P)),C()]),D(t=>Number(t)),C()),variantId:R(S(q([S(v(),D(P)),C()]),D(Number),C()))}),ze=class extends m{static{r(this,"OpenQuickBuyHandler")}async invoke(e){let n=k(Di,e);if(!n.success)return{intent:"open:quick-buy",code:"error",message:"Invalid intent data",issues:n.issues.map(o=>o.message)};let{productId:s,variantId:i}=n.output,a=await this.ui.showQuickBuy({productId:s,variantId:i});return a.code==="closed"?{intent:"open:quick-buy",code:"closed"}:{intent:"open:quick-buy",code:"ok",data:a.data}}};var We=class extends m{static{r(this,"OpenSavesHandler")}async invoke(e){return{intent:"open:saves",code:(await this.ui.showDrawer({view:"saves"})).code,data:void 0}}};var fu=w({returnTo:R(v())}),Qe=class extends m{static{r(this,"OpenSignInHandler")}async invoke(e){return{intent:"open:sign-in",code:(await this.ui.showSignIn({returnTo:e?.returnTo})).code,data:void 0}}};var Ke=class extends m{static{r(this,"SaveCartLineHandler")}async invoke(e){if(!e?.items?.length)return{intent:"save:cart-line",code:"error",message:"No items to save",issues:["items array is empty or missing"]};let{confirm:n,showFeedback:s}=this.options.saveCartLine,i=e.items[0];if(n&&(await this.ui.showToast({title:"Save this for later?",text:i.title??"",image:i.image,action:{label:"Save for later"},variant:"full"})).code!=="ok")return{intent:"save:cart-line",code:"closed"};for(let a of e.items){let o=await this.swish.api.items.create({productId:a.productId,variantId:a.variantId,quantity:a.quantity,source:"cart"});if("error"in o)return{intent:"save:cart-line",code:"error",message:"Failed to save item from cart",issues:[o.error.message]}}return s&&await this.ui.showToast({title:"We've saved this for you",text:i.title??"",image:i.image,variant:"full"}),{intent:"save:cart-line",code:"ok",data:e.items}}};var Li=w({productId:S(q([S(v(),D(P)),C()]),D(t=>Number(t)),C()),variantId:R(S(q([S(v(),D(P)),C()]),D(Number),C())),quantity:R(S(C(),K(1))),tags:R(oe(v()))}),Xe=class extends m{static{r(this,"SaveItemHandler")}async invoke(e){let n=k(Li,e);if(!n.success)return{intent:"save:item",code:"error",message:"Invalid intent data",issues:n.issues.map(f=>f.message)};let{productId:s,variantId:i,quantity:a,tags:o}=n.output,u=await this.swish.storefront.loadSaveIntentData({productId:N("Product",s),variantId:i?N("ProductVariant",i):void 0});if(u.errors)return{intent:"save:item",code:"error",message:u.errors.message??"Failed to load save intent data",issues:u.errors.graphQLErrors?.map(f=>f.message)??[]};if(!u.data||!u.data.product)return{intent:"save:item",code:"error",message:"Failed to load save intent data",issues:["API response missing data"]};let{product:c}=u.data,p=c.variantsCount?.count&&c.variantsCount.count>1,l=!!i,h=!this.options.saveProduct.promptVariantIfMissing||!this.options.saveProduct.promptVariantIfPresent&&l;if(!p||h){let f=r(()=>!p&&c.selectedOrFirstAvailableVariant?Number(P(c.selectedOrFirstAvailableVariant.id)):i,"variantIdToUse"),E=await this.swish.api.items.create({productId:s,variantId:f(),quantity:a,tags:o});if("error"in E)return{intent:"save:item",code:"error",message:"Failed to create item",issues:[E.error.message]};if(!E.data)return{intent:"save:item",code:"error",message:"Could not complete item creation",issues:["API response missing data"]};let g="variant"in u.data?u.data.variant:void 0;return{intent:"save:item",code:"ok",data:{item:E.data,product:c,variant:p?g:c.selectedOrFirstAvailableVariant}}}let y=await this.ui.showVariantSelect({productId:s,variantId:i});return y.code==="closed"?{intent:"save:item",code:"closed"}:{intent:"save:item",code:"ok",data:y.data}}};function ve(t,e){let{storeDomain:n}=t.options.storefrontApi,{rootUrl:s,listDetailPagePath:i}=t.options.storefrontContext.routes,a=new URL(`https://${n}`),o=new URL(`${s==="/"?"":s}${i}`,a);return o.searchParams.set("public-list-id",e.publicListId),o}r(ve,"buildShareListUrl");async function ge(t){return typeof navigator?.clipboard?.writeText!="function"?{ok:!1,issues:["Clipboard API not available"]}:navigator.clipboard.writeText(t).then(()=>({ok:!0})).catch(e=>({ok:!1,issues:[e?.message??"Failed to copy to clipboard"]}))}r(ge,"copyToClipboard");function kn(){let t=navigator.userAgent.includes("Mac OS")&&navigator.maxTouchPoints>1;return/Android|Mobile/i.test(navigator.userAgent)||t}r(kn,"isMobileDevice");var _i=w({listId:v()}),Je=class extends m{static{r(this,"ShareListHandler")}async invoke(e){let n=k(_i,e);if(!n.success)return{intent:"initiate:share",code:"error",message:"Invalid intent data",issues:n.issues.map(c=>c.message)};let{listId:s}=n.output,i=await this.swish.api.lists.findById(s);if("error"in i)return{intent:"initiate:share",code:"error",message:"Failed to fetch list",issues:[i.error.message]};if(!i.data)return{intent:"initiate:share",code:"error",message:"List not found",issues:[]};if(i.data.access!=="public"){let p=await(await this.swish.intents.invoke("edit:list-access",{listId:s,access:"public"})).complete;if(p.code!=="ok")return{...p,intent:"initiate:share"}}let a=ve(this.swish,{publicListId:s}).toString();if(kn()&&typeof navigator.share=="function"&&(await navigator.share({title:"Share list",url:a}).then(()=>({ok:!0})).catch(()=>({ok:!1}))).ok)return{intent:"initiate:share",code:"ok",data:{listId:s,url:a,method:"native"}};let u=await ge(a);return u.ok?{intent:"initiate:share",code:"ok",data:{listId:s,url:a,method:"clipboard"}}:{intent:"initiate:share",code:"error",message:"Failed to share list",issues:u.issues}}};var $u=w({title:R(v()),text:v(),image:R(v()),action:R(w({label:v(),url:R(v())})),variant:R(ae(["compact","full"])),icon:R(v())}),Ye=class extends m{static{r(this,"ShowToastHandler")}async invoke(e){return{intent:"show:toast",code:(await this.ui.showToast(e)).code,data:void 0}}};var Oi=w({itemId:v(),delete:R(xt())}),Ze=class extends m{static{r(this,"UnsaveItemHandler")}async invoke(e){let n=k(Oi,e);if(!n.success)return{intent:"unsave:item",code:"error",message:"Invalid intent data",issues:n.issues.map(o=>o.message)};let{itemId:s,delete:i}=n.output;if(this.options.unsaveProduct.selectList&&!i){let o=await this.ui.showListSelect({itemId:s});if(o.code==="closed")return{intent:"unsave:item",code:"closed"};if(o.data.action==="submit"){let{item:u,product:c,variant:p}=o.data.data;return{intent:"edit:item-lists",code:"ok",data:{item:u,product:c,variant:p}}}if(o.data.action==="unsave"){let{itemId:u}=o.data.data;return{intent:"unsave:item",code:"ok",data:{itemId:u}}}}if(!this.options.unsaveProduct.confirm){let o=await this.swish.api.items.deleteById(s);return"error"in o?{intent:"unsave:item",code:"error",message:"Failed to delete item",issues:[o.error.message]}:{intent:"unsave:item",code:"ok",data:{itemId:s}}}return(await this.ui.showUnsaveAlert({itemId:s})).code==="closed"?{intent:"unsave:item",code:"closed"}:{intent:"unsave:item",code:"ok",data:{itemId:s}}}};var U=class{constructor(e,n,s){this.swish=e;this.ui=n;this.options=s}static{r(this,"IntentHook")}};var et=class extends U{static{r(this,"AfterCreateCartLineHook")}async invoke(e){this.options.createCartLine.afterComplete?.(e)}};var tt=class extends U{static{r(this,"AfterEditItemListsHook")}async invoke(e){if(this.options.editSavedProduct.showFeedback&&e.code==="ok"){if("itemId"in e.data)return;let{product:n,variant:s}=e.data;n&&(await(await this.swish.intents.invoke("show:toast",{title:"Saved",text:n.title,image:s?.image?.url??n.featuredImage?.url,action:{label:"View"}})).complete).code==="ok"&&this.swish.intents.invoke("open:home")}}};var nt=class extends U{static{r(this,"AfterEditListAccessHook")}async invoke(e){if(e.code!=="ok")return;let n=e.data.list.access==="public"?"List is now public":"List is now private";await(await this.swish.intents.invoke("show:toast",{text:n,variant:"compact",icon:"check"})).complete}};var st=class extends U{static{r(this,"AfterOpenHomeHook")}async invoke(e){if(e.code==="closed"){let n=new URL(window.location.href);(n.hash==="#swish-home"||n.hash==="#swish")&&(n.hash="",window.history.replaceState({},document.title,n.toString()))}}};var it=class extends U{static{r(this,"AfterSaveCartLineHook")}async invoke(e){this.options.saveCartLine.afterComplete?.(e)}};var rt=class extends U{static{r(this,"AfterSaveItemHook")}async invoke(e){if(this.options.saveProduct.showFeedback&&e.code==="ok"){let{item:n,product:s,variant:i}=e.data;s&&(await(await this.swish.intents.invoke("show:toast",{title:"Saved",text:s.title,image:i?.image?.url??s.featuredImage?.url,action:{label:"Add to List"}})).complete).code==="ok"&&this.swish.intents.invoke("edit:item-lists",{itemId:n.id})}}};var ot=class extends U{static{r(this,"AfterShareListHook")}async invoke(e){if(e.code!=="ok")return;await(await this.swish.intents.invoke("show:toast",{variant:"compact",text:"Link copied",icon:"check"})).complete}};var at=class{static{r(this,"Intents")}constructor(e,n){this.swish=e,this.ui=n,this.eventBus=new EventTarget,this.options=e.options.intents,this.handlers={"create:cart-line":new Ce(this.swish,this.ui,this.eventBus,this.options),"initiate:checkout":new _e(this.swish,this.ui,this.eventBus,this.options),"save:item":new Xe(this.swish,this.ui,this.eventBus,this.options),"save:cart-line":new Ke(this.swish,this.ui,this.eventBus,this.options),"unsave:item":new Ze(this.swish,this.ui,this.eventBus,this.options),"edit:item-variant":new Te(this.swish,this.ui,this.eventBus,this.options),"edit:item-lists":new Pe(this.swish,this.ui,this.eventBus,this.options),"create:list":new Re(this.swish,this.ui,this.eventBus,this.options),"edit:list":new Le(this.swish,this.ui,this.eventBus,this.options),"edit:list-access":new De(this.swish,this.ui,this.eventBus,this.options),"delete:list":new Ae(this.swish,this.ui,this.eventBus,this.options),"open:home":new qe(this.swish,this.ui,this.eventBus,this.options),"initiate:share":new Je(this.swish,this.ui,this.eventBus,this.options),"open:list":new $e(this.swish,this.ui,this.eventBus,this.options),"open:lists":new Be(this.swish,this.ui,this.eventBus,this.options),"open:orders":new je(this.swish,this.ui,this.eventBus,this.options),"open:order":new Ve(this.swish,this.ui,this.eventBus,this.options),"open:saves":new We(this.swish,this.ui,this.eventBus,this.options),"open:notifications":new Ue(this.swish,this.ui,this.eventBus,this.options),"open:profile":new Ge(this.swish,this.ui,this.eventBus,this.options),"open:product":new He(this.swish,this.ui,this.eventBus,this.options),"open:list-menu":new Ne(this.swish,this.ui,this.eventBus,this.options),"open:order-menu":new Fe(this.swish,this.ui,this.eventBus,this.options),"open:list-detail-page-menu":new Me(this.swish,this.ui,this.eventBus,this.options),"initiate:sign-in":new Oe(this.swish,this.ui,this.eventBus,this.options),"open:sign-in":new Qe(this.swish,this.ui,this.eventBus,this.options),"open:quick-buy":new ze(this.swish,this.ui,this.eventBus,this.options),"show:toast":new Ye(this.swish,this.ui,this.eventBus,this.options)},this.initIntentHooks(),this.initIntentWatcher(),this.initCartChangeListener()}publishAnalyticsEvent(e,n){typeof window.Shopify?.analytics?.publish=="function"&&window.Shopify.analytics.publish(e,n)}async invoke(e,...n){let s=n[0],i={lifecycle:"before",intent:e,data:s};return this.publishAnalyticsEvent("swish-intent",i),this.publishAnalyticsEvent(`swish-intent=${e}`,i),{intent:e,data:s,complete:this.handleIntent(e,s).then(a=>{let o={lifecycle:"after",intent:e,data:s,response:a};return this.publishAnalyticsEvent("swish-intent",o),this.publishAnalyticsEvent(`swish-intent=${e}`,o),this.eventBus.dispatchEvent(new CustomEvent(e,{detail:a})),a})}}listen(e,n){let s=r(a=>{"detail"in a&&a.detail?n(a.detail):console.warn("Intent response event without detail",a)},"eventListener"),i=r(()=>{this.eventBus.removeEventListener(e,s)},"unsubscribe");return this.eventBus.addEventListener(e,s),i}parseIntentFromString(e){if(typeof e=="string"){let[n,...s]=e.split(","),i=s.reduce((a,o)=>{let[u,c]=o.split("=");return a[u]=c,a},{});return{intent:n,data:i}}return{intent:e,data:{}}}parseIntentFromHash(e){let n=e.startsWith("#")?e.slice(1):e;return{swish:"open:home","swish-home":"open:home","swish-lists":"open:lists","swish-orders":"open:orders","swish-saves":"open:saves","swish-notifications":"open:notifications","swish-profile":"open:profile"}[n]||null}async handleIntent(e,n){let s=this.handlers[e];return s?s.invoke(n):{intent:e,code:"error",message:"Invalid intent",issues:[`Intent ${e} not found`]}}initIntentHooks(){this.eventBus.addEventListener("create:cart-line",e=>{new et(this.swish,this.ui,this.options).invoke(e.detail)}),this.eventBus.addEventListener("save:item",e=>{new rt(this.swish,this.ui,this.options).invoke(e.detail)}),this.eventBus.addEventListener("edit:item-lists",e=>{new tt(this.swish,this.ui,this.options).invoke(e.detail)}),this.eventBus.addEventListener("open:home",e=>{new st(this.swish,this.ui,this.options).invoke(e.detail)}),this.eventBus.addEventListener("edit:list-access",e=>{new nt(this.swish,this.ui,this.options).invoke(e.detail)}),this.eventBus.addEventListener("initiate:share",e=>{new ot(this.swish,this.ui,this.options).invoke(e.detail)}),this.eventBus.addEventListener("save:cart-line",e=>{new it(this.swish,this.ui,this.options).invoke(e.detail)})}initCartChangeListener(){this.swish.events.subscribe("cart-change",e=>{if(!this.options.removeCartLine.saveCartLine)return;let s=e.detail?.items_removed;if(!s?.length)return;let i=s.map(a=>({productId:a.product_id,variantId:a.variant_id,quantity:a.quantity,title:a.product_title,image:a.image,variantTitle:a.variant_title}));this.invoke("save:cart-line",{items:i})})}initIntentWatcher(){re({selector:"[swish-intent]",onElementFound:r(e=>{let n=e.getAttribute("swish-intent");n&&e.addEventListener("click",()=>{let{intent:s,data:i}=this.parseIntentFromString(n);Object.keys(i).length>0?this.invoke(s,i):this.invoke(s)})},"onElementFound")}),re({selector:"a[href*='swish-intent='],a[href*='#swish']",onElementFound:r(e=>{e instanceof HTMLAnchorElement&&e.addEventListener("click",n=>{if(!n.metaKey&&!n.ctrlKey&&!n.shiftKey&&!n.altKey){let s=new URL(e.href),i=s.hash,a=s.searchParams.get("swish-intent");if(a){let{intent:o,data:u}=this.parseIntentFromString(a);o&&(n.preventDefault(),n.stopPropagation(),Object.keys(u).length>0?this.invoke(o,u):this.invoke(o))}else if(i){let o=this.parseIntentFromHash(i);o&&(n.preventDefault(),n.stopPropagation(),this.invoke(o))}}})},"onElementFound")}),pe({fireOnInit:!0,onLocationChange:r(e=>{let n=new URL(e.href),s=n.hash,i=n.searchParams.get("swish-intent");if(i){let{intent:a,data:o}=this.parseIntentFromString(i);a&&(Object.keys(o).length>0?this.invoke(a,o):this.invoke(a))}else if(s){let a=this.parseIntentFromHash(s);a&&this.invoke(a)}},"onLocationChange")})}};var xn=r(t=>({swishApi:{authProxy:t.swishApi?.authProxy??"/apps/wishlist/api"},storefrontApi:{storeDomain:t.storefrontApi?.storeDomain??"",accessToken:t.storefrontApi?.accessToken??""},storefrontContext:{...t.storefrontContext,routes:{...t.storefrontContext.routes,rootUrl:t.storefrontContext.routes?.rootUrl??"/",listDetailPagePath:t.storefrontContext.routes?.listDetailPagePath??"/apps/wishlist"},localization:{country:t.storefrontContext.localization.country.toUpperCase(),language:t.storefrontContext.localization.language.toUpperCase(),market:t.storefrontContext.localization.market}},features:{accounts:t?.features?.accounts??!0,lists:t?.features?.lists??!0,orders:t?.features?.orders??!0,notifications:t?.features?.notifications??!0},products:{metafields:{product:t.products?.metafields?.product??[],productVariant:t.products?.metafields?.productVariant??[]},transform:{badges:t.products?.transform?.badges??(({defaultBadges:e})=>e),title:t.products?.transform?.title??(({product:e})=>e?.title??""),description:t.products?.transform?.description??(({product:e})=>e?.descriptionHtml??""),variantTitle:t.products?.transform?.variantTitle??(({variant:e})=>e?.title??""),optionValues:t.products?.transform?.optionValues??(({optionValues:e})=>e)}},intents:{saveProduct:{promptVariantIfMissing:t?.intents?.saveProduct?.promptVariantIfMissing??!0,promptVariantIfPresent:t?.intents?.saveProduct?.promptVariantIfPresent??!0,showFeedback:t?.intents?.saveProduct?.showFeedback??!0},unsaveProduct:{selectList:t?.intents?.unsaveProduct?.selectList??!0,confirm:t?.intents?.unsaveProduct?.confirm??!0,showFeedback:t?.intents?.unsaveProduct?.showFeedback??!0},editSavedProduct:{promptVariantChange:t?.intents?.editSavedProduct?.promptVariantChange??!0,showFeedback:t?.intents?.editSavedProduct?.showFeedback??!0},createCartLine:{afterComplete:t?.intents?.createCartLine?.afterComplete},removeCartLine:{saveCartLine:t?.intents?.removeCartLine?.saveCartLine??!1},saveCartLine:{confirm:t?.intents?.saveCartLine?.confirm??!1,showFeedback:t?.intents?.saveCartLine?.showFeedback??!0,afterComplete:t?.intents?.saveCartLine?.afterComplete}},translations:t.translations,swishUi:{baseUrl:t.swishUi?.baseUrl??"https://swish.app/cdn",components:{productRow:{showVariantTitle:t.swishUi?.components?.productRow?.showVariantTitle??!1},productDetail:{descriptionMaxLines:t.swishUi?.components?.productDetail?.descriptionMaxLines??4},variantSelect:{displayType:t.swishUi?.components?.variantSelect?.displayType??"pills"},icons:t.swishUi?.components?.icons??{},imageSlider:{flush:t.swishUi?.components?.imageSlider?.flush??!1,loop:t.swishUi?.components?.imageSlider?.loop??!1},images:{baseTint:t.swishUi?.components?.images?.baseTint??!1},buyButtons:{shopPay:t.swishUi?.components?.buyButtons?.shopPay??!1},listDetailPage:{desktopColumns:t.swishUi?.components?.listDetailPage?.desktopColumns??4,showBuyButton:t.swishUi?.components?.listDetailPage?.showBuyButton??!0,showVariantOptionNames:t.swishUi?.components?.listDetailPage?.showVariantOptionNames??!1,enableVariantChange:t.swishUi?.components?.listDetailPage?.enableVariantChange??!0},drawer:{title:t.swishUi?.components?.drawer?.title??"",logo:{url:t.swishUi?.components?.drawer?.logo?.url??"",altText:t.swishUi?.components?.drawer?.logo?.altText??""},navigation:{enabled:t.swishUi?.components?.drawer?.navigation?.enabled??!0,variant:t.swishUi?.components?.drawer?.navigation?.variant??"docked",showIcons:t.swishUi?.components?.drawer?.navigation?.showIcons??!1,items:t.swishUi?.components?.drawer?.navigation?.items??[]},emptyCallout:{enabled:t.swishUi?.components?.drawer?.emptyCallout?.enabled??!1,shoppingCalloutUrl:t.swishUi?.components?.drawer?.emptyCallout?.shoppingCalloutUrl??"/collections/all"},miniMenu:{enabled:t.swishUi?.components?.drawer?.miniMenu?.enabled??!0,items:t.swishUi?.components?.drawer?.miniMenu?.items??[]},listDetailView:{enableVariantChange:t.swishUi?.components?.drawer?.listDetailView?.enableVariantChange??!1,showVariantOptionNames:t.swishUi?.components?.drawer?.listDetailView?.showVariantOptionNames??!1}}},css:t.swishUi?.css??[],design:t.swishUi?.design??{}}}),"createSwishOptions");var qi=Symbol.for("preact-signals");function ct(){if(ne>1)ne--;else{for(var t,e=!1;we!==void 0;){var n=we;for(we=void 0,Ct++;n!==void 0;){var s=n.o;if(n.o=void 0,n.f&=-3,!(8&n.f)&&Pn(n))try{n.c()}catch(i){e||(t=i,e=!0)}n=s}}if(Ct=0,ne--,e)throw t}}r(ct,"t");function se(t){if(ne>0)return t();ne++;try{return t()}finally{ct()}}r(se,"n");var A=void 0;function Rn(t){var e=A;A=void 0;try{return t()}finally{A=e}}r(Rn,"o");var Cn,we=void 0,ne=0,Ct=0,ut=0;function An(t){if(A!==void 0){var e=t.n;if(e===void 0||e.t!==A)return e={i:0,S:t,p:A.s,n:void 0,t:A,e:void 0,x:void 0,r:e},A.s!==void 0&&(A.s.n=e),A.s=e,t.n=e,32&A.f&&t.S(e),e;if(e.i===-1)return e.i=0,e.n!==void 0&&(e.n.p=e.p,e.p!==void 0&&(e.p.n=e.n),e.p=A.s,e.n=void 0,A.s.n=e,A.s=e),e}}r(An,"e");function V(t,e){this.v=t,this.i=0,this.n=void 0,this.t=void 0,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}r(V,"d");V.prototype.brand=qi;V.prototype.h=function(){return!0};V.prototype.S=function(t){var e=this,n=this.t;n!==t&&t.e===void 0&&(t.x=n,this.t=t,n!==void 0?n.e=t:Rn(function(){var s;(s=e.W)==null||s.call(e)}))};V.prototype.U=function(t){var e=this;if(this.t!==void 0){var n=t.e,s=t.x;n!==void 0&&(n.x=s,t.e=void 0),s!==void 0&&(s.e=n,t.x=void 0),t===this.t&&(this.t=s,s===void 0&&Rn(function(){var i;(i=e.Z)==null||i.call(e)}))}};V.prototype.subscribe=function(t){var e=this;return z(function(){var n=e.value,s=A;A=void 0;try{t(n)}finally{A=s}},{name:"sub"})};V.prototype.valueOf=function(){return this.value};V.prototype.toString=function(){return this.value+""};V.prototype.toJSON=function(){return this.value};V.prototype.peek=function(){var t=A;A=void 0;try{return this.value}finally{A=t}};Object.defineProperty(V.prototype,"value",{get:r(function(){var t=An(this);return t!==void 0&&(t.i=this.i),this.v},"get"),set:r(function(t){if(t!==this.v){if(Ct>100)throw new Error("Cycle detected");this.v=t,this.i++,ut++,ne++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{ct()}}},"set")});function $(t,e){return new V(t,e)}r($,"c");function Pn(t){for(var e=t.s;e!==void 0;e=e.n)if(e.S.i!==e.i||!e.S.h()||e.S.i!==e.i)return!0;return!1}r(Pn,"a");function Tn(t){for(var e=t.s;e!==void 0;e=e.n){var n=e.S.n;if(n!==void 0&&(e.r=n),e.S.n=e,e.i=-1,e.n===void 0){t.s=e;break}}}r(Tn,"l");function Dn(t){for(var e=t.s,n=void 0;e!==void 0;){var s=e.p;e.i===-1?(e.S.U(e),s!==void 0&&(s.n=e.n),e.n!==void 0&&(e.n.p=s)):n=e,e.S.n=e.r,e.r!==void 0&&(e.r=void 0),e=s}t.s=n}r(Dn,"y");function ue(t,e){V.call(this,void 0),this.x=t,this.s=void 0,this.g=ut-1,this.f=4,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}r(ue,"w");ue.prototype=new V;ue.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===ut))return!0;if(this.g=ut,this.f|=1,this.i>0&&!Pn(this))return this.f&=-2,!0;var t=A;try{Tn(this),A=this;var e=this.x();(16&this.f||this.v!==e||this.i===0)&&(this.v=e,this.f&=-17,this.i++)}catch(n){this.v=n,this.f|=16,this.i++}return A=t,Dn(this),this.f&=-2,!0};ue.prototype.S=function(t){if(this.t===void 0){this.f|=36;for(var e=this.s;e!==void 0;e=e.n)e.S.S(e)}V.prototype.S.call(this,t)};ue.prototype.U=function(t){if(this.t!==void 0&&(V.prototype.U.call(this,t),this.t===void 0)){this.f&=-33;for(var e=this.s;e!==void 0;e=e.n)e.S.U(e)}};ue.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var t=this.t;t!==void 0;t=t.x)t.t.N()}};Object.defineProperty(ue.prototype,"value",{get:r(function(){if(1&this.f)throw new Error("Cycle detected");var t=An(this);if(this.h(),t!==void 0&&(t.i=this.i),16&this.f)throw this.v;return this.v},"get")});function j(t,e){return new ue(t,e)}r(j,"b");function Ln(t){var e=t.u;if(t.u=void 0,typeof e=="function"){ne++;var n=A;A=void 0;try{e()}catch(s){throw t.f&=-2,t.f|=8,Rt(t),s}finally{A=n,ct()}}}r(Ln,"_");function Rt(t){for(var e=t.s;e!==void 0;e=e.n)e.S.U(e);t.x=void 0,t.s=void 0,Ln(t)}r(Rt,"p");function Mi(t){if(A!==this)throw new Error("Out-of-order effect");Dn(this),A=t,this.f&=-2,8&this.f&&Rt(this),ct()}r(Mi,"g");function he(t,e){this.x=t,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32,this.name=e?.name,Cn&&Cn.push(this)}r(he,"S");he.prototype.c=function(){var t=this.S();try{if(8&this.f||this.x===void 0)return;var e=this.x();typeof e=="function"&&(this.u=e)}finally{t()}};he.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,Ln(this),Tn(this),ne++;var t=A;return A=this,Mi.bind(this,t)};he.prototype.N=function(){2&this.f||(this.f|=2,this.o=we,we=this)};he.prototype.d=function(){this.f|=8,1&this.f||Rt(this)};he.prototype.dispose=function(){this.d()};function z(t,e){var n=new he(t,e);try{n.c()}catch(i){throw n.d(),i}var s=n.d.bind(n);return s[Symbol.dispose]=s,s}r(z,"m");var $i=/\/products\/([^/?#]+)(?:\?(?:[^#]*?&)?variant=(\d+))?/,At=r(t=>{let e=t.match($i);return e?{productHandle:e[1],variantId:e[2]}:null},"parseProductUrl"),_n=r(({source:t,onProductUrlChange:e})=>{let n=r(s=>{let i=At(s);i?.productHandle&&e(i)},"handleChange");if(t instanceof HTMLAnchorElement)return fn({element:t,onHrefChange:r(s=>n(s),"onHrefChange")});if(t instanceof Location)return pe({onLocationChange:r(s=>n(s.href),"onLocationChange")});throw new Error("Invalid source for observing product url")},"observeProductUrl");var On=r(t=>e=>{let{productHandle:n,productId:s,variantId:i,itemId:a}=e?.dataset??{},c=!!(s||n)||!!a,p=$({loading:!1,productId:s,variantId:i,itemId:a});if(!c){let l=e instanceof HTMLAnchorElement?e:window.location,h=At(l.href);h?.productHandle&&h.productHandle!==p.value.productHandle&&(p.value={...p.value,...h,productId:void 0},_n({source:l,onProductUrlChange:r(y=>{p.value={...p.value,...y,productId:y.productHandle!==p.value.productHandle?void 0:p.value.productId}},"onProductUrlChange")}))}return z(()=>{p.value.loading||!p.value.productId&&p.value.productHandle&&(p.value={...p.value,loading:!0},t.storefront.loadProductId({productHandle:p.value.productHandle}).then(l=>{l.errors&&console.error("Error loading product id",l.errors),p.value={...p.value,productId:l.data?.product?.id?P(l.data.product.id):void 0,loading:!1}}))}),p},"itemContextSignal");var qn=r(t=>e=>{let n=j(()=>{let{productId:L,variantId:b,loading:T}=e.value;return!L||T?null:b?`variant:${P(b)}`:`product:${P(L)}`}),s=j(()=>e.value.loading||!!e.value.itemId||!e.value.productId),i=j(()=>({limit:1,query:n.value??void 0})),a=$(!s.value),o=$(null),u=$(!1),c=$(!1),{data:p,loading:l,error:h,refetching:y}=t.state.swishQuery(L=>t.api.items.list(L),{refetch:["item-create","item-update","item-delete"],variables:i,skip:s}),f=$(e.value.itemId??null);z(()=>{se(()=>{if(a.value=l.value,o.value=h.value,!e.value.itemId){let L=p.value?.[0]?.id??null;L!==f.value&&(f.value=L)}})});async function E(){if(!f.value)return;u.value=!0;let b=await(await t.intents.invoke("unsave:item",{itemId:f.value})).complete;b.code==="ok"&&"itemId"in b.data&&(f.value=null),u.value=!1}r(E,"unsave");async function g(){if(!f.value)return;u.value=!0;let b=await(await t.intents.invoke("edit:item-lists",{itemId:f.value})).complete;b.code==="ok"&&"itemId"in b.data&&(f.value=null),u.value=!1}r(g,"update");async function _(){let{productId:L,variantId:b}=e.value;if(!L)return;u.value=!0,c.value=!0;let x=await(await t.intents.invoke("save:item",{productId:L,variantId:b})).complete;if(x.code==="ok"){let te=x.data;f.value=te.item.id,u.value=!1}else x.code==="error"&&console.warn("Failed to create item",x),se(()=>{u.value=!1,c.value=!1})}r(_,"save");let B=j(()=>a.value||u.value||e.value.loading);z(()=>{c.value&&!u.value&&!y.value&&(c.value=!1)});let O=j(()=>{let L=y.value&&c.value,b=!!f.value,T=!b&&(u.value||L),x=b&&(u.value||L),te=j(()=>T?"saving":x?"unsaving":b?"saved":"unsaved");return{error:o.value,status:te.value,savedItemId:f.value,loading:B.value,submitting:u.value,saved:b,saving:T,unsaving:x}});async function H(){B.value||(O.value.saved&&O.value.savedItemId?E():O.value.saved||await _())}return r(H,"toggle"),Object.assign(O,{save:_,unsave:E,update:g,toggle:H})},"itemStateSignal");var Mn=r(t=>()=>{let{data:e,loading:n,error:s}=t.state.swishQuery(()=>t.api.items.count(),{refetch:["item-create","item-delete"]}),i=$(0),a=$(!0),o=$(null);return z(()=>{se(()=>{a.value=n.value,o.value=s.value,i.value=e.value?.count??0})}),j(()=>({count:i.value,loading:a.value,error:o.value}))},"itemCountSignal");var Ni="token-update",$n=r(t=>(e,n)=>{let s=$(null),i=$(null),a=$(null),o=$(!n?.skip),u=$(!1),c=j(()=>o.value&&u.value);async function p(){if(!n?.skip?.value)try{o.value=!0;let l=await e(n?.variables?.value);se(()=>{a.value="error"in l?l.error:null,s.value="data"in l?l.data:null,i.value="pageInfo"in l?l.pageInfo:null,o.value=!1,u.value=!0})}catch(l){se(()=>{a.value=l,o.value=!1,u.value=!0})}}return r(p,"executeFetch"),z(()=>{if(p(),n?.refetch?.length){let l=[...n.refetch,Ni];return t.events.subscribe(l,p)}}),{data:s,pageInfo:i,error:a,loading:o,refetching:c}},"swishQuerySignals");var ce="GraphQL Client";var Pt="An error occurred while fetching from the API. Review 'graphQLErrors' for details.",Tt="Response returned unexpected Content-Type:",Dt="An unknown error has occurred. The API did not return a data object or any errors in its response.",lt={json:"application/json",multipart:"multipart/mixed"},Lt="X-SDK-Variant",_t="X-SDK-Version",Bn="shopify-graphql-client",Un="1.4.1",pt=1e3,Vn=[429,503],Ot=/@(defer)\b/i,Nn=`\r
|
|
8
|
-
`,Fn=/boundary="?([^=";]+)"?/i,qt=Nn+Nn;function X(t,e=ce){return t.startsWith(`${e}`)?t:`${e}: ${t}`}r(X,"formatErrorMessage");function Z(t){return t instanceof Error?t.message:JSON.stringify(t)}r(Z,"getErrorMessage");function Mt(t){return t instanceof Error&&t.cause?t.cause:void 0}r(Mt,"getErrorCause");function $t(t){return t.flatMap(({errors:e})=>e??[])}r($t,"combineErrors");function dt({client:t,retries:e}){if(e!==void 0&&(typeof e!="number"||e<0||e>3))throw new Error(`${t}: The provided "retries" value (${e}) is invalid - it cannot be less than ${0} or greater than ${3}`)}r(dt,"validateRetries");function F(t,e){return e&&(typeof e!="object"||Array.isArray(e)||typeof e=="object"&&Object.keys(e).length>0)?{[t]:e}:{}}r(F,"getKeyValueIfValid");function Nt(t,e){if(t.length===0)return e;let s={[t.pop()]:e};return t.length===0?s:Nt(t,s)}r(Nt,"buildDataObjectByPath");function Gn(t,e){return Object.keys(e||{}).reduce((n,s)=>(typeof e[s]=="object"||Array.isArray(e[s]))&&t[s]?(n[s]=Gn(t[s],e[s]),n):(n[s]=e[s],n),Array.isArray(t)?[...t]:{...t})}r(Gn,"combineObjects");function Bt([t,...e]){return e.reduce(Gn,{...t})}r(Bt,"buildCombinedDataObject");function Ut({clientLogger:t,customFetchApi:e=fetch,client:n=ce,defaultRetryWaitTime:s=pt,retriableCodes:i=Vn}){let a=r(async(o,u,c)=>{let p=u+1,l=c+1,h;try{if(h=await e(...o),t({type:"HTTP-Response",content:{requestParams:o,response:h}}),!h.ok&&i.includes(h.status)&&p<=l)throw new Error;let y=h?.headers.get("X-Shopify-API-Deprecated-Reason")||"";return y&&t({type:"HTTP-Response-GraphQL-Deprecation-Notice",content:{requestParams:o,deprecationNotice:y}}),h}catch(y){if(p<=l){let f=h?.headers.get("Retry-After");return await Bi(f?parseInt(f,10):s),t({type:"HTTP-Retry",content:{requestParams:o,lastResponse:h,retryAttempt:u,maxRetries:c}}),a(o,p,c)}throw new Error(X(`${c>0?`Attempted maximum number of ${c} network retries. Last message - `:""}${Z(y)}`,n))}},"httpFetch");return a}r(Ut,"generateHttpFetch");async function Bi(t){return new Promise(e=>setTimeout(e,t))}r(Bi,"sleep");function Vt({headers:t,url:e,customFetchApi:n=fetch,retries:s=0,logger:i}){dt({client:ce,retries:s});let a={headers:t,url:e,retries:s},o=Ui(i),u=Ut({customFetchApi:n,clientLogger:o,defaultRetryWaitTime:pt}),c=Vi(u,a),p=Fi(c),l=Ki(c);return{config:a,fetch:c,request:p,requestStream:l}}r(Vt,"createGraphQLClient");function Ui(t){return e=>{t&&t(e)}}r(Ui,"generateClientLogger");async function zn(t){let{errors:e,data:n,extensions:s}=await t.json();return{...F("data",n),...F("extensions",s),headers:t.headers,...e||!n?{errors:{networkStatusCode:t.status,message:X(e?Pt:Dt),...F("graphQLErrors",e),response:t}}:{}}}r(zn,"processJSONResponse");function Vi(t,{url:e,headers:n,retries:s}){return async(i,a={})=>{let{variables:o,headers:u,url:c,retries:p,keepalive:l,signal:h}=a,y=JSON.stringify({query:i,variables:o});dt({client:ce,retries:p});let f=Object.entries({...n,...u}).reduce((g,[_,B])=>(g[_]=Array.isArray(B)?B.join(", "):B.toString(),g),{});return!f[Lt]&&!f[_t]&&(f[Lt]=Bn,f[_t]=Un),t([c??e,{method:"POST",headers:f,body:y,signal:h,keepalive:l}],1,p??s)}}r(Vi,"generateFetch");function Fi(t){return async(...e)=>{if(Ot.test(e[0]))throw new Error(X("This operation will result in a streamable response - use requestStream() instead."));let n=null;try{n=await t(...e);let{status:s,statusText:i}=n,a=n.headers.get("content-type")||"";return n.ok?a.includes(lt.json)?await zn(n):{errors:{networkStatusCode:s,message:X(`${Tt} ${a}`),response:n}}:{errors:{networkStatusCode:s,message:X(i),response:n}}}catch(s){return{errors:{message:Z(s),...n==null?{}:{networkStatusCode:n.status,response:n}}}}}}r(Fi,"generateRequest");async function*ji(t){let e=new TextDecoder;if(t.body[Symbol.asyncIterator])for await(let n of t.body)yield e.decode(n);else{let n=t.body.getReader(),s;try{for(;!(s=await n.read()).done;)yield e.decode(s.value)}finally{n.cancel()}}}r(ji,"getStreamBodyIterator");function Hi(t,e){return{async*[Symbol.asyncIterator](){try{let n="";for await(let s of t)if(n+=s,n.indexOf(e)>-1){let i=n.lastIndexOf(e),o=n.slice(0,i).split(e).filter(u=>u.trim().length>0).map(u=>u.slice(u.indexOf(qt)+qt.length).trim());o.length>0&&(yield o),n=n.slice(i+e.length),n.trim()==="--"&&(n="")}}catch(n){throw new Error(`Error occured while processing stream payload - ${Z(n)}`)}}}}r(Hi,"readStreamChunk");function Gi(t){return{async*[Symbol.asyncIterator](){yield{...await zn(t),hasNext:!1}}}}r(Gi,"createJsonResponseAsyncIterator");function zi(t){return t.map(e=>{try{return JSON.parse(e)}catch(n){throw new Error(`Error in parsing multipart response - ${Z(n)}`)}}).map(e=>{let{data:n,incremental:s,hasNext:i,extensions:a,errors:o}=e;if(!s)return{data:n||{},...F("errors",o),...F("extensions",a),hasNext:i};let u=s.map(({data:c,path:p,errors:l})=>({data:c&&p?Nt(p,c):{},...F("errors",l)}));return{data:u.length===1?u[0].data:Bt([...u.map(({data:c})=>c)]),...F("errors",$t(u)),hasNext:i}})}r(zi,"getResponseDataFromChunkBodies");function Wi(t,e){if(t.length>0)throw new Error(Pt,{cause:{graphQLErrors:t}});if(Object.keys(e).length===0)throw new Error(Dt)}r(Wi,"validateResponseData");function Qi(t,e){let n=(e??"").match(Fn),s=`--${n?n[1]:"-"}`;if(!t.body?.getReader&&!t.body?.[Symbol.asyncIterator])throw new Error("API multipart response did not return an iterable body",{cause:t});let i=ji(t),a={},o;return{async*[Symbol.asyncIterator](){try{let u=!0;for await(let c of Hi(i,s)){let p=zi(c);o=p.find(h=>h.extensions)?.extensions??o;let l=$t(p);a=Bt([a,...p.map(({data:h})=>h)]),u=p.slice(-1)[0].hasNext,Wi(l,a),yield{...F("data",a),...F("extensions",o),hasNext:u}}if(u)throw new Error("Response stream terminated unexpectedly")}catch(u){let c=Mt(u);yield{...F("data",a),...F("extensions",o),errors:{message:X(Z(u)),networkStatusCode:t.status,...F("graphQLErrors",c?.graphQLErrors),response:t},hasNext:!1}}}}}r(Qi,"createMultipartResponseAsyncInterator");function Ki(t){return async(...e)=>{if(!Ot.test(e[0]))throw new Error(X("This operation does not result in a streamable response - use request() instead."));try{let n=await t(...e),{statusText:s}=n;if(!n.ok)throw new Error(s,{cause:n});let i=n.headers.get("content-type")||"";switch(!0){case i.includes(lt.json):return Gi(n);case i.includes(lt.multipart):return Qi(n,i);default:throw new Error(`${Tt} ${i}`,{cause:n})}}catch(n){return{async*[Symbol.asyncIterator](){let s=Mt(n);yield{errors:{message:X(Z(n)),...F("networkStatusCode",s?.status),...F("response",s)},hasNext:!1}}}}}}r(Ki,"generateRequestStream");function Ft({client:t,storeDomain:e}){try{if(!e||typeof e!="string")throw new Error;let n=e.trim(),s=n.match(/^https?:/)?n:`https://${n}`,i=new URL(s);return i.protocol="https",i.origin}catch(n){throw new Error(`${t}: a valid store domain ("${e}") must be provided`,{cause:n})}}r(Ft,"validateDomainAndGetStoreUrl");function ht({client:t,currentSupportedApiVersions:e,apiVersion:n,logger:s}){let i=`${t}: the provided apiVersion ("${n}")`,a=`Currently supported API versions: ${e.join(", ")}`;if(!n||typeof n!="string")throw new Error(`${i} is invalid. ${a}`);let o=n.trim();e.includes(o)||(s?s({type:"Unsupported_Api_Version",content:{apiVersion:n,supportedApiVersions:e}}):console.warn(`${i} is likely deprecated or not supported. ${a}`))}r(ht,"validateApiVersion");function ft(t){let e=t*3-2;return e===10?e:`0${e}`}r(ft,"getQuarterMonth");function jt(t,e,n){let s=e-n;return s<=0?`${t-1}-${ft(s+4)}`:`${t}-${ft(s)}`}r(jt,"getPrevousVersion");function Wn(){let t=new Date,e=t.getUTCMonth(),n=t.getUTCFullYear(),s=Math.floor(e/3+1);return{year:n,quarter:s,version:`${n}-${ft(s)}`}}r(Wn,"getCurrentApiVersion");function Ht(){let{year:t,quarter:e,version:n}=Wn(),s=e===4?`${t+1}-01`:`${t}-${ft(e+1)}`;return[jt(t,e,3),jt(t,e,2),jt(t,e,1),n,s,"unstable"]}r(Ht,"getCurrentSupportedApiVersions");function Gt(t){return e=>({...e??{},...t.headers})}r(Gt,"generateGetHeaders");function zt({getHeaders:t,getApiUrl:e}){return(n,s)=>{let i=[n];if(s&&Object.keys(s).length>0){let{variables:a,apiVersion:o,headers:u,retries:c,signal:p}=s;i.push({...a?{variables:a}:{},...u?{headers:t(u)}:{},...o?{url:e(o)}:{},...c?{retries:c}:{},...p?{signal:p}:{}})}return i}}r(zt,"generateGetGQLClientParams");var Wt="application/json",Qn="storefront-api-client",Kn="1.0.9",Xn="X-Shopify-Storefront-Access-Token",Jn="Shopify-Storefront-Private-Token",Yn="X-SDK-Variant",Zn="X-SDK-Version",es="X-SDK-Variant-Source",le="Storefront API Client";function ts(t){if(t&&typeof window<"u")throw new Error(`${le}: private access tokens and headers should only be used in a server-to-server implementation. Use the public API access token in nonserver environments.`)}r(ts,"validatePrivateAccessTokenUsage");function ns(t,e){if(!t&&!e)throw new Error(`${le}: a public or private access token must be provided`);if(t&&e)throw new Error(`${le}: only provide either a public or private access token`)}r(ns,"validateRequiredAccessTokens");function Qt({storeDomain:t,apiVersion:e,publicAccessToken:n,privateAccessToken:s,clientName:i,retries:a=0,customFetchApi:o,logger:u}){let c=Ht(),p=Ft({client:le,storeDomain:t}),l={client:le,currentSupportedApiVersions:c,logger:u};ht({...l,apiVersion:e}),ns(n,s),ts(s);let h=Xi(p,e,l),y={storeDomain:p,apiVersion:e,...n?{publicAccessToken:n}:{privateAccessToken:s},headers:{"Content-Type":Wt,Accept:Wt,[Yn]:Qn,[Zn]:Kn,...i?{[es]:i}:{},...n?{[Xn]:n}:{[Jn]:s}},apiUrl:h(),clientName:i},f=Vt({headers:y.headers,url:y.apiUrl,retries:a,customFetchApi:o,logger:u}),E=Gt(y),g=Ji(y,h),_=zt({getHeaders:E,getApiUrl:g});return Object.freeze({config:y,getHeaders:E,getApiUrl:g,fetch:r((...O)=>f.fetch(..._(...O)),"fetch"),request:r((...O)=>f.request(..._(...O)),"request"),requestStream:r((...O)=>f.requestStream(..._(...O)),"requestStream")})}r(Qt,"createStorefrontApiClient");function Xi(t,e,n){return s=>{s&&ht({...n,apiVersion:s});let i=(s??e).trim();return`${t}/api/${i}/graphql.json`}}r(Xi,"generateApiUrlFormatter");function Ji(t,e){return n=>n?e(n):t.apiUrl}r(Ji,"generateGetApiUrl");var fe=`
|
|
7
|
+
`+String(s)));Gn(e);for(var i=0;i<e.callbacks.length;i++){var o=s[i];o instanceof Error?e.callbacks[i].reject(o):e.callbacks[i].resolve(o)}}).catch(function(s){Qn(t,e,s)})}r(tu,"dispatchBatch");function Qn(t,e,n){Gn(e);for(var s=0;s<e.keys.length;s++)t.clear(e.keys[s]),e.callbacks[s].reject(n)}r(Qn,"failedDispatch");function Gn(t){if(t.cacheHits)for(var e=0;e<t.cacheHits.length;e++)t.cacheHits[e]()}r(Gn,"resolveCacheHits");function nu(t){var e=!t||t.batch!==!1;if(!e)return 1;var n=t&&t.maxBatchSize;if(n===void 0)return 1/0;if(typeof n!="number"||n<1)throw new TypeError("maxBatchSize must be a positive number: "+n);return n}r(nu,"getValidMaxBatchSize");function su(t){var e=t&&t.batchScheduleFn;if(e===void 0)return Za;if(typeof e!="function")throw new TypeError("batchScheduleFn must be a function: "+e);return e}r(su,"getValidBatchScheduleFn");function iu(t){var e=t&&t.cacheKeyFn;if(e===void 0)return function(n){return n};if(typeof e!="function")throw new TypeError("cacheKeyFn must be a function: "+e);return e}r(iu,"getValidCacheKeyFn");function ru(t){var e=!t||t.cache!==!1;if(!e)return null;var n=t&&t.cacheMap;if(n===void 0)return new Map;if(n!==null){var s=["get","set","delete","clear"],i=s.filter(function(o){return n&&typeof n[o]!="function"});if(i.length!==0)throw new TypeError("Custom cacheMap missing methods: "+i.join(", "))}return n}r(ru,"getValidCacheMap");function ou(t){return t&&t.name?t.name:null}r(ou,"getValidName");function Hi(t){return typeof t=="object"&&t!==null&&typeof t.length=="number"&&(t.length===0||t.length>0&&Object.prototype.hasOwnProperty.call(t,t.length-1))}r(Hi,"isArrayLike");Qi.exports=Ya});function Yn(t,e="",n=new Map){for(let[s,i]of Object.entries(t)){let o=e?`${e}.${s}`:s;typeof i=="object"&&i!==null?Yn(i,o,n):typeof i=="string"&&n.set(o,i)}return n}r(Yn,"u");function sr(t,e,n){let{isTranslatable:s,key:i}=Zt(e);return s?(e=Zn(i,n),t.has(e)):!1}r(sr,"T");function Xn(t,e,n){let{isTranslatable:s,key:i}=Zt(e);if(!s)return e;e=Zn(i,n);let o=t.get(e)??e;return n&&(n.count!==void 0&&(o=o.replace("{{count}}",n.count.toString())),Object.entries(n).forEach(([a,u])=>{a!=="count"&&typeof u=="string"&&(o=o.replace(`{{${a}}}`,u))})),o}r(Xn,"d");var Jn="i18n:";function Zt(t){if(!t.startsWith(Jn))return{isTranslatable:!1,key:null};let e=t.slice(Jn.length).trim();return e?{isTranslatable:!0,key:e}:{isTranslatable:!1,key:null}}r(Zt,"f");function Zn(t,e){return e?.count===void 0?t:e.count===1?`${t}One`:`${t}Other`}r(Zn,"L");var ir=new Set(["en"]),Te="en";function es(t,e){let n=null;async function s(o){let a=await import(`${t}/locales/${o.toLowerCase()}.js`);return Yn(a.default)}r(s,"i");function i(o,a){let{isTranslatable:u,key:c}=Zt(o);return u?n?sr(n,o,a)?{status:"ready",value:Xn(n,o,a),key:c}:{status:"missing",value:Xn(n,o,a),key:c}:{status:"pending",value:c,key:c}:{status:"ready",value:o,key:o}}return r(i,"s"),{t(o,a){return i(o,a).value},resolveTranslation:i,async loadLocale(o){let a=o;ir.has(o)||(console.warn(`[swish] Unsupported language "${o}", falling back to "${Te}".`),a=Te);let u;try{u=await s(a)}catch(c){if(console.warn(`[swish-i18n] Failed to load locale "${a}".`,c),a!==Te)try{u=await s(Te)}catch{console.warn(`[swish] Failed to load fallback locale "${Te}".`);return}else return}if(e?.[a])for(let[c,p]of Object.entries(e[a]))p!==void 0&&u.set(c,p);n=u}}}r(es,"m");var O=r(t=>t.split("/").pop()??"","shopifyGidToId"),pe=r((t,e)=>`gid://shopify/${t}/${e}`,"shopifyIdToGid"),Z=r(t=>t.toLowerCase().replace(".myshopify.com",""),"toShopName");var de=class{constructor(e,n,s=""){this.revalidationPromises=new Map;this.inFlightRequests=new Map;this.clearCachePromise=null;this.cacheName=e,this.defaultCacheControl=n,this.keyPrefix=s}static{r(this,"FetchCache")}async get(e){try{let n=await caches.open(this.cacheName),s=await n.match(e);if(s&&this.isExpired(s)){await n.delete(e);return}return s}catch(n){console.warn("Cache get error:",n);return}}async set(e,n,s){try{if(s?.includes("no-cache"))return;let i=this.createCacheableResponse(n,s);await(await caches.open(this.cacheName)).put(e,i)}catch(i){console.warn("Cache set error:",i)}}async fetchWithCache(e,n,s){let i=await this.getCacheKey(e,n);if(this.clearCachePromise&&await this.clearCachePromise,this.inFlightRequests.has(i))return this.inFlightRequests.get(i).then(a=>a.clone());let o=(async()=>{let a=await this.get(i);if(a)return this.isStaleButRevalidatable(a)&&this.revalidateInBackground(i,e,n,s),a.clone();let u=await fetch(e,n);return u.ok&&await this.set(i,u.clone(),s??this.defaultCacheControl),u})().finally(()=>{this.inFlightRequests.delete(i)});return this.inFlightRequests.set(i,o),o}async delete(e){try{return await(await caches.open(this.cacheName)).delete(e)}catch(n){return console.warn("Cache delete error:",n),!1}}async clear(){return this.clearCachePromise?this.clearCachePromise:(this.clearCachePromise=new Promise(async(e,n)=>{try{let s=await caches.open(this.cacheName),i=await s.keys();await Promise.all(i.map(o=>s.delete(o))),e()}catch(s){console.warn("Cache clear error:",s),n(s)}}),this.clearCachePromise.then(()=>{this.clearCachePromise=null}).catch(e=>{console.warn("Cache clear error:",e)}))}async keys(){try{return(await(await caches.open(this.cacheName)).keys()).map(s=>s.url)}catch(e){return console.warn("Cache keys error:",e),[]}}async has(e){try{let n=await caches.open(this.cacheName),s=await n.match(e);return s&&this.isExpired(s)?(await n.delete(e),!1):s!==void 0}catch(n){return console.warn("Cache has error:",n),!1}}async getStats(){try{return{total:(await(await caches.open(this.cacheName)).keys()).length}}catch(e){return console.warn("Cache stats error:",e),{total:0}}}async cleanupExpiredEntries(){try{let e=await caches.open(this.cacheName),n=await e.keys(),s=0;for(let o of n){let a=await e.match(o);a&&this.isExpired(a)&&(await e.delete(o),s++)}let i=n.length-s;return{removed:s,remaining:i}}catch(e){return console.warn("Cache cleanup error:",e),{removed:0,remaining:0}}}async getCacheKey(e,n){let s=this.getInputUrl(e),i=`${this.keyPrefix}${s}/${JSON.stringify(n)}`,a=new TextEncoder().encode(i),u=await crypto.subtle.digest("SHA-256",a);return`/${Array.from(new Uint8Array(u)).map(l=>l.toString(16).padStart(2,"0")).join("")}`}getInputUrl(e){return e instanceof URL?e.toString():typeof e=="string"?e:e.url}isExpired(e){let n=e.headers.get("Cache-Control");if(!n)return!1;let s=this.parseMaxAge(n),i=this.parseStaleWhileRevalidate(n);if(s===null)return!1;let o=e.headers.get("Date");if(!o)return!1;let a=new Date(o).getTime(),c=(Date.now()-a)/1e3,p=s+(i??0);return c>p}isStaleButRevalidatable(e){let n=e.headers.get("Cache-Control");if(!n)return!1;let s=this.parseMaxAge(n),i=this.parseStaleWhileRevalidate(n);if(s===null||i===null)return!1;let o=e.headers.get("Date");if(!o)return!1;let a=new Date(o).getTime(),c=(Date.now()-a)/1e3;return c>s&&c<=s+i}async revalidateInBackground(e,n,s,i){if(this.revalidationPromises.has(e))return;let o=(async()=>{try{let a=await fetch(n,s);a.ok&&await this.set(e,a.clone(),i??this.defaultCacheControl)}catch(a){console.warn("Background revalidation error:",a)}finally{this.revalidationPromises.delete(e)}})();this.revalidationPromises.set(e,o)}parseMaxAge(e){let n=new RegExp(/max-age=(\d+)/).exec(e);return n?parseInt(n[1],10):null}parseStaleWhileRevalidate(e){let n=new RegExp(/stale-while-revalidate=(\d+)/).exec(e);return n?parseInt(n[1],10):null}createCacheableResponse(e,n){let s=new Headers(e.headers);return s.set("Cache-Control",n),s.has("Date")||s.set("Date",new Date().toUTCString()),new Response(e.body,{status:e.status,statusText:e.statusText,headers:s})}};var je=class{static{r(this,"AjaxApiClient")}constructor(e){this.config=e;let n=Z(e.storeDomain);this.cache=new de(`ajax-api-${n}`,"max-age=60, stale-while-revalidate=3600"),this.cache.cleanupExpiredEntries().catch(s=>{console.warn("Ajax API cache initialization cleanup error:",s)})}patchFetch(){if(!window.fetch||typeof window.fetch!="function")return;let e=window.fetch,n=this.config.responseInterceptor,s=this.getFetchRequest.bind(this);window.fetch=function(...i){let o=e.apply(this,i);if(typeof n=="function"){let a=s(i[0]);o.then(u=>n(u,a))}return o}}getFetchRequest(e){return e instanceof Request?e:new Request(e)}getBaseUrl(){if(!this.config?.storeDomain)throw new Error("Cart API client not initialized - missing store domain");return`https://${this.config.storeDomain}`}fetch(e,n){return(e instanceof Request?e.method:n?.method??"GET")==="GET"?this.cache.fetchWithCache(e,n):fetch(e,n)}async request(e,n={}){let s=`${this.getBaseUrl()}${e}`,i={"Content-Type":"application/json",Accept:"application/json"},o=await this.fetch(s,{...n,headers:{...i,...n.headers}});if(!o.ok){let a;try{a=await o.json()}catch{a={message:`HTTP ${o.status}: ${o.statusText}`,status:o.status.toString(),description:o.statusText}}throw new Error(a.message||a.description)}return o.json()}async fetchCart(){return this.request("/cart.js")}async addToCart(e){let n={...e,items:e.items.map(s=>{let i=Number(O(String(s.id)));if(!Number.isFinite(i)||i<=0)throw new Error(`Invalid Shopify ID: ${s.id}`);return{...s,id:i}})};return this.request("/cart/add.js",{method:"POST",body:JSON.stringify(n)})}async clearCache(){await this.cache.clear()}};var $e=class{constructor(e){this.eventMap={"/cart/add":"cart-add","/cart/update":"cart-update","/cart/change":"cart-change","/cart/clear":"cart-clear"};this.eventBus=e,this.processFetchResponse=this.processFetchResponse.bind(this)}static{r(this,"AjaxApiPublisher")}async processFetchResponse(e,n){try{let s=this.getEventName(n.url);if(s){let i=await e.clone().json();this.eventBus.publish(s,i)}}catch(s){console.warn(s)}}getEventName(e){for(let[n,s]of Object.entries(this.eventMap))if(e.includes(n))return s;return null}};function rr(){let t=document.body||document.documentElement;return t?Promise.resolve(t):new Promise(e=>{window.addEventListener("DOMContentLoaded",()=>e(t))})}r(rr,"waitForDOM");function re({onElementFound:t,selector:e,observerOptions:n,mustMatch:s}){let i=new WeakSet,o=new MutationObserver(p=>{let l=!1;for(let y of p)if(y.addedNodes.length>0){l=!0;break}l&&a()}),a=r(()=>{document.querySelectorAll(e).forEach(p=>{i.has(p)||(i.add(p),s?.(p)!==!1&&u(p))})},"locateElements"),u=r(p=>{if(!n){t(p);return}let l=new IntersectionObserver(y=>{for(let h of y)h.isIntersecting&&(l.disconnect(),t(p))},n);l.observe(p)},"observeElement");return r(async()=>{let p=await rr();a(),o.observe(p,{childList:!0,subtree:!0})},"locateAndObserveElements")(),o}r(re,"createElementLocator");function Ee({onLocationChange:t,fireOnInit:e=!1}){let n=r(()=>{t(window.location)},"handleChange");window.addEventListener("popstate",n);let s=history.pushState,i=history.replaceState;return history.pushState=function(...o){s.apply(this,o),n()},history.replaceState=function(...o){i.apply(this,o),n()},e&&n(),()=>{window.removeEventListener("popstate",n),history.pushState=s,history.replaceState=i}}r(Ee,"createLocationObserver");function ns(t,e){let n=t.parentElement;for(;n;){let s=n.querySelector(e);if(s&&s!==t)return s;n=n.parentElement}return null}r(ns,"findNearestElement");function ss({element:t,onHrefChange:e}){let n=r(()=>{e(t.href)},"handleChange"),s=new MutationObserver(()=>{n()});return s.observe(t,{attributes:!0,attributeFilter:["href"]}),()=>{s.disconnect()}}r(ss,"createHrefObserver");function en(t){let e=t.getAttribute("swish-item-context");return e?e==="location"?globalThis.window?.location??t:ns(t,e)??t:t}r(en,"resolveItemContextSource");function is(t,e){return t.getAttribute("swish-item-context")?en(t):e}r(is,"resolvePlacementItemContextSource");function as(t,e){if(!e.element)throw new Error("Element must be provided");let n=null,s=new Map,i=r(()=>{if(n){console.warn("Placement already mounted. Skipping mount.");return}ar(e),n=re({selector:e.target.selector,observerOptions:e.target.observerOptions,mustMatch:e.target.mustMatch,onElementFound:r(p=>o(p),"onElementFound")})},"mount"),o=r(p=>{s.has(p)||p.hasAttribute("swish-ignore")||p.getAttribute("swish-placement-target")===e.id||(p.setAttribute("swish-placement-target",e.id),a(p))},"evaluateAndMount"),a=r(async p=>{let l=[],y=e.mount.mode,h=vr(p,e.mount.at);if(!h)return;let m=await(typeof e.element=="function"?e.element(e):Sr(t,e.element));if(!m)return;if(m.setAttribute("swish-placement-element",e.id),typeof e.element!="function"){let k=e.element;k.props&&Er(m,k.props),k.classNames&&cs(m,k.classNames)}let v;e.container&&(v=Ir(e.id,e.container),v.appendChild(m));let f,w=v??m;if(e.layout?.type==="overlay"){wr(h);let k=e.layout.anchor??"bottom-right";w.setAttribute("swish-placement-overlay",e.id),w.setAttribute("swish-placement-anchor",k)}let b=!1,T;if(e.layout?.type==="inline"){let k=e.layout,P=k.rowSelector?h.closest(k.rowSelector):null;P?f=P:(f=br(e.id,h,k),b=!0),T=f.getAttribute("swish-placement-inline-row"),f.setAttribute("swish-placement-inline-row",e.id)}let U=v??m;if(!gr(h,U,y)){try{U.remove()}catch{}return}let x={targetEl:p,renderTargetEl:h,mountEl:m,containerEl:v,rowEl:f,rowWasCreated:b,rowInlineAttrPrevValue:T,cleanupFns:l,ownsNode:!0};s.set(p,x);let D={id:e.id,targetEl:p,renderTargetEl:h,mountEl:x.mountEl,containerEl:v,rowEl:f,cleanup:r(k=>l.push(k),"cleanup")};e.element?.name==="save-button"&&or(t,D),e.onMount?.(D)},"mountElement"),u=r(p=>{let l=s.get(p);if(l){if(e.onUnmount?.({id:e.id,targetEl:l.targetEl,renderTargetEl:l.renderTargetEl,mountEl:l.mountEl,containerEl:l.containerEl,rowEl:l.rowEl}),l.cleanupFns.forEach(y=>y()),l.targetEl.getAttribute("swish-placement-target")===e.id&&l.targetEl.removeAttribute("swish-placement-target"),l.ownsNode&&(l.containerEl||l.mountEl).remove(),l.rowEl){if(l.rowWasCreated){let y=l.rowEl.parentElement;y&&l.targetEl.parentElement===l.rowEl?l.rowEl.replaceWith(l.targetEl):y?y.removeChild(l.rowEl):l.rowEl.remove()}else if(l.rowInlineAttrPrevValue!==void 0){let y=l.rowInlineAttrPrevValue;y===null?l.rowEl.removeAttribute("swish-placement-inline-row"):l.rowEl.setAttribute("swish-placement-inline-row",y)}}s.delete(p)}},"unmountElement");return{mount:i,unmount:r(()=>{n&&(n.disconnect(),n=null),s.forEach((p,l)=>u(l)),s.clear()},"unmount")}}r(as,"createPlacement");var or=r((t,{mountEl:e,targetEl:n,cleanup:s})=>{let i=is(e,n),o=t.state.itemContext(i),a=t.state.effect(()=>{let{loading:u,productId:c,variantId:p}=o.value;u||(e.setAttribute("product-id",c??""),e.setAttribute("variant-id",p??""))});s(()=>a?.())},"saveButtonMount");function ar(t){let e=ur(t.id),n=yr(t),s=document.getElementById(e);if(s){s.textContent=n;return}let i=document.createElement("style");i.id=e,i.setAttribute("swish-placement-style",t.id),i.textContent=n,document.head.appendChild(i)}r(ar,"ensurePlacementStylesheet");function ur(t){return`swish-placement-style-${cr(t)}`}r(ur,"getPlacementStyleId");function cr(t){return t.replace(/[^a-zA-Z0-9\-_]/g,"_")}r(cr,"cssEscapeId");function rs(t){return`--swish-placement-${lr(String(t))}`}r(rs,"designKeyToCSSVar");function lr(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z])([A-Z][a-z])/g,"$1-$2").toLowerCase()}r(lr,"toKebabCase");function pr(t){return Object.entries(t??{sm:500,lg:700}).map(([s,i])=>({name:s,minWidth:i})).sort((s,i)=>s.minWidth-i.minWidth)}r(pr,"getBreakpoints");function us(t,e){if(t==null)return{};if(typeof t=="object"&&!Array.isArray(t)){if(e&&e.size){let n=Object.keys(t);return"base"in t||n.some(i=>e.has(i))?t:{base:t}}return t}return{base:t}}r(us,"normalizeResponsiveValue");var dr=new Set(["fontWeight","lineHeight","pressedScale","backgroundAlpha","pressedOpacity","pressedScale"]);function os(t,e){if(e!=null)return typeof e=="number"&&!dr.has(t)?`${e}px`:String(e)}r(os,"formatDesignValue");function hr(t,e,n){if(!e)return"";let s=new Set(n.map(c=>c.name)),i=[],o={},a=Object.entries(e).map(([c,p])=>[c,p]);for(let[c,p]of a){let l=us(p,s),y=os(String(c),l.base);y!==void 0&&i.push(`${rs(c)}:${y};`);for(let h of n){let m=l[h.name],v=os(String(c),m);v!==void 0&&(o[h.name]||(o[h.name]=[]),o[h.name].push(`${rs(c)}:${v};`))}}let u=[];i.length&&u.push(`[swish-placement-element="${t}"]{${i.join("")}}`);for(let c of n){let p=o[c.name];p?.length&&u.push(`@media(min-width:${c.minWidth}px){[swish-placement-element="${t}"]{${p.join("")}}}`)}return u.join("")}r(hr,"emitDesignCSS");function He(t){return t==null?"0px":typeof t=="number"?`${t}px`:t}r(He,"formatOffsetValue");function fr(t){return t==null?"":typeof t=="number"?`${t}`:t}r(fr,"formatZIndexValue");function mr(t,e,n){let s=new Set(n.map(p=>p.name)),i=us(e,s),o=i.base??{},a=He(o.x),u=He(o.y),c=[];c.push(`[swish-placement-overlay="${t}"]{--swish-placement-offset-x:${a};--swish-placement-offset-y:${u};}`);for(let p of n){let l=i[p.name];if(!l)continue;let y=He(l.x),h=He(l.y);c.push(`@media(min-width:${p.minWidth}px){[swish-placement-overlay="${t}"]{--swish-placement-offset-x:${y};--swish-placement-offset-y:${h};}}`)}return c.join("")}r(mr,"emitOverlayOffsetCSS");function yr(t){let e=t.id,n=pr(t.breakpoints),s=`[swish-placement-inline-row="${e}"]{display:flex;flex-direction:row;align-items:center;gap:var(--swish-placement-inline-gap,8px);width:100%}[swish-placement-inline-row="${e}"]>*:not([swish-placement-element="${e}"]){flex:1;min-width:0}`,i=`[swish-placement-overlay="${e}"]{position:absolute;z-index:var(--swish-placement-overlay-z,10);transform:translate(calc(var(--swish-placement-sign-x,1)*var(--swish-placement-offset-x,0px)),calc(var(--swish-placement-sign-y,1)*var(--swish-placement-offset-y,0px)));}[swish-placement-overlay="${e}"][swish-placement-anchor="top-left"]{top:0;left:0;}[swish-placement-overlay="${e}"][swish-placement-anchor="top-right"]{top:0;right:0;}[swish-placement-overlay="${e}"][swish-placement-anchor="bottom-left"]{bottom:0;left:0;}[swish-placement-overlay="${e}"][swish-placement-anchor="bottom-right"]{bottom:0;right:0;}[swish-placement-overlay="${e}"][swish-placement-anchor$="left"]{--swish-placement-sign-x:1;}[swish-placement-overlay="${e}"][swish-placement-anchor$="right"]{--swish-placement-sign-x:-1;}[swish-placement-overlay="${e}"][swish-placement-anchor^="top"]{--swish-placement-sign-y:1;}[swish-placement-overlay="${e}"][swish-placement-anchor^="bottom"]{--swish-placement-sign-y:-1;}`,o="";if(t.layout?.type==="overlay"){let a=mr(e,t.layout.offset,n),u=t.layout.zIndex?`[swish-placement-overlay="${e}"]{--swish-placement-overlay-z:${fr(t.layout.zIndex)};}`:"";o+=a+u+i}else t.layout?.type==="inline"&&(o+=s);if(t.design){let a=hr(e,t.design,n);a&&(o+=a)}return t.css&&(o+=t.css.trim()),o}r(yr,"buildPlacementCSS");function vr(t,e){if(!e||e==="target")return t;if("closest"in e)return t.closest(e.closest);if("query"in e)return t.querySelector(e.query);if("withinClosest"in e){let n=t.closest(e.withinClosest.root);return n?n.querySelector(e.withinClosest.selector):null}return t}r(vr,"resolveMountTarget");function gr(t,e,n){switch(n){case"before":return t.parentElement?(t.before(e),!0):!1;case"after":{let s=t.parentElement;return s?(s.insertBefore(e,t.nextSibling),!0):!1}case"append":return t.appendChild(e),!0;case"prepend":return t.insertBefore(e,t.firstChild),!0;case"replace":return t.parentElement?(t.replaceWith(e),!0):!1}}r(gr,"insertIntoDOM");function wr(t){let e=t.parentElement;return e?(window.getComputedStyle(e).position==="static"&&(e.style.position="relative"),e):null}r(wr,"ensureRelativeParent");function br(t,e,n){if(!e.parentElement)throw new Error("Cannot inline-wrap: refEl has no parentElement");let i=document.createElement("div");return i.setAttribute("swish-placement-inline-row",t),e.before(i),i.appendChild(e),i}r(br,"wrapWithFlexRow");function Ir(t,e){let n=e.tag||"div",s=document.createElement(n);return s.setAttribute("swish-placement-container",t),e.classNames&&cs(s,e.classNames),s}r(Ir,"createContainer");function Sr(t,e){return t.ui.createElement(e.name,{})}r(Sr,"createElement");function Er(t,e){for(let[n,s]of Object.entries(e)){let i=n.replace(/([A-Z])/g,"-$1").toLowerCase();s===!1||s===void 0||s===null||(s===!0?t.setAttribute(i,"true"):t.setAttribute(i,String(s)))}}r(Er,"applyProps");function cs(t,e){t.classList.add(...e)}r(cs,"applyClassNames");var Qe=class{constructor(){this.eventBus=new EventTarget}static{r(this,"EventBus")}subscribe(e,n,s){return Array.isArray(e)||(e=[e]),e.forEach(i=>{this.eventBus.addEventListener(i,n,s)}),()=>{e.forEach(i=>{this.eventBus.removeEventListener(i,n,s)})}}unsubscribe(e,n,s){this.eventBus.removeEventListener(e,n,s)}publish(e,n){this.eventBus.dispatchEvent(new CustomEvent(e,{detail:n}))}};var kr=/\/products\/([^/?#]+)(?:\?(?:[^#]*?&)?variant=(\d+))?/,De=r(t=>{let e=t.match(kr);return e?{productHandle:decodeURIComponent(e[1]),variantId:e[2]}:null},"parseProductUrl"),ls=r(({source:t,onProductUrlChange:e})=>{let n=r(s=>{let i=De(s);i?.productHandle&&e(i)},"handleChange");if(t instanceof HTMLAnchorElement)return ss({element:t,onHrefChange:r(s=>n(s),"onHrefChange")});if(t instanceof Location)return Ee({onLocationChange:r(s=>n(s.href),"onLocationChange")});throw new Error("Invalid source for observing product url")},"observeProductUrl");var tn;function ds(t){return{lang:t?.lang??tn?.lang,message:t?.message,abortEarly:t?.abortEarly??tn?.abortEarly,abortPipeEarly:t?.abortPipeEarly??tn?.abortPipeEarly}}r(ds,"getGlobalConfig");var xr;function Cr(t){return xr?.get(t)}r(Cr,"getGlobalMessage");var Rr;function Pr(t){return Rr?.get(t)}r(Pr,"getSchemaMessage");var Ar;function Tr(t,e){return Ar?.get(t)?.get(e)}r(Tr,"getSpecificMessage");function Ge(t){let e=typeof t;return e==="string"?`"${t}"`:e==="number"||e==="bigint"||e==="boolean"?`${t}`:e==="object"||e==="function"?(t&&Object.getPrototypeOf(t)?.constructor?.name)??"null":e}r(Ge,"_stringify");function te(t,e,n,s,i){let o=i&&"input"in i?i.input:n.value,a=i?.expected??t.expects??null,u=i?.received??Ge(o),c={kind:t.kind,type:t.type,input:o,expected:a,received:u,message:`Invalid ${e}: ${a?`Expected ${a} but r`:"R"}eceived ${u}`,requirement:t.requirement,path:i?.path,issues:i?.issues,lang:s.lang,abortEarly:s.abortEarly,abortPipeEarly:s.abortPipeEarly},p=t.kind==="schema",l=i?.message??t.message??Tr(t.reference,c.lang)??(p?Pr(c.lang):null)??s.message??Cr(c.lang);l!==void 0&&(c.message=typeof l=="function"?l(c):l),p&&(n.typed=!1),n.issues?n.issues.push(c):n.issues=[c]}r(te,"_addIssue");function he(t){return{version:1,vendor:"valibot",validate(e){return t["~run"]({value:e},ds())}}}r(he,"_getStandardProps");function hs(t,e){let n=[...new Set(t)];return n.length>1?`(${n.join(` ${e} `)})`:n[0]??"never"}r(hs,"_joinExpects");function Le(t,e){return{kind:"validation",type:"min_length",reference:Le,async:!1,expects:`>=${t}`,requirement:t,message:e,"~run"(n,s){return n.typed&&n.value.length<this.requirement&&te(this,"length",n,s,{received:`${n.value.length}`}),n}}}r(Le,"minLength");function ne(t,e){return{kind:"validation",type:"min_value",reference:ne,async:!1,expects:`>=${t instanceof Date?t.toJSON():Ge(t)}`,requirement:t,message:e,"~run"(n,s){return n.typed&&!(n.value>=this.requirement)&&te(this,"value",n,s,{received:n.value instanceof Date?n.value.toJSON():Ge(n.value)}),n}}}r(ne,"minValue");function q(t){return{kind:"transformation",type:"transform",reference:q,async:!1,operation:t,"~run"(e){return e.value=this.operation(e.value),e}}}r(q,"transform");function Dr(t,e,n){return typeof t.fallback=="function"?t.fallback(e,n):t.fallback}r(Dr,"getFallback");function fs(t,e,n){return typeof t.default=="function"?t.default(e,n):t.default}r(fs,"getDefault");function ge(t,e){return{kind:"schema",type:"array",reference:ge,expects:"Array",async:!1,item:t,message:e,get"~standard"(){return he(this)},"~run"(n,s){let i=n.value;if(Array.isArray(i)){n.typed=!0,n.value=[];for(let o=0;o<i.length;o++){let a=i[o],u=this.item["~run"]({value:a},s);if(u.issues){let c={type:"array",origin:"value",input:i,key:o,value:a};for(let p of u.issues)p.path?p.path.unshift(c):p.path=[c],n.issues?.push(p);if(n.issues||(n.issues=u.issues),s.abortEarly){n.typed=!1;break}}u.typed||(n.typed=!1),n.value.push(u.value)}}else te(this,"type",n,s);return n}}}r(ge,"array");function nn(t){return{kind:"schema",type:"boolean",reference:nn,expects:"boolean",async:!1,message:t,get"~standard"(){return he(this)},"~run"(e,n){return typeof e.value=="boolean"?e.typed=!0:te(this,"type",e,n),e}}}r(nn,"boolean");function A(t){return{kind:"schema",type:"number",reference:A,expects:"number",async:!1,message:t,get"~standard"(){return he(this)},"~run"(e,n){return typeof e.value=="number"&&!isNaN(e.value)?e.typed=!0:te(this,"type",e,n),e}}}r(A,"number");function S(t,e){return{kind:"schema",type:"object",reference:S,expects:"Object",async:!1,entries:t,message:e,get"~standard"(){return he(this)},"~run"(n,s){let i=n.value;if(i&&typeof i=="object"){n.typed=!0,n.value={};for(let o in this.entries){let a=this.entries[o];if(o in i||(a.type==="exact_optional"||a.type==="optional"||a.type==="nullish")&&a.default!==void 0){let u=o in i?i[o]:fs(a),c=a["~run"]({value:u},s);if(c.issues){let p={type:"object",origin:"value",input:i,key:o,value:u};for(let l of c.issues)l.path?l.path.unshift(p):l.path=[p],n.issues?.push(l);if(n.issues||(n.issues=c.issues),s.abortEarly){n.typed=!1;break}}c.typed||(n.typed=!1),n.value[o]=c.value}else if(a.fallback!==void 0)n.value[o]=Dr(a);else if(a.type!=="exact_optional"&&a.type!=="optional"&&a.type!=="nullish"&&(te(this,"key",n,s,{input:void 0,expected:`"${o}"`,path:[{type:"object",origin:"key",input:i,key:o,value:i[o]}]}),s.abortEarly))break}}else te(this,"type",n,s);return n}}}r(S,"object");function _(t,e){return{kind:"schema",type:"optional",reference:_,expects:`(${t.expects} | undefined)`,async:!1,wrapped:t,default:e,get"~standard"(){return he(this)},"~run"(n,s){return n.value===void 0&&(this.default!==void 0&&(n.value=fs(this,n,s)),n.value===void 0)?(n.typed=!0,n):this.wrapped["~run"](n,s)}}}r(_,"optional");function we(t,e){return{kind:"schema",type:"picklist",reference:we,expects:hs(t.map(Ge),"|"),async:!1,options:t,message:e,get"~standard"(){return he(this)},"~run"(n,s){return this.options.includes(n.value)?n.typed=!0:te(this,"type",n,s),n}}}r(we,"picklist");function I(t){return{kind:"schema",type:"string",reference:I,expects:"string",async:!1,message:t,get"~standard"(){return he(this)},"~run"(e,n){return typeof e.value=="string"?e.typed=!0:te(this,"type",e,n),e}}}r(I,"string");function ps(t){let e;if(t)for(let n of t)e?e.push(...n.issues):e=n.issues;return e}r(ps,"_subIssues");function j(t,e){return{kind:"schema",type:"union",reference:j,expects:hs(t.map(n=>n.expects),"|"),async:!1,options:t,message:e,get"~standard"(){return he(this)},"~run"(n,s){let i,o,a;for(let u of this.options){let c=u["~run"]({value:n.value},s);if(c.typed)if(c.issues)o?o.push(c):o=[c];else{i=c;break}else a?a.push(c):a=[c]}if(i)return i;if(o){if(o.length===1)return o[0];te(this,"type",n,s,{issues:ps(o)}),n.typed=!0}else{if(a?.length===1)return a[0];te(this,"type",n,s,{issues:ps(a)})}return n}}}r(j,"union");function C(...t){return{...t[0],pipe:t,get"~standard"(){return he(this)},"~run"(e,n){for(let s of t)if(s.kind!=="metadata"){if(e.issues&&(s.kind==="schema"||s.kind==="transformation")){e.typed=!1;break}(!e.issues||!n.abortEarly&&!n.abortPipeEarly)&&(e=s["~run"](e,n))}return e}}}r(C,"pipe");function R(t,e,n){let s=t["~run"]({value:e},ds(n));return{typed:s.typed,success:!s.issues,output:s.value,issues:s.issues}}r(R,"safeParse");var ke=C(j([C(I(),q(O)),A()]),q(t=>Number(t)),C(A(),ne(1)));var g=class{constructor(e,n,s,i){this.swish=e;this.ui=n;this.eventBus=s;this.options=i}static{r(this,"IntentHandler")}};var Lr=j([S({variantId:ke,quantity:_(C(A(),ne(1)),1)}),S({items:C(ge(S({variantId:ke,quantity:_(C(A(),ne(1)),1)})),Le(1))})]),ze=class extends g{static{r(this,"CreateCartLineHandler")}async invoke(e){let n=R(Lr,e);if(!n.success)return{intent:"create:cart-line",code:"error",message:"Invalid intent data",issues:n.issues.map(i=>i.message)};let s=n.output;try{let i="items"in s?s.items.map(a=>({id:a.variantId,quantity:a.quantity})):[{id:s.variantId,quantity:s.quantity}];return{intent:"create:cart-line",code:"ok",data:await this.swish.ajax.addToCart({items:i})}}catch(i){let o=[],a="Failed to add item to cart";return i instanceof Error?(i.message&&(a=i.message,o.push(i.message)),i.stack&&o.push(i.stack)):typeof i=="string"&&i.trim()?(a=i,o.push(i)):i!=null&&o.push(String(i)),{intent:"create:cart-line",code:"error",message:a,issues:o.length?o:["Cart request failed"]}}}};var Ke=class extends g{static{r(this,"CreateListHandler")}async invoke(e){let n=await this.ui.showListEditor();if(n.code==="closed")return{intent:"create:list",code:"closed"};let{list:s}=n.data;return{intent:"create:list",code:"ok",data:{list:s}}}};var Or=S({listId:I()}),We=class extends g{static{r(this,"DeleteListHandler")}async invoke(e){let n=R(Or,e);if(!n.success)return{intent:"delete:list",code:"error",message:"Invalid intent data",issues:n.issues.map(o=>o.message)};let{listId:s}=n.output;return(await this.ui.showDeleteListAlert({listId:s})).code==="closed"?{intent:"delete:list",code:"closed"}:{intent:"delete:list",code:"ok",data:{listId:s}}}};var _r=S({itemId:I()}),Xe=class extends g{static{r(this,"EditItemListsHandler")}async invoke(e){let n=R(_r,e);if(!n.success)return{intent:"edit:item-lists",code:"error",message:"Invalid intent data",issues:n.issues.map(o=>o.message)};let{itemId:s}=n.output,i=await this.ui.showListSelect({itemId:s});if(i.code==="closed")return{intent:"edit:item-lists",code:"closed"};if(i.data.action==="submit"){let{item:o,product:a,variant:u}=i.data.data;return{intent:"edit:item-lists",code:"ok",data:{item:o,product:a,variant:u}}}return{intent:"unsave:item",code:"ok",data:{itemId:i.data.data.itemId}}}};var Mr=S({itemId:C(I()),productId:C(j([C(I(),q(O)),A()]),q(t=>Number(t)),A()),variantId:_(C(j([C(I(),q(O)),A()]),q(t=>Number(t)),A()))}),Je=class extends g{static{r(this,"EditItemVariantHandler")}async invoke(e){let n=R(Mr,e);if(!n.success)return{intent:"edit:item-variant",code:"error",message:"Invalid intent data",issues:n.issues.map(h=>h.message)};let{itemId:s,productId:i,variantId:o}=n.output;if(!(!o||this.swish.options.intents.editSavedProduct.promptVariantChange)){let h=await this.swish.api.items.updateById(s,{productId:i,variantId:o});if("error"in h)return{intent:"edit:item-variant",code:"error",message:"Failed to update variant",issues:[h.error.message]};if(!h.data)return{intent:"edit:item-variant",code:"error",message:"Failed to update variant",issues:["No item returned from API"]};let m=await this.swish.storefront.loadProduct({productId:String(i),variantId:o?String(o):void 0});if(!m.data?.product)return{intent:"edit:item-variant",code:"error",message:"Failed to load product data",issues:[m.errors?.message??"No product data returned from API"]};let v=m.data.product,f=m.data.variant;return{intent:"edit:item-variant",code:"ok",data:{item:h.data,product:v,variant:f}}}let u=await this.ui.showVariantSelect({itemId:s,productId:i,variantId:o});if(u.code==="closed")return{intent:"edit:item-variant",code:"closed"};let{item:c,product:p,variant:l}=u.data;return{intent:"edit:item-variant",code:"ok",data:{item:c,product:p,variant:l}}}};var qr=S({listId:I(),access:we(["public","private"])}),Ye=class extends g{static{r(this,"EditListAccessHandler")}async invoke(e){let n=R(qr,e);if(!n.success)return{intent:"edit:list-access",code:"error",message:"Invalid intent data",issues:n.issues.map(u=>u.message)};let{listId:s,access:i}=n.output;if((await this.ui.showConfirmDialog({titleKey:i==="public"?"listMenu.public.title":"listMenu.private.title",descriptionKey:i==="public"?"listMenu.public.description":"listMenu.private.description",confirmLabelKey:i==="public"?"listMenu.public.text":"listMenu.private.text",cancelLabelKey:"listMenu.cancel",danger:!1})).code==="closed")return{intent:"edit:list-access",code:"closed"};let a=await this.swish.api.lists.updateById(s,{access:i});return"error"in a?{intent:"edit:list-access",code:"error",message:"Failed to update list access",issues:[a.error.message]}:a.data?{intent:"edit:list-access",code:"ok",data:{list:a.data}}:{intent:"edit:list-access",code:"error",message:"Failed to update list access",issues:["API response missing data"]}}};var Ur=S({listId:I()}),Ze=class extends g{static{r(this,"EditListHandler")}async invoke(e){let n=R(Ur,e);if(!n.success)return{intent:"edit:list",code:"error",message:"Invalid intent data",issues:n.issues.map(a=>a.message)};let{listId:s}=n.output,i=await this.ui.showListEditor({listId:s});if(i.code==="closed")return{intent:"edit:list",code:"closed"};let{list:o}=i.data;return{intent:"edit:list",code:"ok",data:{list:o}}}};var Fr=S({variantId:ke,quantity:_(C(A(),ne(1)),1)}),Nr=150,Br=j([S({variantId:ke,quantity:_(C(A(),ne(1)),1)}),S({items:C(ge(Fr),Le(1))})]),et=class extends g{static{r(this,"InitiateCheckoutHandler")}async invoke(e){let n=R(Br,e);if(!n.success)return{intent:"initiate:checkout",code:"error",message:"Invalid intent data",issues:n.issues.map(u=>u.message)};let s=n.output,o=("items"in s?s.items:[{variantId:s.variantId,quantity:s.quantity}]).map(u=>`${u.variantId}:${u.quantity}`).join(","),a=new URL(`/cart/${o}`,this.swish.shopUrl);return a.searchParams.set("checkout","1"),typeof window<"u"&&window.setTimeout(()=>window.location.assign(a.href),Nr),{intent:"initiate:checkout",code:"ok",data:{checkoutUrl:a.href}}}};var Vr=S({productId:C(j([C(I(),q(O)),A()]),q(t=>Number(t)),A()),variantId:_(C(j([C(I(),q(O)),A()]),q(Number),A()))}),tt=class extends g{static{r(this,"InitiateQuickBuyHandler")}async invoke(e){let n=R(Vr,e);if(!n.success)return{intent:"initiate:quick-buy",code:"error",message:"Invalid intent data",issues:n.issues.map(a=>a.message)};let{productId:s,variantId:i}=n.output,o=await this.ui.showQuickBuy({productId:s,variantId:i});return o.code==="closed"?{intent:"initiate:quick-buy",code:"closed"}:{intent:"initiate:quick-buy",code:"ok",data:o.data}}};var jr=150,$r=S({returnTo:I()}),nt=class extends g{static{r(this,"InitiateSignInHandler")}async invoke(e){let n=R($r,e);if(!n.success)return{intent:"initiate:sign-in",code:"error",message:"Invalid intent data",issues:n.issues.map(o=>o.message)};let s=n.output.returnTo;return(await this.ui.showConfirmDialog({titleKey:"signIn.title",descriptionKey:"signIn.description",confirmLabelKey:"signIn.continue",danger:!1})).code==="closed"?{intent:"initiate:sign-in",code:"closed"}:(this.scheduleRedirect(s),{intent:"initiate:sign-in",code:"ok",data:void 0})}scheduleRedirect(e){window.setTimeout(()=>this.redirectToSignIn(e),jr)}redirectToSignIn(e){let n=this.swish.storefrontContext.routes.accountUrl,s=new URL(n,window.location.origin);s.searchParams.set("return_url",e),window.location.assign(s.toString())}};var st=class extends g{static{r(this,"SaveCartLineHandler")}async invoke(e){if(!e?.items?.length)return{intent:"save:cart-line",code:"error",message:"No items to save",issues:["items array is empty or missing"]};let{confirm:n,showFeedback:s}=this.options.saveCartLine,i=e.items[0];if(n&&(await this.ui.showToast({title:"Save this for later?",text:i.title??"",image:i.image,action:{label:"Save for later"},variant:"full"})).code!=="ok")return{intent:"save:cart-line",code:"closed"};for(let o of e.items){let a=await this.swish.api.items.create({productId:o.productId,variantId:o.variantId,quantity:o.quantity,source:"cart"});if("error"in a)return{intent:"save:cart-line",code:"error",message:"Failed to save item from cart",issues:[a.error.message]}}return s&&await this.ui.showToast({title:"We've saved this for you",text:i.title??"",image:i.image,variant:"full"}),{intent:"save:cart-line",code:"ok",data:e.items}}};var Hr=S({productId:C(j([C(I(),q(O)),A()]),q(t=>Number(t)),A()),variantId:_(C(j([C(I(),q(O)),A()]),q(Number),A())),quantity:_(C(A(),ne(1))),tags:_(ge(I()))}),it=class extends g{static{r(this,"SaveItemHandler")}async invoke(e){let n=R(Hr,e);if(!n.success)return{intent:"save:item",code:"error",message:"Invalid intent data",issues:n.issues.map(w=>w.message)};let{productId:s,variantId:i,quantity:o,tags:a}=n.output,u=await this.swish.storefront.loadProduct({productId:String(s),variantId:i?String(i):void 0});if(u.errors)return{intent:"save:item",code:"error",message:u.errors.message??"Failed to load product data",issues:u.errors.graphQLErrors?.map(w=>w.message)??[]};if(!u.data||!u.data.product)return{intent:"save:item",code:"error",message:"Failed to load product data",issues:["API response missing data"]};let{product:c,variant:p}=u.data,l=c.variantsCount?.count&&c.variantsCount.count>1,y=!!i,m=!(typeof this.options.saveProduct.promptVariantIfMissing=="function"?this.options.saveProduct.promptVariantIfMissing({product:c,variant:p}):this.options.saveProduct.promptVariantIfMissing)||!this.options.saveProduct.promptVariantIfPresent&&y;if(!l||m){let w=r(()=>!l&&c.selectedOrFirstAvailableVariant?Number(O(c.selectedOrFirstAvailableVariant.id)):i,"variantIdToUse"),b=await this.swish.api.items.create({productId:s,variantId:w(),quantity:o,tags:a});return"error"in b?{intent:"save:item",code:"error",message:"Failed to create item",issues:[b.error.message]}:b.data?{intent:"save:item",code:"ok",data:{item:b.data,product:c,variant:l?p:c.selectedOrFirstAvailableVariant}}:{intent:"save:item",code:"error",message:"Could not complete item creation",issues:["API response missing data"]}}let v;if(this.options.saveProduct.saveBeforeVariantPrompt){let w=await this.swish.api.items.create({productId:s,quantity:o,tags:a});"data"in w&&w.data&&(v=w.data)}let f=await this.ui.showVariantSelect({productId:s,variantId:i,itemId:v?.id});return f.code==="closed"?v?{intent:"save:item",code:"ok",data:{item:v,product:c,variant:p}}:{intent:"save:item",code:"closed"}:{intent:"save:item",code:"ok",data:f.data}}};function Oe(t,e){let{storeDomain:n}=t.options.storefrontApi,{rootUrl:s,listDetailPagePath:i}=t.options.storefrontContext.routes,o=new URL(`https://${n}`),a=new URL(`${s==="/"?"":s}${i}`,o);return a.searchParams.set("public-list-id",e.publicListId),a}r(Oe,"buildShareListUrl");async function _e(t){return typeof navigator?.clipboard?.writeText!="function"?{ok:!1,issues:["Clipboard API not available"]}:navigator.clipboard.writeText(t).then(()=>({ok:!0})).catch(e=>({ok:!1,issues:[e?.message??"Failed to copy to clipboard"]}))}r(_e,"copyToClipboard");function ms(){let t=navigator.userAgent.includes("Mac OS")&&navigator.maxTouchPoints>1;return/Android|Mobile/i.test(navigator.userAgent)||t}r(ms,"isMobileDevice");var Qr=S({listId:I()}),rt=class extends g{static{r(this,"ShareListHandler")}async invoke(e){let n=R(Qr,e);if(!n.success)return{intent:"initiate:share",code:"error",message:"Invalid intent data",issues:n.issues.map(c=>c.message)};let{listId:s}=n.output,i=await this.swish.api.lists.findById(s);if("error"in i)return{intent:"initiate:share",code:"error",message:"Failed to fetch list",issues:[i.error.message]};if(!i.data)return{intent:"initiate:share",code:"error",message:"List not found",issues:[]};if(i.data.access!=="public"){let p=await(await this.swish.intents.invoke("edit:list-access",{listId:s,access:"public"})).complete;if(p.code!=="ok")return{...p,intent:"initiate:share"}}let o=Oe(this.swish,{publicListId:s}).toString();if(ms()&&typeof navigator.share=="function"&&(await navigator.share({title:"Share list",url:o}).then(()=>({ok:!0})).catch(()=>({ok:!1}))).ok)return{intent:"initiate:share",code:"ok",data:{listId:s,url:o,method:"native"}};let u=await _e(o);return u.ok?{intent:"initiate:share",code:"ok",data:{listId:s,url:o,method:"clipboard"}}:{intent:"initiate:share",code:"error",message:"Failed to share list",issues:u.issues}}};var zc=S({title:_(I()),text:I(),image:_(I()),action:_(S({label:I(),url:_(I())})),variant:_(we(["compact","full"])),icon:_(I())}),ot=class extends g{static{r(this,"ShowToastHandler")}async invoke(e){return{intent:"show:toast",code:(await this.ui.showToast(e)).code,data:void 0}}};var Gr=S({itemId:I(),delete:_(nn())}),at=class extends g{static{r(this,"UnsaveItemHandler")}async invoke(e){let n=R(Gr,e);if(!n.success)return{intent:"unsave:item",code:"error",message:"Invalid intent data",issues:n.issues.map(a=>a.message)};let{itemId:s,delete:i}=n.output;if(this.options.unsaveProduct.selectList&&!i){let a=await this.ui.showListSelect({itemId:s});if(a.code==="closed")return{intent:"unsave:item",code:"closed"};if(a.data.action==="submit"){let{item:u,product:c,variant:p}=a.data.data;return{intent:"edit:item-lists",code:"ok",data:{item:u,product:c,variant:p}}}if(a.data.action==="unsave"){let{itemId:u}=a.data.data;return{intent:"unsave:item",code:"ok",data:{itemId:u}}}}if(!this.options.unsaveProduct.confirm){let a=await this.swish.api.items.deleteById(s);return"error"in a?{intent:"unsave:item",code:"error",message:"Failed to delete item",issues:[a.error.message]}:{intent:"unsave:item",code:"ok",data:{itemId:s}}}return(await this.ui.showUnsaveAlert({itemId:s})).code==="closed"?{intent:"unsave:item",code:"closed"}:{intent:"unsave:item",code:"ok",data:{itemId:s}}}};var ut=class extends g{static{r(this,"ViewHomeHandler")}async invoke(e){return{intent:"view:home",code:(await this.ui.showDrawer()).code,data:void 0}}};var zr=S({listId:I()}),ct=class extends g{static{r(this,"ViewListDetailPageMenuHandler")}async invoke(e){let n=R(zr,e);if(!n.success)return{intent:"view:list-detail-page-menu",code:"error",message:"Invalid intent data",issues:n.issues.map(o=>o.message)};let{listId:s}=n.output;return{intent:"view:list-detail-page-menu",code:(await this.ui.showListDetailPageMenu({listId:s})).code,data:void 0}}};var Kr=S({listId:I(),listType:_(we(["user","smart","shared"]),"user")}),lt=class extends g{static{r(this,"ViewListHandler")}async invoke(e){let n=R(Kr,e);if(!n.success)return{intent:"view:list",code:"error",message:"Invalid intent data",issues:n.issues.map(a=>a.message)};let{listId:s,listType:i}=n.output;return{intent:"view:list",code:(await this.ui.showDrawer({view:"list",listId:s,listType:i})).code,data:void 0}}};var Wr=S({listId:I()}),pt=class extends g{static{r(this,"ViewListMenuHandler")}async invoke(e){let n=R(Wr,e);if(!n.success)return{intent:"view:list-menu",code:"error",message:"Invalid intent data",issues:n.issues.map(o=>o.message)};let{listId:s}=n.output,i=await this.ui.showListMenu({listId:s});if(i.code==="closed")return{intent:"view:list-menu",code:"closed"};if(i.data.action==="edit")return{intent:"edit:list",code:"ok",data:i.data.data};if(i.data.action==="delete")return{intent:"delete:list",code:"ok",data:{listId:s}};if(i.data.action==="edit-access"){let o=i.data.data?.currentListAccess,a=o==="public"?"private":o==="private"?"public":void 0;return a?(await this.swish.intents.invoke("edit:list-access",{listId:s,access:a})).complete:{intent:"view:list-menu",code:"error",message:"Missing list access from UI",issues:["List menu UI did not provide currentListAccess"]}}return i.data.action==="share"?(await this.swish.intents.invoke("initiate:share",{listId:s})).complete:i.data.action==="add-items"?{intent:"view:list-menu",code:"ok",data:{listId:s}}:{intent:"view:list-menu",code:"error",message:"Unknown list menu action",issues:["Unknown action returned from list menu UI"]}}};var dt=class extends g{static{r(this,"ViewListsHandler")}async invoke(e){return{intent:"view:lists",code:(await this.ui.showDrawer({view:"lists"})).code,data:void 0}}};var ht=class extends g{static{r(this,"ViewNotificationsHandler")}async invoke(e){return{intent:"view:notifications",code:(await this.ui.showDrawer({view:"notifications"})).code,data:void 0}}};var Xr=S({orderId:C(j([C(I(),q(O)),A()]),q(t=>Number(t)),A())}),ft=class extends g{static{r(this,"ViewOrderHandler")}async invoke(e){let n=R(Xr,e);if(!n.success)return{intent:"view:order",code:"error",message:"Invalid intent data",issues:n.issues.map(o=>o.message)};let{orderId:s}=n.output;return{intent:"view:order",code:(await this.ui.showDrawer({view:"order",orderId:s.toString()})).code,data:void 0}}};var Jr=S({orderId:I()}),mt=class extends g{static{r(this,"ViewOrderMenuHandler")}async invoke(e){let n=R(Jr,e);if(!n.success)return{intent:"view:order-menu",code:"error",message:"Invalid intent data",issues:n.issues.map(o=>o.message)};let{orderId:s}=n.output;return{intent:"view:order-menu",code:(await this.ui.showOrderMenu({orderId:s})).code,data:void 0}}};var yt=class extends g{static{r(this,"ViewOrdersHandler")}async invoke(e){return{intent:"view:orders",code:(await this.ui.showDrawer({view:"orders"})).code,data:void 0}}};var Yr=S({productId:C(j([C(I(),q(O)),A()]),q(t=>Number(t)),A()),variantId:_(C(j([C(I(),q(O)),A()]),q(Number),A()))}),vt=class extends g{static{r(this,"ViewProductHandler")}async invoke(e){let n=R(Yr,e);if(!n.success)return{intent:"view:product",code:"error",message:"Invalid intent data",issues:n.issues.map(a=>a.message)};let{productId:s,variantId:i}=n.output;return{intent:"view:product",code:(await this.ui.showDrawer({view:"product",productId:s.toString(),variantId:i?.toString()})).code,data:void 0}}};var gt=class extends g{static{r(this,"ViewProfileHandler")}async invoke(e){return{intent:"view:profile",code:(await this.ui.showDrawer({view:"profile"})).code,data:void 0}}};var wt=class extends g{static{r(this,"ViewSavesHandler")}async invoke(e){return{intent:"view:saves",code:(await this.ui.showDrawer({view:"saves"})).code,data:void 0}}};var G=class{constructor(e,n,s){this.swish=e;this.ui=n;this.options=s}static{r(this,"IntentHook")}};var bt=class extends G{static{r(this,"AfterCreateCartLineHook")}async invoke(e){this.options.createCartLine.afterComplete?.(e)}};var It=class extends G{static{r(this,"AfterEditItemListsHook")}async invoke(e){if(this.options.editSavedProduct.showFeedback&&e.code==="ok"){if("itemId"in e.data)return;let{product:n,variant:s}=e.data;n&&(await(await this.swish.intents.invoke("show:toast",{title:"Saved",text:n.title,image:s?.image?.url??n.featuredImage?.url,action:{label:"View"}})).complete).code==="ok"&&this.swish.intents.invoke("view:home")}}};var St=class extends G{static{r(this,"AfterEditListAccessHook")}async invoke(e){if(e.code!=="ok")return;let n=e.data.list.access==="public"?"List is now public":"List is now private";await(await this.swish.intents.invoke("show:toast",{text:n,variant:"compact",icon:"check"})).complete}};var Et=class extends G{static{r(this,"AfterSaveCartLineHook")}async invoke(e){this.options.saveCartLine.afterComplete?.(e)}};var kt=class extends G{static{r(this,"AfterSaveItemHook")}async invoke(e){if(this.options.saveProduct.showFeedback&&e.code==="ok"){let{item:n,product:s,variant:i}=e.data;s&&(await(await this.swish.intents.invoke("show:toast",{title:"Saved",text:s.title,image:i?.image?.url??s.featuredImage?.url,action:{label:"Add to List"}})).complete).code==="ok"&&this.swish.intents.invoke("edit:item-lists",{itemId:n.id})}}};var xt=class extends G{static{r(this,"AfterShareListHook")}async invoke(e){if(e.code!=="ok")return;await(await this.swish.intents.invoke("show:toast",{variant:"compact",text:"Link copied",icon:"check"})).complete}};var Ct=class extends G{static{r(this,"AfterViewHomeHook")}async invoke(e){if(e.code==="closed"){let n=new URL(window.location.href);(n.hash==="#swish-home"||n.hash==="#swish")&&(n.hash="",window.history.replaceState({},document.title,n.toString()))}}};var Rt=class{static{r(this,"Intents")}constructor(e,n){this.swish=e,this.ui=n,this.eventBus=new EventTarget,this.options=e.options.intents,this.handlers={"create:cart-line":new ze(this.swish,this.ui,this.eventBus,this.options),"initiate:checkout":new et(this.swish,this.ui,this.eventBus,this.options),"save:item":new it(this.swish,this.ui,this.eventBus,this.options),"save:cart-line":new st(this.swish,this.ui,this.eventBus,this.options),"unsave:item":new at(this.swish,this.ui,this.eventBus,this.options),"edit:item-variant":new Je(this.swish,this.ui,this.eventBus,this.options),"edit:item-lists":new Xe(this.swish,this.ui,this.eventBus,this.options),"create:list":new Ke(this.swish,this.ui,this.eventBus,this.options),"edit:list":new Ze(this.swish,this.ui,this.eventBus,this.options),"edit:list-access":new Ye(this.swish,this.ui,this.eventBus,this.options),"delete:list":new We(this.swish,this.ui,this.eventBus,this.options),"view:home":new ut(this.swish,this.ui,this.eventBus,this.options),"initiate:share":new rt(this.swish,this.ui,this.eventBus,this.options),"view:list":new lt(this.swish,this.ui,this.eventBus,this.options),"view:lists":new dt(this.swish,this.ui,this.eventBus,this.options),"view:orders":new yt(this.swish,this.ui,this.eventBus,this.options),"view:order":new ft(this.swish,this.ui,this.eventBus,this.options),"view:saves":new wt(this.swish,this.ui,this.eventBus,this.options),"view:notifications":new ht(this.swish,this.ui,this.eventBus,this.options),"view:profile":new gt(this.swish,this.ui,this.eventBus,this.options),"view:product":new vt(this.swish,this.ui,this.eventBus,this.options),"view:list-menu":new pt(this.swish,this.ui,this.eventBus,this.options),"view:order-menu":new mt(this.swish,this.ui,this.eventBus,this.options),"view:list-detail-page-menu":new ct(this.swish,this.ui,this.eventBus,this.options),"initiate:sign-in":new nt(this.swish,this.ui,this.eventBus,this.options),"initiate:quick-buy":new tt(this.swish,this.ui,this.eventBus,this.options),"show:toast":new ot(this.swish,this.ui,this.eventBus,this.options)},this.initIntentHooks(),this.initIntentWatcher(),this.initCartChangeListener()}publishAnalyticsEvent(e,n){typeof window.Shopify?.analytics?.publish=="function"&&window.Shopify.analytics.publish(e,n)}async invoke(e,...n){let s=n[0],i={lifecycle:"before",intent:e,data:s};return this.publishAnalyticsEvent("swish-intent",i),this.publishAnalyticsEvent(`swish-intent=${e}`,i),{intent:e,data:s,complete:this.handleIntent(e,s).then(o=>{let a={lifecycle:"after",intent:e,data:s,response:o};return this.publishAnalyticsEvent("swish-intent",a),this.publishAnalyticsEvent(`swish-intent=${e}`,a),this.eventBus.dispatchEvent(new CustomEvent(e,{detail:o})),o.code==="ok"&&o.intent!==e&&this.eventBus.dispatchEvent(new CustomEvent(o.intent,{detail:o})),o})}}listen(e,n){let s=r(o=>{"detail"in o&&o.detail?n(o.detail):console.warn("Intent response event without detail",o)},"eventListener"),i=r(()=>{this.eventBus.removeEventListener(e,s)},"unsubscribe");return this.eventBus.addEventListener(e,s),i}parseIntentFromString(e){let n=String(e),s=n.indexOf("?");if(s===-1)return{intent:n,data:{}};let i=n.slice(0,s),o=new URLSearchParams(n.slice(s+1)),a={};return o.forEach((u,c)=>{a[c]=u}),{intent:i,data:a}}parseIntentFromUrl(e){let n=e.searchParams.get("swish-intent");if(!n)return null;let s=n,i={};e.searchParams.forEach((a,u)=>{u!=="swish-intent"&&(i[u]=a)});let o=De(e.pathname);return o&&(!i.product&&!i.productId&&(i.product=o.productHandle),!i.variant&&!i.variantId&&o.variantId&&(i.variant=o.variantId)),{intent:s,data:i}}mapParamNames(e){let n={product:"productId",variant:"variantId",list:"listId",order:"orderId",item:"itemId"},s={};for(let[i,o]of Object.entries(e))s[n[i]??i]=o;return s}async resolveIntentData(e){let{productId:n}=e;if(!n||/^\d+$/.test(n)||n.startsWith("gid://"))return e;let s=await this.swish.storefront.loadProductId({productHandle:n});return s.data?.product?.id?{...e,productId:O(s.data.product.id)}:e}async invokeFromParsed(e,n){let s=this.mapParamNames(n),i=await this.resolveIntentData(s);Object.keys(i).length>0?this.invoke(e,i):this.invoke(e)}parseIntentFromHash(e){let n=e.startsWith("#")?e.slice(1):e;return{swish:"view:home","swish-home":"view:home","swish-lists":"view:lists","swish-orders":"view:orders","swish-saves":"view:saves","swish-notifications":"view:notifications","swish-profile":"view:profile"}[n]||null}async handleIntent(e,n){let s=this.handlers[e];return s?s.invoke(n):{intent:e,code:"error",message:"Invalid intent",issues:[`Intent ${e} not found`]}}initIntentHooks(){this.eventBus.addEventListener("create:cart-line",e=>{new bt(this.swish,this.ui,this.options).invoke(e.detail)}),this.eventBus.addEventListener("save:item",e=>{new kt(this.swish,this.ui,this.options).invoke(e.detail)}),this.eventBus.addEventListener("edit:item-lists",e=>{new It(this.swish,this.ui,this.options).invoke(e.detail)}),this.eventBus.addEventListener("view:home",e=>{new Ct(this.swish,this.ui,this.options).invoke(e.detail)}),this.eventBus.addEventListener("edit:list-access",e=>{new St(this.swish,this.ui,this.options).invoke(e.detail)}),this.eventBus.addEventListener("initiate:share",e=>{new xt(this.swish,this.ui,this.options).invoke(e.detail)}),this.eventBus.addEventListener("save:cart-line",e=>{new Et(this.swish,this.ui,this.options).invoke(e.detail)})}initCartChangeListener(){this.swish.events.subscribe("cart-change",e=>{if(!this.options.removeCartLine.saveCartLine)return;let s=e.detail?.items_removed;if(!s?.length)return;let i=s.map(o=>({productId:o.product_id,variantId:o.variant_id,quantity:o.quantity,title:o.product_title,image:o.image,variantTitle:o.variant_title}));this.invoke("save:cart-line",{items:i})})}initIntentWatcher(){re({selector:"[swish-intent]",onElementFound:r(e=>{let n=e.getAttribute("swish-intent");if(!n)return;let{intent:s,data:i}=this.parseIntentFromString(n);e.addEventListener("click",()=>{this.invokeFromParsed(s,i)})},"onElementFound")}),re({selector:"a[href*='swish-intent='],a[href*='#swish']",onElementFound:r(e=>{e instanceof HTMLAnchorElement&&e.addEventListener("click",n=>{if(!n.metaKey&&!n.ctrlKey&&!n.shiftKey&&!n.altKey){let s=new URL(e.href),i=this.parseIntentFromUrl(s);if(i)n.preventDefault(),n.stopPropagation(),this.invokeFromParsed(i.intent,i.data);else if(s.hash){let o=this.parseIntentFromHash(s.hash);o&&(n.preventDefault(),n.stopPropagation(),this.invoke(o))}}})},"onElementFound")}),Ee({fireOnInit:!0,onLocationChange:r(e=>{let n=new URL(e.href),s=this.parseIntentFromUrl(n);if(s)n.searchParams.delete("swish-intent"),history.replaceState(history.state,"",n.toString()),this.invokeFromParsed(s.intent,s.data);else if(n.hash){let i=this.parseIntentFromHash(n.hash);i&&this.invoke(i)}},"onLocationChange")})}};var ys=r(t=>({auth:{tokenUrl:t.auth?.tokenUrl??"/apps/wishlist/api/profiles/token"},swishApi:{},storefrontApi:{storeDomain:t.storefrontApi?.storeDomain??"",accessToken:t.storefrontApi?.accessToken??""},storefrontContext:{...t.storefrontContext,routes:{...t.storefrontContext.routes,rootUrl:t.storefrontContext.routes?.rootUrl??"/",listDetailPagePath:t.storefrontContext.routes?.listDetailPagePath??"/apps/wishlist"},localization:{country:t.storefrontContext.localization.country.toUpperCase(),language:t.storefrontContext.localization.language.toUpperCase(),market:t.storefrontContext.localization.market}},features:{accounts:t?.features?.accounts??!0,lists:t?.features?.lists??!0,orders:t?.features?.orders??!0,notifications:t?.features?.notifications??!0,recentlyViewed:t?.features?.recentlyViewed??!0,savedFromCart:t?.features?.savedFromCart??!0},products:{metafields:{product:t.products?.metafields?.product??[],productVariant:t.products?.metafields?.productVariant??[]},transform:{badges:t.products?.transform?.badges??(({defaultBadges:e})=>e),title:t.products?.transform?.title??(({product:e})=>e?.title??""),description:t.products?.transform?.description??(({product:e})=>e?.descriptionHtml??""),variantTitle:t.products?.transform?.variantTitle??(({variant:e})=>e?.title??""),optionValues:t.products?.transform?.optionValues??(({optionValues:e})=>e)}},intents:{saveProduct:{promptVariantIfMissing:t?.intents?.saveProduct?.promptVariantIfMissing??!0,promptVariantIfPresent:t?.intents?.saveProduct?.promptVariantIfPresent??!0,saveBeforeVariantPrompt:t?.intents?.saveProduct?.saveBeforeVariantPrompt??!1,showFeedback:t?.intents?.saveProduct?.showFeedback??!0},unsaveProduct:{selectList:t?.intents?.unsaveProduct?.selectList??!0,confirm:t?.intents?.unsaveProduct?.confirm??!0,showFeedback:t?.intents?.unsaveProduct?.showFeedback??!0},editSavedProduct:{promptVariantChange:t?.intents?.editSavedProduct?.promptVariantChange??!0,showFeedback:t?.intents?.editSavedProduct?.showFeedback??!0},initiateQuickBuy:{promptVariantIfPresent:t?.intents?.initiateQuickBuy?.promptVariantIfPresent??!1},createCartLine:{afterComplete:t?.intents?.createCartLine?.afterComplete},removeCartLine:{saveCartLine:t?.intents?.removeCartLine?.saveCartLine??!1},saveCartLine:{confirm:t?.intents?.saveCartLine?.confirm??!1,showFeedback:t?.intents?.saveCartLine?.showFeedback??!0,afterComplete:t?.intents?.saveCartLine?.afterComplete}},translations:t.translations,swishUi:{baseUrl:t.swishUi?.baseUrl??"https://swish.app/cdn",components:{productCard:{linkToProductPage:t.swishUi?.components?.productCard?.linkToProductPage??!1},productRow:{showVariantTitle:t.swishUi?.components?.productRow?.showVariantTitle??!1},productDetail:{descriptionMaxLines:t.swishUi?.components?.productDetail?.descriptionMaxLines??4},variantSelect:{displayType:t.swishUi?.components?.variantSelect?.displayType??"pills",hideSingleValueOptions:t.swishUi?.components?.variantSelect?.hideSingleValueOptions??!0},icons:t.swishUi?.components?.icons??{},imageSlider:{flush:t.swishUi?.components?.imageSlider?.flush??!1,loop:t.swishUi?.components?.imageSlider?.loop??!1},images:{baseTint:t.swishUi?.components?.images?.baseTint??!1},buyButtons:{shopPay:t.swishUi?.components?.buyButtons?.shopPay??!1},listsSection:{displayType:t.swishUi?.components?.listsSection?.displayType??"slider"},listDetailPage:{desktopColumns:t.swishUi?.components?.listDetailPage?.desktopColumns??4,showBuyButton:t.swishUi?.components?.listDetailPage?.showBuyButton??!0,showVariantOptionNames:t.swishUi?.components?.listDetailPage?.showVariantOptionNames??!1,enableVariantChange:t.swishUi?.components?.listDetailPage?.enableVariantChange??!0},drawer:{title:t.swishUi?.components?.drawer?.title??"",logo:{url:t.swishUi?.components?.drawer?.logo?.url??"",altText:t.swishUi?.components?.drawer?.logo?.altText??""},navigation:{enabled:t.swishUi?.components?.drawer?.navigation?.enabled??!0,variant:t.swishUi?.components?.drawer?.navigation?.variant??"docked",showIcons:t.swishUi?.components?.drawer?.navigation?.showIcons??!1,showText:t.swishUi?.components?.drawer?.navigation?.showText??!0,items:t.swishUi?.components?.drawer?.navigation?.items??[]},emptyCallout:{enabled:t.swishUi?.components?.drawer?.emptyCallout?.enabled??!1,shoppingCalloutUrl:t.swishUi?.components?.drawer?.emptyCallout?.shoppingCalloutUrl??"/collections/all"},miniMenu:{enabled:t.swishUi?.components?.drawer?.miniMenu?.enabled??!0,items:t.swishUi?.components?.drawer?.miniMenu?.items??[]},listDetailView:{enableVariantChange:t.swishUi?.components?.drawer?.listDetailView?.enableVariantChange??!1,showVariantOptionNames:t.swishUi?.components?.drawer?.listDetailView?.showVariantOptionNames??!1},home:{contentBlock:t.swishUi?.components?.drawer?.home?.contentBlock}}},css:t.swishUi?.css??[],design:t.swishUi?.design??{}}}),"createSwishOptions");function vs(t){return O(String(t).trim())}r(vs,"normalizeSwishQueryId");function Pt(t){let e=t.productId?vs(t.productId):"",n=t.variantId?vs(t.variantId):"";return n?["swish","items",e,n]:["swish","items",e]}r(Pt,"swishItemsQueryKey");var Zr=["item-create","item-update","item-delete"],gs="auth-cache-clear",ws="token-update";function bs({events:t,queryClient:e}){return t.subscribe([...Zr,gs,ws],n=>{if(!(n instanceof CustomEvent))return;if(n.type===gs){e.clear();return}if(n.type===ws){e.invalidateQueries({queryKey:["swish"]});return}if(!n.detail?.productId)return;let s=Pt({productId:n.detail.productId});e.invalidateQueries({queryKey:s})})}r(bs,"bindSwishItemQueryInvalidation");var oe=class{static{r(this,"Subscribable")}constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(t){return this.listeners.add(t),this.onSubscribe(),()=>{this.listeners.delete(t),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}};var eo={setTimeout:r((t,e)=>setTimeout(t,e),"setTimeout"),clearTimeout:r(t=>clearTimeout(t),"clearTimeout"),setInterval:r((t,e)=>setInterval(t,e),"setInterval"),clearInterval:r(t=>clearInterval(t),"clearInterval")},to=class{static{r(this,"TimeoutManager")}#e=eo;#t=!1;setTimeoutProvider(t){this.#e=t}setTimeout(t,e){return this.#e.setTimeout(t,e)}clearTimeout(t){this.#e.clearTimeout(t)}setInterval(t,e){return this.#e.setInterval(t,e)}clearInterval(t){this.#e.clearInterval(t)}},ae=new to;function Is(t){setTimeout(t,0)}r(Is,"systemSetTimeoutZero");var se=typeof window>"u"||"Deno"in globalThis;function B(){}r(B,"noop");function ks(t,e){return typeof t=="function"?t(e):t}r(ks,"functionalUpdate");function Me(t){return typeof t=="number"&&t>=0&&t!==1/0}r(Me,"isValidTimeout");function At(t,e){return Math.max(t+(e||0)-Date.now(),0)}r(At,"timeUntilStale");function ie(t,e){return typeof t=="function"?t(e):t}r(ie,"resolveStaleTime");function J(t,e){return typeof t=="function"?t(e):t}r(J,"resolveEnabled");function rn(t,e){let{type:n="all",exact:s,fetchStatus:i,predicate:o,queryKey:a,stale:u}=t;if(a){if(s){if(e.queryHash!==qe(a,e.options))return!1}else if(!Ce(e.queryKey,a))return!1}if(n!=="all"){let c=e.isActive();if(n==="active"&&!c||n==="inactive"&&c)return!1}return!(typeof u=="boolean"&&e.isStale()!==u||i&&i!==e.state.fetchStatus||o&&!o(e))}r(rn,"matchQuery");function on(t,e){let{exact:n,status:s,predicate:i,mutationKey:o}=t;if(o){if(!e.options.mutationKey)return!1;if(n){if(xe(e.options.mutationKey)!==xe(o))return!1}else if(!Ce(e.options.mutationKey,o))return!1}return!(s&&e.state.status!==s||i&&!i(e))}r(on,"matchMutation");function qe(t,e){return(e?.queryKeyHashFn||xe)(t)}r(qe,"hashQueryKeyByOptions");function xe(t){return JSON.stringify(t,(e,n)=>sn(n)?Object.keys(n).sort().reduce((s,i)=>(s[i]=n[i],s),{}):n)}r(xe,"hashKey");function Ce(t,e){return t===e?!0:typeof t!=typeof e?!1:t&&e&&typeof t=="object"&&typeof e=="object"?Object.keys(e).every(n=>Ce(t[n],e[n])):!1}r(Ce,"partialMatchKey");var no=Object.prototype.hasOwnProperty;function xs(t,e,n=0){if(t===e)return t;if(n>500)return e;let s=Ss(t)&&Ss(e);if(!s&&!(sn(t)&&sn(e)))return e;let o=(s?t:Object.keys(t)).length,a=s?e:Object.keys(e),u=a.length,c=s?new Array(u):{},p=0;for(let l=0;l<u;l++){let y=s?l:a[l],h=t[y],m=e[y];if(h===m){c[y]=h,(s?l<o:no.call(t,y))&&p++;continue}if(h===null||m===null||typeof h!="object"||typeof m!="object"){c[y]=m;continue}let v=xs(h,m,n+1);c[y]=v,v===h&&p++}return o===u&&p===o?t:c}r(xs,"replaceEqualDeep");function Tt(t,e){if(!e||Object.keys(t).length!==Object.keys(e).length)return!1;for(let n in t)if(t[n]!==e[n])return!1;return!0}r(Tt,"shallowEqualObjects");function Ss(t){return Array.isArray(t)&&t.length===Object.keys(t).length}r(Ss,"isPlainArray");function sn(t){if(!Es(t))return!1;let e=t.constructor;if(e===void 0)return!0;let n=e.prototype;return!(!Es(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}r(sn,"isPlainObject");function Es(t){return Object.prototype.toString.call(t)==="[object Object]"}r(Es,"hasObjectPrototype");function Cs(t){return new Promise(e=>{ae.setTimeout(e,t)})}r(Cs,"sleep");function Ue(t,e,n){return typeof n.structuralSharing=="function"?n.structuralSharing(t,e):n.structuralSharing!==!1?xs(t,e):e}r(Ue,"replaceData");function Rs(t,e,n=0){let s=[...t,e];return n&&s.length>n?s.slice(1):s}r(Rs,"addToEnd");function Ps(t,e,n=0){let s=[e,...t];return n&&s.length>n?s.slice(0,-1):s}r(Ps,"addToStart");var Fe=Symbol();function Dt(t,e){return!t.queryFn&&e?.initialPromise?()=>e.initialPromise:!t.queryFn||t.queryFn===Fe?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}r(Dt,"ensureQueryFn");function As(t,e,n){let s=!1,i;return Object.defineProperty(t,"signal",{enumerable:!0,get:r(()=>(i??=e(),s||(s=!0,i.aborted?n():i.addEventListener("abort",n,{once:!0})),i),"get")}),t}r(As,"addConsumeAwareSignal");var so=class extends oe{static{r(this,"FocusManager")}#e;#t;#n;constructor(){super(),this.#n=t=>{if(!se&&window.addEventListener){let e=r(()=>t(),"listener");return window.addEventListener("visibilitychange",e,!1),()=>{window.removeEventListener("visibilitychange",e)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(t){this.#n=t,this.#t?.(),this.#t=t(e=>{typeof e=="boolean"?this.setFocused(e):this.onFocus()})}setFocused(t){this.#e!==t&&(this.#e=t,this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(e=>{e(t)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},Re=new so;function Ne(){let t,e,n=new Promise((i,o)=>{t=i,e=o});n.status="pending",n.catch(()=>{});function s(i){Object.assign(n,i),delete n.resolve,delete n.reject}return r(s,"finalize"),n.resolve=i=>{s({status:"fulfilled",value:i}),t(i)},n.reject=i=>{s({status:"rejected",reason:i}),e(i)},n}r(Ne,"pendingThenable");function Ts(t){let e;if(t.then(n=>(e=n,n),B)?.catch(B),e!==void 0)return{data:e}}r(Ts,"tryResolveSync");function Ds(t){return t}r(Ds,"defaultTransformerFn");function io(t){return{mutationKey:t.options.mutationKey,state:t.state,...t.options.scope&&{scope:t.options.scope},...t.meta&&{meta:t.meta}}}r(io,"dehydrateMutation");function ro(t,e,n){let s=r(()=>{let i=t.promise?.then(e).catch(o=>n(o)?Promise.reject(new Error("redacted")):Promise.reject(o));return i?.catch(B),i},"dehydratePromise");return{dehydratedAt:Date.now(),state:{...t.state,...t.state.data!==void 0&&{data:e(t.state.data)}},queryKey:t.queryKey,queryHash:t.queryHash,...t.state.status==="pending"&&{promise:s()},...t.meta&&{meta:t.meta}}}r(ro,"dehydrateQuery");function Ls(t){return t.state.isPaused}r(Ls,"defaultShouldDehydrateMutation");function Os(t){return t.state.status==="success"}r(Os,"defaultShouldDehydrateQuery");function oo(t){return!0}r(oo,"defaultShouldRedactErrors");function an(t,e={}){let n=e.shouldDehydrateMutation??t.getDefaultOptions().dehydrate?.shouldDehydrateMutation??Ls,s=t.getMutationCache().getAll().flatMap(c=>n(c)?[io(c)]:[]),i=e.shouldDehydrateQuery??t.getDefaultOptions().dehydrate?.shouldDehydrateQuery??Os,o=e.shouldRedactErrors??t.getDefaultOptions().dehydrate?.shouldRedactErrors??oo,a=e.serializeData??t.getDefaultOptions().dehydrate?.serializeData??Ds,u=t.getQueryCache().getAll().flatMap(c=>i(c)?[ro(c,a,o)]:[]);return{mutations:s,queries:u}}r(an,"dehydrate");function un(t,e,n){if(typeof e!="object"||e===null)return;let s=t.getMutationCache(),i=t.getQueryCache(),o=n?.defaultOptions?.deserializeData??t.getDefaultOptions().hydrate?.deserializeData??Ds,a=e.mutations||[],u=e.queries||[];a.forEach(({state:c,...p})=>{s.build(t,{...t.getDefaultOptions().hydrate?.mutations,...n?.defaultOptions?.mutations,...p},c)}),u.forEach(({queryKey:c,state:p,queryHash:l,meta:y,promise:h,dehydratedAt:m})=>{let v=h?Ts(h):void 0,f=p.data===void 0?v?.data:p.data,w=f===void 0?f:o(f),b=i.get(l),T=b?.state.status==="pending",U=b?.state.fetchStatus==="fetching";if(b){let N=v&&m!==void 0&&m>b.state.dataUpdatedAt;if(p.dataUpdatedAt>b.state.dataUpdatedAt||N){let{fetchStatus:x,...D}=p;b.setState({...D,data:w})}}else b=i.build(t,{...t.getDefaultOptions().hydrate?.queries,...n?.defaultOptions?.queries,queryKey:c,queryHash:l,meta:y},{...p,data:w,fetchStatus:"idle",status:w!==void 0?"success":p.status});h&&!T&&!U&&(m===void 0||m>b.state.dataUpdatedAt)&&b.fetch(void 0,{initialPromise:Promise.resolve(h).then(o)}).catch(B)})}r(un,"hydrate");var ao=Is;function uo(){let t=[],e=0,n=r(u=>{u()},"notifyFn"),s=r(u=>{u()},"batchNotifyFn"),i=ao,o=r(u=>{e?t.push(u):i(()=>{n(u)})},"schedule"),a=r(()=>{let u=t;t=[],u.length&&i(()=>{s(()=>{u.forEach(c=>{n(c)})})})},"flush");return{batch:r(u=>{let c;e++;try{c=u()}finally{e--,e||a()}return c},"batch"),batchCalls:r(u=>(...c)=>{o(()=>{u(...c)})},"batchCalls"),schedule:o,setNotifyFunction:r(u=>{n=u},"setNotifyFunction"),setBatchNotifyFunction:r(u=>{s=u},"setBatchNotifyFunction"),setScheduler:r(u=>{i=u},"setScheduler")}}r(uo,"createNotifyManager");var V=uo();var co=class extends oe{static{r(this,"OnlineManager")}#e=!0;#t;#n;constructor(){super(),this.#n=t=>{if(!se&&window.addEventListener){let e=r(()=>t(!0),"onlineListener"),n=r(()=>t(!1),"offlineListener");return window.addEventListener("online",e,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",e),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(t){this.#n=t,this.#t?.(),this.#t=t(this.setOnline.bind(this))}setOnline(t){this.#e!==t&&(this.#e=t,this.listeners.forEach(n=>{n(t)}))}isOnline(){return this.#e}},Pe=new co;function lo(t){return Math.min(1e3*2**t,3e4)}r(lo,"defaultRetryDelay");function cn(t){return(t??"online")==="online"?Pe.isOnline():!0}r(cn,"canFetch");var Lt=class extends Error{static{r(this,"CancelledError")}constructor(t){super("CancelledError"),this.revert=t?.revert,this.silent=t?.silent}};function Ot(t){let e=!1,n=0,s,i=Ne(),o=r(()=>i.status!=="pending","isResolved"),a=r(f=>{if(!o()){let w=new Lt(f);h(w),t.onCancel?.(w)}},"cancel"),u=r(()=>{e=!0},"cancelRetry"),c=r(()=>{e=!1},"continueRetry"),p=r(()=>Re.isFocused()&&(t.networkMode==="always"||Pe.isOnline())&&t.canRun(),"canContinue"),l=r(()=>cn(t.networkMode)&&t.canRun(),"canStart"),y=r(f=>{o()||(s?.(),i.resolve(f))},"resolve"),h=r(f=>{o()||(s?.(),i.reject(f))},"reject"),m=r(()=>new Promise(f=>{s=r(w=>{(o()||p())&&f(w)},"continueFn"),t.onPause?.()}).then(()=>{s=void 0,o()||t.onContinue?.()}),"pause"),v=r(()=>{if(o())return;let f,w=n===0?t.initialPromise:void 0;try{f=w??t.fn()}catch(b){f=Promise.reject(b)}Promise.resolve(f).then(y).catch(b=>{if(o())return;let T=t.retry??(se?0:3),U=t.retryDelay??lo,N=typeof U=="function"?U(n,b):U,x=T===!0||typeof T=="number"&&n<T||typeof T=="function"&&T(n,b);if(e||!x){h(b);return}n++,t.onFail?.(n,b),Cs(N).then(()=>p()?void 0:m()).then(()=>{e?h(b):v()})})},"run");return{promise:i,status:r(()=>i.status,"status"),cancel:a,continue:r(()=>(s?.(),i),"continue"),cancelRetry:u,continueRetry:c,canStart:l,start:r(()=>(l()?v():m().then(v),i),"start")}}r(Ot,"createRetryer");var _t=class{static{r(this,"Removable")}#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Me(this.gcTime)&&(this.#e=ae.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(se?1/0:300*1e3))}clearGcTimeout(){this.#e&&(ae.clearTimeout(this.#e),this.#e=void 0)}};var qs=class extends _t{static{r(this,"Query")}#e;#t;#n;#i;#s;#a;#o;constructor(t){super(),this.#o=!1,this.#a=t.defaultOptions,this.setOptions(t.options),this.observers=[],this.#i=t.client,this.#n=this.#i.getQueryCache(),this.queryKey=t.queryKey,this.queryHash=t.queryHash,this.#e=Ms(this.options),this.state=t.state??this.#e,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#s?.promise}setOptions(t){if(this.options={...this.#a,...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=Ms(this.options);e.data!==void 0&&(this.setState(_s(e.data,e.dataUpdatedAt)),this.#e=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#n.remove(this)}setData(t,e){let n=Ue(this.state.data,t,this.options);return this.#r({data:n,type:"success",dataUpdatedAt:e?.updatedAt,manual:e?.manual}),n}setState(t,e){this.#r({type:"setState",state:t,setStateOptions:e})}cancel(t){let e=this.#s?.promise;return this.#s?.cancel(t),e?e.then(B).catch(B):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#e)}isActive(){return this.observers.some(t=>J(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Fe||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>ie(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!At(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#s?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#s?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(e=>e!==t),this.observers.length||(this.#s&&(this.#o?this.#s.cancel({revert:!0}):this.#s.cancelRetry()),this.scheduleGc()),this.#n.notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#r({type:"invalidate"})}async fetch(t,e){if(this.state.fetchStatus!=="idle"&&this.#s?.status()!=="rejected"){if(this.state.data!==void 0&&e?.cancelRefetch)this.cancel({silent:!0});else if(this.#s)return this.#s.continueRetry(),this.#s.promise}if(t&&this.setOptions(t),!this.options.queryFn){let u=this.observers.find(c=>c.options.queryFn);u&&this.setOptions(u.options)}let n=new AbortController,s=r(u=>{Object.defineProperty(u,"signal",{enumerable:!0,get:r(()=>(this.#o=!0,n.signal),"get")})},"addSignalProperty"),i=r(()=>{let u=Dt(this.options,e),p=r(()=>{let l={client:this.#i,queryKey:this.queryKey,meta:this.meta};return s(l),l},"createQueryFnContext")();return this.#o=!1,this.options.persister?this.options.persister(u,p,this):u(p)},"fetchFn"),a=r(()=>{let u={fetchOptions:e,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return s(u),u},"createFetchContext")();this.options.behavior?.onFetch(a,this),this.#t=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#r({type:"fetch",meta:a.fetchOptions?.meta}),this.#s=Ot({initialPromise:e?.initialPromise,fn:a.fetchFn,onCancel:r(u=>{u instanceof Lt&&u.revert&&this.setState({...this.#t,fetchStatus:"idle"}),n.abort()},"onCancel"),onFail:r((u,c)=>{this.#r({type:"failed",failureCount:u,error:c})},"onFail"),onPause:r(()=>{this.#r({type:"pause"})},"onPause"),onContinue:r(()=>{this.#r({type:"continue"})},"onContinue"),retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:r(()=>!0,"canRun")});try{let u=await this.#s.start();if(u===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(u),this.#n.config.onSuccess?.(u,this),this.#n.config.onSettled?.(u,this.state.error,this),u}catch(u){if(u instanceof Lt){if(u.silent)return this.#s.promise;if(u.revert){if(this.state.data===void 0)throw u;return this.state.data}}throw this.#r({type:"error",error:u}),this.#n.config.onError?.(u,this),this.#n.config.onSettled?.(this.state.data,u,this),u}finally{this.scheduleGc()}}#r(t){let e=r(n=>{switch(t.type){case"failed":return{...n,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...ln(n.data,this.options),fetchMeta:t.meta??null};case"success":let s={...n,..._s(t.data,t.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#t=t.manual?s:void 0,s;case"error":let i=t.error;return{...n,error:i,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...t.state}}},"reducer");this.state=e(this.state),V.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#n.notify({query:this,type:"updated",action:t})})}};function ln(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:cn(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}r(ln,"fetchState");function _s(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}r(_s,"successState");function Ms(t){let e=typeof t.initialData=="function"?t.initialData():t.initialData,n=e!==void 0,s=n?typeof t.initialDataUpdatedAt=="function"?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:n?s??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}r(Ms,"getDefaultState");var dn=class extends oe{static{r(this,"QueryObserver")}constructor(t,e){super(),this.options=e,this.#e=t,this.#r=null,this.#o=Ne(),this.bindMethods(),this.setOptions(e)}#e;#t=void 0;#n=void 0;#i=void 0;#s;#a;#o;#r;#m;#d;#h;#c;#l;#u;#f=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Us(this.#t,this.options)?this.#p():this.updateResult(),this.#w())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return pn(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return pn(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#I(),this.#t.removeObserver(this)}setOptions(t){let e=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof J(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#S(),this.#t.setOptions(this.options),e._defaulted&&!Tt(this.options,e)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});let s=this.hasListeners();s&&Fs(this.#t,n,this.options,e)&&this.#p(),this.updateResult(),s&&(this.#t!==n||J(this.options.enabled,this.#t)!==J(e.enabled,this.#t)||ie(this.options.staleTime,this.#t)!==ie(e.staleTime,this.#t))&&this.#y();let i=this.#v();s&&(this.#t!==n||J(this.options.enabled,this.#t)!==J(e.enabled,this.#t)||i!==this.#u)&&this.#g(i)}getOptimisticResult(t){let e=this.#e.getQueryCache().build(this.#e,t),n=this.createResult(e,t);return ho(this,n)&&(this.#i=n,this.#a=this.options,this.#s=this.#t.state),n}getCurrentResult(){return this.#i}trackResult(t,e){return new Proxy(t,{get:r((n,s)=>(this.trackProp(s),e?.(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(n,s)),"get")})}trackProp(t){this.#f.add(t)}getCurrentQuery(){return this.#t}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let e=this.#e.defaultQueryOptions(t),n=this.#e.getQueryCache().build(this.#e,e);return n.fetch().then(()=>this.createResult(n,e))}fetch(t){return this.#p({...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#i))}#p(t){this.#S();let e=this.#t.fetch(this.options,t);return t?.throwOnError||(e=e.catch(B)),e}#y(){this.#b();let t=ie(this.options.staleTime,this.#t);if(se||this.#i.isStale||!Me(t))return;let n=At(this.#i.dataUpdatedAt,t)+1;this.#c=ae.setTimeout(()=>{this.#i.isStale||this.updateResult()},n)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#g(t){this.#I(),this.#u=t,!(se||J(this.options.enabled,this.#t)===!1||!Me(this.#u)||this.#u===0)&&(this.#l=ae.setInterval(()=>{(this.options.refetchIntervalInBackground||Re.isFocused())&&this.#p()},this.#u))}#w(){this.#y(),this.#g(this.#v())}#b(){this.#c&&(ae.clearTimeout(this.#c),this.#c=void 0)}#I(){this.#l&&(ae.clearInterval(this.#l),this.#l=void 0)}createResult(t,e){let n=this.#t,s=this.options,i=this.#i,o=this.#s,a=this.#a,c=t!==n?t.state:this.#n,{state:p}=t,l={...p},y=!1,h;if(e._optimisticResults){let P=this.hasListeners(),F=!P&&Us(t,e),Q=P&&Fs(t,n,e,s);(F||Q)&&(l={...l,...ln(p.data,t.options)}),e._optimisticResults==="isRestoring"&&(l.fetchStatus="idle")}let{error:m,errorUpdatedAt:v,status:f}=l;h=l.data;let w=!1;if(e.placeholderData!==void 0&&h===void 0&&f==="pending"){let P;i?.isPlaceholderData&&e.placeholderData===a?.placeholderData?(P=i.data,w=!0):P=typeof e.placeholderData=="function"?e.placeholderData(this.#h?.state.data,this.#h):e.placeholderData,P!==void 0&&(f="success",h=Ue(i?.data,P,e),y=!0)}if(e.select&&h!==void 0&&!w)if(i&&h===o?.data&&e.select===this.#m)h=this.#d;else try{this.#m=e.select,h=e.select(h),h=Ue(i?.data,h,e),this.#d=h,this.#r=null}catch(P){this.#r=P}this.#r&&(m=this.#r,h=this.#d,v=Date.now(),f="error");let b=l.fetchStatus==="fetching",T=f==="pending",U=f==="error",N=T&&b,x=h!==void 0,k={status:f,fetchStatus:l.fetchStatus,isPending:T,isSuccess:f==="success",isError:U,isInitialLoading:N,isLoading:N,data:h,dataUpdatedAt:l.dataUpdatedAt,error:m,errorUpdatedAt:v,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:l.dataUpdateCount>0||l.errorUpdateCount>0,isFetchedAfterMount:l.dataUpdateCount>c.dataUpdateCount||l.errorUpdateCount>c.errorUpdateCount,isFetching:b,isRefetching:b&&!T,isLoadingError:U&&!x,isPaused:l.fetchStatus==="paused",isPlaceholderData:y,isRefetchError:U&&x,isStale:hn(t,e),refetch:this.refetch,promise:this.#o,isEnabled:J(e.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let P=k.data!==void 0,F=k.status==="error"&&!P,Q=r(ye=>{F?ye.reject(k.error):P&&ye.resolve(k.data)},"finalizeThenableIfPossible"),X=r(()=>{let ye=this.#o=k.promise=Ne();Q(ye)},"recreateThenable"),H=this.#o;switch(H.status){case"pending":t.queryHash===n.queryHash&&Q(H);break;case"fulfilled":(F||k.data!==H.value)&&X();break;case"rejected":(!F||k.error!==H.reason)&&X();break}}return k}updateResult(){let t=this.#i,e=this.createResult(this.#t,this.options);if(this.#s=this.#t.state,this.#a=this.options,this.#s.data!==void 0&&(this.#h=this.#t),Tt(e,t))return;this.#i=e;let n=r(()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!this.#f.size)return!0;let o=new Set(i??this.#f);return this.options.throwOnError&&o.add("error"),Object.keys(this.#i).some(a=>{let u=a;return this.#i[u]!==t[u]&&o.has(u)})},"shouldNotifyListeners");this.#E({listeners:n()})}#S(){let t=this.#e.getQueryCache().build(this.#e,this.options);if(t===this.#t)return;let e=this.#t;this.#t=t,this.#n=t.state,this.hasListeners()&&(e?.removeObserver(this),t.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#w()}#E(t){V.batch(()=>{t.listeners&&this.listeners.forEach(e=>{e(this.#i)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function po(t,e){return J(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&e.retryOnMount===!1)}r(po,"shouldLoadOnMount");function Us(t,e){return po(t,e)||t.state.data!==void 0&&pn(t,e,e.refetchOnMount)}r(Us,"shouldFetchOnMount");function pn(t,e,n){if(J(e.enabled,t)!==!1&&ie(e.staleTime,t)!=="static"){let s=typeof n=="function"?n(t):n;return s==="always"||s!==!1&&hn(t,e)}return!1}r(pn,"shouldFetchOn");function Fs(t,e,n,s){return(t!==e||J(s.enabled,t)===!1)&&(!n.suspense||t.state.status!=="error")&&hn(t,n)}r(Fs,"shouldFetchOptionally");function hn(t,e){return J(e.enabled,t)!==!1&&t.isStaleByTime(ie(e.staleTime,t))}r(hn,"isStale");function ho(t,e){return!Tt(t.getCurrentResult(),e)}r(ho,"shouldAssignObserverCurrentProperties");function fn(t){return{onFetch:r((e,n)=>{let s=e.options,i=e.fetchOptions?.meta?.fetchMore?.direction,o=e.state.data?.pages||[],a=e.state.data?.pageParams||[],u={pages:[],pageParams:[]},c=0,p=r(async()=>{let l=!1,y=r(v=>{As(v,()=>e.signal,()=>l=!0)},"addSignalProperty"),h=Dt(e.options,e.fetchOptions),m=r(async(v,f,w)=>{if(l)return Promise.reject();if(f==null&&v.pages.length)return Promise.resolve(v);let T=r(()=>{let D={client:e.client,queryKey:e.queryKey,pageParam:f,direction:w?"backward":"forward",meta:e.options.meta};return y(D),D},"createQueryFnContext")(),U=await h(T),{maxPages:N}=e.options,x=w?Ps:Rs;return{pages:x(v.pages,U,N),pageParams:x(v.pageParams,f,N)}},"fetchPage");if(i&&o.length){let v=i==="backward",f=v?fo:Ns,w={pages:o,pageParams:a},b=f(s,w);u=await m(w,b,v)}else{let v=t??o.length;do{let f=c===0?a[0]??s.initialPageParam:Ns(s,u);if(c>0&&f==null)break;u=await m(u,f),c++}while(c<v)}return u},"fetchFn");e.options.persister?e.fetchFn=()=>e.options.persister?.(p,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},n):e.fetchFn=p},"onFetch")}}r(fn,"infiniteQueryBehavior");function Ns(t,{pages:e,pageParams:n}){let s=e.length-1;return e.length>0?t.getNextPageParam(e[s],e,n[s],n):void 0}r(Ns,"getNextPageParam");function fo(t,{pages:e,pageParams:n}){return e.length>0?t.getPreviousPageParam?.(e[0],e,n[0],n):void 0}r(fo,"getPreviousPageParam");var Bs=class extends _t{static{r(this,"Mutation")}#e;#t;#n;#i;constructor(t){super(),this.#e=t.client,this.mutationId=t.mutationId,this.#n=t.mutationCache,this.#t=[],this.state=t.state||mo(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){this.#t.includes(t)||(this.#t.push(t),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){this.#t=this.#t.filter(e=>e!==t),this.scheduleGc(),this.#n.notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#n.remove(this))}continue(){return this.#i?.continue()??this.execute(this.state.variables)}async execute(t){let e=r(()=>{this.#s({type:"continue"})},"onContinue"),n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#i=Ot({fn:r(()=>this.options.mutationFn?this.options.mutationFn(t,n):Promise.reject(new Error("No mutationFn found")),"fn"),onFail:r((o,a)=>{this.#s({type:"failed",failureCount:o,error:a})},"onFail"),onPause:r(()=>{this.#s({type:"pause"})},"onPause"),onContinue:e,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:r(()=>this.#n.canRun(this),"canRun")});let s=this.state.status==="pending",i=!this.#i.canStart();try{if(s)e();else{this.#s({type:"pending",variables:t,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(t,this,n);let a=await this.options.onMutate?.(t,n);a!==this.state.context&&this.#s({type:"pending",context:a,variables:t,isPaused:i})}let o=await this.#i.start();return await this.#n.config.onSuccess?.(o,t,this.state.context,this,n),await this.options.onSuccess?.(o,t,this.state.context,n),await this.#n.config.onSettled?.(o,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(o,null,t,this.state.context,n),this.#s({type:"success",data:o}),o}catch(o){try{await this.#n.config.onError?.(o,t,this.state.context,this,n)}catch(a){Promise.reject(a)}try{await this.options.onError?.(o,t,this.state.context,n)}catch(a){Promise.reject(a)}try{await this.#n.config.onSettled?.(void 0,o,this.state.variables,this.state.context,this,n)}catch(a){Promise.reject(a)}try{await this.options.onSettled?.(void 0,o,t,this.state.context,n)}catch(a){Promise.reject(a)}throw this.#s({type:"error",error:o}),o}finally{this.#n.runNext(this)}}#s(t){let e=r(n=>{switch(t.type){case"failed":return{...n,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...n,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:t.error,failureCount:n.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}},"reducer");this.state=e(this.state),V.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(t)}),this.#n.notify({mutation:this,type:"updated",action:t})})}};function mo(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}r(mo,"getDefaultState");var Vs=class extends oe{static{r(this,"MutationCache")}constructor(t={}){super(),this.config=t,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(t,e,n){let s=new Bs({client:t,mutationCache:this,mutationId:++this.#n,options:t.defaultMutationOptions(e),state:n});return this.add(s),s}add(t){this.#e.add(t);let e=Mt(t);if(typeof e=="string"){let n=this.#t.get(e);n?n.push(t):this.#t.set(e,[t])}this.notify({type:"added",mutation:t})}remove(t){if(this.#e.delete(t)){let e=Mt(t);if(typeof e=="string"){let n=this.#t.get(e);if(n)if(n.length>1){let s=n.indexOf(t);s!==-1&&n.splice(s,1)}else n[0]===t&&this.#t.delete(e)}}this.notify({type:"removed",mutation:t})}canRun(t){let e=Mt(t);if(typeof e=="string"){let s=this.#t.get(e)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let e=Mt(t);return typeof e=="string"?this.#t.get(e)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){V.batch(()=>{this.#e.forEach(t=>{this.notify({type:"removed",mutation:t})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(t){let e={exact:!0,...t};return this.getAll().find(n=>on(e,n))}findAll(t={}){return this.getAll().filter(e=>on(t,e))}notify(t){V.batch(()=>{this.listeners.forEach(e=>{e(t)})})}resumePausedMutations(){let t=this.getAll().filter(e=>e.state.isPaused);return V.batch(()=>Promise.all(t.map(e=>e.continue().catch(B))))}};function Mt(t){return t.options.scope?.id}r(Mt,"scopeFor");var js=class extends oe{static{r(this,"QueryCache")}constructor(t={}){super(),this.config=t,this.#e=new Map}#e;build(t,e,n){let s=e.queryKey,i=e.queryHash??qe(s,e),o=this.get(i);return o||(o=new qs({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(e),state:n,defaultOptions:t.getQueryDefaults(s)}),this.add(o)),o}add(t){this.#e.has(t.queryHash)||(this.#e.set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let e=this.#e.get(t.queryHash);e&&(t.destroy(),e===t&&this.#e.delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){V.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return this.#e.get(t)}getAll(){return[...this.#e.values()]}find(t){let e={exact:!0,...t};return this.getAll().find(n=>rn(e,n))}findAll(t={}){let e=this.getAll();return Object.keys(t).length>0?e.filter(n=>rn(t,n)):e}notify(t){V.batch(()=>{this.listeners.forEach(e=>{e(t)})})}onFocus(){V.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){V.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}};var mn=class{static{r(this,"QueryClient")}#e;#t;#n;#i;#s;#a;#o;#r;constructor(t={}){this.#e=t.queryCache||new js,this.#t=t.mutationCache||new Vs,this.#n=t.defaultOptions||{},this.#i=new Map,this.#s=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=Re.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#r=Pe.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#r?.(),this.#r=void 0)}isFetching(t){return this.#e.findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return this.#t.findAll({...t,status:"pending"}).length}getQueryData(t){let e=this.defaultQueryOptions({queryKey:t});return this.#e.get(e.queryHash)?.state.data}ensureQueryData(t){let e=this.defaultQueryOptions(t),n=this.#e.build(this,e),s=n.state.data;return s===void 0?this.fetchQuery(t):(t.revalidateIfStale&&n.isStaleByTime(ie(e.staleTime,n))&&this.prefetchQuery(e),Promise.resolve(s))}getQueriesData(t){return this.#e.findAll(t).map(({queryKey:e,state:n})=>{let s=n.data;return[e,s]})}setQueryData(t,e,n){let s=this.defaultQueryOptions({queryKey:t}),o=this.#e.get(s.queryHash)?.state.data,a=ks(e,o);if(a!==void 0)return this.#e.build(this,s).setData(a,{...n,manual:!0})}setQueriesData(t,e,n){return V.batch(()=>this.#e.findAll(t).map(({queryKey:s})=>[s,this.setQueryData(s,e,n)]))}getQueryState(t){let e=this.defaultQueryOptions({queryKey:t});return this.#e.get(e.queryHash)?.state}removeQueries(t){let e=this.#e;V.batch(()=>{e.findAll(t).forEach(n=>{e.remove(n)})})}resetQueries(t,e){let n=this.#e;return V.batch(()=>(n.findAll(t).forEach(s=>{s.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){let n={revert:!0,...e},s=V.batch(()=>this.#e.findAll(t).map(i=>i.cancel(n)));return Promise.all(s).then(B).catch(B)}invalidateQueries(t,e={}){return V.batch(()=>(this.#e.findAll(t).forEach(n=>{n.invalidate()}),t?.refetchType==="none"?Promise.resolve():this.refetchQueries({...t,type:t?.refetchType??t?.type??"active"},e)))}refetchQueries(t,e={}){let n={...e,cancelRefetch:e.cancelRefetch??!0},s=V.batch(()=>this.#e.findAll(t).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let o=i.fetch(void 0,n);return n.throwOnError||(o=o.catch(B)),i.state.fetchStatus==="paused"?Promise.resolve():o}));return Promise.all(s).then(B)}fetchQuery(t){let e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);let n=this.#e.build(this,e);return n.isStaleByTime(ie(e.staleTime,n))?n.fetch(e):Promise.resolve(n.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(B).catch(B)}fetchInfiniteQuery(t){return t.behavior=fn(t.pages),this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(B).catch(B)}ensureInfiniteQueryData(t){return t.behavior=fn(t.pages),this.ensureQueryData(t)}resumePausedMutations(){return Pe.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(t){this.#n=t}setQueryDefaults(t,e){this.#i.set(xe(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){let e=[...this.#i.values()],n={};return e.forEach(s=>{Ce(t,s.queryKey)&&Object.assign(n,s.defaultOptions)}),n}setMutationDefaults(t,e){this.#s.set(xe(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){let e=[...this.#s.values()],n={};return e.forEach(s=>{Ce(t,s.mutationKey)&&Object.assign(n,s.defaultOptions)}),n}defaultQueryOptions(t){if(t._defaulted)return t;let e={...this.#n.queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=qe(e.queryKey,e)),e.refetchOnReconnect===void 0&&(e.refetchOnReconnect=e.networkMode!=="always"),e.throwOnError===void 0&&(e.throwOnError=!!e.suspense),!e.networkMode&&e.persister&&(e.networkMode="offlineFirst"),e.queryFn===Fe&&(e.enabled=!1),e}defaultMutationOptions(t){return t?._defaulted?t:{...this.#n.mutations,...t?.mutationKey&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}};function $s(){return new mn({defaultOptions:{queries:{retry:!1,refetchOnWindowFocus:!1,gcTime:1e3*60*60*1,staleTime:1e3*60*10}}})}r($s,"createSwishQueryClient");var yo=Symbol.for("preact-signals");function Ut(){if(me>1)me--;else{for(var t,e=!1;Be!==void 0;){var n=Be;for(Be=void 0,yn++;n!==void 0;){var s=n.o;if(n.o=void 0,n.f&=-3,!(8&n.f)&&zs(n))try{n.c()}catch(i){e||(t=i,e=!0)}n=s}}if(yn=0,me--,e)throw t}}r(Ut,"t");function ue(t){if(me>0)return t();me++;try{return t()}finally{Ut()}}r(ue,"n");var L=void 0;function Qs(t){var e=L;L=void 0;try{return t()}finally{L=e}}r(Qs,"o");var Hs,Be=void 0,me=0,yn=0,qt=0;function Gs(t){if(L!==void 0){var e=t.n;if(e===void 0||e.t!==L)return e={i:0,S:t,p:L.s,n:void 0,t:L,e:void 0,x:void 0,r:e},L.s!==void 0&&(L.s.n=e),L.s=e,t.n=e,32&L.f&&t.S(e),e;if(e.i===-1)return e.i=0,e.n!==void 0&&(e.n.p=e.p,e.p!==void 0&&(e.p.n=e.n),e.p=L.s,e.n=void 0,L.s.n=e,L.s=e),e}}r(Gs,"e");function z(t,e){this.v=t,this.i=0,this.n=void 0,this.t=void 0,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}r(z,"d");z.prototype.brand=yo;z.prototype.h=function(){return!0};z.prototype.S=function(t){var e=this,n=this.t;n!==t&&t.e===void 0&&(t.x=n,this.t=t,n!==void 0?n.e=t:Qs(function(){var s;(s=e.W)==null||s.call(e)}))};z.prototype.U=function(t){var e=this;if(this.t!==void 0){var n=t.e,s=t.x;n!==void 0&&(n.x=s,t.e=void 0),s!==void 0&&(s.e=n,t.x=void 0),t===this.t&&(this.t=s,s===void 0&&Qs(function(){var i;(i=e.Z)==null||i.call(e)}))}};z.prototype.subscribe=function(t){var e=this;return K(function(){var n=e.value,s=L;L=void 0;try{t(n)}finally{L=s}},{name:"sub"})};z.prototype.valueOf=function(){return this.value};z.prototype.toString=function(){return this.value+""};z.prototype.toJSON=function(){return this.value};z.prototype.peek=function(){var t=L;L=void 0;try{return this.value}finally{L=t}};Object.defineProperty(z.prototype,"value",{get:r(function(){var t=Gs(this);return t!==void 0&&(t.i=this.i),this.v},"get"),set:r(function(t){if(t!==this.v){if(yn>100)throw new Error("Cycle detected");this.v=t,this.i++,qt++,me++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{Ut()}}},"set")});function M(t,e){return new z(t,e)}r(M,"c");function zs(t){for(var e=t.s;e!==void 0;e=e.n)if(e.S.i!==e.i||!e.S.h()||e.S.i!==e.i)return!0;return!1}r(zs,"a");function Ks(t){for(var e=t.s;e!==void 0;e=e.n){var n=e.S.n;if(n!==void 0&&(e.r=n),e.S.n=e,e.i=-1,e.n===void 0){t.s=e;break}}}r(Ks,"l");function Ws(t){for(var e=t.s,n=void 0;e!==void 0;){var s=e.p;e.i===-1?(e.S.U(e),s!==void 0&&(s.n=e.n),e.n!==void 0&&(e.n.p=s)):n=e,e.S.n=e.r,e.r!==void 0&&(e.r=void 0),e=s}t.s=n}r(Ws,"y");function be(t,e){z.call(this,void 0),this.x=t,this.s=void 0,this.g=qt-1,this.f=4,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}r(be,"w");be.prototype=new z;be.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===qt))return!0;if(this.g=qt,this.f|=1,this.i>0&&!zs(this))return this.f&=-2,!0;var t=L;try{Ks(this),L=this;var e=this.x();(16&this.f||this.v!==e||this.i===0)&&(this.v=e,this.f&=-17,this.i++)}catch(n){this.v=n,this.f|=16,this.i++}return L=t,Ws(this),this.f&=-2,!0};be.prototype.S=function(t){if(this.t===void 0){this.f|=36;for(var e=this.s;e!==void 0;e=e.n)e.S.S(e)}z.prototype.S.call(this,t)};be.prototype.U=function(t){if(this.t!==void 0&&(z.prototype.U.call(this,t),this.t===void 0)){this.f&=-33;for(var e=this.s;e!==void 0;e=e.n)e.S.U(e)}};be.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var t=this.t;t!==void 0;t=t.x)t.t.N()}};Object.defineProperty(be.prototype,"value",{get:r(function(){if(1&this.f)throw new Error("Cycle detected");var t=Gs(this);if(this.h(),t!==void 0&&(t.i=this.i),16&this.f)throw this.v;return this.v},"get")});function Y(t,e){return new be(t,e)}r(Y,"b");function Xs(t){var e=t.u;if(t.u=void 0,typeof e=="function"){me++;var n=L;L=void 0;try{e()}catch(s){throw t.f&=-2,t.f|=8,vn(t),s}finally{L=n,Ut()}}}r(Xs,"_");function vn(t){for(var e=t.s;e!==void 0;e=e.n)e.S.U(e);t.x=void 0,t.s=void 0,Xs(t)}r(vn,"p");function vo(t){if(L!==this)throw new Error("Out-of-order effect");Ws(this),L=t,this.f&=-2,8&this.f&&vn(this),Ut()}r(vo,"g");function Ae(t,e){this.x=t,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32,this.name=e?.name,Hs&&Hs.push(this)}r(Ae,"S");Ae.prototype.c=function(){var t=this.S();try{if(8&this.f||this.x===void 0)return;var e=this.x();typeof e=="function"&&(this.u=e)}finally{t()}};Ae.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,Xs(this),Ks(this),me++;var t=L;return L=this,vo.bind(this,t)};Ae.prototype.N=function(){2&this.f||(this.f|=2,this.o=Be,Be=this)};Ae.prototype.d=function(){this.f|=8,1&this.f||vn(this)};Ae.prototype.dispose=function(){this.d()};function K(t,e){var n=new Ae(t,e);try{n.c()}catch(i){throw n.d(),i}var s=n.d.bind(n);return s[Symbol.dispose]=s,s}r(K,"m");var go="swish-query-cache";function wo(t){return t.replace(/\.myshopify\.com$/,"")||"unknown-store"}r(wo,"normalizeStoreKeyPart");function Ft({customerId:t,storeDomain:e}){let n=t??"guest",s=wo(e??"");return`${go}:${s}:${n}`}r(Ft,"getSwishQueryStorageKey");var bo=1e3*60*60*24,Io=1e3;function gn(){return!!globalThis.window?.localStorage}r(gn,"canUseLocalStorage");function So(t){if(!gn())return null;let e=globalThis.window.localStorage.getItem(t);if(!e)return null;try{return JSON.parse(e)}catch{return globalThis.window.localStorage.removeItem(t),null}}r(So,"readPersistedState");function Eo(t,e){if(gn())try{globalThis.window.localStorage.setItem(t,JSON.stringify(e))}catch{}}r(Eo,"writePersistedState");function ko(t){if(gn())try{globalThis.window.localStorage.removeItem(t)}catch{}}r(ko,"removePersistedState");function xo(t,e){return Number.isFinite(t.timestamp)?Date.now()-t.timestamp>e:!0}r(xo,"isPersistedStateExpired");function Js({queryClient:t,cacheBuster:e,customerId:n,storeDomain:s,maxAgeMs:i=bo,throttleMs:o=Io}){let a=Ft({customerId:n,storeDomain:s}),u=M(!1),c=So(a);c?.buster===e&&!xo(c,i)?un(t,c.clientState):c&&ko(a),u.value=!0;let p=null,l=!1,y=r(()=>{Eo(a,{buster:e,timestamp:Date.now(),clientState:an(t)})},"persistNow"),h=r(()=>{l=!0,!p&&(p=setTimeout(()=>{p=null,l&&(l=!1,y())},Math.max(o,0)))},"schedulePersist"),m=r(()=>{l&&(l=!1,p&&(clearTimeout(p),p=null),y())},"flushPersist"),v=t.getQueryCache().subscribe(w=>{u.value&&h()}),f=r(()=>{m()},"onPageHide");return globalThis.window?.addEventListener("pagehide",f),{restored:u,storageKey:a,dispose:r(()=>{globalThis.window?.removeEventListener("pagehide",f),v(),m()},"dispose")}}r(Js,"initSwishQueryPersistence");function Ys({events:t,cacheBuster:e,customerId:n,storeDomain:s}){let i=$s(),o=Js({queryClient:i,cacheBuster:e,customerId:n,storeDomain:s});return bs({events:t,queryClient:i}),{client:i,cacheBuster:e,restored:o.restored,storageKey:o.storageKey,keys:{items:Pt}}}r(Ys,"createSwishQuery");var Zs=r(t=>e=>{let n=e instanceof Location,s=e instanceof HTMLAnchorElement,i=e instanceof HTMLElement;if(!n&&!s&&!i)throw new Error("Invalid source");let{productHandle:o,productId:a,variantId:u,itemId:c}=i?e.dataset:{},y=!!(a||o)||!!c,h=M({loading:!1,productHandle:o,productId:a,variantId:u,itemId:c});if(!y&&(n||s)){let m=e.href,v=De(m);v?.productHandle&&v.productHandle!==h.value.productHandle&&(h.value={...h.value,...v,productId:void 0},ls({source:e,onProductUrlChange:r(f=>{h.value={...h.value,...f,productId:f.productHandle===h.value.productHandle?h.value.productId:void 0}},"onProductUrlChange")}))}return K(()=>{h.value.loading||!h.value.productId&&h.value.productHandle&&(h.value={...h.value,loading:!0},t.storefront.loadProductId({productHandle:h.value.productHandle}).then(m=>{m.errors&&console.error("Error loading product id",m.errors);let v=m.data?.product?.id?O(m.data.product.id):void 0;h.value={...h.value,productId:v,loading:!v}}))}),h},"itemContextSignal");function ei({queryClient:t,options:e,restored:n}){let s=M(null),i=M(!1),o=M(null),a=M(!1),u=r(m=>{let v=n?.value??!0,f=m.enabled??!0;return{...m,enabled:!!(f&&v)}},"getObserverOptions"),c=new dn(t,u(e.value)),p=c.subscribe(m=>{ue(()=>{s.value=m.data??null,i.value=m.isLoading,a.value=m.isRefetching,o.value=m.error??null})}),l=K(()=>{c.setOptions(u(e.value))}),y=!1;return{data:s,loading:i,error:o,refetching:a,refetch:r(()=>c.refetch(),"refetch"),dispose:r(()=>{y||(y=!0,l(),p(),c.destroy())},"dispose")}}r(ei,"createTanstackQuerySignal");var ti=r(t=>e=>{let n=[],s=Y(()=>{let{productId:P,variantId:F,loading:Q}=e.value;return!P||Q?null:F?`variant:${O(F)}`:`product:${O(P)}`}),i=Y(()=>e.value.loading||!!e.value.itemId||!e.value.productId),o=M(!i.value),a=M(null),u=M(!1),c=M(!1),p=Y(()=>{let P=s.value,F=i.value,{productId:Q,variantId:X}=e.value;return{queryKey:t.query.keys.items({productId:Q,variantId:X}),queryFn:r(async()=>{let H=await t.api.items.list({limit:1,query:P??void 0});if("error"in H)throw H.error;return H},"queryFn"),enabled:!F}}),{data:l,loading:y,error:h,refetching:m,dispose:v}=ei({queryClient:t.query.client,options:p,restored:t.query.restored});n.push(v);let f=M(e.value.itemId??null),w=K(()=>{ue(()=>{if(o.value=y.value,a.value=h.value,!e.value.itemId){let P=l.value?.data?.[0]?.id??null;P!==f.value&&(f.value=P)}})});n.push(w);async function b(){if(!f.value)return;u.value=!0;let F=await(await t.intents.invoke("unsave:item",{itemId:f.value})).complete;F.code==="ok"&&"itemId"in F.data&&(f.value=null),u.value=!1}r(b,"unsave");async function T(){if(!f.value)return;u.value=!0;let F=await(await t.intents.invoke("edit:item-lists",{itemId:f.value})).complete;F.code==="ok"&&"itemId"in F.data&&(f.value=null),u.value=!1}r(T,"update");async function U(){let{productId:P,variantId:F}=e.value;if(!P)return;u.value=!0,c.value=!0;let X=await(await t.intents.invoke("save:item",{productId:P,variantId:F})).complete;if(X.code==="ok"){let H=X.data;f.value=H.item.id,u.value=!1}else X.code==="error"&&console.warn("Failed to create item",X),ue(()=>{u.value=!1,c.value=!1})}r(U,"save");let N=Y(()=>o.value||u.value||e.value.loading),x=K(()=>{c.value&&!u.value&&!m.value&&(c.value=!1)});n.push(x);let D=Y(()=>{let P=m.value&&c.value,F=!!f.value,Q=!F&&(u.value||P),X=F&&(u.value||P),H=Y(()=>Q?"saving":X?"unsaving":F?"saved":"unsaved");return{error:a.value,status:H.value,savedItemId:f.value,loading:N.value,submitting:u.value,saved:F,saving:Q,unsaving:X}});async function k(){N.value||(D.value.saved&&D.value.savedItemId?b():D.value.saved||await U())}return r(k,"toggle"),Object.assign(D,{save:U,unsave:b,update:T,toggle:k,dispose:r(()=>{for(;n.length;)n.pop()?.()},"dispose")})},"itemStateSignal");var ni=r(t=>()=>{let{data:e,loading:n,error:s}=t.state.swishQuery(()=>t.api.items.count(),{refetch:["item-create","item-delete"]}),i=M(0),o=M(!0),a=M(null);return K(()=>{ue(()=>{o.value=n.value,a.value=s.value,i.value=e.value?.count??0})}),Y(()=>({count:i.value,loading:o.value,error:a.value}))},"itemCountSignal");var Co="token-update",si=r(t=>(e,n)=>{let s=M(null),i=M(null),o=M(null),a=M(!n?.skip),u=M(!1),c=Y(()=>a.value&&u.value);async function p(){if(!n?.skip?.value)try{a.value=!0;let l=await e(n?.variables?.value);ue(()=>{o.value="error"in l?l.error:null,s.value="data"in l?l.data:null,i.value="pageInfo"in l?l.pageInfo:null,a.value=!1,u.value=!0})}catch(l){ue(()=>{o.value=l,a.value=!1,u.value=!0})}}return r(p,"executeFetch"),K(()=>{if(p(),n?.refetch?.length){let l=[...n.refetch,Co];return t.events.subscribe(l,p)}}),{data:s,pageInfo:i,error:o,loading:a,refetching:c}},"swishQuerySignals");function Ro(t,e){let n=en(e),s=t.state.itemContext(n),i=t.state.itemState(s);t.state.effect(()=>{let{status:a,saved:u}=i.value;e.setAttribute("swish-item-state",a),e.setAttribute("aria-pressed",String(u))});let o=r(()=>{i.toggle()},"onClick");e.addEventListener("click",o)}r(Ro,"bindItemState");function Po(t,e){let n=t.state.itemCount();t.state.effect(()=>{let{count:s,loading:i}=n.value,o=i?"":String(s);e.setAttribute("swish-item-count",o),e.textContent=o})}r(Po,"bindItemCount");function ii(t){re({selector:"[swish-item-state]",onElementFound:r(e=>{Ro(t,e)},"onElementFound")}),re({selector:"[swish-item-count]",onElementFound:r(e=>{Po(t,e)},"onElementFound")})}r(ii,"initDeclarativeState");var Ie="GraphQL Client";var wn="An error occurred while fetching from the API. Review 'graphQLErrors' for details.",bn="Response returned unexpected Content-Type:",In="An unknown error has occurred. The API did not return a data object or any errors in its response.",Nt={json:"application/json",multipart:"multipart/mixed"},Sn="X-SDK-Variant",En="X-SDK-Version",oi="shopify-graphql-client",ai="1.4.1",Bt=1e3,ui=[429,503],kn=/@(defer)\b/i,ri=`\r
|
|
8
|
+
`,ci=/boundary="?([^=";]+)"?/i,xn=ri+ri;function ce(t,e=Ie){return t.startsWith(`${e}`)?t:`${e}: ${t}`}r(ce,"formatErrorMessage");function fe(t){return t instanceof Error?t.message:JSON.stringify(t)}r(fe,"getErrorMessage");function Cn(t){return t instanceof Error&&t.cause?t.cause:void 0}r(Cn,"getErrorCause");function Rn(t){return t.flatMap(({errors:e})=>e??[])}r(Rn,"combineErrors");function Vt({client:t,retries:e}){if(e!==void 0&&(typeof e!="number"||e<0||e>3))throw new Error(`${t}: The provided "retries" value (${e}) is invalid - it cannot be less than ${0} or greater than ${3}`)}r(Vt,"validateRetries");function W(t,e){return e&&(typeof e!="object"||Array.isArray(e)||typeof e=="object"&&Object.keys(e).length>0)?{[t]:e}:{}}r(W,"getKeyValueIfValid");function Pn(t,e){if(t.length===0)return e;let s={[t.pop()]:e};return t.length===0?s:Pn(t,s)}r(Pn,"buildDataObjectByPath");function di(t,e){return Object.keys(e||{}).reduce((n,s)=>(typeof e[s]=="object"||Array.isArray(e[s]))&&t[s]?(n[s]=di(t[s],e[s]),n):(n[s]=e[s],n),Array.isArray(t)?[...t]:{...t})}r(di,"combineObjects");function An([t,...e]){return e.reduce(di,{...t})}r(An,"buildCombinedDataObject");function Tn({clientLogger:t,customFetchApi:e=fetch,client:n=Ie,defaultRetryWaitTime:s=Bt,retriableCodes:i=ui}){let o=r(async(a,u,c)=>{let p=u+1,l=c+1,y;try{if(y=await e(...a),t({type:"HTTP-Response",content:{requestParams:a,response:y}}),!y.ok&&i.includes(y.status)&&p<=l)throw new Error;let h=y?.headers.get("X-Shopify-API-Deprecated-Reason")||"";return h&&t({type:"HTTP-Response-GraphQL-Deprecation-Notice",content:{requestParams:a,deprecationNotice:h}}),y}catch(h){if(p<=l){let m=y?.headers.get("Retry-After");return await Ao(m?parseInt(m,10):s),t({type:"HTTP-Retry",content:{requestParams:a,lastResponse:y,retryAttempt:u,maxRetries:c}}),o(a,p,c)}throw new Error(ce(`${c>0?`Attempted maximum number of ${c} network retries. Last message - `:""}${fe(h)}`,n))}},"httpFetch");return o}r(Tn,"generateHttpFetch");async function Ao(t){return new Promise(e=>setTimeout(e,t))}r(Ao,"sleep");function Dn({headers:t,url:e,customFetchApi:n=fetch,retries:s=0,logger:i}){Vt({client:Ie,retries:s});let o={headers:t,url:e,retries:s},a=To(i),u=Tn({customFetchApi:n,clientLogger:a,defaultRetryWaitTime:Bt}),c=Do(u,o),p=Lo(c),l=No(c);return{config:o,fetch:c,request:p,requestStream:l}}r(Dn,"createGraphQLClient");function To(t){return e=>{t&&t(e)}}r(To,"generateClientLogger");async function hi(t){let{errors:e,data:n,extensions:s}=await t.json();return{...W("data",n),...W("extensions",s),headers:t.headers,...e||!n?{errors:{networkStatusCode:t.status,message:ce(e?wn:In),...W("graphQLErrors",e),response:t}}:{}}}r(hi,"processJSONResponse");function Do(t,{url:e,headers:n,retries:s}){return async(i,o={})=>{let{variables:a,headers:u,url:c,retries:p,keepalive:l,signal:y}=o,h=JSON.stringify({query:i,variables:a});Vt({client:Ie,retries:p});let m=Object.entries({...n,...u}).reduce((f,[w,b])=>(f[w]=Array.isArray(b)?b.join(", "):b.toString(),f),{});return!m[Sn]&&!m[En]&&(m[Sn]=oi,m[En]=ai),t([c??e,{method:"POST",headers:m,body:h,signal:y,keepalive:l}],1,p??s)}}r(Do,"generateFetch");function Lo(t){return async(...e)=>{if(kn.test(e[0]))throw new Error(ce("This operation will result in a streamable response - use requestStream() instead."));let n=null;try{n=await t(...e);let{status:s,statusText:i}=n,o=n.headers.get("content-type")||"";return n.ok?o.includes(Nt.json)?await hi(n):{errors:{networkStatusCode:s,message:ce(`${bn} ${o}`),response:n}}:{errors:{networkStatusCode:s,message:ce(i),response:n}}}catch(s){return{errors:{message:fe(s),...n==null?{}:{networkStatusCode:n.status,response:n}}}}}}r(Lo,"generateRequest");async function*Oo(t){let e=new TextDecoder;if(t.body[Symbol.asyncIterator])for await(let n of t.body)yield e.decode(n);else{let n=t.body.getReader(),s;try{for(;!(s=await n.read()).done;)yield e.decode(s.value)}finally{n.cancel()}}}r(Oo,"getStreamBodyIterator");function _o(t,e){return{async*[Symbol.asyncIterator](){try{let n="";for await(let s of t)if(n+=s,n.indexOf(e)>-1){let i=n.lastIndexOf(e),a=n.slice(0,i).split(e).filter(u=>u.trim().length>0).map(u=>u.slice(u.indexOf(xn)+xn.length).trim());a.length>0&&(yield a),n=n.slice(i+e.length),n.trim()==="--"&&(n="")}}catch(n){throw new Error(`Error occured while processing stream payload - ${fe(n)}`)}}}}r(_o,"readStreamChunk");function Mo(t){return{async*[Symbol.asyncIterator](){yield{...await hi(t),hasNext:!1}}}}r(Mo,"createJsonResponseAsyncIterator");function qo(t){return t.map(e=>{try{return JSON.parse(e)}catch(n){throw new Error(`Error in parsing multipart response - ${fe(n)}`)}}).map(e=>{let{data:n,incremental:s,hasNext:i,extensions:o,errors:a}=e;if(!s)return{data:n||{},...W("errors",a),...W("extensions",o),hasNext:i};let u=s.map(({data:c,path:p,errors:l})=>({data:c&&p?Pn(p,c):{},...W("errors",l)}));return{data:u.length===1?u[0].data:An([...u.map(({data:c})=>c)]),...W("errors",Rn(u)),hasNext:i}})}r(qo,"getResponseDataFromChunkBodies");function Uo(t,e){if(t.length>0)throw new Error(wn,{cause:{graphQLErrors:t}});if(Object.keys(e).length===0)throw new Error(In)}r(Uo,"validateResponseData");function Fo(t,e){let n=(e??"").match(ci),s=`--${n?n[1]:"-"}`;if(!t.body?.getReader&&!t.body?.[Symbol.asyncIterator])throw new Error("API multipart response did not return an iterable body",{cause:t});let i=Oo(t),o={},a;return{async*[Symbol.asyncIterator](){try{let u=!0;for await(let c of _o(i,s)){let p=qo(c);a=p.find(y=>y.extensions)?.extensions??a;let l=Rn(p);o=An([o,...p.map(({data:y})=>y)]),u=p.slice(-1)[0].hasNext,Uo(l,o),yield{...W("data",o),...W("extensions",a),hasNext:u}}if(u)throw new Error("Response stream terminated unexpectedly")}catch(u){let c=Cn(u);yield{...W("data",o),...W("extensions",a),errors:{message:ce(fe(u)),networkStatusCode:t.status,...W("graphQLErrors",c?.graphQLErrors),response:t},hasNext:!1}}}}}r(Fo,"createMultipartResponseAsyncInterator");function No(t){return async(...e)=>{if(!kn.test(e[0]))throw new Error(ce("This operation does not result in a streamable response - use request() instead."));try{let n=await t(...e),{statusText:s}=n;if(!n.ok)throw new Error(s,{cause:n});let i=n.headers.get("content-type")||"";switch(!0){case i.includes(Nt.json):return Mo(n);case i.includes(Nt.multipart):return Fo(n,i);default:throw new Error(`${bn} ${i}`,{cause:n})}}catch(n){return{async*[Symbol.asyncIterator](){let s=Cn(n);yield{errors:{message:ce(fe(n)),...W("networkStatusCode",s?.status),...W("response",s)},hasNext:!1}}}}}}r(No,"generateRequestStream");function Ln({client:t,storeDomain:e}){try{if(!e||typeof e!="string")throw new Error;let n=e.trim(),s=n.match(/^https?:/)?n:`https://${n}`,i=new URL(s);return i.protocol="https",i.origin}catch(n){throw new Error(`${t}: a valid store domain ("${e}") must be provided`,{cause:n})}}r(Ln,"validateDomainAndGetStoreUrl");function jt({client:t,currentSupportedApiVersions:e,apiVersion:n,logger:s}){let i=`${t}: the provided apiVersion ("${n}")`,o=`Currently supported API versions: ${e.join(", ")}`;if(!n||typeof n!="string")throw new Error(`${i} is invalid. ${o}`);let a=n.trim();e.includes(a)||(s?s({type:"Unsupported_Api_Version",content:{apiVersion:n,supportedApiVersions:e}}):console.warn(`${i} is likely deprecated or not supported. ${o}`))}r(jt,"validateApiVersion");function $t(t){let e=t*3-2;return e===10?e:`0${e}`}r($t,"getQuarterMonth");function On(t,e,n){let s=e-n;return s<=0?`${t-1}-${$t(s+4)}`:`${t}-${$t(s)}`}r(On,"getPrevousVersion");function fi(){let t=new Date,e=t.getUTCMonth(),n=t.getUTCFullYear(),s=Math.floor(e/3+1);return{year:n,quarter:s,version:`${n}-${$t(s)}`}}r(fi,"getCurrentApiVersion");function _n(){let{year:t,quarter:e,version:n}=fi(),s=e===4?`${t+1}-01`:`${t}-${$t(e+1)}`;return[On(t,e,3),On(t,e,2),On(t,e,1),n,s,"unstable"]}r(_n,"getCurrentSupportedApiVersions");function Mn(t){return e=>({...e??{},...t.headers})}r(Mn,"generateGetHeaders");function qn({getHeaders:t,getApiUrl:e}){return(n,s)=>{let i=[n];if(s&&Object.keys(s).length>0){let{variables:o,apiVersion:a,headers:u,retries:c,signal:p}=s;i.push({...o?{variables:o}:{},...u?{headers:t(u)}:{},...a?{url:e(a)}:{},...c?{retries:c}:{},...p?{signal:p}:{}})}return i}}r(qn,"generateGetGQLClientParams");var Un="application/json",mi="storefront-api-client",yi="1.0.9",vi="X-Shopify-Storefront-Access-Token",gi="Shopify-Storefront-Private-Token",wi="X-SDK-Variant",bi="X-SDK-Version",Ii="X-SDK-Variant-Source",Se="Storefront API Client";function Si(t){if(t&&typeof window<"u")throw new Error(`${Se}: private access tokens and headers should only be used in a server-to-server implementation. Use the public API access token in nonserver environments.`)}r(Si,"validatePrivateAccessTokenUsage");function Ei(t,e){if(!t&&!e)throw new Error(`${Se}: a public or private access token must be provided`);if(t&&e)throw new Error(`${Se}: only provide either a public or private access token`)}r(Ei,"validateRequiredAccessTokens");function Fn({storeDomain:t,apiVersion:e,publicAccessToken:n,privateAccessToken:s,clientName:i,retries:o=0,customFetchApi:a,logger:u}){let c=_n(),p=Ln({client:Se,storeDomain:t}),l={client:Se,currentSupportedApiVersions:c,logger:u};jt({...l,apiVersion:e}),Ei(n,s),Si(s);let y=Bo(p,e,l),h={storeDomain:p,apiVersion:e,...n?{publicAccessToken:n}:{privateAccessToken:s},headers:{"Content-Type":Un,Accept:Un,[wi]:mi,[bi]:yi,...i?{[Ii]:i}:{},...n?{[vi]:n}:{[gi]:s}},apiUrl:y(),clientName:i},m=Dn({headers:h.headers,url:h.apiUrl,retries:o,customFetchApi:a,logger:u}),v=Mn(h),f=Vo(h,y),w=qn({getHeaders:v,getApiUrl:f});return Object.freeze({config:h,getHeaders:v,getApiUrl:f,fetch:r((...T)=>m.fetch(...w(...T)),"fetch"),request:r((...T)=>m.request(...w(...T)),"request"),requestStream:r((...T)=>m.requestStream(...w(...T)),"requestStream")})}r(Fn,"createStorefrontApiClient");function Bo(t,e,n){return s=>{s&&jt({...n,apiVersion:s});let i=(s??e).trim();return`${t}/api/${i}/graphql.json`}}r(Bo,"generateApiUrlFormatter");function Vo(t,e){return n=>n?e(n):t.apiUrl}r(Vo,"generateGetApiUrl");var Ht=`
|
|
9
9
|
fragment productImageFields on Image {
|
|
10
10
|
id
|
|
11
11
|
altText
|
|
12
12
|
url
|
|
13
13
|
thumbhash
|
|
14
14
|
}
|
|
15
|
-
`,
|
|
16
|
-
fragment saveIntentProductFields on Product {
|
|
17
|
-
id
|
|
18
|
-
availableForSale
|
|
19
|
-
featuredImage {
|
|
20
|
-
...productImageFields
|
|
21
|
-
}
|
|
22
|
-
handle
|
|
23
|
-
title
|
|
24
|
-
variantsCount {
|
|
25
|
-
count
|
|
26
|
-
}
|
|
27
|
-
selectedOrFirstAvailableVariant {
|
|
28
|
-
...saveIntentVariantFields
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
fragment saveIntentVariantFields on ProductVariant {
|
|
32
|
-
id
|
|
33
|
-
availableForSale
|
|
34
|
-
currentlyNotInStock
|
|
35
|
-
image {
|
|
36
|
-
...productImageFields
|
|
37
|
-
}
|
|
38
|
-
title
|
|
39
|
-
}
|
|
40
|
-
`,Xt=`
|
|
15
|
+
`,Nn=`
|
|
41
16
|
fragment productFields on Product {
|
|
42
17
|
id
|
|
43
18
|
availableForSale
|
|
@@ -118,7 +93,7 @@ Values:
|
|
|
118
93
|
}
|
|
119
94
|
# totalInventory
|
|
120
95
|
}
|
|
121
|
-
`,
|
|
96
|
+
`,Bn=`
|
|
122
97
|
fragment productVariantDataFields on ProductVariant {
|
|
123
98
|
id
|
|
124
99
|
availableForSale
|
|
@@ -147,35 +122,7 @@ Values:
|
|
|
147
122
|
value
|
|
148
123
|
}
|
|
149
124
|
}
|
|
150
|
-
`;var
|
|
151
|
-
query GetSaveIntentData(
|
|
152
|
-
$productId: ID!
|
|
153
|
-
$country: CountryCode!
|
|
154
|
-
$language: LanguageCode!
|
|
155
|
-
) @inContext(country: $country, language: $language) {
|
|
156
|
-
product(id: $productId) {
|
|
157
|
-
...saveIntentProductFields
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
${Kt}
|
|
161
|
-
${fe}
|
|
162
|
-
`,is=`
|
|
163
|
-
query GetSaveIntentDataWithVariant(
|
|
164
|
-
$productId: ID!
|
|
165
|
-
$variantId: ID!
|
|
166
|
-
$country: CountryCode!
|
|
167
|
-
$language: LanguageCode!
|
|
168
|
-
) @inContext(country: $country, language: $language) {
|
|
169
|
-
product(id: $productId) {
|
|
170
|
-
...saveIntentProductFields
|
|
171
|
-
}
|
|
172
|
-
variant: node(id: $variantId) {
|
|
173
|
-
...saveIntentVariantFields
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
${Kt}
|
|
177
|
-
${fe}
|
|
178
|
-
`,rs=`
|
|
125
|
+
`;var ki=`
|
|
179
126
|
query GetProduct(
|
|
180
127
|
$productId: ID!
|
|
181
128
|
$variantId: ID!
|
|
@@ -200,10 +147,10 @@ Values:
|
|
|
200
147
|
}
|
|
201
148
|
}
|
|
202
149
|
}
|
|
203
|
-
${
|
|
204
|
-
${
|
|
205
|
-
${
|
|
206
|
-
`,
|
|
150
|
+
${Nn}
|
|
151
|
+
${Bn}
|
|
152
|
+
${Ht}
|
|
153
|
+
`,xi=`
|
|
207
154
|
query GetProductByHandle(
|
|
208
155
|
$handle: String!
|
|
209
156
|
$variantId: ID!
|
|
@@ -228,10 +175,10 @@ Values:
|
|
|
228
175
|
}
|
|
229
176
|
}
|
|
230
177
|
}
|
|
231
|
-
${
|
|
232
|
-
${
|
|
233
|
-
${
|
|
234
|
-
`,
|
|
178
|
+
${Nn}
|
|
179
|
+
${Bn}
|
|
180
|
+
${Ht}
|
|
181
|
+
`,Ci=`
|
|
235
182
|
query GetProductImagesById(
|
|
236
183
|
$ids: [ID!]!
|
|
237
184
|
$country: CountryCode!
|
|
@@ -255,8 +202,8 @@ Values:
|
|
|
255
202
|
}
|
|
256
203
|
}
|
|
257
204
|
}
|
|
258
|
-
${
|
|
259
|
-
`,
|
|
205
|
+
${Ht}
|
|
206
|
+
`,Ri=`
|
|
260
207
|
query GetProductRecommendationsById(
|
|
261
208
|
$productId: ID!
|
|
262
209
|
$intent: ProductRecommendationIntent
|
|
@@ -267,7 +214,7 @@ Values:
|
|
|
267
214
|
id
|
|
268
215
|
}
|
|
269
216
|
}
|
|
270
|
-
`,
|
|
217
|
+
`,Pi=`
|
|
271
218
|
query GetProductRecommendationsByHandle(
|
|
272
219
|
$handle: String!
|
|
273
220
|
$intent: ProductRecommendationIntent
|
|
@@ -278,19 +225,19 @@ Values:
|
|
|
278
225
|
id
|
|
279
226
|
}
|
|
280
227
|
}
|
|
281
|
-
`,
|
|
228
|
+
`,Ai=`
|
|
282
229
|
query GetProductIdByHandle($handle: String!) {
|
|
283
230
|
product(handle: $handle) {
|
|
284
231
|
id
|
|
285
232
|
}
|
|
286
233
|
}
|
|
287
|
-
`;var
|
|
234
|
+
`;var Ti=r(async(t,{productId:e,productHandle:n,variantId:s,selectedOptions:i,productMetafields:o=[],variantMetafields:a=[],country:u,language:c})=>{if(!e&&!n)throw new Error("Either productId or productHandle must be provided");let p=!!s,l=!!i?.length,y=e?ki:xi,h=e?{productId:pe("Product",e),variantId:s?pe("ProductVariant",s):"gid://shopify/ProductVariant/0",selectedOptions:l?i:[],productMetafields:o,variantMetafields:a,includeVariantById:p,includeVariantBySelectedOptions:l,country:u,language:c}:{handle:n,variantId:s?pe("ProductVariant",s):"gid://shopify/ProductVariant/0",selectedOptions:l?i:[],productMetafields:o,variantMetafields:a,includeVariantById:p,includeVariantBySelectedOptions:l,country:u,language:c},m=await t.query(y,h),v=m.data?.product??null,f=m.data?.variantNode??v?.variant??null;return{data:{product:v,variant:f},errors:m.errors}},"loadProduct");var Di=r(async(t,{productHandle:e})=>{if(!e)throw new Error("A product handle must be provided");return t.query(Ai,{handle:e})},"loadProductId");var Li=r(async(t,{items:e,country:n,language:s})=>{if(!e?.length)throw new Error("A list of items must be provided");let i={ids:e.map(o=>o.variantId?pe("ProductVariant",o.variantId.toString()):pe("Product",o.productId.toString())),country:n,language:s};try{return{data:(await t.query(Ci,i)).data?.nodes.map(u=>u===null?null:"image"in u?u.image:"featuredImage"in u?u.featuredImage:null).filter(u=>u!==null)??[],errors:null}}catch(o){return console.error(o),{data:null,errors:o}}},"loadProductImages");var Oi=r(async(t,{productId:e,productHandle:n,intent:s,country:i,language:o})=>{if(!e&&!n)throw new Error("Either productId or productHandle must be provided");if(e){let u={productId:pe("Product",e),intent:s,country:i,language:o};return t.query(Ri,u)}let a={handle:n,intent:s,country:i,language:o};return t.query(Pi,a)},"loadProductRecommendations");var jo="2026-04",$o=["GetProductIdByHandle"],Qt=class{constructor(e,n,s){this.client=null;this.query=r(async(e,n)=>{if(!this.client)throw new Error("Storefront API client not initialized");let s=await this.client.request(e,{variables:n});return{data:s.data,errors:s.errors??null}},"query");this.loadProduct=r(async e=>Ti(this,{...e,...this.metafields,country:this.context.localization.country,language:this.context.localization.language}),"loadProduct");this.loadProductImages=r(async e=>Li(this,{...e,...this.metafields,country:this.context.localization.country,language:this.context.localization.language}),"loadProductImages");this.loadProductRecommendations=r(async e=>Oi(this,{...e,country:this.context.localization.country,language:this.context.localization.language}),"loadProductRecommendations");this.loadProductId=r(async e=>Di(this,e),"loadProductId");this.options=e,this.context=n,this.metafields={productMetafields:s?.product.map(o=>({namespace:o.split(".")[0],key:o.split(".")[1]}))??[],variantMetafields:s?.productVariant.map(o=>({namespace:o.split(".")[0],key:o.split(".")[1]}))??[]};let i=Z(n.myshopifyDomain);this.shortCache=new de(`storefront-api-short-${i}`,"max-age=60, stale-while-revalidate=3600"),this.longCache=new de(`storefront-api-long-${i}`,"max-age=3600, stale-while-revalidate=86400"),this.shortCache.cleanupExpiredEntries().catch(o=>{console.warn("Storefront API cache initialization cleanup error:",o)}),this.longCache.cleanupExpiredEntries().catch(o=>{console.warn("Storefront API cache initialization cleanup error:",o)}),this.client=Fn({apiVersion:jo,customFetchApi:r((o,a)=>a?.method==="OPTIONS"?this.fetch(o,a):$o.some(u=>a?.body?.toString().includes(`query ${u}`))?this.longCache.fetchWithCache(o,a):this.shortCache.fetchWithCache(o,a),"customFetchApi"),publicAccessToken:this.options.accessToken,storeDomain:this.options.storeDomain})}static{r(this,"StorefrontApiClient")}fetch(e,n){return n?.method==="OPTIONS"?fetch(e,n):this.shortCache.fetchWithCache(e,n)}async clearCache(){await this.shortCache.clear()}};var Ho=Object.defineProperty,d=r((t,e)=>Ho(t,"name",{value:e,configurable:!0}),"t"),Qo={bodySerializer:d(t=>JSON.stringify(t,(e,n)=>typeof n=="bigint"?n.toString():n),"bodySerializer")},Go=d(({onRequest:t,onSseError:e,onSseEvent:n,responseTransformer:s,responseValidator:i,sseDefaultRetryDelay:o,sseMaxRetryAttempts:a,sseMaxRetryDelay:u,sseSleepFn:c,url:p,...l})=>{let y,h=c??(m=>new Promise(v=>setTimeout(v,m)));return{stream:d(async function*(){let m=o??3e3,v=0,f=l.signal??new AbortController().signal;for(;!f.aborted;){v++;let w=l.headers instanceof Headers?l.headers:new Headers(l.headers);y!==void 0&&w.set("Last-Event-ID",y);try{let b={redirect:"follow",...l,body:l.serializedBody,headers:w,signal:f},T=new Request(p,b);t&&(T=await t(p,b));let U=await(l.fetch??globalThis.fetch)(T);if(!U.ok)throw new Error(`SSE failed: ${U.status} ${U.statusText}`);if(!U.body)throw new Error("No body in SSE response");let N=U.body.pipeThrough(new TextDecoderStream).getReader(),x="",D=d(()=>{try{N.cancel()}catch{}},"abortHandler");f.addEventListener("abort",D);try{for(;;){let{done:k,value:P}=await N.read();if(k)break;x+=P,x=x.replace(/\r\n/g,`
|
|
288
235
|
`).replace(/\r/g,`
|
|
289
|
-
`);let
|
|
236
|
+
`);let F=x.split(`
|
|
290
237
|
|
|
291
|
-
`);
|
|
292
|
-
`),
|
|
293
|
-
`);try{ie=JSON.parse(W),cn=!0}catch{ie=W}}cn&&(i&&await i(ie),s&&(ie=await s(ie))),n?.({data:ie,event:un,id:h,retry:f}),Ie.length&&(yield ie)}}}finally{g.removeEventListener("abort",T),L.releaseLock()}break}catch(B){if(e?.(B),o!==void 0&&E>=o)break;let O=Math.min(f*2**(E-1),u??3e4);await y(O)}}},"createStream")()}},"createSseClient"),sr=d(t=>{switch(t){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},"separatorArrayExplode"),ir=d(t=>{switch(t){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},"separatorArrayNoExplode"),rr=d(t=>{switch(t){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},"separatorObjectExplode"),gs=d(({allowReserved:t,explode:e,name:n,style:s,value:i})=>{if(!e){let u=(t?i:i.map(c=>encodeURIComponent(c))).join(ir(s));switch(s){case"label":return`.${u}`;case"matrix":return`;${n}=${u}`;case"simple":return u;default:return`${n}=${u}`}}let a=sr(s),o=i.map(u=>s==="label"||s==="simple"?t?u:encodeURIComponent(u):vt({allowReserved:t,name:n,value:u})).join(a);return s==="label"||s==="matrix"?a+o:o},"serializeArrayParam"),vt=d(({allowReserved:t,name:e,value:n})=>{if(n==null)return"";if(typeof n=="object")throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.");return`${e}=${t?n:encodeURIComponent(n)}`},"serializePrimitiveParam"),ws=d(({allowReserved:t,explode:e,name:n,style:s,value:i,valueOnly:a})=>{if(i instanceof Date)return a?i.toISOString():`${n}=${i.toISOString()}`;if(s!=="deepObject"&&!e){let c=[];Object.entries(i).forEach(([l,h])=>{c=[...c,l,t?h:encodeURIComponent(h)]});let p=c.join(",");switch(s){case"form":return`${n}=${p}`;case"label":return`.${p}`;case"matrix":return`;${n}=${p}`;default:return p}}let o=rr(s),u=Object.entries(i).map(([c,p])=>vt({allowReserved:t,name:s==="deepObject"?`${n}[${c}]`:c,value:p})).join(o);return s==="label"||s==="matrix"?o+u:u},"serializeObjectParam"),or=/\{[^{}]+\}/g,ar=d(({path:t,url:e})=>{let n=e,s=e.match(or);if(s)for(let i of s){let a=!1,o=i.substring(1,i.length-1),u="simple";o.endsWith("*")&&(a=!0,o=o.substring(0,o.length-1)),o.startsWith(".")?(o=o.substring(1),u="label"):o.startsWith(";")&&(o=o.substring(1),u="matrix");let c=t[o];if(c==null)continue;if(Array.isArray(c)){n=n.replace(i,gs({explode:a,name:o,style:u,value:c}));continue}if(typeof c=="object"){n=n.replace(i,ws({explode:a,name:o,style:u,value:c,valueOnly:!0}));continue}if(u==="matrix"){n=n.replace(i,`;${vt({name:o,value:c})}`);continue}let p=encodeURIComponent(u==="label"?`.${c}`:c);n=n.replace(i,p)}return n},"defaultPathSerializer"),ur=d(({baseUrl:t,path:e,query:n,querySerializer:s,url:i})=>{let a=i.startsWith("/")?i:`/${i}`,o=(t??"")+a;e&&(o=ar({path:e,url:o}));let u=n?s(n):"";return u.startsWith("?")&&(u=u.substring(1)),u&&(o+=`?${u}`),o},"getUrl");function Zt(t){let e=t.body!==void 0;if(e&&t.bodySerializer)return"serializedBody"in t?t.serializedBody!==void 0&&t.serializedBody!==""?t.serializedBody:null:t.body!==""?t.body:null;if(e)return t.body}r(Zt,"N");d(Zt,"getValidRequestBody");var cr=d(async(t,e)=>{let n=typeof e=="function"?await e(t):e;if(n)return t.scheme==="bearer"?`Bearer ${n}`:t.scheme==="basic"?`Basic ${btoa(n)}`:n},"getAuthToken"),Is=d(({parameters:t={},...e}={})=>d(n=>{let s=[];if(n&&typeof n=="object")for(let i in n){let a=n[i];if(a==null)continue;let o=t[i]||e;if(Array.isArray(a)){let u=gs({allowReserved:o.allowReserved,explode:!0,name:i,style:"form",value:a,...o.array});u&&s.push(u)}else if(typeof a=="object"){let u=ws({allowReserved:o.allowReserved,explode:!0,name:i,style:"deepObject",value:a,...o.object});u&&s.push(u)}else{let u=vt({allowReserved:o.allowReserved,name:i,value:a});u&&s.push(u)}}return s.join("&")},"querySerializer"),"createQuerySerializer"),lr=d(t=>{var e;if(!t)return"stream";let n=(e=t.split(";")[0])==null?void 0:e.trim();if(n){if(n.startsWith("application/json")||n.endsWith("+json"))return"json";if(n==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some(s=>n.startsWith(s)))return"blob";if(n.startsWith("text/"))return"text"}},"getParseAs"),pr=d((t,e)=>{var n,s;return e?!!(t.headers.has(e)||(n=t.query)!=null&&n[e]||(s=t.headers.get("Cookie"))!=null&&s.includes(`${e}=`)):!1},"checkForExistence"),dr=d(async({security:t,...e})=>{for(let n of t){if(pr(e,n.name))continue;let s=await cr(n,e.auth);if(!s)continue;let i=n.name??"Authorization";switch(n.in){case"query":e.query||(e.query={}),e.query[i]=s;break;case"cookie":e.headers.append("Cookie",`${i}=${s}`);break;default:e.headers.set(i,s);break}}},"setAuthParams"),ys=d(t=>ur({baseUrl:t.baseUrl,path:t.path,query:t.query,querySerializer:typeof t.querySerializer=="function"?t.querySerializer:Is(t.querySerializer),url:t.url}),"buildUrl"),vs=d((t,e)=>{var n;let s={...t,...e};return(n=s.baseUrl)!=null&&n.endsWith("/")&&(s.baseUrl=s.baseUrl.substring(0,s.baseUrl.length-1)),s.headers=bs(t.headers,e.headers),s},"mergeConfigs"),hr=d(t=>{let e=[];return t.forEach((n,s)=>{e.push([s,n])}),e},"headersEntries"),bs=d((...t)=>{let e=new Headers;for(let n of t){if(!n)continue;let s=n instanceof Headers?hr(n):Object.entries(n);for(let[i,a]of s)if(a===null)e.delete(i);else if(Array.isArray(a))for(let o of a)e.append(i,o);else a!==void 0&&e.set(i,typeof a=="object"?JSON.stringify(a):a)}return e},"mergeHeaders"),Ss=class{static{r(this,"j")}constructor(){this.fns=[]}clear(){this.fns=[]}eject(e){let n=this.getInterceptorIndex(e);this.fns[n]&&(this.fns[n]=null)}exists(e){let n=this.getInterceptorIndex(e);return!!this.fns[n]}getInterceptorIndex(e){return typeof e=="number"?this.fns[e]?e:-1:this.fns.indexOf(e)}update(e,n){let s=this.getInterceptorIndex(e);return this.fns[s]?(this.fns[s]=n,e):!1}use(e){return this.fns.push(e),this.fns.length-1}};d(Ss,"Interceptors");var Yt=Ss,fr=d(()=>({error:new Yt,request:new Yt,response:new Yt}),"createInterceptors"),mr=Is({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),yr={"Content-Type":"application/json"},yt=d((t={})=>({...tr,headers:yr,parseAs:"auto",querySerializer:mr,...t}),"createConfig"),en=d((t={})=>{let e=vs(yt(),t),n=d(()=>({...e}),"getConfig"),s=d(p=>(e=vs(e,p),n()),"setConfig"),i=fr(),a=d(async p=>{let l={...e,...p,fetch:p.fetch??e.fetch??globalThis.fetch,headers:bs(e.headers,p.headers),serializedBody:void 0};l.security&&await dr({...l,security:l.security}),l.requestValidator&&await l.requestValidator(l),l.body!==void 0&&l.bodySerializer&&(l.serializedBody=l.bodySerializer(l.body)),(l.body===void 0||l.serializedBody==="")&&l.headers.delete("Content-Type");let h=ys(l);return{opts:l,url:h}},"beforeRequest"),o=d(async p=>{let{opts:l,url:h}=await a(p),y={redirect:"follow",...l,body:Zt(l)},f=new Request(h,y);for(let b of i.request.fns)b&&(f=await b(f,l));let E=l.fetch,g;try{g=await E(f)}catch(b){let T=b;for(let x of i.error.fns)x&&(T=await x(b,void 0,f,l));if(T=T||{},l.throwOnError)throw T;return l.responseStyle==="data"?void 0:{error:T,request:f,response:void 0}}for(let b of i.response.fns)b&&(g=await b(g,f,l));let _={request:f,response:g};if(g.ok){let b=(l.parseAs==="auto"?lr(g.headers.get("Content-Type")):l.parseAs)??"json";if(g.status===204||g.headers.get("Content-Length")==="0"){let x;switch(b){case"arrayBuffer":case"blob":case"text":x=await g[b]();break;case"formData":x=new FormData;break;case"stream":x=g.body;break;default:x={};break}return l.responseStyle==="data"?x:{data:x,..._}}let T;switch(b){case"arrayBuffer":case"blob":case"formData":case"text":T=await g[b]();break;case"json":{let x=await g.text();T=x?JSON.parse(x):{};break}case"stream":return l.responseStyle==="data"?g.body:{data:g.body,..._}}return b==="json"&&(l.responseValidator&&await l.responseValidator(T),l.responseTransformer&&(T=await l.responseTransformer(T))),l.responseStyle==="data"?T:{data:T,..._}}let B=await g.text(),O;try{O=JSON.parse(B)}catch{}let H=O??B,L=H;for(let b of i.error.fns)b&&(L=await b(H,g,f,l));if(L=L||{},l.throwOnError)throw L;return l.responseStyle==="data"?void 0:{error:L,..._}},"request"),u=d(p=>l=>o({...l,method:p}),"makeMethodFn"),c=d(p=>async l=>{let{opts:h,url:y}=await a(l);return nr({...h,body:h.body,headers:h.headers,method:p,onRequest:d(async(f,E)=>{let g=new Request(f,E);for(let _ of i.request.fns)_&&(g=await _(g,h));return g},"onRequest"),serializedBody:Zt(h),url:y})},"makeSseFn");return{buildUrl:ys,connect:u("CONNECT"),delete:u("DELETE"),get:u("GET"),getConfig:n,head:u("HEAD"),interceptors:i,options:u("OPTIONS"),patch:u("PATCH"),post:u("POST"),put:u("PUT"),request:o,setConfig:s,sse:{connect:c("CONNECT"),delete:c("DELETE"),get:c("GET"),head:c("HEAD"),options:c("OPTIONS"),patch:c("PATCH"),post:c("POST"),put:c("PUT"),trace:c("TRACE")},trace:u("TRACE")}},"createClient"),I=en(yt({baseUrl:"https://swish.app/api/2026-04"})),vr=d(t=>(t?.client??I).get({security:[{scheme:"bearer",type:"http"}],url:"/lists",...t}),"listControllerFind"),gr=d(t=>(t.client??I).post({security:[{scheme:"bearer",type:"http"}],url:"/lists",...t,headers:{"Content-Type":"application/json",...t.headers}}),"listControllerCreate"),wr=d(t=>(t.client??I).delete({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...t}),"listControllerDeleteById"),Ir=d(t=>(t.client??I).get({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...t}),"listControllerFindById"),br=d(t=>(t.client??I).patch({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...t,headers:{"Content-Type":"application/json",...t.headers}}),"listControllerUpdateById"),Sr=d(t=>(t.client??I).put({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items/order",...t,headers:{"Content-Type":"application/json",...t.headers}}),"listControllerSetListItemsOrder"),Er=d(t=>(t.client??I).post({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items",...t,headers:{"Content-Type":"application/json",...t.headers}}),"listControllerAddItemsToList"),kr=d(t=>(t.client??I).delete({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items/{itemId}",...t}),"listControllerRemoveItemFromList"),xr=d(t=>(t.client??I).delete({security:[{scheme:"bearer",type:"http"}],url:"/items",...t,headers:{"Content-Type":"application/json",...t.headers}}),"itemControllerDelete"),Cr=d(t=>(t?.client??I).get({security:[{scheme:"bearer",type:"http"}],url:"/items",...t}),"itemControllerFind"),Rr=d(t=>(t.client??I).post({security:[{scheme:"bearer",type:"http"}],url:"/items",...t,headers:{"Content-Type":"application/json",...t.headers}}),"itemControllerCreate"),Ar=d(t=>(t?.client??I).get({security:[{scheme:"bearer",type:"http"}],url:"/items/count",...t}),"itemControllerCount"),Pr=d(t=>(t.client??I).delete({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...t}),"itemControllerDeleteById"),Tr=d(t=>(t.client??I).get({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...t}),"itemControllerFindById"),Dr=d(t=>(t.client??I).patch({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...t,headers:{"Content-Type":"application/json",...t.headers}}),"itemControllerUpdateById"),Lr=d(t=>(t.client??I).put({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}/lists",...t,headers:{"Content-Type":"application/json",...t.headers}}),"itemControllerSetListsById"),_r=d(t=>(t.client??I).post({security:[{scheme:"bearer",type:"http"}],url:"/profiles/identify",...t,headers:{"Content-Type":"application/json",...t.headers}}),"profileControllerIdentify"),Or=d(t=>(t.client??I).post({security:[{scheme:"bearer",type:"http"}],url:"/profiles/token",...t,headers:{"Content-Type":"application/json",...t.headers}}),"profileControllerCreateToken"),qr=d(t=>(t?.client??I).get({security:[{scheme:"bearer",type:"http"}],url:"/profiles",...t}),"profileControllerGetProfile"),Mr=d(t=>(t.client??I).patch({security:[{scheme:"bearer",type:"http"}],url:"/profiles/profile",...t,headers:{"Content-Type":"application/json",...t.headers}}),"profileControllerUpdateProfile"),$r=d(t=>(t.client??I).get({security:[{scheme:"bearer",type:"http"}],url:"/analytics/saved-items",...t}),"analyticsControllerLoadSavedItems"),Nr=d(t=>(t.client??I).get({security:[{scheme:"bearer",type:"http"}],url:"/analytics/sessions",...t}),"analyticsControllerLoadSessions"),Br=d(t=>(t.client??I).get({security:[{scheme:"bearer",type:"http"}],url:"/analytics/new-lists",...t}),"analyticsControllerLoadNewLists"),Ur=d(t=>(t.client??I).post({security:[{scheme:"bearer",type:"http"}],url:"/collect",...t,headers:{"Content-Type":"application/json",...t.headers}}),"trackingControllerCollect"),Vr=d(t=>(t?.client??I).get({security:[{scheme:"bearer",type:"http"}],url:"/orders",...t}),"ordersControllerFind"),Fr=d(t=>(t.client??I).get({security:[{scheme:"bearer",type:"http"}],url:"/orders/{orderId}",...t}),"ordersControllerFindOne"),jr=d(t=>(t?.client??I).get({security:[{scheme:"bearer",type:"http"}],url:"/shared-lists",...t}),"sharedListsControllerFindAll"),Hr=d(t=>(t.client??I).post({security:[{scheme:"bearer",type:"http"}],url:"/shared-lists",...t,headers:{"Content-Type":"application/json",...t.headers}}),"sharedListsControllerSave"),Gr=d(t=>(t.client??I).delete({security:[{scheme:"bearer",type:"http"}],url:"/shared-lists/{sharedListId}",...t}),"sharedListsControllerDeleteById"),zr=d(t=>(t.client??I).get({security:[{scheme:"bearer",type:"http"}],url:"/shared-lists/{sharedListId}",...t}),"sharedListsControllerFindById"),Wr=d(t=>(t.client??I).get({security:[{scheme:"bearer",type:"http"}],url:"/shared-lists/{sharedListId}/items",...t}),"sharedListsControllerFindItems"),Qr=d(t=>(t?.client??I).get({security:[{scheme:"bearer",type:"http"}],url:"/notifications",...t}),"notificationsControllerFind"),Kr=d(t=>(t?.client??I).get({security:[{scheme:"bearer",type:"http"}],url:"/notifications/unread/count",...t}),"notificationsControllerGetUnreadCount"),Xr=d(t=>(t.client??I).post({security:[{scheme:"bearer",type:"http"}],url:"/notifications/read",...t,headers:{"Content-Type":"application/json",...t.headers}}),"notificationsControllerMarkAsRead"),Jr=d(t=>(t?.client??I).post({security:[{scheme:"bearer",type:"http"}],url:"/notifications/read/all",...t}),"notificationsControllerMarkAllAsRead"),Yr=d(t=>(t.client??I).delete({security:[{scheme:"bearer",type:"http"}],url:"/notifications/{id}",...t}),"notificationsControllerDeleteById"),Zr=d(t=>(t?.client??I).get({security:[{scheme:"bearer",type:"http"}],url:"/subscriptions",...t}),"subscriptionsControllerFind"),eo=d(t=>(t.client??I).post({security:[{scheme:"bearer",type:"http"}],url:"/subscriptions",...t,headers:{"Content-Type":"application/json",...t.headers}}),"subscriptionsControllerCreate"),to=d(t=>(t.client??I).delete({security:[{scheme:"bearer",type:"http"}],url:"/subscriptions/{id}",...t}),"subscriptionsControllerDelete"),no=d(t=>(t.client??I).get({security:[{scheme:"bearer",type:"http"}],url:"/subscriptions/{id}",...t}),"subscriptionsControllerFindById"),so=d(t=>(t.client??I).patch({security:[{scheme:"bearer",type:"http"}],url:"/subscriptions/{id}",...t,headers:{"Content-Type":"application/json",...t.headers}}),"subscriptionsControllerUpdate"),io=d(t=>(t?.client??I).get({security:[{scheme:"bearer",type:"http"}],url:"/smart-lists",...t}),"smartListsControllerFindAll"),ro=d(t=>(t.client??I).get({security:[{scheme:"bearer",type:"http"}],url:"/smart-lists/{smartListId}",...t}),"smartListsControllerFindById"),oo=d(t=>(t.client??I).get({security:[{scheme:"bearer",type:"http"}],url:"/smart-lists/{smartListId}/items",...t}),"smartListsControllerFindItems"),tn="2026-04",Es=d(t=>new ao(t),"createApiClient"),ks=class{static{r(this,"Ae")}constructor(e){this.version=tn,this.items={list:d(o=>this.handlePaginatedRequest(Cr({query:o,client:this.directClient})),"list"),create:d(o=>this.handleRequest(Rr({body:o,client:this.directClient})),"create"),delete:d(o=>this.handleRequest(xr({body:{itemIds:o},client:this.directClient})),"delete"),findById:d(o=>this.handleRequest(Tr({path:{itemId:o},client:this.directClient})),"findById"),updateById:d((o,u)=>this.handleRequest(Dr({body:u,path:{itemId:o},client:this.directClient})),"updateById"),deleteById:d(o=>this.handleRequest(Pr({path:{itemId:o},client:this.directClient})),"deleteById"),setListsById:d((o,u)=>this.handleRequest(Lr({body:{listIds:u},path:{itemId:o},client:this.directClient})),"setListsById"),count:d(()=>this.handleRequest(Ar({client:this.directClient})),"count")},this.lists={list:d(o=>this.handlePaginatedRequest(vr({query:o,client:this.directClient})),"list"),create:d(o=>this.handleRequest(gr({body:o,client:this.directClient})),"create"),findById:d(o=>this.handleRequest(Ir({path:{listId:o},client:this.directClient})),"findById"),updateById:d((o,u)=>this.handleRequest(br({body:u,path:{listId:o},client:this.directClient})),"updateById"),deleteById:d(o=>this.handleRequest(wr({path:{listId:o},client:this.directClient})),"deleteById"),orderItems:d((o,u)=>this.handleRequest(Sr({body:{itemIds:u},path:{listId:o},client:this.directClient})),"orderItems"),addItemsToList:d((o,u)=>this.handleRequest(Er({body:{itemIds:u},path:{listId:o},client:this.directClient})),"addItemsToList"),removeItemFromList:d((o,u)=>this.handleRequest(kr({path:{listId:o,itemId:u},client:this.directClient})),"removeItemFromList")},this.profiles={createToken:d((o={})=>this.handleRequest(Or({body:o,client:this.proxyClient??this.directClient})),"createToken"),identify:d(o=>this.handleRequest(_r({body:o,client:this.directClient})),"identify"),getProfile:d(()=>this.handleRequest(qr({client:this.directClient})),"getProfile"),updateProfile:d(o=>this.handleRequest(Mr({body:o,client:this.directClient})),"updateProfile")},this.orders={list:d(o=>this.handlePaginatedRequest(Vr({query:o,client:this.directClient})),"list"),findById:d(o=>this.handleRequest(Fr({path:{orderId:o},client:this.directClient})),"findById")},this.sharedLists={list:d(o=>this.handlePaginatedRequest(jr({query:o,client:this.directClient})),"list"),save:d(o=>this.handleRequest(Hr({body:{listId:o},client:this.directClient})),"save"),findById:d(o=>this.handleRequest(zr({path:{sharedListId:o},client:this.directClient})),"findById"),deleteById:d(o=>this.handleRequest(Gr({path:{sharedListId:o},client:this.directClient})),"deleteById"),findItems:d((o,u)=>this.handlePaginatedRequest(Wr({path:{sharedListId:o},query:u,client:this.directClient})),"findItems")},this.analytics={savedItems:d(o=>this.handleRequest($r({query:o,client:this.directClient})),"savedItems"),sessions:d(o=>this.handleRequest(Nr({query:o,client:this.directClient})),"sessions"),newLists:d(o=>this.handleRequest(Br({query:o,client:this.directClient})),"newLists")},this.tracking={track:d(o=>this.handleRequest(Ur({body:o,client:this.directClient})),"track")},this.notifications={list:d(o=>this.handlePaginatedRequest(Qr({query:o,client:this.directClient})),"list"),getUnreadCount:d(()=>this.handleRequest(Kr({client:this.directClient})),"getUnreadCount"),markAsRead:d(o=>this.handleRequest(Xr({body:{notificationIds:o},client:this.directClient})),"markAsRead"),markAllAsRead:d(()=>this.handleRequest(Jr({client:this.directClient})),"markAllAsRead"),deleteById:d(o=>this.handleRequest(Yr({path:{id:o},client:this.directClient})),"deleteById")},this.subscriptions={list:d(o=>this.handlePaginatedRequest(Zr({query:o,client:this.directClient})),"list"),create:d(o=>this.handleRequest(eo({body:o,client:this.directClient})),"create"),findById:d(o=>this.handleRequest(no({path:{id:o},client:this.directClient})),"findById"),updateById:d((o,u)=>this.handleRequest(so({body:u,path:{id:o},client:this.directClient})),"updateById"),deleteById:d(o=>this.handleRequest(to({path:{id:o},client:this.directClient})),"deleteById")},this.smartLists={list:d(()=>this.handleRequest(io({client:this.directClient})),"list"),findById:d(o=>this.handleRequest(ro({path:{smartListId:o},client:this.directClient})),"findById"),findItems:d((o,u)=>this.handlePaginatedRequest(oo({path:{smartListId:o},query:u,client:this.directClient})),"findItems")},this.handleRequest=d(async o=>{let{data:u,error:c}=await o;return c!=null&&c.error?{error:c.error}:{data:u?.data}},"handleRequest"),this.handlePaginatedRequest=d(async o=>{var u;let{data:c,error:p}=await o;return p!=null&&p.error?{error:p.error}:{data:c?.data??[],pageInfo:c?.pageInfo??{next:null,previous:null,totalCount:((u=c?.data)==null?void 0:u.length)??0}}},"handlePaginatedRequest");var n,s,i,a;this.directClient=en(yt({baseUrl:`https://swish.app/api/${this.version}`,...e.config})),(n=e.config)!=null&&n.authProxy&&(this.proxyClient=en(yt({...e.config,baseUrl:e.config.authProxy}))),e.authToken&&(this.authToken=e.authToken),e.requestInterceptor&&((s=this.proxyClient)==null||s.interceptors.request.use(e.requestInterceptor),this.directClient.interceptors.request.use(e.requestInterceptor)),e.responseInterceptor&&((i=this.proxyClient)==null||i.interceptors.response.use(e.responseInterceptor),this.directClient.interceptors.response.use(e.responseInterceptor)),(a=this.proxyClient)==null||a.interceptors.request.use(this.proxyRequestInterceptor.bind(this)),this.directClient.interceptors.request.use(this.directRequestInterceptor.bind(this))}setAuthToken(e){this.authToken=e}proxyRequestInterceptor(e){return this.version&&e.headers.set("Swish-Api-Version",this.version),e}directRequestInterceptor(e){return this.authToken&&e.headers.set("Authorization",`Bearer ${this.authToken}`),e}};d(ks,"SwishClient");var ao=ks;var As=Bs(Rs(),1);var Ps=r(t=>new As.default(async e=>{let n=[...new Set(e)].sort((i,a)=>i.localeCompare(a)),s=await t.items.list({query:n.join(" "),limit:200});return"error"in s?(console.error("Failed to load items",s.error),e.map(()=>({data:[],pageInfo:{next:null,previous:null,totalCount:0}}))):e.map(i=>{let a=s.data.find(o=>i===`variant:${o.variantId}`||i===`product:${o.productId}`);return{data:a?[a]:[],pageInfo:{next:null,previous:null,totalCount:a?1:0}}})},{batchScheduleFn:r(e=>setTimeout(e,50),"batchScheduleFn"),cache:!1,maxBatchSize:200}),"createItemsBatchLoader");var gt=class{constructor(e,n,s){this.tokenHasProfile=!1;this.api=e,this.context=n,this.eventBus=s}static{r(this,"SwishApiAuth")}hasProfile(){return this.tokenHasProfile}hasToken(){return!!this.getSwishToken()}async renewToken(){return this._renewPromise?this._renewPromise:(this._renewPromise=(async()=>{this._initPromise=void 0,this.deleteSwishToken(),await this.init(),this._renewPromise=void 0})(),this._renewPromise)}async init(){return this._initPromise?this._initPromise:(this._initPromise=(async()=>{this.migrateLegacySession();let e=this.context.customer.id;e?(this.hasSessionToken()&&await this.api.clearCache(),await this.initCustomer(e)):(this.hasCustomerToken()&&await this.resetSession(),await this.initSession()),this.eventBus.publish("token-update",null)})(),this._initPromise)}async initCustomer(e){let n=`gid://shopify/Customer/${e}`,s=this.getTokenBySub(n);if(s){this.initToken(s);return}let i=this.getSessionId();await this.acquireToken(i,n)}async initSession(){let e=this.getSessionId(),n=e?this.getTokenBySub(e):null;if(n){this.initToken(n);return}await this.acquireToken(e)}initToken(e){let n=this.getTokenData(e);if(!n)throw new Error("Invalid Swish token.");this.tokenHasProfile=n.has_profile!==!1,this.api.setAuthToken(e)}async acquireToken(e,n){let s=await this.api.profiles.createToken({customer:n,session:e});if("error"in s)throw console.error("Failed to create customer token",s.error),new Error("Failed to create customer token");if(!s.data?.token)throw console.error("Failed to create customer token empty response"),new Error("Failed to create customer token");s.data.profile.startsWith("gid://swish/Session/")&&this.setSessionId(s.data.profile),this.setSwishToken(s.data.token),this.initToken(s.data.token)}async resetSession(){this.deleteSessionId(),this.deleteSwishToken(),await this.api.clearCache()}getTokenData(e){try{return JSON.parse(atob(e.split(".")[1]))}catch(n){return console.error("Failed to parse Swish token",{cause:n}),null}}willTokenExpire(e,n=60){let s=this.getTokenData(e);return!!(s&&s.exp&&s.exp<Date.now()/1e3+n)}hasCustomerToken(){let e=this.getSwishToken();return e?this.getTokenData(e)?.sub?.startsWith("gid://shopify/Customer/")??!1:!1}hasSessionToken(){let e=this.getSwishToken();return e?this.getTokenData(e)?.sub?.startsWith("gid://swish/Session/")??!1:!1}getTokenBySub(e){if(!e)return null;let n=this.getSwishToken();if(!n)return null;let s=this.getTokenData(n);return!s||s.sub!==e||this.willTokenExpire(n,60)?null:n}getSessionId(){let e=G(this.context.myshopifyDomain);return localStorage.getItem(`swish-session-${e}`)??void 0}setSessionId(e){let n=G(this.context.myshopifyDomain);localStorage.setItem(`swish-session-${n}`,e)}deleteSessionId(){let e=G(this.context.myshopifyDomain);localStorage.removeItem(`swish-session-${e}`)}getSwishToken(){let e=G(this.context.myshopifyDomain);return sessionStorage.getItem(`swish-token-${e}`)??void 0}setSwishToken(e){let n=G(this.context.myshopifyDomain);sessionStorage.setItem(`swish-token-${n}`,e)}deleteSwishToken(){let e=G(this.context.myshopifyDomain);sessionStorage.removeItem(`swish-token-${e}`)}migrateLegacySession(){try{let e=localStorage.getItem("wk_session_id")??localStorage.getItem("swish-profile")?.split("/").pop()??localStorage.getItem("swish-session")?.split("/").pop();e&&(this.setSessionId(`gid://swish/Session/${e}`),localStorage.removeItem("wk_session_id"),localStorage.removeItem("swish-profile"),localStorage.removeItem("swish-session"))}catch(e){console.warn("Failed to migrate legacy session id to Swish session",{cause:e})}}};var wt=class{static{r(this,"SwishApi")}constructor(e,n,s,i){this.config=e,this.storefrontContext=n;let a=G(n.myshopifyDomain);this.cache=new J(`swish-api-${a}`,"max-age=60, stale-while-revalidate=3600",i+tn),this.cache.cleanupExpiredEntries().catch(o=>{console.warn("Swish API cache initialization cleanup error:",o)}),this.auth=new gt(this,n,s),this.apiClient=Es({authToken:this.auth.getSwishToken(),config:{...e,fetch:this.fetchFunction.bind(this)},requestInterceptor:this.requestInterceptor.bind(this),responseInterceptor:this.responseInterceptor.bind(this)}),this.itemsLoader=Ps(this)}async fetchFunction(e,n){let s=e instanceof Request?e.method:n?.method??"GET",i=e instanceof Request?e.url:typeof e=="string"?e:e.toString();if(i.includes("/smart-lists"))return fetch(e,n);let o=i.includes("/orders");return s==="GET"&&!o?this.cache.fetchWithCache(e,n):fetch(e,n)}async requestInterceptor(e){let n=new URL(e.url,window.location.origin);this.config.authProxy&&n.pathname.startsWith(this.config.authProxy)||await this.initAuth();try{e.headers.set("Country",this.storefrontContext.localization.country),e.headers.set("Language",this.storefrontContext.localization.language),e.headers.set("Market",this.storefrontContext.localization.market)}catch(i){console.warn("Failed to set storefront context headers:",i)}return this.config.requestInterceptor&&(e=await this.config.requestInterceptor(e)),e}async responseInterceptor(e,n){let s=n.method!=="GET",i=n.url.includes("/profiles/token");if(s&&!i){let a=this.auth.hasToken(),o=!this.auth.hasProfile(),u=e.ok;await this.cache.clear(),a&&o&&u&&await this.auth.renewToken()}return await this.config.responseInterceptor?.(e,n),e}setAuthToken(e){this.apiClient.setAuthToken(e)}initAuth(){return this.auth.init()}async withFallback(e,n){return await this.initAuth(),this.auth.hasProfile()?e():Promise.resolve(n)}async withSignedInCustomerFallback(e,n){return await this.initAuth(),!!this.storefrontContext.customer.id&&this.auth.hasProfile()?e():Promise.resolve(n)}get items(){return{...this.apiClient.items,count:r(async()=>this.withFallback(()=>this.apiClient.items.count(),{data:{count:0}}),"count"),list:r(async(e,n)=>{let s=r(()=>{if(n?.batch&&e?.query){e.limit!==1&&console.warn("Batching will always limit to 1 item");let i=e.query.split(" ");i.length>1&&console.warn("Batching will only support one query parameter");let a=i[0];if(!a.match(/^product:\d+$/)&&!a.match(/^variant:\d+$/))console.warn("Batching will only support product:<id> or variant:<id>");else return this.itemsLoader?.load(a)}return this.apiClient.items.list(e)},"execute");return n?.shared?s():this.withFallback(s,{data:[],pageInfo:{next:null,previous:null,totalCount:0}})},"list"),findById:r(async e=>this.withFallback(()=>this.apiClient.items.findById(e),{data:null}),"findById")}}get lists(){return{...this.apiClient.lists,list:r(async e=>this.withFallback(()=>this.apiClient.lists.list(e),{data:[],pageInfo:{next:null,previous:null,totalCount:0}}),"list"),findById:r(async(e,n)=>{let s=r(()=>this.apiClient.lists.findById(e),"execute");return n?.shared?s():this.withFallback(()=>this.apiClient.lists.findById(e),{data:null})},"findById")}}get orders(){return{...this.apiClient.orders,list:r(async e=>this.withFallback(()=>this.apiClient.orders.list(e),{data:[],pageInfo:{next:null,previous:null,totalCount:0}}),"list"),findById:r(async e=>this.withFallback(()=>(typeof e=="string"&&(e=parseInt(e.split("/").pop()??e)),this.apiClient.orders.findById(e)),{data:null}),"findById")}}get notifications(){return{...this.apiClient.notifications,list:r(async e=>this.withSignedInCustomerFallback(()=>this.apiClient.notifications.list(e),{data:[],pageInfo:{next:null,previous:null,totalCount:0}}),"list"),getUnreadCount:r(async()=>this.withSignedInCustomerFallback(()=>this.apiClient.notifications.getUnreadCount(),{data:{count:0}}),"getUnreadCount"),markAsRead:r(e=>this.apiClient.notifications.markAsRead(e),"markAsRead"),markAllAsRead:r(()=>this.apiClient.notifications.markAllAsRead(),"markAllAsRead"),deleteById:r(e=>this.apiClient.notifications.deleteById(e),"deleteById")}}get smartLists(){return{...this.apiClient.smartLists,list:r(async()=>this.withFallback(()=>this.apiClient.smartLists.list(),{data:null}),"list"),findById:r(async e=>e==="recently-viewed"?this.apiClient.smartLists.findById(e):this.withFallback(()=>this.apiClient.smartLists.findById(e),{data:null}),"findById"),findItems:r(async(e,n)=>e==="recently-viewed"?this.apiClient.smartLists.findItems(e,n):this.withFallback(()=>this.apiClient.smartLists.findItems(e,n),{data:[],pageInfo:{next:null,previous:null,totalCount:0}}),"findItems")}}get profiles(){return this.apiClient.profiles}async clearCache(){await this.cache.clear()}};var It=class{constructor(e){this.eventMap={"POST /items\\/?$":"item-create","DELETE /items\\/?$":"item-delete","PATCH /items\\/([^/]+)\\/?$":"item-update","DELETE /items\\/([^/]+)\\/?$":"item-delete","PUT /items\\/([^/]+)\\/lists\\/?$":"item-lists-update","POST /lists\\/?$":"list-create","DELETE /lists\\/?$":"list-delete","PATCH /lists\\/([^/]+)\\/?$":"list-update","DELETE /lists\\/([^/]+)\\/?$":"list-delete","POST /notifications\\/read\\/all\\/?$":"notification-update","POST /notifications\\/read\\/?$":"notification-update","PATCH /notifications\\/([^/]+)\\/?$":"notification-update","DELETE /notifications\\/([^/]+)\\/?$":"notification-delete"};this.eventBus=e,this.processFetchResponse=this.processFetchResponse.bind(this)}static{r(this,"SwishApiPublisher")}async processFetchResponse(e,n){try{let s=this.getEventName(n.method,e.status,n.url);if(!s)return;let i=await e.clone().text();if(e.headers.get("Content-Type")?.includes("application/json"))try{i=JSON.parse(i).data}catch(a){console.warn(a)}this.eventBus.publish(s,i)}catch(s){console.warn(s)}}getEventName(e,n,s){e=e.toUpperCase();let i=new URL(s).pathname;return e==="GET"||n<200||n>=300?void 0:Object.entries(this.eventMap).find(([o])=>{let[u,c]=o.split(" ");return u!==e?!1:new RegExp(c).test(i)})?.[1]}};var bt=class{constructor(e){this.inflightModals=new Map;this.modalsWithScrollLock=new Set;this.scrollLockRefCount=0;this.scrollPositionBeforeLock=0;this._templatePromises=new Map;this._importPromises=new Map;this._lockScroll=r(()=>this.lockScroll(),"_lockScroll");this._unlockScroll=r(()=>this.unlockScroll(),"_unlockScroll");this.swishApp=e}static{r(this,"SwishUi")}async hideModal(e){if(this.inflightModals.has(e))return this.inflightModals.get(e);let n=(async()=>{try{if(typeof e=="string"&&(e=await this.requireUiComponent(e)),!e||e.getAttribute("open")!=="true")return;e.setAttribute("open","false")}finally{e&&typeof e!="string"&&this.modalsWithScrollLock.has(e)&&(this.modalsWithScrollLock.delete(e),this.unlockScroll())}})().finally(()=>{this.inflightModals.delete(e)});return this.inflightModals.set(e,n),n}async showModal(e){if(this.inflightModals.has(e))return this.inflightModals.get(e);let n=(async()=>{typeof e=="string"&&(e=await this.requireUiComponent(e)),!(!e||e.getAttribute("open")==="true")&&(this.lockScroll(),this.modalsWithScrollLock.add(e),e.setAttribute("open","true"))})().finally(()=>{this.inflightModals.delete(e)});return this.inflightModals.set(e,n),n}waitForEvent(e,n){return new Promise(s=>{let i=[],a=r(()=>{i.forEach(({event:o,listener:u})=>{e.removeEventListener(o,u)})},"cleanup");Object.entries(n).forEach(([o,u])=>{let c=r(p=>{let l=u(p);a(),s(l)},"listener");i.push({event:o,listener:c}),e.addEventListener(o,c)})})}async showSignIn(e){let n=await this.requireUiComponent("sign-in");n.setAttribute("return-to",e?.returnTo??window.location.pathname),await this.showModal(n);let s=await this.waitForEvent(n,{submit:r(()=>({code:"ok",data:void 0}),"submit"),close:r(()=>({code:"closed"}),"close")});return await this.hideModal(n),s}async showUnsaveAlert(e){if(!e.itemId)throw new Error("An itemId is required to show the unsave alert");await this.hideAllToasts();let n=await this.requireUiComponent("unsave-alert");n.setAttribute("item-id",e.itemId),await this.showModal(n);let s=await this.waitForEvent(n,{submit:r(i=>i instanceof CustomEvent?{code:"ok",data:i.detail}:(console.warn("Unsave alert submitted without detail",i),{code:"closed"}),"submit"),close:r(()=>({code:"closed"}),"close")});return await this.hideModal(n),s}async showDeleteListAlert(e){if(!e.listId)throw new Error("A listId is required to show the delete list alert");await this.hideAllToasts();let n=await this.requireUiComponent("delete-list-alert");n.setAttribute("list-id",e.listId),await this.showModal(n);let s=await this.waitForEvent(n,{submit:r(()=>({code:"ok",data:void 0}),"submit"),close:r(()=>({code:"closed"}),"close")});return await this.hideModal(n),s}async showConfirmDialog(e){await this.hideAllToasts();let n=await this.requireUiComponent("confirm-dialog");e.titleKey?n.setAttribute("title-key",e.titleKey):n.removeAttribute("title-key"),e.descriptionKey?n.setAttribute("description-key",e.descriptionKey):n.removeAttribute("description-key"),e.confirmLabelKey?n.setAttribute("confirm-label-key",e.confirmLabelKey):n.removeAttribute("confirm-label-key"),e.cancelLabelKey?n.setAttribute("cancel-label-key",e.cancelLabelKey):n.removeAttribute("cancel-label-key"),e.danger?n.setAttribute("danger",""):n.removeAttribute("danger"),await this.showModal(n);let s=await this.waitForEvent(n,{submit:r(()=>({code:"ok",data:void 0}),"submit"),close:r(()=>({code:"closed"}),"close")});return await this.hideModal(n),s}async showDrawer(e){await this.hideAllToasts();let n=await this.requireUiComponent("drawer");n.setAttribute("account-url",this.swishApp.storefrontContext.routes.accountUrl),this.swishApp.storefrontContext.customer.id&&n.setAttribute("customer-id",this.swishApp.storefrontContext.customer.id),n.setAttribute("view",e?.view??"home"),e?.listId&&n.setAttribute("list-id",e.listId),e?.listType&&n.setAttribute("list-type",e.listType),e?.productId&&n.setAttribute("product-id",e.productId),e?.variantId&&n.setAttribute("variant-id",e.variantId),e?.orderId&&n.setAttribute("order-id",e.orderId),await this.showModal(n);let s=await this.waitForEvent(n,{close:r(()=>({code:"closed"}),"close")});return await this.hideModal(n),s}async showListMenu(e){if(!e.listId)throw new Error("listId is required");await this.hideAllToasts();let n=await this.requireUiComponent("list-menu");n.setAttribute("list-id",e.listId),await this.showModal(n);let s=await this.waitForEvent(n,{close:r(()=>({code:"closed"}),"close"),edit:r(i=>i instanceof CustomEvent?{code:"ok",data:{action:"edit",data:i.detail}}:(console.warn("List menu edit without detail",i),{code:"closed"}),"edit"),delete:r(()=>({code:"ok",data:{action:"delete"}}),"delete"),"add-items":r(()=>({code:"ok",data:{action:"add-items"}}),"add-items"),share:r(()=>({code:"ok",data:{action:"share"}}),"share"),"edit-access":r(i=>{if(i instanceof CustomEvent){let o=i.detail?.currentListAccess;if(o==="public"||o==="private")return{code:"ok",data:{action:"edit-access",data:{currentListAccess:o}}}}return{code:"ok",data:{action:"edit-access"}}},"edit-access")});return await this.hideModal(n),s}async showOrderMenu(e){if(!e.orderId)throw new Error("orderId is required");await this.hideAllToasts();let n=await this.requireUiComponent("order-menu");n.setAttribute("order-id",e.orderId),await this.showModal(n);let s=await this.waitForEvent(n,{close:r(()=>({code:"closed"}),"close")});return await this.hideModal(n),s}async showListDetailPageMenu(e){await this.hideAllToasts();let n=await this.requireUiComponent("list-detail-page-menu");n.setAttribute("list-id",e.listId),await this.showModal(n);let s=await this.waitForEvent(n,{close:r(()=>({code:"closed"}),"close")});return await this.hideModal(n),s}async showListSelect(e){if(!e.itemId)throw new Error("itemId is required");await this.hideAllToasts();let n=await this.requireUiComponent("list-select");n.setAttribute("item-id",e.itemId),await this.showModal(n);let s=await this.waitForEvent(n,{close:r(()=>({code:"closed"}),"close"),submit:r(i=>"detail"in i&&i.detail?{code:"ok",data:{action:"submit",data:i.detail}}:(console.warn("List select submit without detail",i),{code:"closed"}),"submit"),unsave:r(i=>i instanceof CustomEvent?{code:"ok",data:{action:"unsave",data:i.detail}}:(console.warn("List select unsave without detail",i),{code:"closed"}),"unsave")});return await this.hideModal(n),s}async initListDetailPage(e,n){let s=await this.requireUiComponent("list-detail-page",{refElement:n});e.listId&&s.setAttribute("list-id",e.listId)}async showToast(e){let n=Date.now(),s=await this.requireUiComponent("toast-manager",{onHydrated:r(i=>{i.current.show(e,n)},"onHydrated")});return this.waitForEvent(s,{[`close-${n}`]:()=>({code:"closed"}),[`submit-${n}`]:()=>({code:"ok",data:void 0})})}async hideAllToasts(){this.queryComponent("toast-manager")&&await this.requireUiComponent("toast-manager",{onHydrated:r(e=>{e.current.clear()},"onHydrated")})}async showVariantSelect(e){await this.hideAllToasts();let n=await this.requireUiComponent("variant-select");if(e?.itemId&&n.setAttribute("item-id",e.itemId),e?.productId)n.setAttribute("product-id",e.productId.toString());else if(e?.productHandle)n.setAttribute("product-handle",e.productHandle);else throw new Error("Either productId or productHandle must be provided");e?.variantId&&n.setAttribute("variant-id",e.variantId.toString()),await this.showModal(n);let s=await this.waitForEvent(n,{close:r(()=>({code:"closed"}),"close"),submit:r(i=>"detail"in i&&i.detail?{code:"ok",data:i.detail}:(console.warn("Variant select submit without detail",i),{code:"closed"}),"submit")});return await this.hideModal(n),s}async showQuickBuy(e){await this.hideAllToasts();let n=await this.requireUiComponent("quick-buy");if(e?.productId)n.setAttribute("product-id",e.productId.toString());else if(e?.productHandle)n.setAttribute("product-handle",e.productHandle);else throw new Error("ProductId or productHandle must be provided");e?.variantId&&n.setAttribute("variant-id",e.variantId.toString()),await this.showModal(n);let s=await this.waitForEvent(n,{close:r(()=>({code:"closed"}),"close"),submit:r(i=>"detail"in i&&i.detail?{code:"ok",data:i.detail}:(console.warn("Quick buy submit without detail",i),{code:"closed"}),"submit")});return await this.hideModal(n),s}async showListEditor(e){let n=await this.requireUiComponent("list-editor");e?.listId&&n.setAttribute("list-id",e.listId),await this.showModal(n);let s=await this.waitForEvent(n,{close:r(()=>({code:"closed"}),"close"),submit:r(i=>"detail"in i&&i.detail?{code:"ok",data:i.detail}:(console.warn("List editor submit without detail",i),{code:"closed"}),"submit")});return await this.hideModal(n),s}async createElement(e,n){let[s,{themeVariablesStylesheet:i}]=await Promise.all([this.loadTemplate(e),this.loadCricalResources()]),a=document.createElement("template");a.innerHTML=s.replace(' shadowrootmode="open"',"");let o=a.content.firstElementChild;return o.addEventListener("connected",()=>{o.shadowRoot&&(o.shadowRoot.adoptedStyleSheets=[i],this.hydrateElement(e,o,n?.onHydrated))},{once:!0}),o}async hydrateElement(e,n,s){if(n.hasAttribute("hydrated")){s?.(n.getComponentRef());return}await Promise.all([this.loadNonCriticalResources(),this.loadLocale(),this.importScript(e)]).then(([{bundleCssStylesheet:i,customCssStylesheets:a},,{hydrate:o}])=>{n.shadowRoot&&i&&(n.shadowRoot.adoptedStyleSheets=[...n.shadowRoot.adoptedStyleSheets,...a,i],n.shadowRoot?.querySelector(":host > style")?.remove()),o(n),n.setAttribute("hydrated","")}),s?.(n.getComponentRef())}async requireUiComponent(e,n){this.loadCricalResources();let s=await this.loadTemplate(e),i=this.queryComponent(e)??await this.insertComponent({name:e,template:s,refElement:n?.refElement??document.body,position:"beforeend"});return i.shadowRoot&&!i.hasAttribute("hydrated")?Promise.all([this.loadNonCriticalResources(),this.loadLocale(),this.importScript(e)]).then(([{bundleCssStylesheet:a,customCssStylesheets:o},,{hydrate:u}])=>{i.shadowRoot&&a&&(i.shadowRoot.adoptedStyleSheets=[...i.shadowRoot.adoptedStyleSheets,...o,a],i.shadowRoot?.querySelector(":host > style")?.remove()),u(i),i.setAttribute("hydrated",""),n?.onHydrated?.(i.getComponentRef())}):i.hasAttribute("hydrated")&&n?.onHydrated?.(i.getComponentRef()),i}async loadTemplate(e){let n=`${this.swishApp.options.swishUi.baseUrl}/ui@${ee}/${e}.html`;if(this._templatePromises.has(n))return this._templatePromises.get(n);let s=fetch(n).then(i=>i.text());return this._templatePromises.set(n,s),s}async importScript(e){let n=`${this.swishApp.options.swishUi.baseUrl}/ui@${ee}/${e}.js`;if(this._importPromises.has(n))return this._importPromises.get(n);let s=import(n);return this._importPromises.set(n,s),s}async loadLocale(){if(this._loadLocalePromise)return this._loadLocalePromise;let e=this.swishApp.storefrontContext.localization.language.toLowerCase();return this._loadLocalePromise=this.swishApp.i18n.loadLocale(e),this._loadLocalePromise}async loadCricalResources(){return this._loadCricalResourcesPromise?this._loadCricalResourcesPromise:(this._loadCricalResourcesPromise=(async()=>{let e=`${this.swishApp.options.swishUi.baseUrl}/ui@${ee}/theme.css`,n=await fetch(e).then(a=>a.text()),s=new CSSStyleSheet;s.replaceSync(n);let i=go(this.swishApp.options.swishUi.design);return Object.entries(i).forEach(([a,o])=>{s.cssRules[0].cssRules[0].style.setProperty(a,o)}),{themeVariablesStylesheet:s}})(),this._loadCricalResourcesPromise)}async loadNonCriticalResources(){return this._loadNonCriticalResourcesPromise?this._loadNonCriticalResourcesPromise:(this._loadNonCriticalResourcesPromise=(async()=>{let e=`${this.swishApp.options.swishUi.baseUrl}/ui@${ee}/bundle.css`,n=r(a=>{let o=new CSSStyleSheet;return o.replaceSync(a),o},"createCssStylesheet"),[s,...i]=await Promise.all([fetch(e).then(a=>a.text()).then(n),...this.swishApp.options.swishUi.css.map(async a=>a instanceof URL?n(await fetch(a).then(o=>o.text())):n(a))]);return{bundleCssStylesheet:s,customCssStylesheets:i}})(),this._loadNonCriticalResourcesPromise)}async insertComponent({name:e,template:n,position:s,refElement:i}){let{themeVariablesStylesheet:a}=await this.loadCricalResources();i.insertAdjacentHTML(s,n.replace(' shadowrootmode="open"',""));let o=this.queryComponent(e);if(!o)throw new Error(`Element ${e} not found in DOM`);return o.shadowRoot&&(o.shadowRoot.adoptedStyleSheets=[a]),o}queryComponent(e,n){let s=`swish-ui[ref="${e}${n?`-${n}`:""}"]`;return document.querySelector(s)}lockScroll(){this.scrollLockRefCount++,this.scrollLockRefCount===1&&(this.scrollPositionBeforeLock=window.scrollY,this.scrollLockStyleSheet||(this.scrollLockStyleSheet=new CSSStyleSheet,document.adoptedStyleSheets=[...document.adoptedStyleSheets,this.scrollLockStyleSheet]),this.scrollLockStyleSheet.replaceSync(`
|
|
238
|
+
`);x=F.pop()??"";for(let Q of F){let X=Q.split(`
|
|
239
|
+
`),H=[],ye;for(let ee of X)if(ee.startsWith("data:"))H.push(ee.replace(/^data:\s*/,""));else if(ee.startsWith("event:"))ye=ee.replace(/^event:\s*/,"");else if(ee.startsWith("id:"))y=ee.replace(/^id:\s*/,"");else if(ee.startsWith("retry:")){let Wn=Number.parseInt(ee.replace(/^retry:\s*/,""),10);Number.isNaN(Wn)||(m=Wn)}let ve,Kn=!1;if(H.length){let ee=H.join(`
|
|
240
|
+
`);try{ve=JSON.parse(ee),Kn=!0}catch{ve=ee}}Kn&&(i&&await i(ve),s&&(ve=await s(ve))),n?.({data:ve,event:ye,id:y,retry:m}),H.length&&(yield ve)}}}finally{f.removeEventListener("abort",D),N.releaseLock()}break}catch(b){if(e?.(b),a!==void 0&&v>=a)break;let T=Math.min(m*2**(v-1),u??3e4);await h(T)}}},"createStream")()}},"createSseClient"),zo=d(t=>{switch(t){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},"separatorArrayExplode"),Ko=d(t=>{switch(t){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},"separatorArrayNoExplode"),Wo=d(t=>{switch(t){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},"separatorObjectExplode"),qi=d(({allowReserved:t,explode:e,name:n,style:s,value:i})=>{if(!e){let u=(t?i:i.map(c=>encodeURIComponent(c))).join(Ko(s));switch(s){case"label":return`.${u}`;case"matrix":return`;${n}=${u}`;case"simple":return u;default:return`${n}=${u}`}}let o=zo(s),a=i.map(u=>s==="label"||s==="simple"?t?u:encodeURIComponent(u):Gt({allowReserved:t,name:n,value:u})).join(o);return s==="label"||s==="matrix"?o+a:a},"serializeArrayParam"),Gt=d(({allowReserved:t,name:e,value:n})=>{if(n==null)return"";if(typeof n=="object")throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.");return`${e}=${t?n:encodeURIComponent(n)}`},"serializePrimitiveParam"),Ui=d(({allowReserved:t,explode:e,name:n,style:s,value:i,valueOnly:o})=>{if(i instanceof Date)return o?i.toISOString():`${n}=${i.toISOString()}`;if(s!=="deepObject"&&!e){let c=[];Object.entries(i).forEach(([l,y])=>{c=[...c,l,t?y:encodeURIComponent(y)]});let p=c.join(",");switch(s){case"form":return`${n}=${p}`;case"label":return`.${p}`;case"matrix":return`;${n}=${p}`;default:return p}}let a=Wo(s),u=Object.entries(i).map(([c,p])=>Gt({allowReserved:t,name:s==="deepObject"?`${n}[${c}]`:c,value:p})).join(a);return s==="label"||s==="matrix"?a+u:u},"serializeObjectParam"),Xo=/\{[^{}]+\}/g,Jo=d(({path:t,url:e})=>{let n=e,s=e.match(Xo);if(s)for(let i of s){let o=!1,a=i.substring(1,i.length-1),u="simple";a.endsWith("*")&&(o=!0,a=a.substring(0,a.length-1)),a.startsWith(".")?(a=a.substring(1),u="label"):a.startsWith(";")&&(a=a.substring(1),u="matrix");let c=t[a];if(c==null)continue;if(Array.isArray(c)){n=n.replace(i,qi({explode:o,name:a,style:u,value:c}));continue}if(typeof c=="object"){n=n.replace(i,Ui({explode:o,name:a,style:u,value:c,valueOnly:!0}));continue}if(u==="matrix"){n=n.replace(i,`;${Gt({name:a,value:c})}`);continue}let p=encodeURIComponent(u==="label"?`.${c}`:c);n=n.replace(i,p)}return n},"defaultPathSerializer"),Yo=d(({baseUrl:t,path:e,query:n,querySerializer:s,url:i})=>{let o=i.startsWith("/")?i:`/${i}`,a=(t??"")+o;e&&(a=Jo({path:e,url:a}));let u=n?s(n):"";return u.startsWith("?")&&(u=u.substring(1)),u&&(a+=`?${u}`),a},"getUrl");function jn(t){let e=t.body!==void 0;if(e&&t.bodySerializer)return"serializedBody"in t?t.serializedBody!==void 0&&t.serializedBody!==""?t.serializedBody:null:t.body!==""?t.body:null;if(e)return t.body}r(jn,"N");d(jn,"getValidRequestBody");var Zo=d(async(t,e)=>{let n=typeof e=="function"?await e(t):e;if(n)return t.scheme==="bearer"?`Bearer ${n}`:t.scheme==="basic"?`Basic ${btoa(n)}`:n},"getAuthToken"),Fi=d(({parameters:t={},...e}={})=>d(n=>{let s=[];if(n&&typeof n=="object")for(let i in n){let o=n[i];if(o==null)continue;let a=t[i]||e;if(Array.isArray(o)){let u=qi({allowReserved:a.allowReserved,explode:!0,name:i,style:"form",value:o,...a.array});u&&s.push(u)}else if(typeof o=="object"){let u=Ui({allowReserved:a.allowReserved,explode:!0,name:i,style:"deepObject",value:o,...a.object});u&&s.push(u)}else{let u=Gt({allowReserved:a.allowReserved,name:i,value:o});u&&s.push(u)}}return s.join("&")},"querySerializer"),"createQuerySerializer"),ea=d(t=>{var e;if(!t)return"stream";let n=(e=t.split(";")[0])==null?void 0:e.trim();if(n){if(n.startsWith("application/json")||n.endsWith("+json"))return"json";if(n==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some(s=>n.startsWith(s)))return"blob";if(n.startsWith("text/"))return"text"}},"getParseAs"),ta=d((t,e)=>{var n,s;return e?!!(t.headers.has(e)||(n=t.query)!=null&&n[e]||(s=t.headers.get("Cookie"))!=null&&s.includes(`${e}=`)):!1},"checkForExistence"),na=d(async({security:t,...e})=>{for(let n of t){if(ta(e,n.name))continue;let s=await Zo(n,e.auth);if(!s)continue;let i=n.name??"Authorization";switch(n.in){case"query":e.query||(e.query={}),e.query[i]=s;break;case"cookie":e.headers.append("Cookie",`${i}=${s}`);break;default:e.headers.set(i,s);break}}},"setAuthParams"),_i=d(t=>Yo({baseUrl:t.baseUrl,path:t.path,query:t.query,querySerializer:typeof t.querySerializer=="function"?t.querySerializer:Fi(t.querySerializer),url:t.url}),"buildUrl"),Mi=d((t,e)=>{var n;let s={...t,...e};return(n=s.baseUrl)!=null&&n.endsWith("/")&&(s.baseUrl=s.baseUrl.substring(0,s.baseUrl.length-1)),s.headers=Ni(t.headers,e.headers),s},"mergeConfigs"),sa=d(t=>{let e=[];return t.forEach((n,s)=>{e.push([s,n])}),e},"headersEntries"),Ni=d((...t)=>{let e=new Headers;for(let n of t){if(!n)continue;let s=n instanceof Headers?sa(n):Object.entries(n);for(let[i,o]of s)if(o===null)e.delete(i);else if(Array.isArray(o))for(let a of o)e.append(i,a);else o!==void 0&&e.set(i,typeof o=="object"?JSON.stringify(o):o)}return e},"mergeHeaders"),Bi=class{static{r(this,"j")}constructor(){this.fns=[]}clear(){this.fns=[]}eject(e){let n=this.getInterceptorIndex(e);this.fns[n]&&(this.fns[n]=null)}exists(e){let n=this.getInterceptorIndex(e);return!!this.fns[n]}getInterceptorIndex(e){return typeof e=="number"?this.fns[e]?e:-1:this.fns.indexOf(e)}update(e,n){let s=this.getInterceptorIndex(e);return this.fns[s]?(this.fns[s]=n,e):!1}use(e){return this.fns.push(e),this.fns.length-1}};d(Bi,"Interceptors");var Vn=Bi,ia=d(()=>({error:new Vn,request:new Vn,response:new Vn}),"createInterceptors"),ra=Fi({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),oa={"Content-Type":"application/json"},$n=d((t={})=>({...Qo,headers:oa,parseAs:"auto",querySerializer:ra,...t}),"createConfig"),Vi=d((t={})=>{let e=Mi($n(),t),n=d(()=>({...e}),"getConfig"),s=d(p=>(e=Mi(e,p),n()),"setConfig"),i=ia(),o=d(async p=>{let l={...e,...p,fetch:p.fetch??e.fetch??globalThis.fetch,headers:Ni(e.headers,p.headers),serializedBody:void 0};l.security&&await na({...l,security:l.security}),l.requestValidator&&await l.requestValidator(l),l.body!==void 0&&l.bodySerializer&&(l.serializedBody=l.bodySerializer(l.body)),(l.body===void 0||l.serializedBody==="")&&l.headers.delete("Content-Type");let y=_i(l);return{opts:l,url:y}},"beforeRequest"),a=d(async p=>{let{opts:l,url:y}=await o(p),h={redirect:"follow",...l,body:jn(l)},m=new Request(y,h);for(let x of i.request.fns)x&&(m=await x(m,l));let v=l.fetch,f;try{f=await v(m)}catch(x){let D=x;for(let k of i.error.fns)k&&(D=await k(x,void 0,m,l));if(D=D||{},l.throwOnError)throw D;return l.responseStyle==="data"?void 0:{error:D,request:m,response:void 0}}for(let x of i.response.fns)x&&(f=await x(f,m,l));let w={request:m,response:f};if(f.ok){let x=(l.parseAs==="auto"?ea(f.headers.get("Content-Type")):l.parseAs)??"json";if(f.status===204||f.headers.get("Content-Length")==="0"){let k;switch(x){case"arrayBuffer":case"blob":case"text":k=await f[x]();break;case"formData":k=new FormData;break;case"stream":k=f.body;break;default:k={};break}return l.responseStyle==="data"?k:{data:k,...w}}let D;switch(x){case"arrayBuffer":case"blob":case"formData":case"text":D=await f[x]();break;case"json":{let k=await f.text();D=k?JSON.parse(k):{};break}case"stream":return l.responseStyle==="data"?f.body:{data:f.body,...w}}return x==="json"&&(l.responseValidator&&await l.responseValidator(D),l.responseTransformer&&(D=await l.responseTransformer(D))),l.responseStyle==="data"?D:{data:D,...w}}let b=await f.text(),T;try{T=JSON.parse(b)}catch{}let U=T??b,N=U;for(let x of i.error.fns)x&&(N=await x(U,f,m,l));if(N=N||{},l.throwOnError)throw N;return l.responseStyle==="data"?void 0:{error:N,...w}},"request"),u=d(p=>l=>a({...l,method:p}),"makeMethodFn"),c=d(p=>async l=>{let{opts:y,url:h}=await o(l);return Go({...y,body:y.body,headers:y.headers,method:p,onRequest:d(async(m,v)=>{let f=new Request(m,v);for(let w of i.request.fns)w&&(f=await w(f,y));return f},"onRequest"),serializedBody:jn(y),url:h})},"makeSseFn");return{buildUrl:_i,connect:u("CONNECT"),delete:u("DELETE"),get:u("GET"),getConfig:n,head:u("HEAD"),interceptors:i,options:u("OPTIONS"),patch:u("PATCH"),post:u("POST"),put:u("PUT"),request:a,setConfig:s,sse:{connect:c("CONNECT"),delete:c("DELETE"),get:c("GET"),head:c("HEAD"),options:c("OPTIONS"),patch:c("PATCH"),post:c("POST"),put:c("PUT"),trace:c("TRACE")},trace:u("TRACE")}},"createClient"),E=Vi($n({baseUrl:"https://swish.app/api/2026-04"})),aa=d(t=>(t?.client??E).get({security:[{scheme:"bearer",type:"http"}],url:"/lists",...t}),"listControllerFind"),ua=d(t=>(t.client??E).post({security:[{scheme:"bearer",type:"http"}],url:"/lists",...t,headers:{"Content-Type":"application/json",...t.headers}}),"listControllerCreate"),ca=d(t=>(t.client??E).delete({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...t}),"listControllerDeleteById"),la=d(t=>(t.client??E).get({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...t}),"listControllerFindById"),pa=d(t=>(t.client??E).patch({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...t,headers:{"Content-Type":"application/json",...t.headers}}),"listControllerUpdateById"),da=d(t=>(t.client??E).put({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items/order",...t,headers:{"Content-Type":"application/json",...t.headers}}),"listControllerSetListItemsOrder"),ha=d(t=>(t.client??E).post({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items",...t,headers:{"Content-Type":"application/json",...t.headers}}),"listControllerAddItemsToList"),fa=d(t=>(t.client??E).delete({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items/{itemId}",...t}),"listControllerRemoveItemFromList"),ma=d(t=>(t.client??E).delete({security:[{scheme:"bearer",type:"http"}],url:"/items",...t,headers:{"Content-Type":"application/json",...t.headers}}),"itemControllerDelete"),ya=d(t=>(t?.client??E).get({security:[{scheme:"bearer",type:"http"}],url:"/items",...t}),"itemControllerFind"),va=d(t=>(t.client??E).post({security:[{scheme:"bearer",type:"http"}],url:"/items",...t,headers:{"Content-Type":"application/json",...t.headers}}),"itemControllerCreate"),ga=d(t=>(t?.client??E).get({security:[{scheme:"bearer",type:"http"}],url:"/items/count",...t}),"itemControllerCount"),wa=d(t=>(t.client??E).delete({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...t}),"itemControllerDeleteById"),ba=d(t=>(t.client??E).get({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...t}),"itemControllerFindById"),Ia=d(t=>(t.client??E).patch({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...t,headers:{"Content-Type":"application/json",...t.headers}}),"itemControllerUpdateById"),Sa=d(t=>(t.client??E).put({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}/lists",...t,headers:{"Content-Type":"application/json",...t.headers}}),"itemControllerSetListsById"),Ea=d(t=>(t.client??E).post({security:[{scheme:"bearer",type:"http"}],url:"/profiles/identify",...t,headers:{"Content-Type":"application/json",...t.headers}}),"profileControllerIdentify"),ka=d(t=>(t.client??E).post({security:[{scheme:"bearer",type:"http"}],url:"/profiles/token",...t,headers:{"Content-Type":"application/json",...t.headers}}),"profileControllerCreateToken"),xa=d(t=>(t?.client??E).get({security:[{scheme:"bearer",type:"http"}],url:"/profiles",...t}),"profileControllerGetProfile"),Ca=d(t=>(t.client??E).patch({security:[{scheme:"bearer",type:"http"}],url:"/profiles/profile",...t,headers:{"Content-Type":"application/json",...t.headers}}),"profileControllerUpdateProfile"),Ra=d(t=>(t.client??E).get({security:[{scheme:"bearer",type:"http"}],url:"/analytics/saved-items",...t}),"analyticsControllerLoadSavedItems"),Pa=d(t=>(t.client??E).get({security:[{scheme:"bearer",type:"http"}],url:"/analytics/sessions",...t}),"analyticsControllerLoadSessions"),Aa=d(t=>(t.client??E).get({security:[{scheme:"bearer",type:"http"}],url:"/analytics/new-lists",...t}),"analyticsControllerLoadNewLists"),Ta=d(t=>(t.client??E).post({security:[{scheme:"bearer",type:"http"}],url:"/collect",...t,headers:{"Content-Type":"application/json",...t.headers}}),"trackingControllerCollect"),Da=d(t=>(t?.client??E).get({security:[{scheme:"bearer",type:"http"}],url:"/orders",...t}),"ordersControllerFind"),La=d(t=>(t.client??E).get({security:[{scheme:"bearer",type:"http"}],url:"/orders/{orderId}",...t}),"ordersControllerFindOne"),Oa=d(t=>(t?.client??E).get({security:[{scheme:"bearer",type:"http"}],url:"/shared-lists",...t}),"sharedListsControllerFindAll"),_a=d(t=>(t.client??E).post({security:[{scheme:"bearer",type:"http"}],url:"/shared-lists",...t,headers:{"Content-Type":"application/json",...t.headers}}),"sharedListsControllerSave"),Ma=d(t=>(t.client??E).delete({security:[{scheme:"bearer",type:"http"}],url:"/shared-lists/{sharedListId}",...t}),"sharedListsControllerDeleteById"),qa=d(t=>(t.client??E).get({security:[{scheme:"bearer",type:"http"}],url:"/shared-lists/{sharedListId}",...t}),"sharedListsControllerFindById"),Ua=d(t=>(t.client??E).get({security:[{scheme:"bearer",type:"http"}],url:"/shared-lists/{sharedListId}/items",...t}),"sharedListsControllerFindItems"),Fa=d(t=>(t?.client??E).get({security:[{scheme:"bearer",type:"http"}],url:"/notifications",...t}),"notificationsControllerFind"),Na=d(t=>(t?.client??E).get({security:[{scheme:"bearer",type:"http"}],url:"/notifications/unread/count",...t}),"notificationsControllerGetUnreadCount"),Ba=d(t=>(t.client??E).post({security:[{scheme:"bearer",type:"http"}],url:"/notifications/read",...t,headers:{"Content-Type":"application/json",...t.headers}}),"notificationsControllerMarkAsRead"),Va=d(t=>(t?.client??E).post({security:[{scheme:"bearer",type:"http"}],url:"/notifications/read/all",...t}),"notificationsControllerMarkAllAsRead"),ja=d(t=>(t.client??E).delete({security:[{scheme:"bearer",type:"http"}],url:"/notifications/{id}",...t}),"notificationsControllerDeleteById"),$a=d(t=>(t?.client??E).get({security:[{scheme:"bearer",type:"http"}],url:"/subscriptions",...t}),"subscriptionsControllerFind"),Ha=d(t=>(t.client??E).post({security:[{scheme:"bearer",type:"http"}],url:"/subscriptions",...t,headers:{"Content-Type":"application/json",...t.headers}}),"subscriptionsControllerCreate"),Qa=d(t=>(t.client??E).delete({security:[{scheme:"bearer",type:"http"}],url:"/subscriptions/{id}",...t}),"subscriptionsControllerDelete"),Ga=d(t=>(t.client??E).get({security:[{scheme:"bearer",type:"http"}],url:"/subscriptions/{id}",...t}),"subscriptionsControllerFindById"),za=d(t=>(t.client??E).patch({security:[{scheme:"bearer",type:"http"}],url:"/subscriptions/{id}",...t,headers:{"Content-Type":"application/json",...t.headers}}),"subscriptionsControllerUpdate"),Ka=d(t=>(t?.client??E).get({security:[{scheme:"bearer",type:"http"}],url:"/smart-lists",...t}),"smartListsControllerFindAll"),Wa=d(t=>(t.client??E).get({security:[{scheme:"bearer",type:"http"}],url:"/smart-lists/{smartListId}",...t}),"smartListsControllerFindById"),Xa=d(t=>(t.client??E).get({security:[{scheme:"bearer",type:"http"}],url:"/smart-lists/{smartListId}/items",...t}),"smartListsControllerFindItems"),Ve="2026-04",ji=d(t=>new Ja(t),"createApiClient"),$i=class{static{r(this,"xe")}constructor(e){this.version=Ve,this.items={list:d(n=>this.handlePaginatedRequest(ya({query:n,client:this.client})),"list"),create:d(n=>this.handleRequest(va({body:n,client:this.client})),"create"),delete:d(n=>this.handleRequest(ma({body:{itemIds:n},client:this.client})),"delete"),findById:d(n=>this.handleRequest(ba({path:{itemId:n},client:this.client})),"findById"),updateById:d((n,s)=>this.handleRequest(Ia({body:s,path:{itemId:n},client:this.client})),"updateById"),deleteById:d(n=>this.handleRequest(wa({path:{itemId:n},client:this.client})),"deleteById"),setListsById:d((n,s)=>this.handleRequest(Sa({body:{listIds:s},path:{itemId:n},client:this.client})),"setListsById"),count:d(()=>this.handleRequest(ga({client:this.client})),"count")},this.lists={list:d(n=>this.handlePaginatedRequest(aa({query:n,client:this.client})),"list"),create:d(n=>this.handleRequest(ua({body:n,client:this.client})),"create"),findById:d(n=>this.handleRequest(la({path:{listId:n},client:this.client})),"findById"),updateById:d((n,s)=>this.handleRequest(pa({body:s,path:{listId:n},client:this.client})),"updateById"),deleteById:d(n=>this.handleRequest(ca({path:{listId:n},client:this.client})),"deleteById"),orderItems:d((n,s)=>this.handleRequest(da({body:{itemIds:s},path:{listId:n},client:this.client})),"orderItems"),addItemsToList:d((n,s)=>this.handleRequest(ha({body:{itemIds:s},path:{listId:n},client:this.client})),"addItemsToList"),removeItemFromList:d((n,s)=>this.handleRequest(fa({path:{listId:n,itemId:s},client:this.client})),"removeItemFromList")},this.profiles={createToken:d((n={})=>this.handleRequest(ka({body:n,client:this.client})),"createToken"),identify:d(n=>this.handleRequest(Ea({body:n,client:this.client})),"identify"),getProfile:d(()=>this.handleRequest(xa({client:this.client})),"getProfile"),updateProfile:d(n=>this.handleRequest(Ca({body:n,client:this.client})),"updateProfile")},this.orders={list:d(n=>this.handlePaginatedRequest(Da({query:n,client:this.client})),"list"),findById:d(n=>this.handleRequest(La({path:{orderId:n},client:this.client})),"findById")},this.sharedLists={list:d(n=>this.handlePaginatedRequest(Oa({query:n,client:this.client})),"list"),save:d(n=>this.handleRequest(_a({body:{listId:n},client:this.client})),"save"),findById:d(n=>this.handleRequest(qa({path:{sharedListId:n},client:this.client})),"findById"),deleteById:d(n=>this.handleRequest(Ma({path:{sharedListId:n},client:this.client})),"deleteById"),findItems:d((n,s)=>this.handlePaginatedRequest(Ua({path:{sharedListId:n},query:s,client:this.client})),"findItems")},this.analytics={savedItems:d(n=>this.handleRequest(Ra({query:n,client:this.client})),"savedItems"),sessions:d(n=>this.handleRequest(Pa({query:n,client:this.client})),"sessions"),newLists:d(n=>this.handleRequest(Aa({query:n,client:this.client})),"newLists")},this.tracking={track:d(n=>this.handleRequest(Ta({body:n,client:this.client})),"track")},this.notifications={list:d(n=>this.handlePaginatedRequest(Fa({query:n,client:this.client})),"list"),getUnreadCount:d(()=>this.handleRequest(Na({client:this.client})),"getUnreadCount"),markAsRead:d(n=>this.handleRequest(Ba({body:{notificationIds:n},client:this.client})),"markAsRead"),markAllAsRead:d(()=>this.handleRequest(Va({client:this.client})),"markAllAsRead"),deleteById:d(n=>this.handleRequest(ja({path:{id:n},client:this.client})),"deleteById")},this.subscriptions={list:d(n=>this.handlePaginatedRequest($a({query:n,client:this.client})),"list"),create:d(n=>this.handleRequest(Ha({body:n,client:this.client})),"create"),findById:d(n=>this.handleRequest(Ga({path:{id:n},client:this.client})),"findById"),updateById:d((n,s)=>this.handleRequest(za({body:s,path:{id:n},client:this.client})),"updateById"),deleteById:d(n=>this.handleRequest(Qa({path:{id:n},client:this.client})),"deleteById")},this.smartLists={list:d(()=>this.handleRequest(Ka({client:this.client})),"list"),findById:d(n=>this.handleRequest(Wa({path:{smartListId:n},client:this.client})),"findById"),findItems:d((n,s)=>this.handlePaginatedRequest(Xa({path:{smartListId:n},query:s,client:this.client})),"findItems")},this.handleRequest=d(async n=>{let{data:s,error:i}=await n;return i!=null&&i.error?{error:i.error}:{data:s?.data}},"handleRequest"),this.handlePaginatedRequest=d(async n=>{var s;let{data:i,error:o}=await n;return o!=null&&o.error?{error:o.error}:{data:i?.data??[],pageInfo:i?.pageInfo??{next:null,previous:null,totalCount:((s=i?.data)==null?void 0:s.length)??0}}},"handlePaginatedRequest"),this.client=Vi($n({baseUrl:`https://swish.app/api/${this.version}`,...e.config})),e.authToken&&(this.authToken=e.authToken),e.requestInterceptor&&this.client.interceptors.request.use(e.requestInterceptor),e.responseInterceptor&&this.client.interceptors.response.use(e.responseInterceptor),this.client.interceptors.request.use(this.directRequestInterceptor.bind(this))}setAuthToken(e){this.authToken=e}directRequestInterceptor(e){return this.authToken&&e.headers.set("Authorization",`Bearer ${this.authToken}`),e}};d($i,"SwishClient");var Ja=$i;var zi=nr(Gi(),1);var Ki=r(t=>new zi.default(async e=>{let n=[...new Set(e)].sort((i,o)=>i.localeCompare(o)),s=await t.items.list({query:n.join(" "),limit:200});return"error"in s?(console.error("Failed to load items",s.error),e.map(()=>({data:[],pageInfo:{next:null,previous:null,totalCount:0}}))):e.map(i=>{let o=s.data.find(a=>i===`variant:${a.variantId}`||i===`product:${a.productId}`);return{data:o?[o]:[],pageInfo:{next:null,previous:null,totalCount:o?1:0}}})},{batchScheduleFn:r(e=>setTimeout(e,50),"batchScheduleFn"),cache:!1,maxBatchSize:200}),"createItemsBatchLoader");var zt=class{constructor(e,n,s,i){this.tokenHasProfile=!1;this.api=e,this.context=n,this.eventBus=s,this.tokenUrl=i}static{r(this,"SwishApiAuth")}hasProfile(){return this.tokenHasProfile}hasToken(){return!!this.getSwishToken()}async renewToken(){return this._renewPromise?this._renewPromise:(this._renewPromise=(async()=>{this._initPromise=void 0,this.deleteSwishToken(),await this.init(),this._renewPromise=void 0})(),this._renewPromise)}async init(){return this._initPromise?this._initPromise:(this._initPromise=(async()=>{let e=this.getSwishToken();this.migrateLegacySession();let n=this.context.customer.id;n?(this.hasSessionToken()&&(this.eventBus.publish("auth-cache-clear",null),await this.api.clearCache()),await this.initCustomer(n)):(this.hasCustomerToken()&&await this.resetSession(),await this.initSession());let s=this.getSwishToken();s&&s!==e&&this.eventBus.publish("token-update",null)})(),this._initPromise)}async initCustomer(e){let n=`gid://shopify/Customer/${e}`,s=this.getTokenBySub(n);if(s){this.initToken(s);return}let i=this.getSessionId();await this.acquireToken(i,n)}async initSession(){let e=this.getSessionId(),n=e?this.getTokenBySub(e):null;if(n){this.initToken(n);return}await this.acquireToken(e)}initToken(e){let n=this.getTokenData(e);if(!n)throw new Error("Invalid Swish token.");this.tokenHasProfile=n.has_profile!==!1,this.api.setAuthToken(e)}async acquireToken(e,n){let s={};n&&(s.customer=n),e&&(s.session=e);let i=await fetch(this.tokenUrl,{method:"POST",headers:{"Content-Type":"application/json","Swish-Api-Version":Ve},body:JSON.stringify(s)});if(!i.ok)throw console.error("Failed to create customer token",i.status),new Error("Failed to create customer token");let a=(await i.json()).data;if(!a?.token)throw console.error("Failed to create customer token empty response"),new Error("Failed to create customer token");a.profile.startsWith("gid://swish/Session/")&&this.setSessionId(a.profile),this.setSwishToken(a.token),this.initToken(a.token)}async resetSession(){this.deleteSessionId(),this.deleteSwishToken(),await this.api.clearCache(),this.eventBus.publish("auth-cache-clear",null)}getTokenData(e){try{return JSON.parse(atob(e.split(".")[1]))}catch(n){return console.error("Failed to parse Swish token",{cause:n}),null}}willTokenExpire(e,n=60){let s=this.getTokenData(e);return!!(s&&s.exp&&s.exp<Date.now()/1e3+n)}hasCustomerToken(){let e=this.getSwishToken();return e?this.getTokenData(e)?.sub?.startsWith("gid://shopify/Customer/")??!1:!1}hasSessionToken(){let e=this.getSwishToken();return e?this.getTokenData(e)?.sub?.startsWith("gid://swish/Session/")??!1:!1}getTokenBySub(e){if(!e)return null;let n=this.getSwishToken();if(!n)return null;let s=this.getTokenData(n);return!s||s.sub!==e||this.willTokenExpire(n,60)?null:n}getSessionId(){let e=Z(this.context.myshopifyDomain);return localStorage.getItem(`swish-session-${e}`)??void 0}setSessionId(e){let n=Z(this.context.myshopifyDomain);localStorage.setItem(`swish-session-${n}`,e)}deleteSessionId(){let e=Z(this.context.myshopifyDomain);localStorage.removeItem(`swish-session-${e}`)}getSwishToken(){let e=Z(this.context.myshopifyDomain);return sessionStorage.getItem(`swish-token-${e}`)??void 0}setSwishToken(e){let n=Z(this.context.myshopifyDomain);sessionStorage.setItem(`swish-token-${n}`,e)}deleteSwishToken(){let e=Z(this.context.myshopifyDomain);sessionStorage.removeItem(`swish-token-${e}`)}migrateLegacySession(){try{let e=localStorage.getItem("wk_session_id")??localStorage.getItem("swish-profile")?.split("/").pop()??localStorage.getItem("swish-session")?.split("/").pop();e&&(this.setSessionId(`gid://swish/Session/${e}`),localStorage.removeItem("wk_session_id"),localStorage.removeItem("swish-profile"),localStorage.removeItem("swish-session"))}catch(e){console.warn("Failed to migrate legacy session id to Swish session",{cause:e})}}};var Kt=class{static{r(this,"SwishApi")}constructor(e,n,s,i,o){this.config=e,this.storefrontContext=n;let a=Z(n.myshopifyDomain);this.cache=new de(`swish-api-${a}`,"max-age=60, stale-while-revalidate=3600",i+Ve),this.cache.cleanupExpiredEntries().catch(u=>{console.warn("Swish API cache initialization cleanup error:",u)}),this.auth=new zt(this,n,s,o),this.apiClient=ji({authToken:this.auth.getSwishToken(),config:{...e,fetch:this.fetchFunction.bind(this)},requestInterceptor:this.requestInterceptor.bind(this),responseInterceptor:this.responseInterceptor.bind(this)}),this.itemsLoader=Ki(this)}async fetchFunction(e,n){let s=e instanceof Request?e.method:n?.method??"GET",i=e instanceof Request?e.url:typeof e=="string"?e:e.toString();if(i.includes("/smart-lists"))return fetch(e,n);let a=i.includes("/orders");return s==="GET"&&!a?this.cache.fetchWithCache(e,n):fetch(e,n)}async requestInterceptor(e){await this.initAuth();try{e.headers.set("Country",this.storefrontContext.localization.country),e.headers.set("Language",this.storefrontContext.localization.language),e.headers.set("Market",this.storefrontContext.localization.market)}catch(n){console.warn("Failed to set storefront context headers:",n)}return this.config.requestInterceptor&&(e=await this.config.requestInterceptor(e)),e}async responseInterceptor(e,n){let s=n.method!=="GET",i=n.url.includes("/profiles/token");if(s&&!i){let o=this.auth.hasToken(),a=!this.auth.hasProfile(),u=e.ok;await this.cache.clear(),o&&a&&u&&await this.auth.renewToken()}return await this.config.responseInterceptor?.(e,n),e}setAuthToken(e){this.apiClient.setAuthToken(e)}initAuth(){return this.auth.init()}async withFallback(e,n){return await this.initAuth(),this.auth.hasProfile()?e():Promise.resolve(n)}async withSignedInCustomerFallback(e,n){return await this.initAuth(),!!this.storefrontContext.customer.id&&this.auth.hasProfile()?e():Promise.resolve(n)}get items(){return{...this.apiClient.items,count:r(async()=>this.withFallback(()=>this.apiClient.items.count(),{data:{count:0}}),"count"),list:r(async(e,n)=>{let s=r(()=>{if(n?.batch&&e?.query){e.limit!==1&&console.warn("Batching will always limit to 1 item");let i=e.query.split(" ");i.length>1&&console.warn("Batching will only support one query parameter");let o=i[0];if(!o.match(/^product:\d+$/)&&!o.match(/^variant:\d+$/))console.warn("Batching will only support product:<id> or variant:<id>");else return this.itemsLoader?.load(o)}return this.apiClient.items.list(e)},"execute");return n?.shared?s():this.withFallback(s,{data:[],pageInfo:{next:null,previous:null,totalCount:0}})},"list"),findById:r(async e=>this.withFallback(()=>this.apiClient.items.findById(e),{data:null}),"findById")}}get lists(){return{...this.apiClient.lists,list:r(async e=>this.withFallback(()=>this.apiClient.lists.list(e),{data:[],pageInfo:{next:null,previous:null,totalCount:0}}),"list"),findById:r(async(e,n)=>{let s=r(()=>this.apiClient.lists.findById(e),"execute");return n?.shared?s():this.withFallback(()=>this.apiClient.lists.findById(e),{data:null})},"findById")}}get orders(){return{...this.apiClient.orders,list:r(async e=>this.withFallback(()=>this.apiClient.orders.list(e),{data:[],pageInfo:{next:null,previous:null,totalCount:0}}),"list"),findById:r(async e=>this.withFallback(()=>(typeof e=="string"&&(e=parseInt(e.split("/").pop()??e)),this.apiClient.orders.findById(e)),{data:null}),"findById")}}get notifications(){return{...this.apiClient.notifications,list:r(async e=>this.withSignedInCustomerFallback(()=>this.apiClient.notifications.list(e),{data:[],pageInfo:{next:null,previous:null,totalCount:0}}),"list"),getUnreadCount:r(async()=>this.withSignedInCustomerFallback(()=>this.apiClient.notifications.getUnreadCount(),{data:{count:0}}),"getUnreadCount"),markAsRead:r(e=>this.apiClient.notifications.markAsRead(e),"markAsRead"),markAllAsRead:r(()=>this.apiClient.notifications.markAllAsRead(),"markAllAsRead"),deleteById:r(e=>this.apiClient.notifications.deleteById(e),"deleteById")}}get smartLists(){return{...this.apiClient.smartLists,list:r(async()=>this.withFallback(()=>this.apiClient.smartLists.list(),{data:null}),"list"),findById:r(async e=>e==="recently-viewed"?this.apiClient.smartLists.findById(e):this.withFallback(()=>this.apiClient.smartLists.findById(e),{data:null}),"findById"),findItems:r(async(e,n)=>e==="recently-viewed"?this.apiClient.smartLists.findItems(e,n):this.withFallback(()=>this.apiClient.smartLists.findItems(e,n),{data:[],pageInfo:{next:null,previous:null,totalCount:0}}),"findItems")}}get profiles(){return this.apiClient.profiles}async clearCache(){await this.cache.clear()}};var Wt=class{constructor(e){this.eventMap={"POST /items\\/?$":"item-create","DELETE /items\\/?$":"item-delete","PATCH /items\\/([^/]+)\\/?$":"item-update","DELETE /items\\/([^/]+)\\/?$":"item-delete","PUT /items\\/([^/]+)\\/lists\\/?$":"item-lists-update","POST /lists\\/?$":"list-create","DELETE /lists\\/?$":"list-delete","PATCH /lists\\/([^/]+)\\/?$":"list-update","DELETE /lists\\/([^/]+)\\/?$":"list-delete","POST /notifications\\/read\\/all\\/?$":"notification-update","POST /notifications\\/read\\/?$":"notification-update","PATCH /notifications\\/([^/]+)\\/?$":"notification-update","DELETE /notifications\\/([^/]+)\\/?$":"notification-delete"};this.eventBus=e,this.processFetchResponse=this.processFetchResponse.bind(this)}static{r(this,"SwishApiPublisher")}async processFetchResponse(e,n){try{let s=this.getEventName(n.method,e.status,n.url);if(!s)return;let i=await e.clone().text();if(e.headers.get("Content-Type")?.includes("application/json"))try{i=JSON.parse(i).data}catch(o){console.warn(o)}this.eventBus.publish(s,i)}catch(s){console.warn(s)}}getEventName(e,n,s){e=e.toUpperCase();let i=new URL(s).pathname;return e==="GET"||n<200||n>=300?void 0:Object.entries(this.eventMap).find(([a])=>{let[u,c]=a.split(" ");return u!==e?!1:new RegExp(c).test(i)})?.[1]}};var Xt=class{constructor(e){this.inflightModals=new Map;this.modalsWithScrollLock=new Set;this.scrollLockRefCount=0;this.scrollPositionBeforeLock=0;this.elementId=0;this._templatePromises=new Map;this._importPromises=new Map;this._lockScroll=r(()=>this.lockScroll(),"_lockScroll");this._unlockScroll=r(()=>this.unlockScroll(),"_unlockScroll");this.swishApp=e}static{r(this,"SwishUi")}async showModal(e){if(this.inflightModals.has(e))return this.inflightModals.get(e);let n=(async()=>{typeof e=="string"&&(e=await this.requireUiComponent(e)),!(!e||e.getAttribute("open")==="true")&&(this.lockScroll(),this.modalsWithScrollLock.add(e),e.setAttribute("open","true"))})().finally(()=>{this.inflightModals.delete(e)});return this.inflightModals.set(e,n),n}async hideModal(e){if(this.inflightModals.has(e))return this.inflightModals.get(e);let n=(async()=>{try{if(typeof e=="string"&&(e=await this.requireUiComponent(e)),e?.getAttribute("open")!=="true")return;e.setAttribute("open","false"),e.hasAttribute("swish-singleton")||e.addEventListener("closed",()=>{e.remove()},{once:!0})}finally{e&&typeof e!="string"&&this.modalsWithScrollLock.has(e)&&(this.modalsWithScrollLock.delete(e),this.unlockScroll())}})().finally(()=>{this.inflightModals.delete(e)});return this.inflightModals.set(e,n),n}waitForEvent(e,n){return new Promise(s=>{let i=[],o=r(()=>{i.forEach(({event:a,listener:u})=>{e.removeEventListener(a,u)})},"cleanup");Object.entries(n).forEach(([a,u])=>{let c=r(p=>{let l=u(p);o(),s(l)},"listener");i.push({event:a,listener:c}),e.addEventListener(a,c)})})}async showSignIn(e){let n=await this.requireUiComponent("sign-in");n.setAttribute("return-to",e?.returnTo??window.location.pathname),await this.showModal(n);let s=await this.waitForEvent(n,{submit:r(()=>({code:"ok",data:void 0}),"submit"),close:r(()=>({code:"closed"}),"close")});return await this.hideModal(n),s}async showUnsaveAlert(e){if(!e.itemId)throw new Error("An itemId is required to show the unsave alert");await this.hideAllToasts();let n=await this.requireUiComponent("unsave-alert");n.setAttribute("item-id",e.itemId),await this.showModal(n);let s=await this.waitForEvent(n,{submit:r(i=>i instanceof CustomEvent?{code:"ok",data:i.detail}:(console.warn("Unsave alert submitted without detail",i),{code:"closed"}),"submit"),close:r(()=>({code:"closed"}),"close")});return await this.hideModal(n),s}async showDeleteListAlert(e){if(!e.listId)throw new Error("A listId is required to show the delete list alert");await this.hideAllToasts();let n=await this.requireUiComponent("delete-list-alert");n.setAttribute("list-id",e.listId),await this.showModal(n);let s=await this.waitForEvent(n,{submit:r(()=>({code:"ok",data:void 0}),"submit"),close:r(()=>({code:"closed"}),"close")});return await this.hideModal(n),s}async showConfirmDialog(e){await this.hideAllToasts();let n=await this.requireUiComponent("confirm-dialog");e.titleKey?n.setAttribute("title-key",e.titleKey):n.removeAttribute("title-key"),e.descriptionKey?n.setAttribute("description-key",e.descriptionKey):n.removeAttribute("description-key"),e.confirmLabelKey?n.setAttribute("confirm-label-key",e.confirmLabelKey):n.removeAttribute("confirm-label-key"),e.cancelLabelKey?n.setAttribute("cancel-label-key",e.cancelLabelKey):n.removeAttribute("cancel-label-key"),e.danger?n.setAttribute("danger",""):n.removeAttribute("danger"),await this.showModal(n);let s=await this.waitForEvent(n,{submit:r(()=>({code:"ok",data:void 0}),"submit"),close:r(()=>({code:"closed"}),"close")});return await this.hideModal(n),s}async showDrawer(e){await this.hideAllToasts();let n=await this.requireUiComponent("drawer",{singleInstance:!0});n.setAttribute("account-url",this.swishApp.storefrontContext.routes.accountUrl),this.swishApp.storefrontContext.customer.id&&n.setAttribute("customer-id",this.swishApp.storefrontContext.customer.id),n.setAttribute("view",e?.view??"home"),e?.listId&&n.setAttribute("list-id",e.listId),e?.listType&&n.setAttribute("list-type",e.listType),e?.productId&&n.setAttribute("product-id",e.productId),e?.variantId&&n.setAttribute("variant-id",e.variantId),e?.orderId&&n.setAttribute("order-id",e.orderId),await this.showModal(n);let s=await this.waitForEvent(n,{close:r(()=>({code:"closed"}),"close")});return await this.hideModal(n),s}async showListMenu(e){if(!e.listId)throw new Error("listId is required");await this.hideAllToasts();let n=await this.requireUiComponent("list-menu");n.setAttribute("list-id",e.listId),await this.showModal(n);let s=await this.waitForEvent(n,{close:r(()=>({code:"closed"}),"close"),edit:r(i=>i instanceof CustomEvent?{code:"ok",data:{action:"edit",data:i.detail}}:(console.warn("List menu edit without detail",i),{code:"closed"}),"edit"),delete:r(()=>({code:"ok",data:{action:"delete"}}),"delete"),"add-items":r(()=>({code:"ok",data:{action:"add-items"}}),"add-items"),share:r(()=>({code:"ok",data:{action:"share"}}),"share"),"edit-access":r(i=>{if(i instanceof CustomEvent){let a=i.detail?.currentListAccess;if(a==="public"||a==="private")return{code:"ok",data:{action:"edit-access",data:{currentListAccess:a}}}}return{code:"ok",data:{action:"edit-access"}}},"edit-access")});return await this.hideModal(n),s}async showOrderMenu(e){if(!e.orderId)throw new Error("orderId is required");await this.hideAllToasts();let n=await this.requireUiComponent("order-menu");n.setAttribute("order-id",e.orderId),await this.showModal(n);let s=await this.waitForEvent(n,{close:r(()=>({code:"closed"}),"close")});return await this.hideModal(n),s}async showListDetailPageMenu(e){await this.hideAllToasts();let n=await this.requireUiComponent("list-detail-page-menu");n.setAttribute("list-id",e.listId),await this.showModal(n);let s=await this.waitForEvent(n,{close:r(()=>({code:"closed"}),"close")});return await this.hideModal(n),s}async showListSelect(e){if(!e.itemId)throw new Error("itemId is required");await this.hideAllToasts();let n=await this.requireUiComponent("list-select");n.setAttribute("item-id",e.itemId),await this.showModal(n);let s=await this.waitForEvent(n,{close:r(()=>({code:"closed"}),"close"),submit:r(i=>"detail"in i&&i.detail?{code:"ok",data:{action:"submit",data:i.detail}}:(console.warn("List select submit without detail",i),{code:"closed"}),"submit"),unsave:r(i=>i instanceof CustomEvent?{code:"ok",data:{action:"unsave",data:i.detail}}:(console.warn("List select unsave without detail",i),{code:"closed"}),"unsave")});return await this.hideModal(n),s}async initListDetailPage(e,n){let s=await this.requireUiComponent("list-detail-page",{refElement:n});e.listId&&s.setAttribute("list-id",e.listId)}async showToast(e){let n=Date.now(),s=await this.requireUiComponent("toast-manager",{singleInstance:!0,onHydrated:r(i=>{i.current.show(e,n)},"onHydrated")});return this.waitForEvent(s,{[`close-${n}`]:()=>({code:"closed"}),[`submit-${n}`]:()=>({code:"ok",data:void 0})})}async hideAllToasts(){this.queryComponent("toast-manager")&&await this.requireUiComponent("toast-manager",{singleInstance:!0,onHydrated:r(e=>{e.current.clear()},"onHydrated")})}async showVariantSelect(e){await this.hideAllToasts();let n=await this.requireUiComponent("variant-select");if(e?.itemId&&n.setAttribute("item-id",e.itemId),e?.productId)n.setAttribute("product-id",e.productId.toString());else if(e?.productHandle)n.setAttribute("product-handle",e.productHandle);else throw new Error("Either productId or productHandle must be provided");e?.variantId&&n.setAttribute("variant-id",e.variantId.toString()),await this.showModal(n);let s=await this.waitForEvent(n,{close:r(()=>({code:"closed"}),"close"),submit:r(i=>"detail"in i&&i.detail?{code:"ok",data:i.detail}:(console.warn("Variant select submit without detail",i),{code:"closed"}),"submit")});return await this.hideModal(n),s}async showQuickBuy(e){await this.hideAllToasts();let n=await this.requireUiComponent("quick-buy");if(e?.productId)n.setAttribute("product-id",e.productId.toString());else if(e?.productHandle)n.setAttribute("product-handle",e.productHandle);else throw new Error("ProductId or productHandle must be provided");e?.variantId&&n.setAttribute("variant-id",e.variantId.toString()),await this.showModal(n);let s=await this.waitForEvent(n,{close:r(()=>({code:"closed"}),"close"),submit:r(i=>"detail"in i&&i.detail?{code:"ok",data:i.detail}:(console.warn("Quick buy submit without detail",i),{code:"closed"}),"submit")});return await this.hideModal(n),s}async showListEditor(e){let n=await this.requireUiComponent("list-editor");e?.listId&&n.setAttribute("list-id",e.listId),await this.showModal(n);let s=await this.waitForEvent(n,{close:r(()=>({code:"closed"}),"close"),submit:r(i=>"detail"in i&&i.detail?{code:"ok",data:i.detail}:(console.warn("List editor submit without detail",i),{code:"closed"}),"submit")});return await this.hideModal(n),s}async createElement(e,n){let[s,{themeVariablesStylesheet:i}]=await Promise.all([this.loadTemplate(e),this.loadCricalResources()]),o=document.createElement("template");o.innerHTML=s.replace(' shadowrootmode="open"',"");let a=o.content.firstElementChild;return a.addEventListener("connected",()=>{a.shadowRoot&&(a.shadowRoot.adoptedStyleSheets=[i],this.hydrateElement(e,a,n?.onHydrated))},{once:!0}),a}async hydrateElement(e,n,s){if(n.hasAttribute("hydrated")){s?.(n.getComponentRef());return}await Promise.all([this.loadNonCriticalResources(),this.loadLocale(),this.importScript(e)]).then(([{bundleCssStylesheet:i,customCssStylesheets:o},,{hydrate:a}])=>{n.shadowRoot&&i&&(n.shadowRoot.adoptedStyleSheets=[...n.shadowRoot.adoptedStyleSheets,...o,i],n.shadowRoot?.querySelector(":host > style")?.remove()),a(n),n.setAttribute("hydrated","")}),s?.(n.getComponentRef())}async requireUiComponent(e,n){this.loadCricalResources();let s=await this.loadTemplate(e),i=await this.insertComponent({name:e,template:s,refElement:n?.refElement??document.body,position:"beforeend",singleInstance:n?.singleInstance??!1});return i.shadowRoot&&!i.hasAttribute("hydrated")?Promise.all([this.loadNonCriticalResources(),this.loadLocale(),this.importScript(e)]).then(([{bundleCssStylesheet:o,customCssStylesheets:a},,{hydrate:u}])=>{i.shadowRoot&&o&&(i.shadowRoot.adoptedStyleSheets=[...i.shadowRoot.adoptedStyleSheets,...a,o],i.shadowRoot?.querySelector(":host > style")?.remove()),u(i),i.setAttribute("hydrated",""),n?.onHydrated?.(i.getComponentRef())}):i.hasAttribute("hydrated")&&n?.onHydrated?.(i.getComponentRef()),i}async loadTemplate(e){let n=`${this.swishApp.options.swishUi.baseUrl}/ui@${le}/${e}.html`;if(this._templatePromises.has(n))return this._templatePromises.get(n);let s=fetch(n).then(i=>i.text());return this._templatePromises.set(n,s),s}async importScript(e){let n=`${this.swishApp.options.swishUi.baseUrl}/ui@${le}/${e}.js`;if(this._importPromises.has(n))return this._importPromises.get(n);let s=import(n);return this._importPromises.set(n,s),s}async loadLocale(){if(this._loadLocalePromise)return this._loadLocalePromise;let e=this.swishApp.storefrontContext.localization.language.toLowerCase();return this._loadLocalePromise=this.swishApp.i18n.loadLocale(e),this._loadLocalePromise}async loadCricalResources(){return this._loadCricalResourcesPromise?this._loadCricalResourcesPromise:(this._loadCricalResourcesPromise=(async()=>{let e=`${this.swishApp.options.swishUi.baseUrl}/ui@${le}/theme.css`,n=await fetch(e).then(o=>o.text()),s=new CSSStyleSheet;s.replaceSync(n);let i=au(this.swishApp.options.swishUi.design);return Object.entries(i).forEach(([o,a])=>{s.cssRules[0].cssRules[0].style.setProperty(o,a)}),{themeVariablesStylesheet:s}})(),this._loadCricalResourcesPromise)}async loadNonCriticalResources(){return this._loadNonCriticalResourcesPromise?this._loadNonCriticalResourcesPromise:(this._loadNonCriticalResourcesPromise=(async()=>{let e=`${this.swishApp.options.swishUi.baseUrl}/ui@${le}/bundle.css`,n=r(o=>{let a=new CSSStyleSheet;return a.replaceSync(o),a},"createCssStylesheet"),[s,...i]=await Promise.all([fetch(e).then(o=>o.text()).then(n),...this.swishApp.options.swishUi.css.map(async o=>o instanceof URL?n(await fetch(o).then(a=>a.text())):n(o))]);return{bundleCssStylesheet:s,customCssStylesheets:i}})(),this._loadNonCriticalResourcesPromise)}async insertComponent({name:e,template:n,position:s,refElement:i,singleInstance:o}){if(o&&this.queryComponent(e))return this.queryComponent(e);let{themeVariablesStylesheet:a}=await this.loadCricalResources(),u=o?0:++this.elementId;i.insertAdjacentHTML(s,n.replace(' shadowrootmode="open"',"").replace(`ref="${e}"`,`ref="${e}" instance="${u}"`));let c=this.queryComponent(e,u);if(!c)throw new Error(`Element ${e} not found in DOM`);return o&&c.setAttribute("swish-singleton",""),c.shadowRoot&&(c.shadowRoot.adoptedStyleSheets=[a]),c}queryComponent(e,n=0){let s=`swish-ui[ref="${e}"][instance="${n}"]`;return document.querySelector(s)}lockScroll(){this.scrollLockRefCount++,this.scrollLockRefCount===1&&(this.scrollPositionBeforeLock=window.scrollY,this.scrollLockStyleSheet||(this.scrollLockStyleSheet=new CSSStyleSheet,document.adoptedStyleSheets=[...document.adoptedStyleSheets,this.scrollLockStyleSheet]),this.scrollLockStyleSheet.replaceSync(`
|
|
294
241
|
html[swish-locked] body {
|
|
295
242
|
overflow: hidden;
|
|
296
243
|
position: fixed;
|
|
@@ -298,4 +245,4 @@ Values:
|
|
|
298
245
|
left: 0px;
|
|
299
246
|
right: 0px;
|
|
300
247
|
}
|
|
301
|
-
`),document.documentElement.setAttribute("swish-locked",""))}unlockScroll(){this.scrollLockRefCount>0&&this.scrollLockRefCount--,this.scrollLockRefCount===0&&(this.scrollLockStyleSheet&&this.scrollLockStyleSheet.replaceSync(""),window.scrollTo({top:this.scrollPositionBeforeLock,behavior:"instant"}),this.scrollPositionBeforeLock=0,document.documentElement.removeAttribute("swish-locked"))}};function
|
|
248
|
+
`),document.documentElement.setAttribute("swish-locked",""))}unlockScroll(){this.scrollLockRefCount>0&&this.scrollLockRefCount--,this.scrollLockRefCount===0&&(this.scrollLockStyleSheet&&this.scrollLockStyleSheet.replaceSync(""),window.scrollTo({top:this.scrollPositionBeforeLock,behavior:"instant"}),this.scrollPositionBeforeLock=0,document.documentElement.removeAttribute("swish-locked"))}};function au(t){if(!t)return{};let e={},n=r(s=>{Object.entries(s).forEach(([i,o])=>{if(o!=null){if(typeof o=="object"&&!Array.isArray(o)){n(o);return}if(typeof o=="string"||typeof o=="number"){let a=i.startsWith("--")?i:`--swish-theme-${uu(i)}`;e[a]=cu(i,o)}}})},"walk");return n(t),e}r(au,"flattenDesignTokens");function uu(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z])([A-Z][a-z])/g,"$1-$2").toLowerCase()}r(uu,"toKebabCase");function cu(t,e){return typeof e=="number"&&!lu(t)?`${e}px`:String(e)}r(cu,"formatDesignValue");function lu(t){let e=t.toLowerCase();return e.includes("fontweight")||e.includes("scale")||e.includes("letterspacing")||e.includes("lineheight")}r(lu,"isNonPxValue");var pu=typeof HTMLElement<"u"?HTMLElement:class{},Jt=class extends pu{constructor(){super();this.getComponentRef=r(()=>this.componentRef,"getComponentRef");this.setComponentRef=r(n=>{this.componentRef=n},"setComponentRef");this.shadowRoot||this.attachShadow({mode:"open"});let n=this.querySelector("template");n&&this.shadowRoot&&(this.shadowRoot.appendChild(n.content),n.remove())}static{r(this,"SwishUiElement")}connectedCallback(){this.dispatchEvent(new CustomEvent("connected"))}};var le="0.121.0",gv=`https://swish.app/cdn/sdk@${le}/swish.js`,wv=r(async t=>{if(globalThis.window===void 0)throw new Error("Swish is not supported in this environment");if(globalThis.window.swish)return globalThis.window.swish;let e=ys(t),n=new zn(e);return globalThis.window.swish=n,document.dispatchEvent(new Event("swish-ready")),n.api.initAuth().then(()=>{typeof globalThis.window.Shopify?.analytics?.publish=="function"&&globalThis.window.Shopify.analytics.publish("swish-ready",{market:e.storefrontContext.localization.market,country:e.storefrontContext.localization.country,language:e.storefrontContext.localization.language,rootUrl:e.storefrontContext.routes.rootUrl,preRelease:le==="unstable"})}),n},"createSwish"),zn=class{constructor(e){this.dom={createElementLocator:re,createLocationObserver:Ee,createPlacement:r(e=>as(this,e),"createPlacement")};this.ui={createElement:r((e,n)=>this.swishUi.createElement(e,n),"createElement")};this.utils={copyToClipboard:_e,createShareUrl:r(e=>Oe(this,e),"createShareUrl")};this.state={itemContext:Zs(this),itemState:ti(this),itemCount:ni(this),swishQuery:si(this),effect:K,signal:M,computed:Y};this.swishOptions=e,this.events=new Qe,this._i18n=es(`${e.swishUi.baseUrl}/i18n@${le}`,e.translations),this.swishApiPublisher=new Wt(this.events);let n=le;this.swishApi=new Kt({...this.swishOptions.swishApi,responseInterceptor:this.swishApiPublisher.processFetchResponse},this.swishOptions.storefrontContext,this.events,n,this.swishOptions.auth.tokenUrl),this.ajaxApiPublisher=new $e(this.events),this.ajaxApi=new je({storeDomain:this.swishOptions.storefrontApi.storeDomain,responseInterceptor:this.ajaxApiPublisher.processFetchResponse}),this.ajaxApi.patchFetch(),this.storefrontApi=new Qt(this.swishOptions.storefrontApi,this.swishOptions.storefrontContext,this.swishOptions.products.metafields),this.swishUi=new Xt(this),this.query=Ys({events:this.events,cacheBuster:le,customerId:this.swishOptions.storefrontContext.customer.id,storeDomain:this.swishOptions.storefrontContext.myshopifyDomain}),this.events.subscribe(["cart-add","cart-update","cart-change","cart-clear"],()=>{this.ajaxApi.clearCache()}),customElements.get("swish-ui")||customElements.define("swish-ui",Jt),this.intents=new Rt(this,this.swishUi),ii(this)}static{r(this,"SwishApp")}get options(){return this.swishOptions}get storefrontContext(){return this.swishOptions.storefrontContext}get api(){return this.swishApi}get storefront(){return this.storefrontApi}get ajax(){return this.ajaxApi}get i18n(){return this._i18n}get shopUrl(){return`https://${this.swishOptions.storefrontApi.storeDomain}`}};export{le as VERSION,Oe as buildShareListUrl,_e as copyToClipboard,wv as createSwish,Ft as getSwishQueryStorageKey,gv as swishSdkUrl};
|