@swishapp/sdk 0.72.0 → 0.73.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.
Files changed (2) hide show
  1. package/dist/swish.js +2 -2
  2. package/package.json +1 -1
package/dist/swish.js CHANGED
@@ -442,7 +442,7 @@ Values:
442
442
  `);try{J=JSON.parse(M),$t=!0}catch{J=M}}$t&&(i&&await i(J),n&&(J=await n(J))),t?.({data:J,event:Lt,id:d,retry:h}),he.length&&(yield J)}}}finally{y.removeEventListener("abort",P),I.releaseLock()}break}catch(O){if(e?.(O),a!==void 0&&D>=a)break;let k=Math.min(h*2**(D-1),u??3e4);await m(k)}}},"createStream")()}},"createSseClient"),ii=f(r=>{switch(r){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},"separatorArrayExplode"),si=f(r=>{switch(r){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},"separatorArrayNoExplode"),oi=f(r=>{switch(r){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},"separatorObjectExplode"),Hr=f(({allowReserved:r,explode:e,name:t,style:n,value:i})=>{if(!e){let u=(r?i:i.map(l=>encodeURIComponent(l))).join(si(n));switch(n){case"label":return`.${u}`;case"matrix":return`;${t}=${u}`;case"simple":return u;default:return`${t}=${u}`}}let o=ii(n),a=i.map(u=>n==="label"||n==="simple"?r?u:encodeURIComponent(u):Ne({allowReserved:r,name:t,value:u})).join(o);return n==="label"||n==="matrix"?o+a:a},"serializeArrayParam"),Ne=f(({allowReserved:r,name:e,value:t})=>{if(t==null)return"";if(typeof t=="object")throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.");return`${e}=${r?t:encodeURIComponent(t)}`},"serializePrimitiveParam"),Qr=f(({allowReserved:r,explode:e,name:t,style:n,value:i,valueOnly:o})=>{if(i instanceof Date)return o?i.toISOString():`${t}=${i.toISOString()}`;if(n!=="deepObject"&&!e){let l=[];Object.entries(i).forEach(([p,d])=>{l=[...l,p,r?d:encodeURIComponent(d)]});let c=l.join(",");switch(n){case"form":return`${t}=${c}`;case"label":return`.${c}`;case"matrix":return`;${t}=${c}`;default:return c}}let a=oi(n),u=Object.entries(i).map(([l,c])=>Ne({allowReserved:r,name:n==="deepObject"?`${t}[${l}]`:l,value:c})).join(a);return n==="label"||n==="matrix"?a+u:u},"serializeObjectParam"),ai=/\{[^{}]+\}/g,ui=f(({path:r,url:e})=>{let t=e,n=e.match(ai);if(n)for(let i of n){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 l=r[a];if(l==null)continue;if(Array.isArray(l)){t=t.replace(i,Hr({explode:o,name:a,style:u,value:l}));continue}if(typeof l=="object"){t=t.replace(i,Qr({explode:o,name:a,style:u,value:l,valueOnly:!0}));continue}if(u==="matrix"){t=t.replace(i,`;${Ne({name:a,value:l})}`);continue}let c=encodeURIComponent(u==="label"?`.${l}`:l);t=t.replace(i,c)}return t},"defaultPathSerializer"),li=f(({baseUrl:r,path:e,query:t,querySerializer:n,url:i})=>{let o=i.startsWith("/")?i:`/${i}`,a=(r??"")+o;e&&(a=ui({path:e,url:a}));let u=t?n(t):"";return u.startsWith("?")&&(u=u.substring(1)),u&&(a+=`?${u}`),a},"getUrl");function zr(r){let e=r.body!==void 0;if(e&&r.bodySerializer)return"serializedBody"in r?r.serializedBody!==void 0&&r.serializedBody!==""?r.serializedBody:null:r.body!==""?r.body:null;if(e)return r.body}s(zr,"G");f(zr,"getValidRequestBody");var ci=f(async(r,e)=>{let t=typeof e=="function"?await e(r):e;if(t)return r.scheme==="bearer"?`Bearer ${t}`:r.scheme==="basic"?`Basic ${btoa(t)}`:t},"getAuthToken"),Wr=f(({allowReserved:r,array:e,object:t}={})=>f(n=>{let i=[];if(n&&typeof n=="object")for(let o in n){let a=n[o];if(a!=null)if(Array.isArray(a)){let u=Hr({allowReserved:r,explode:!0,name:o,style:"form",value:a,...e});u&&i.push(u)}else if(typeof a=="object"){let u=Qr({allowReserved:r,explode:!0,name:o,style:"deepObject",value:a,...t});u&&i.push(u)}else{let u=Ne({allowReserved:r,name:o,value:a});u&&i.push(u)}}return i.join("&")},"querySerializer"),"createQuerySerializer"),pi=f(r=>{var e;if(!r)return"stream";let t=(e=r.split(";")[0])==null?void 0:e.trim();if(t){if(t.startsWith("application/json")||t.endsWith("+json"))return"json";if(t==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some(n=>t.startsWith(n)))return"blob";if(t.startsWith("text/"))return"text"}},"getParseAs"),fi=f((r,e)=>{var t,n;return e?!!(r.headers.has(e)||(t=r.query)!=null&&t[e]||(n=r.headers.get("Cookie"))!=null&&n.includes(`${e}=`)):!1},"checkForExistence"),di=f(async({security:r,...e})=>{for(let t of r){if(fi(e,t.name))continue;let n=await ci(t,e.auth);if(!n)continue;let i=t.name??"Authorization";switch(t.in){case"query":e.query||(e.query={}),e.query[i]=n;break;case"cookie":e.headers.append("Cookie",`${i}=${n}`);break;case"header":default:e.headers.set(i,n);break}}},"setAuthParams"),Mr=f(r=>li({baseUrl:r.baseUrl,path:r.path,query:r.query,querySerializer:typeof r.querySerializer=="function"?r.querySerializer:Wr(r.querySerializer),url:r.url}),"buildUrl"),jr=f((r,e)=>{var t;let n={...r,...e};return(t=n.baseUrl)!=null&&t.endsWith("/")&&(n.baseUrl=n.baseUrl.substring(0,n.baseUrl.length-1)),n.headers=Xr(r.headers,e.headers),n},"mergeConfigs"),hi=f(r=>{let e=[];return r.forEach((t,n)=>{e.push([n,t])}),e},"headersEntries"),Xr=f((...r)=>{let e=new Headers;for(let t of r){if(!t)continue;let n=t instanceof Headers?hi(t):Object.entries(t);for(let[i,o]of n)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"),Kr=class{static{s(this,"$")}constructor(){this.fns=[]}clear(){this.fns=[]}eject(e){let t=this.getInterceptorIndex(e);this.fns[t]&&(this.fns[t]=null)}exists(e){let t=this.getInterceptorIndex(e);return!!this.fns[t]}getInterceptorIndex(e){return typeof e=="number"?this.fns[e]?e:-1:this.fns.indexOf(e)}update(e,t){let n=this.getInterceptorIndex(e);return this.fns[n]?(this.fns[n]=t,e):!1}use(e){return this.fns.push(e),this.fns.length-1}};f(Kr,"Interceptors");var St=Kr,yi=f(()=>({error:new St,request:new St,response:new St}),"createInterceptors"),mi=Wr({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),vi={"Content-Type":"application/json"},Ue=f((r={})=>({...ti,headers:vi,parseAs:"auto",querySerializer:mi,...r}),"createConfig"),At=f((r={})=>{let e=jr(Ue(),r),t=f(()=>({...e}),"getConfig"),n=f(c=>(e=jr(e,c),t()),"setConfig"),i=yi(),o=f(async c=>{let p={...e,...c,fetch:c.fetch??e.fetch??globalThis.fetch,headers:Xr(e.headers,c.headers),serializedBody:void 0};p.security&&await di({...p,security:p.security}),p.requestValidator&&await p.requestValidator(p),p.body!==void 0&&p.bodySerializer&&(p.serializedBody=p.bodySerializer(p.body)),(p.body===void 0||p.serializedBody==="")&&p.headers.delete("Content-Type");let d=Mr(p);return{opts:p,url:d}},"beforeRequest"),a=f(async c=>{let{opts:p,url:d}=await o(c),m={redirect:"follow",...p,body:zr(p)},h=new Request(d,m);for(let v of i.request.fns)v&&(h=await v(h,p));let D=p.fetch,y=await D(h);for(let v of i.response.fns)v&&(y=await v(y,h,p));let S={request:h,response:y};if(y.ok){let v=(p.parseAs==="auto"?pi(y.headers.get("Content-Type")):p.parseAs)??"json";if(y.status===204||y.headers.get("Content-Length")==="0"){let T;switch(v){case"arrayBuffer":case"blob":case"text":T=await y[v]();break;case"formData":T=new FormData;break;case"stream":T=y.body;break;case"json":default:T={};break}return p.responseStyle==="data"?T:{data:T,...S}}let P;switch(v){case"arrayBuffer":case"blob":case"formData":case"json":case"text":P=await y[v]();break;case"stream":return p.responseStyle==="data"?y.body:{data:y.body,...S}}return v==="json"&&(p.responseValidator&&await p.responseValidator(P),p.responseTransformer&&(P=await p.responseTransformer(P))),p.responseStyle==="data"?P:{data:P,...S}}let O=await y.text(),k;try{k=JSON.parse(O)}catch{}let F=k??O,I=F;for(let v of i.error.fns)v&&(I=await v(F,y,h,p));if(I=I||{},p.throwOnError)throw I;return p.responseStyle==="data"?void 0:{error:I,...S}},"request"),u=f(c=>p=>a({...p,method:c}),"makeMethodFn"),l=f(c=>async p=>{let{opts:d,url:m}=await o(p);return ni({...d,body:d.body,headers:d.headers,method:c,onRequest:f(async(h,D)=>{let y=new Request(h,D);for(let S of i.request.fns)S&&(y=await S(y,d));return y},"onRequest"),url:m})},"makeSseFn");return{buildUrl:Mr,connect:u("CONNECT"),delete:u("DELETE"),get:u("GET"),getConfig:t,head:u("HEAD"),interceptors:i,options:u("OPTIONS"),patch:u("PATCH"),post:u("POST"),put:u("PUT"),request:a,setConfig:n,sse:{connect:l("CONNECT"),delete:l("DELETE"),get:l("GET"),head:l("HEAD"),options:l("OPTIONS"),patch:l("PATCH"),post:l("POST"),put:l("PUT"),trace:l("TRACE")},trace:u("TRACE")}},"createClient"),x=At(Ue({baseUrl:"https://swish.app/api/2026-01"})),gi=f(r=>(r?.client??x).get({security:[{scheme:"bearer",type:"http"}],url:"/lists",...r}),"listControllerFind"),Ii=f(r=>(r.client??x).post({security:[{scheme:"bearer",type:"http"}],url:"/lists",...r,headers:{"Content-Type":"application/json",...r.headers}}),"listControllerCreate"),wi=f(r=>(r.client??x).delete({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...r}),"listControllerDeleteById"),bi=f(r=>(r.client??x).get({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...r}),"listControllerFindById"),Ei=f(r=>(r.client??x).patch({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...r,headers:{"Content-Type":"application/json",...r.headers}}),"listControllerUpdateById"),Ci=f(r=>(r.client??x).put({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items/order",...r,headers:{"Content-Type":"application/json",...r.headers}}),"listControllerSetListItemsOrder"),xi=f(r=>(r.client??x).post({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items",...r,headers:{"Content-Type":"application/json",...r.headers}}),"listControllerAddItemsToList"),Si=f(r=>(r.client??x).delete({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items/{itemId}",...r}),"listControllerRemoveItemFromList"),Ai=f(r=>(r.client??x).delete({security:[{scheme:"bearer",type:"http"}],url:"/items",...r,headers:{"Content-Type":"application/json",...r.headers}}),"itemControllerDelete"),ki=f(r=>(r?.client??x).get({security:[{scheme:"bearer",type:"http"}],url:"/items",...r}),"itemControllerFind"),Ri=f(r=>(r.client??x).post({security:[{scheme:"bearer",type:"http"}],url:"/items",...r,headers:{"Content-Type":"application/json",...r.headers}}),"itemControllerCreate"),Di=f(r=>(r?.client??x).get({security:[{scheme:"bearer",type:"http"}],url:"/items/count",...r}),"itemControllerCount"),Pi=f(r=>(r.client??x).delete({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...r}),"itemControllerDeleteById"),Ti=f(r=>(r.client??x).get({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...r}),"itemControllerFindById"),_i=f(r=>(r.client??x).patch({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...r,headers:{"Content-Type":"application/json",...r.headers}}),"itemControllerUpdateById"),Oi=f(r=>(r.client??x).put({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}/lists",...r,headers:{"Content-Type":"application/json",...r.headers}}),"itemControllerSetListsById"),Li=f(r=>(r?.client??x).get({security:[{scheme:"bearer",type:"http"}],url:"/profiles/accounts-version",...r}),"profileControllerCustomerAccountsVersion"),$i=f(r=>(r.client??x).post({security:[{scheme:"bearer",type:"http"}],url:"/profiles/identify",...r,headers:{"Content-Type":"application/json",...r.headers}}),"profileControllerIdentify"),Bi=f(r=>(r.client??x).post({security:[{scheme:"bearer",type:"http"}],url:"/profiles/token",...r,headers:{"Content-Type":"application/json",...r.headers}}),"profileControllerCreateToken"),qi=f(r=>(r?.client??x).get({security:[{scheme:"bearer",type:"http"}],url:"/orders",...r}),"ordersControllerFind"),Vi=f(r=>(r.client??x).get({security:[{scheme:"bearer",type:"http"}],url:"/orders/{orderId}",...r}),"ordersControllerFindOne"),kt="2026-01",Fr="/apps/wishlist/api",Yr=f(r=>new Ui(r),"createApiClient"),Jr=class{static{s(this,"H")}constructor(e){this.useProxy=!1,this.version=kt,this.items={list:f(n=>this.handlePaginatedRequest(ki({query:n,client:this.useProxy?this.proxyClient:this.directClient})),"list"),create:f(n=>this.handleRequest(Ri({body:n,client:this.useProxy?this.proxyClient:this.directClient})),"create"),delete:f(n=>this.handleRequest(Ai({body:{itemIds:n},client:this.useProxy?this.proxyClient:this.directClient})),"delete"),findById:f(n=>this.handleRequest(Ti({path:{itemId:n},client:this.useProxy?this.proxyClient:this.directClient})),"findById"),updateById:f((n,i)=>this.handleRequest(_i({body:i,path:{itemId:n},client:this.useProxy?this.proxyClient:this.directClient})),"updateById"),deleteById:f(n=>this.handleRequest(Pi({path:{itemId:n},client:this.useProxy?this.proxyClient:this.directClient})),"deleteById"),setListsById:f((n,i)=>this.handleRequest(Oi({body:{listIds:i},path:{itemId:n},client:this.useProxy?this.proxyClient:this.directClient})),"setListsById"),count:f(()=>this.handleRequest(Di({client:this.useProxy?this.proxyClient:this.directClient})),"count")},this.lists={list:f(n=>this.handlePaginatedRequest(gi({query:n,client:this.useProxy?this.proxyClient:this.directClient})),"list"),create:f(n=>this.handleRequest(Ii({body:n,client:this.useProxy?this.proxyClient:this.directClient})),"create"),findById:f(n=>this.handleRequest(bi({path:{listId:n},client:this.useProxy?this.proxyClient:this.directClient})),"findById"),updateById:f((n,i)=>this.handleRequest(Ei({body:i,path:{listId:n},client:this.useProxy?this.proxyClient:this.directClient})),"updateById"),deleteById:f(n=>this.handleRequest(wi({path:{listId:n},client:this.useProxy?this.proxyClient:this.directClient})),"deleteById"),orderItems:f((n,i)=>this.handleRequest(Ci({body:{itemIds:i},path:{listId:n},client:this.useProxy?this.proxyClient:this.directClient})),"orderItems"),addItemsToList:f((n,i)=>this.handleRequest(xi({body:{itemIds:i},path:{listId:n},client:this.useProxy?this.proxyClient:this.directClient})),"addItemsToList"),removeItemFromList:f((n,i)=>this.handleRequest(Si({path:{listId:n,itemId:i},client:this.useProxy?this.proxyClient:this.directClient})),"removeItemFromList")},this.profiles={customerAccountsVersion:f(()=>this.handleRequest(Li({client:this.useProxy?this.proxyClient:this.directClient})),"customerAccountsVersion"),createToken:f((n={},i)=>this.handleRequest(Bi({body:n,client:this.useProxy||i!=null&&i.useProxy?this.proxyClient:this.directClient})),"createToken"),identify:f(n=>this.handleRequest($i({body:n,client:this.useProxy?this.proxyClient:this.directClient})),"identify")},this.orders={list:f(n=>this.handlePaginatedRequest(qi({query:n,client:this.useProxy?this.proxyClient:this.directClient})),"list"),findById:f(n=>this.handleRequest(Vi({path:{orderId:n},client:this.useProxy?this.proxyClient:this.directClient})),"findById")},this.handleRequest=f(async n=>{let{data:i,error:o}=await n;return o!=null&&o.error?{error:o.error}:{data:i?.data}},"handleRequest"),this.handlePaginatedRequest=f(async n=>{var i;let{data:o,error:a}=await n;return a!=null&&a.error?{error:a.error}:{data:o?.data??[],pageInfo:o?.pageInfo??{next:null,previous:null,totalCount:((i=o?.data)==null?void 0:i.length)??0}}},"handlePaginatedRequest");var t;this.profile=e.profile,(t=e.config)!=null&&t.version&&(this.version=e.config.version),this.directClient=At(Ue({baseUrl:`https://swish.app/api/${this.version}`})),this.proxyClient=At(Ue({baseUrl:Fr})),e.authToken&&(this.authToken=e.authToken),e.config&&this.setConfig(e.config),e.requestInterceptor&&(this.proxyClient.interceptors.request.use(e.requestInterceptor),this.directClient.interceptors.request.use(e.requestInterceptor)),e.responseInterceptor&&(this.proxyClient.interceptors.response.use(e.responseInterceptor),this.directClient.interceptors.response.use(e.responseInterceptor)),this.proxyClient.interceptors.request.use(this.proxyRequestInterceptor.bind(this)),this.directClient.interceptors.request.use(this.directRequestInterceptor.bind(this))}setProfile(e){this.profile=e}getProfile(){return this.profile}setAuthToken(e){this.authToken=e}setConfig({proxyBaseUrl:e=Fr,baseUrl:t,useProxy:n=!1,...i}){this.useProxy=n,this.proxyClient.setConfig({...i,baseUrl:e}),this.directClient.setConfig({...i})}proxyRequestInterceptor(e){return this.profile&&(e.headers.set("Profile",this.profile),e.headers.set("Swish-Api-Version",this.version)),e}directRequestInterceptor(e){return this.authToken&&e.headers.set("Authorization",`Bearer ${this.authToken}`),e}};f(Jr,"SwishClient");var Ui=Jr;var Zr=s(r=>r?JSON.parse(atob(r.split(".")[1])):null,"getTokenData"),en=s((r,e=60)=>{let t=Zr(r);return t?t.exp&&t.exp<Date.now()/1e3+e:!1},"isTokenExpired"),tn=s(r=>{let e=Zr(r);return e?e.sub.startsWith("gid://shopify/Customer/"):!1},"isCustomerToken");var on=gn(sn(),1);var an=s(r=>new on.default(async e=>{let t=[...new Set(e)].sort((i,o)=>i.localeCompare(o)),n=await r.items.list({query:t.join(" "),limit:200});return"error"in n?(console.error("Failed to load items",n.error),e.map(()=>({data:[],pageInfo:{next:null,previous:null,totalCount:0}}))):e.map(i=>{let o=n.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:s(e=>setTimeout(e,50),"batchScheduleFn"),cache:!1,maxBatchSize:200}),"createItemsBatchLoader");var se={profile:{get:s(()=>localStorage.getItem("swish-profile")??void 0,"get"),set:s(r=>localStorage.setItem("swish-profile",r),"set"),delete:s(()=>localStorage.removeItem("swish-profile"),"delete")},authToken:{get:s(()=>sessionStorage.getItem("swish-token")??void 0,"get"),set:s(r=>sessionStorage.setItem("swish-token",r),"set"),delete:s(()=>sessionStorage.removeItem("swish-token"),"delete")}},Ge=class{static{s(this,"SwishApi")}constructor(e,t,n){this.config=e,this.context=t,this.cache=new Q("swish-api","max-age=60, stale-while-revalidate=3600",n+(e.version??kt)),this.cache.cleanupExpiredEntries().catch(a=>{console.warn("Swish API cache initialization cleanup error:",a)});let i=se.profile.get(),o=se.authToken.get();this.apiClient=Yr({profile:i,authToken:o,proxyMode:this.config.proxyMode,config:{...e,fetch:s((a,u)=>(a instanceof Request?a.method:u?.method??"GET")==="GET"?this.cache.fetchWithCache(a,u):fetch(a,u),"fetch")},requestInterceptor:s(async a=>{let u=new URL(a.url,window.location.origin),l=this.config.proxyBaseUrl??"/apps/wishlist/api",c=u.pathname==="/profiles/token";return!u.pathname.startsWith(l)&&!c&&await this.bootstrapAuth(),a},"requestInterceptor"),responseInterceptor:s(async(a,u)=>(this.processProfileHeader(a),u.method!=="GET"&&await this.cache.clear(),await this.config.responseInterceptor?.(a,u),a),"responseInterceptor")}),this.itemsLoader=an(this)}async bootstrapAuth(){if(this._bootstrapAuthPromise)return this._bootstrapAuthPromise;this._bootstrapAuthPromise=(async()=>{let e=se.authToken.get();if(e)try{if(en(e,60))throw new Error("TOKEN_EXPIRED")}catch(o){(!(o instanceof Error)||o.message!=="TOKEN_EXPIRED")&&console.error("Failed to decode cached auth token",{cause:o}),se.authToken.delete(),e=void 0}if(e){this.apiClient.setAuthToken(e);return}let t=this.apiClient.getProfile(),n=this.config.customerId,i=await this.apiClient.profiles.createToken({customer:n,session:t},{useProxy:!0});if("error"in i){console.error("Failed to bootstrap auth with error",i.error);return}if(!i.data?.token){console.error("Failed to bootstrap auth with no token");return}se.authToken.set(i.data.token),this.apiClient.setAuthToken(i.data.token)})();try{return await this._bootstrapAuthPromise}finally{this._bootstrapAuthPromise=void 0}}processProfileHeader(e){let t=e.headers.get("Set-Profile");t?(this.apiClient.setProfile(t),se.profile.set(t)):t===""&&se.profile.delete()}get items(){return{...this.apiClient.items,list:s(async(e,t)=>{if(!this.config.customerId&&!this.apiClient.getProfile())return{data:[],pageInfo:{next:null,previous:null,totalCount:0}};if(t?.batch&&e?.query){e.limit!==1&&console.warn("Batching will always limit to 1 item");let n=e.query.split(" ");n.length>1&&console.warn("Batching will only support one query parameter");let i=n[0];if(!i.match(/^product:\d+$/)&&!i.match(/^variant:\d+$/))console.warn("Batching will only support product:<id> or variant:<id>");else return this.itemsLoader?.load(i)}return this.apiClient.items.list(e)},"list"),findById:s(async e=>!this.config.customerId&&!this.apiClient.getProfile()?{data:null}:this.apiClient.items.findById(e),"findById")}}get lists(){return{...this.apiClient.lists,list:s(async e=>!this.config.customerId&&!this.apiClient.getProfile()?{data:[],pageInfo:{next:null,previous:null,totalCount:0}}:this.apiClient.lists.list(e),"list"),findById:s(async e=>!this.config.customerId&&!this.apiClient.getProfile()?{data:null}:this.apiClient.lists.findById(e),"findById")}}get orders(){return{...this.apiClient.orders,list:s(async e=>!this.context.customer.id&&!this.apiClient.getProfile()?{data:[],pageInfo:{next:null,previous:null,totalCount:0}}:this.apiClient.orders.list(e),"list"),findById:s(async e=>!this.context.customer.id&&!this.apiClient.getProfile()?{data:null}:this.apiClient.orders.findById(e),"findById")}}get profiles(){return this.apiClient.profiles}async clearCache(){await this.cache.clear()}};var Me=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"};this.eventBus=e,this.processFetchResponse=this.processFetchResponse.bind(this)}static{s(this,"SwishApiPublisher")}async processFetchResponse(e,t){try{let n=this.getEventName(t.method,e.status,t.url);if(!n)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(n,i)}catch(n){console.warn(n)}}getEventName(e,t,n){e=e.toUpperCase();let i=new URL(n).pathname;return e==="GET"||t<200||t>=300?void 0:Object.entries(this.eventMap).find(([a])=>{let[u,l]=a.split(" ");return u!==e?!1:new RegExp(l).test(i)})?.[1]}};var Xi=typeof HTMLElement<"u"?HTMLElement:class{},je=class extends Xi{constructor(){super();this.getComponentRef=s(()=>this.componentRef,"getComponentRef");this.setComponentRef=s(t=>{this.componentRef=t},"setComponentRef");this.shadowRoot||this.attachShadow({mode:"open"});let t=this.querySelector("template");t&&this.shadowRoot&&(this.shadowRoot.appendChild(t.content),t.remove())}static{s(this,"SwishUiElement")}};var Fe=class{static{s(this,"ShopifyBadgesUtils")}#e;constructor({getBadges:e}){this.#e=e?.bind(this)}getBadges({product:e,variant:t}){try{let n=this.getDefaultBadges({product:e,variant:t});return this.#e?this.mapBadges(this.#e({product:e,variant:t,defaultBadges:n})??[]):this.mapBadges(n)}catch(n){return console.error("Error getting badges",n),[]}}getDefaultBadges({product:e,variant:t}){let n=[];if(e?.availableForSale===!1||t?.availableForSale===!1)return n.push("Sold out"),n;let i=t?t.price.amount:e?.priceRange?.minVariantPrice.amount,o=t?t.compareAtPrice?.amount:e?.compareAtPriceRange?.minVariantPrice.amount;return o&&parseFloat(o)>parseFloat(i)&&n.push("Sale"),n}mapBadges(e){return e.map(t=>typeof t=="string"?{id:t.toLowerCase().replace(/[^a-z0-9]/g,"_"),label:t}:t)}};var un=s(r=>{let e=r.proxy?.baseUrl??"/apps/wishlist";return{proxy:{baseUrl:e},storefrontApi:{storeDomain:r.storefrontApi?.storeDomain??"",accessToken:r.storefrontApi?.accessToken??""},storefrontContext:{...r.storefrontContext,localization:{country:r.storefrontContext.localization.country.toUpperCase(),language:r.storefrontContext.localization.language.toUpperCase(),market:r.storefrontContext.localization.market}},badges:{getBadges:r.badges?.getBadges??(({defaultBadges:t})=>t)},metafields:{product:r.metafields?.product??[],productVariant:r.metafields?.productVariant??[]},swishApi:{version:r.swishApi?.version??"2026-01"},swishUi:{baseUrl:r.swishUi?.baseUrl??`${e}/assets`,components:{productRow:{showVariantTitle:r.swishUi?.components?.productRow?.showVariantTitle??!1},productDetail:{descriptionMaxLines:r.swishUi?.components?.productDetail?.descriptionMaxLines??4},variantSelect:{displayType:r.swishUi?.components?.variantSelect?.displayType??"pills"},imageSlider:{flush:r.swishUi?.components?.imageSlider?.flush??!1,loop:r.swishUi?.components?.imageSlider?.loop??!1},images:{baseTint:r.swishUi?.components?.images?.baseTint??!1},buyButtons:{shopPay:r.swishUi?.components?.buyButtons?.shopPay??!1},listDetailPage:{desktopColumns:r.swishUi?.components?.listDetailPage?.desktopColumns??4,showBuyButton:r.swishUi?.components?.listDetailPage?.showBuyButton??!0},drawer:{title:r.swishUi?.components?.drawer?.title??"",logo:{url:r.swishUi?.components?.drawer?.logo?.url??"",altText:r.swishUi?.components?.drawer?.logo?.altText??""},navigation:{variant:r.swishUi?.components?.drawer?.navigation?.variant??"floating",items:r.swishUi?.components?.drawer?.navigation?.items??[{id:"home",enabled:!0,href:"/"},{id:"items",enabled:!0,href:"/items"},{id:"lists",enabled:!0,href:"/lists"},{id:"chat",enabled:!1,href:"/chat"},{id:"orders",enabled:!0,href:"/orders"},{id:"profile",enabled:!0,href:"/profile"}]},miniMenu:{items:r.swishUi?.components?.drawer?.miniMenu?.items??[]}}},css:r.swishUi?.css??[],intents:{save:{requireVariant:r.swishUi?.intents?.save?.requireVariant??!1,showToast:r.swishUi?.intents?.save?.showToast??!1},edit:{showToast:r.swishUi?.intents?.edit?.showToast??!1},unsave:{requireConfirmation:r.swishUi?.intents?.unsave?.requireConfirmation??!1,openEditor:r.swishUi?.intents?.unsave?.openEditor??!1,showToast:r.swishUi?.intents?.unsave?.showToast??!1}},theme:r.swishUi?.theme??{},version:r.swishUi?.version??"0.40.0"}}},"createSwishOptions");var Ki=".swish-shop-bridge{position:absolute!important;top:0!important;left:0!important;padding:0!important;border:0!important;margin:0!important;pointer-events:none!important}.swish-shop-bridge input{appearance:none!important;border:none!important;width:1px!important;height:1px!important;padding:0!important;margin:0!important;background:rgba(0,0,0,0)!important}",Yi=s(()=>{let r="/";return typeof window<"u"&&(r=window.location.pathname),`<form class=swish-shop-bridge data-login-with-shop-sign-in=true id=customer_login><input name=customer[email] id=customer_login_email> <input name=return_url type=hidden value=${r}></form>`},"getHtml"),Ji=typeof HTMLElement<"u"?HTMLElement:class{},Tt=class extends Ji{static{s(this,"ShopBridge")}get swish(){return typeof window<"u"?window.swish:void 0}constructor(){super(),this.emailInput=this.querySelector('form[data-login-with-shop-sign-in] input[type="email"],form[data-login-with-shop-sign-in] input[name="customer[email]"'),this.emailInput||(this.innerHTML=`
443
443
  <style>${Ki}</style>
444
444
  ${Yi()}
445
- `,this.emailInput=this.querySelector("#customer_login_email")),this.shopModalObserver=new MutationObserver(e=>{e.forEach(t=>{t.attributeName==="style"&&document.documentElement.style.overflow==="hidden"&&this.dispatchEvent(new CustomEvent("shop-modal-open"))})}),this.shopModalObserver.observe(document.documentElement,{attributes:!0,attributeFilter:["style"]})}disconnectedCallback(){this.shopModalObserver?.disconnect()}async load(){try{(window.Shopify?.featureAssets?.["shop-js"]?.["init-customer-accounts"]?.[0]??"").includes("init-customer-accounts")&&window.Shopify?.SignInWithShop?.initCustomerAccounts?.(!0,{fedCMEnabled:!0,windoidEnabled:!1})}catch(e){console.warn("Failed to initialize Shop JS",e)}}update(e){if(e.email&&(this.emailInput.value=e.email,this.emailInput.dispatchEvent(new Event("input"))),e.returnTo){let t=this.querySelector("input[name='return_url']");t&&(t.value=e.returnTo)}}};typeof customElements<"u"&&customElements.define("swish-shop-bridge",Tt);var He=class{constructor(e,t){this.inflightModals=new Map;this.eventListeners=new Map;this.scrollLockRefCount=0;this.scrollPositionBeforeLock=0;this._lockScroll=s(()=>this.lockScroll(),"_lockScroll");this._unlockScroll=s(()=>this.unlockScroll(),"_unlockScroll");this.swishUiOptions=e,this.storefrontContext=t}static{s(this,"SwishUi")}async hideModal(e){if(this.inflightModals.has(e))return this.inflightModals.get(e);let t=(async()=>{typeof e=="string"&&(e=await this.requireUiComponent(e)),!(!e||e.getAttribute("open")!=="true")&&e.setAttribute("open","false")})().finally(()=>{this.inflightModals.delete(e)});return this.unlockScroll(),this.inflightModals.set(e,t),t}async showModal(e){if(this.inflightModals.has(e))return this.inflightModals.get(e);let t=(async()=>{typeof e=="string"&&(e=await this.requireUiComponent(e)),!(!e||e.getAttribute("open")==="true")&&e.setAttribute("open","true")})().finally(()=>{this.inflightModals.delete(e)});return this.lockScroll(),this.inflightModals.set(e,t),t}async showSignIn(e){let t=await this.requireUiComponent("sign-in",{listeners:{close:s(()=>e?.onClose?.(),"close")}});t.setAttribute("return-to",e?.returnTo??window.location.pathname),await this.showModal(t)}async showUnsaveAlert(e){if(!e.itemId)throw new Error("An itemId is required to show the unsave alert");await this.hideAllToasts();let t=await this.requireUiComponent("unsave-alert",{listeners:{submit:s(n=>{n instanceof CustomEvent?e.onSubmit?.(n.detail):console.warn("Unsave alert submitted without detail",n)},"submit"),close:s(()=>{e.onClose?.()},"close")}});t.setAttribute("item-id",e.itemId),await this.showModal(t)}async showDeleteListAlert(e){if(!e.listId)throw new Error("A listId is required to show the delete list alert");await this.hideAllToasts();let t=await this.requireUiComponent("delete-list-alert",{listeners:{submit:s(()=>{e.onSubmit?.()},"submit"),close:s(()=>{e.onClose?.()},"close")}});t.setAttribute("list-id",e.listId),await this.showModal(t)}async showDrawer(e){await this.hideAllToasts();let t=await this.requireUiComponent("drawer",{listeners:{close:s(()=>{e?.onClose?.()},"close")}});t.setAttribute("account-url",this.storefrontContext.routes.accountUrl),this.storefrontContext.customer.id&&t.setAttribute("customer-id",this.storefrontContext.customer.id),await this.showModal(t)}async showListMenu(e){if(!e.listId)throw new Error("listId is required");await this.hideAllToasts();let t=await this.requireUiComponent("list-menu",{listeners:{close:s(n=>{e.onClose?.()},"close"),edit:s(n=>{n instanceof CustomEvent?e.onEdit?.(n.detail):console.warn("List menu submitted without detail",n)},"edit"),delete:s(n=>{n instanceof CustomEvent?e.onDelete?.():console.warn("List menu deleted without detail",n)},"delete")}});t.setAttribute("list-id",e.listId),await this.showModal(t)}async showListSelect(e){if(!e.itemId)throw new Error("itemId is required");await this.hideAllToasts();let t=await this.requireUiComponent("list-select",{listeners:{submit:s(async n=>{"detail"in n&&n.detail?e?.onSubmit?.(n.detail):console.warn("List select form submitted without detail",n)},"submit"),close:s(()=>{e.onClose?.()},"close"),unsave:s(n=>{n instanceof CustomEvent?e.onUnsave?.(n.detail):console.warn("List select unsave without detail",n)},"unsave")}});t.setAttribute("item-id",e.itemId),await this.showModal(t)}async initListDetailPage(e,t){let n=await this.requireUiComponent("list-detail-page",{refElement:t});e.listId&&n.setAttribute("list-id",e.listId)}async showToast(e){await this.requireUiComponent("toast-manager",{onHydrated:s(t=>{t.current.show(e)},"onHydrated")})}async hideAllToasts(){this.queryComponent("toast-manager")&&await this.requireUiComponent("toast-manager",{onHydrated:s(e=>{e.current.clear()},"onHydrated")})}async showVariantSelect(e){await this.hideAllToasts();let t=await this.requireUiComponent("variant-select",{listeners:{submit:s(async n=>{"detail"in n&&n.detail?e?.onSubmit?.(n.detail):console.warn("Variant select form submitted without detail",n)},"submit"),close:s(()=>{e?.onClose?.()},"close")}});if(e?.productId)t.setAttribute("product-id",e.productId);else if(e?.productHandle)t.setAttribute("product-handle",e.productHandle);else throw new Error("Either productId or productHandle must be provided");e?.variantId&&t.setAttribute("variant-id",e.variantId),e?.displayType&&t.setAttribute("display-type",e.displayType),await this.showModal(t)}async showQuickBuy(e){await this.hideAllToasts();let t=await this.requireUiComponent("quick-buy",{listeners:{submit:s(async n=>{"detail"in n&&n.detail?e?.onSubmit?.(n.detail):console.warn("Quick buy form submitted without detail",n)},"submit"),close:s(()=>{e?.onClose?.()},"close")}});if(e?.productId)t.setAttribute("product-id",e.productId);else throw new Error("ProductId must be provided");e?.variantId&&t.setAttribute("variant-id",e.variantId),await this.showModal(t)}async showListEditor(e){let t=await this.requireUiComponent("list-editor",{listeners:{submit:s(async n=>{"detail"in n&&n.detail?e?.onSubmit?.(n.detail):console.warn("List editor form submitted without detail",n)},"submit"),close:s(()=>{e?.onClose?.()},"close")}});e?.listId&&t.setAttribute("list-id",e.listId),await this.showModal(t)}async initShopBridge({onShopModalOpen:e}){let t=document.querySelector("swish-shop-bridge");if(t||(document.body.insertAdjacentHTML("beforeend","<swish-shop-bridge></swish-shop-bridge>"),t=document.querySelector("swish-shop-bridge")),!t)throw new Error("Failed to initialize Shop Bridge");return t.addEventListener("shop-modal-open",()=>e(),{once:!0}),await t.load(),t}async requireUiComponent(e,t){this.loadCricalResources();let n=`${this.swishUiOptions.baseUrl}/ui@${this.swishUiOptions.version}/${e}.html`,i=await fetch(n).then(l=>l.text()),o=t?.instance,a=t?.listeners,u=this.queryComponent(e,o)??await this.insertComponent({name:e,template:i,refElement:t?.refElement??document.body,position:"beforeend",instance:o});if(u.shadowRoot&&!u.hasAttribute("hydrated")){let l=`${this.swishUiOptions.baseUrl}/ui@${this.swishUiOptions.version}/${e}.js`;Promise.all([this.loadNonCriticalResources(),import(l)]).then(([{bundleCssStylesheet:c,customCssStylesheets:p},{hydrate:d}])=>{u.shadowRoot&&c&&(u.shadowRoot.adoptedStyleSheets=[...u.shadowRoot.adoptedStyleSheets,...p,c],u.shadowRoot?.querySelector(":host > style")?.remove()),d(u),u.setAttribute("hydrated",""),t?.onHydrated?.(u.getComponentRef())})}else u.hasAttribute("hydrated")&&t?.onHydrated?.(u.getComponentRef());for(let{event:l,listener:c}of this.eventListeners.values())u.removeEventListener(l,c);for(let[l,c]of Object.entries(a??{}))this.eventListeners.set(`${e}-${o}-${l}`,{event:l,listener:c}),u.addEventListener(l,c);return u}async loadCricalResources(){return this._loadCricalResourcesPromise?this._loadCricalResourcesPromise:(this._loadCricalResourcesPromise=(async()=>{let e=`${this.swishUiOptions.baseUrl}/ui@${this.swishUiOptions.version}/theme.css`,t=await fetch(e).then(i=>i.text()),n=new CSSStyleSheet;return n.replaceSync(t),{themeVariablesStylesheet:n}})(),this._loadCricalResourcesPromise)}async loadNonCriticalResources(){return this._loadNonCriticalResourcesPromise?this._loadNonCriticalResourcesPromise:(this._loadNonCriticalResourcesPromise=(async()=>{let e=`${this.swishUiOptions.baseUrl}/ui@${this.swishUiOptions.version}/bundle.css`,t=s(o=>{let a=new CSSStyleSheet;return a.replaceSync(o),a},"createCssStylesheet"),[n,...i]=await Promise.all([fetch(e).then(o=>o.text()).then(t),...this.swishUiOptions.css.map(async o=>o instanceof URL?t(await fetch(o).then(a=>a.text())):t(o))]);return{bundleCssStylesheet:n,customCssStylesheets:i}})(),this._loadNonCriticalResourcesPromise)}async insertComponent({name:e,instance:t,template:n,position:i,refElement:o}){let{themeVariablesStylesheet:a}=await this.loadCricalResources();o.insertAdjacentHTML(i,n.replace(' shadowrootmode="open"',""));let u=this.queryComponent(e,t);if(!u)throw new Error(`Element ${e} not found in DOM`);return u.shadowRoot&&(u.shadowRoot.adoptedStyleSheets=[a]),u}queryComponent(e,t){let n=`swish-ui[ref="${e}${t?`-${t}`:""}"]`;return document.querySelector(n)}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(`
445
+ `,this.emailInput=this.querySelector("#customer_login_email")),this.shopModalObserver=new MutationObserver(e=>{e.forEach(t=>{t.attributeName==="style"&&document.documentElement.style.overflow==="hidden"&&this.dispatchEvent(new CustomEvent("shop-modal-open"))})}),this.shopModalObserver.observe(document.documentElement,{attributes:!0,attributeFilter:["style"]})}disconnectedCallback(){this.shopModalObserver?.disconnect()}async load(){try{(window.Shopify?.featureAssets?.["shop-js"]?.["init-customer-accounts"]?.[0]??"").includes("init-customer-accounts")&&window.Shopify?.SignInWithShop?.initCustomerAccounts?.(!0,{fedCMEnabled:!0,windoidEnabled:!1})}catch(e){console.warn("Failed to initialize Shop JS",e)}}update(e){if(e.email&&(this.emailInput.value=e.email,this.emailInput.dispatchEvent(new Event("input"))),e.returnTo){let t=this.querySelector("input[name='return_url']");t&&(t.value=e.returnTo)}}};typeof customElements<"u"&&customElements.define("swish-shop-bridge",Tt);var He=class{constructor(e,t){this.inflightModals=new Map;this.eventListeners=new Map;this.scrollLockRefCount=0;this.scrollPositionBeforeLock=0;this._lockScroll=s(()=>this.lockScroll(),"_lockScroll");this._unlockScroll=s(()=>this.unlockScroll(),"_unlockScroll");this.swishUiOptions=e,this.storefrontContext=t}static{s(this,"SwishUi")}async hideModal(e){if(this.inflightModals.has(e))return this.inflightModals.get(e);let t=(async()=>{typeof e=="string"&&(e=await this.requireUiComponent(e)),!(!e||e.getAttribute("open")!=="true")&&e.setAttribute("open","false")})().finally(()=>{this.inflightModals.delete(e)});return this.unlockScroll(),this.inflightModals.set(e,t),t}async showModal(e){if(this.inflightModals.has(e))return this.inflightModals.get(e);let t=(async()=>{typeof e=="string"&&(e=await this.requireUiComponent(e)),!(!e||e.getAttribute("open")==="true")&&e.setAttribute("open","true")})().finally(()=>{this.inflightModals.delete(e)});return this.lockScroll(),this.inflightModals.set(e,t),t}async showSignIn(e){let t=await this.requireUiComponent("sign-in",{listeners:{close:s(()=>e?.onClose?.(),"close")}});t.setAttribute("return-to",e?.returnTo??window.location.pathname),await this.showModal(t)}async showUnsaveAlert(e){if(!e.itemId)throw new Error("An itemId is required to show the unsave alert");await this.hideAllToasts();let t=await this.requireUiComponent("unsave-alert",{listeners:{submit:s(n=>{n instanceof CustomEvent?e.onSubmit?.(n.detail):console.warn("Unsave alert submitted without detail",n)},"submit"),close:s(()=>{e.onClose?.()},"close")}});t.setAttribute("item-id",e.itemId),await this.showModal(t)}async showDeleteListAlert(e){if(!e.listId)throw new Error("A listId is required to show the delete list alert");await this.hideAllToasts();let t=await this.requireUiComponent("delete-list-alert",{listeners:{submit:s(()=>{e.onSubmit?.()},"submit"),close:s(()=>{e.onClose?.()},"close")}});t.setAttribute("list-id",e.listId),await this.showModal(t)}async showDrawer(e){await this.hideAllToasts();let t=await this.requireUiComponent("drawer",{listeners:{close:s(()=>{e?.onClose?.()},"close")}});t.setAttribute("account-url",this.storefrontContext.routes.accountUrl),this.storefrontContext.customer.id&&t.setAttribute("customer-id",this.storefrontContext.customer.id),await this.showModal(t)}async showListMenu(e){if(!e.listId)throw new Error("listId is required");await this.hideAllToasts();let t=await this.requireUiComponent("list-menu",{listeners:{close:s(n=>{e.onClose?.()},"close"),edit:s(n=>{n instanceof CustomEvent?e.onEdit?.(n.detail):console.warn("List menu submitted without detail",n)},"edit"),delete:s(n=>{n instanceof CustomEvent?e.onDelete?.():console.warn("List menu deleted without detail",n)},"delete")}});t.setAttribute("list-id",e.listId),await this.showModal(t)}async showListSelect(e){if(!e.itemId)throw new Error("itemId is required");await this.hideAllToasts();let t=await this.requireUiComponent("list-select",{listeners:{submit:s(async n=>{"detail"in n&&n.detail?e?.onSubmit?.(n.detail):console.warn("List select form submitted without detail",n)},"submit"),close:s(()=>{e.onClose?.()},"close"),unsave:s(n=>{n instanceof CustomEvent?e.onUnsave?.(n.detail):console.warn("List select unsave without detail",n)},"unsave")}});t.setAttribute("item-id",e.itemId),await this.showModal(t)}async initListDetailPage(e,t){let n=await this.requireUiComponent("list-detail-page",{refElement:t});e.listId&&n.setAttribute("list-id",e.listId)}async showToast(e){await this.requireUiComponent("toast-manager",{onHydrated:s(t=>{t.current.show(e)},"onHydrated")})}async hideAllToasts(){this.queryComponent("toast-manager")&&await this.requireUiComponent("toast-manager",{onHydrated:s(e=>{e.current.clear()},"onHydrated")})}async showVariantSelect(e){await this.hideAllToasts();let t=await this.requireUiComponent("variant-select",{listeners:{submit:s(async n=>{"detail"in n&&n.detail?e?.onSubmit?.(n.detail):console.warn("Variant select form submitted without detail",n)},"submit"),close:s(()=>{e?.onClose?.()},"close")}});if(e?.productId)t.setAttribute("product-id",e.productId);else if(e?.productHandle)t.setAttribute("product-handle",e.productHandle);else throw new Error("Either productId or productHandle must be provided");e?.variantId&&t.setAttribute("variant-id",e.variantId),e?.displayType&&t.setAttribute("display-type",e.displayType),await this.showModal(t)}async showQuickBuy(e){await this.hideAllToasts();let t=await this.requireUiComponent("quick-buy",{listeners:{submit:s(async n=>{"detail"in n&&n.detail?e?.onSubmit?.(n.detail):console.warn("Quick buy form submitted without detail",n)},"submit"),close:s(()=>{e?.onClose?.()},"close")}});if(e?.productId)t.setAttribute("product-id",e.productId);else throw new Error("ProductId must be provided");e?.variantId&&t.setAttribute("variant-id",e.variantId),await this.showModal(t)}async showListEditor(e){let t=await this.requireUiComponent("list-editor",{listeners:{submit:s(async n=>{"detail"in n&&n.detail?e?.onSubmit?.(n.detail):console.warn("List editor form submitted without detail",n)},"submit"),close:s(()=>{e?.onClose?.()},"close")}});e?.listId&&t.setAttribute("list-id",e.listId),await this.showModal(t)}async initShopBridge({onShopModalOpen:e}){let t=document.querySelector("swish-shop-bridge");if(t||(document.body.insertAdjacentHTML("beforeend","<swish-shop-bridge></swish-shop-bridge>"),t=document.querySelector("swish-shop-bridge")),!t)throw new Error("Failed to initialize Shop Bridge");return t.addEventListener("shop-modal-open",()=>e(),{once:!0}),await t.load(),t}async requireUiComponent(e,t){this.loadCricalResources();let n=`${this.swishUiOptions.baseUrl}/ui@${this.swishUiOptions.version}/${e}.html`,i=await fetch(n).then(l=>l.text()),o=t?.instance,a=t?.listeners,u=this.queryComponent(e,o)??await this.insertComponent({name:e,template:i,refElement:t?.refElement??document.body,position:"beforeend",instance:o});if(u.shadowRoot&&!u.hasAttribute("hydrated")){let l=`${this.swishUiOptions.baseUrl}/ui@${this.swishUiOptions.version}/${e}.js`;Promise.all([this.loadNonCriticalResources(),import(l)]).then(([{bundleCssStylesheet:c,customCssStylesheets:p},{hydrate:d}])=>{u.shadowRoot&&c&&(u.shadowRoot.adoptedStyleSheets=[...u.shadowRoot.adoptedStyleSheets,...p,c],u.shadowRoot?.querySelector(":host > style")?.remove()),d(u),u.setAttribute("hydrated",""),t?.onHydrated?.(u.getComponentRef())})}else u.hasAttribute("hydrated")&&t?.onHydrated?.(u.getComponentRef());for(let{event:l,listener:c}of this.eventListeners.values())u.removeEventListener(l,c);for(let[l,c]of Object.entries(a??{}))this.eventListeners.set(`${e}-${o}-${l}`,{event:l,listener:c}),u.addEventListener(l,c);return u}async loadCricalResources(){return this._loadCricalResourcesPromise?this._loadCricalResourcesPromise:(this._loadCricalResourcesPromise=(async()=>{let e=`${this.swishUiOptions.baseUrl}/ui@${this.swishUiOptions.version}/theme.css`,t=await fetch(e).then(i=>i.text()),n=new CSSStyleSheet;return n.replaceSync(t),this.swishUiOptions.theme&&Object.entries(this.swishUiOptions.theme).forEach(([i,o])=>{n.cssRules[0].cssRules[0].style.setProperty(i,o)}),{themeVariablesStylesheet:n}})(),this._loadCricalResourcesPromise)}async loadNonCriticalResources(){return this._loadNonCriticalResourcesPromise?this._loadNonCriticalResourcesPromise:(this._loadNonCriticalResourcesPromise=(async()=>{let e=`${this.swishUiOptions.baseUrl}/ui@${this.swishUiOptions.version}/bundle.css`,t=s(o=>{let a=new CSSStyleSheet;return a.replaceSync(o),a},"createCssStylesheet"),[n,...i]=await Promise.all([fetch(e).then(o=>o.text()).then(t),...this.swishUiOptions.css.map(async o=>o instanceof URL?t(await fetch(o).then(a=>a.text())):t(o))]);return{bundleCssStylesheet:n,customCssStylesheets:i}})(),this._loadNonCriticalResourcesPromise)}async insertComponent({name:e,instance:t,template:n,position:i,refElement:o}){let{themeVariablesStylesheet:a}=await this.loadCricalResources();o.insertAdjacentHTML(i,n.replace(' shadowrootmode="open"',""));let u=this.queryComponent(e,t);if(!u)throw new Error(`Element ${e} not found in DOM`);return u.shadowRoot&&(u.shadowRoot.adoptedStyleSheets=[a]),u}queryComponent(e,t){let n=`swish-ui[ref="${e}${t?`-${t}`:""}"]`;return document.querySelector(n)}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(`
446
446
  html[swish-locked] body {
447
447
  overflow: hidden;
448
448
  position: fixed;
@@ -450,4 +450,4 @@ Values:
450
450
  left: 0px;
451
451
  right: 0px;
452
452
  }
453
- `),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"))}};var Zi="0.72.0",Hl=s(async r=>{if(typeof window>"u")throw new Error("Swish is not supported in this environment");if(window.swish)return window.swish;try{let n=localStorage.getItem("wk_session_id");n&&(localStorage.setItem("swish-profile",`gid://swish/Session/${n}`),localStorage.removeItem("wk_session_id"))}catch(n){console.warn("Failed to migrate legacy session id to Swish profile",{cause:n})}let e=un(r),t=new _t(e);try{let n=sessionStorage.getItem("swish-token"),i=n&&tn(n),o=!!e.storefrontContext.customer.id;o!==i&&sessionStorage.removeItem("swish-token");let u=!!localStorage.getItem("swish-profile");o===u&&await t.api.clearCache()}catch(n){console.warn("Could not check if customer logged out.",{cause:n})}return window.swish=t,document.dispatchEvent(new Event("swish-ready")),typeof window.Shopify?.analytics?.publish=="function"&&window.Shopify.analytics.publish("swish-ready",{proxyUrl:e.proxy.baseUrl,market:e.storefrontContext.localization.market,country:e.storefrontContext.localization.country,language:e.storefrontContext.localization.language,rootUrl:e.storefrontContext.routes.rootUrl}),t},"createSwish"),_t=class{constructor(e){this.dom={createElementLocator:pe,createQueryParamsObserver:oe};this.state={itemContext:Xt(this),itemState:Kt(this),itemCount:Yt(this),swishQuery:Jt(this),effect:V,signal:C,computed:B};this.swishOptions=e,this.events=new ve,this.swishBadges=new Fe({getBadges:this.swishOptions.badges?.getBadges});let t={proxyBaseUrl:`${this.swishOptions.proxy.baseUrl}/api`,...this.swishOptions.swishApi??{}};this.swishApiPublisher=new Me(this.events);let n=[Zi,e.swishUi?.version].join("-");this.swishApi=new Ge({...t,customerId:e.storefrontContext.customer.id??void 0,responseInterceptor:this.swishApiPublisher.processFetchResponse},this.swishOptions.storefrontContext,n),this.ajaxApiPublisher=new me(this.events),this.ajaxApi=new ye({storeDomain:this.swishOptions.storefrontApi.storeDomain,responseInterceptor:this.ajaxApiPublisher.processFetchResponse}),this.ajaxApi.patchFetch(),this.storefrontApi=new Ve(this.swishOptions.storefrontApi,this.swishOptions.storefrontContext,this.swishBadges,this.swishOptions.metafields),this.swishUi=new He(this.swishOptions.swishUi,this.swishOptions.storefrontContext),this.events.subscribe(["cart-add","cart-update","cart-change","cart-clear"],()=>{this.ajaxApi.clearCache()}),customElements.get("swish-ui")||customElements.define("swish-ui",je),this.intents=new Pe(this,this.swishUi)}static{s(this,"SwishApp")}get options(){return this.swishOptions}get customer(){return this.swishOptions.storefrontContext.customer}get localization(){return this.swishOptions.storefrontContext.localization}get routes(){return this.swishOptions.storefrontContext.routes}get badges(){return this.swishBadges}get api(){return this.swishApi}get storefront(){return this.storefrontApi}get ajax(){return this.ajaxApi}get shopUrl(){return`https://${this.swishOptions.storefrontApi.storeDomain}`}get ui(){return this.swishUi}};export{_t as SwishApp,Zi as VERSION,Hl as createSwish};
453
+ `),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"))}};var Zi="0.73.0",Hl=s(async r=>{if(typeof window>"u")throw new Error("Swish is not supported in this environment");if(window.swish)return window.swish;try{let n=localStorage.getItem("wk_session_id");n&&(localStorage.setItem("swish-profile",`gid://swish/Session/${n}`),localStorage.removeItem("wk_session_id"))}catch(n){console.warn("Failed to migrate legacy session id to Swish profile",{cause:n})}let e=un(r),t=new _t(e);try{let n=sessionStorage.getItem("swish-token"),i=n&&tn(n),o=!!e.storefrontContext.customer.id;o!==i&&sessionStorage.removeItem("swish-token");let u=!!localStorage.getItem("swish-profile");o===u&&await t.api.clearCache()}catch(n){console.warn("Could not check if customer logged out.",{cause:n})}return window.swish=t,document.dispatchEvent(new Event("swish-ready")),typeof window.Shopify?.analytics?.publish=="function"&&window.Shopify.analytics.publish("swish-ready",{proxyUrl:e.proxy.baseUrl,market:e.storefrontContext.localization.market,country:e.storefrontContext.localization.country,language:e.storefrontContext.localization.language,rootUrl:e.storefrontContext.routes.rootUrl}),t},"createSwish"),_t=class{constructor(e){this.dom={createElementLocator:pe,createQueryParamsObserver:oe};this.state={itemContext:Xt(this),itemState:Kt(this),itemCount:Yt(this),swishQuery:Jt(this),effect:V,signal:C,computed:B};this.swishOptions=e,this.events=new ve,this.swishBadges=new Fe({getBadges:this.swishOptions.badges?.getBadges});let t={proxyBaseUrl:`${this.swishOptions.proxy.baseUrl}/api`,...this.swishOptions.swishApi??{}};this.swishApiPublisher=new Me(this.events);let n=[Zi,e.swishUi?.version].join("-");this.swishApi=new Ge({...t,customerId:e.storefrontContext.customer.id??void 0,responseInterceptor:this.swishApiPublisher.processFetchResponse},this.swishOptions.storefrontContext,n),this.ajaxApiPublisher=new me(this.events),this.ajaxApi=new ye({storeDomain:this.swishOptions.storefrontApi.storeDomain,responseInterceptor:this.ajaxApiPublisher.processFetchResponse}),this.ajaxApi.patchFetch(),this.storefrontApi=new Ve(this.swishOptions.storefrontApi,this.swishOptions.storefrontContext,this.swishBadges,this.swishOptions.metafields),this.swishUi=new He(this.swishOptions.swishUi,this.swishOptions.storefrontContext),this.events.subscribe(["cart-add","cart-update","cart-change","cart-clear"],()=>{this.ajaxApi.clearCache()}),customElements.get("swish-ui")||customElements.define("swish-ui",je),this.intents=new Pe(this,this.swishUi)}static{s(this,"SwishApp")}get options(){return this.swishOptions}get customer(){return this.swishOptions.storefrontContext.customer}get localization(){return this.swishOptions.storefrontContext.localization}get routes(){return this.swishOptions.storefrontContext.routes}get badges(){return this.swishBadges}get api(){return this.swishApi}get storefront(){return this.storefrontApi}get ajax(){return this.ajaxApi}get shopUrl(){return`https://${this.swishOptions.storefrontApi.storeDomain}`}get ui(){return this.swishUi}};export{_t as SwishApp,Zi as VERSION,Hl as createSwish};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@swishapp/sdk",
3
- "version": "0.72.0",
3
+ "version": "0.73.0",
4
4
  "description": "JS SDK for Swish.",
5
5
  "author": "Swish",
6
6
  "license": "UNLICENSED",