@swishapp/sdk 0.53.0 → 0.54.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/swish.js +2 -2
- package/package.json +1 -1
package/dist/swish.js
CHANGED
|
@@ -393,7 +393,7 @@ Values:
|
|
|
393
393
|
`);try{X=JSON.parse(U),ft=!0}catch{X=U}}ft&&(o&&await o(X),n&&(X=await n(X))),r?.({data:X,event:de,id:h,retry:m}),J.length&&(yield X)}}}finally{g.removeEventListener("abort",w),N.releaseLock()}break}catch(P){if(e?.(P),s!==void 0&&I>=s)break;let T=Math.min(m*2**(I-1),c??3e4);await C(T)}}},"createStream")()}},"createSseClient"),En=u(t=>{switch(t){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},"separatorArrayExplode"),Sn=u(t=>{switch(t){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},"separatorArrayNoExplode"),An=u(t=>{switch(t){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},"separatorObjectExplode"),vr=u(({allowReserved:t,explode:e,name:r,style:n,value:o})=>{if(!e){let c=(t?o:o.map(l=>encodeURIComponent(l))).join(Sn(n));switch(n){case"label":return`.${c}`;case"matrix":return`;${r}=${c}`;case"simple":return c;default:return`${r}=${c}`}}let i=En(n),s=o.map(c=>n==="label"||n==="simple"?t?c:encodeURIComponent(c):Ee({allowReserved:t,name:r,value:c})).join(i);return n==="label"||n==="matrix"?i+s:s},"serializeArrayParam"),Ee=u(({allowReserved:t,name:e,value:r})=>{if(r==null)return"";if(typeof r=="object")throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.");return`${e}=${t?r:encodeURIComponent(r)}`},"serializePrimitiveParam"),Cr=u(({allowReserved:t,explode:e,name:r,style:n,value:o,valueOnly:i})=>{if(o instanceof Date)return i?o.toISOString():`${r}=${o.toISOString()}`;if(n!=="deepObject"&&!e){let l=[];Object.entries(o).forEach(([d,h])=>{l=[...l,d,t?h:encodeURIComponent(h)]});let p=l.join(",");switch(n){case"form":return`${r}=${p}`;case"label":return`.${p}`;case"matrix":return`;${r}=${p}`;default:return p}}let s=An(n),c=Object.entries(o).map(([l,p])=>Ee({allowReserved:t,name:n==="deepObject"?`${r}[${l}]`:l,value:p})).join(s);return n==="label"||n==="matrix"?s+c:c},"serializeObjectParam"),Rn=/\{[^{}]+\}/g,Tn=u(({path:t,url:e})=>{let r=e,n=e.match(Rn);if(n)for(let o of n){let i=!1,s=o.substring(1,o.length-1),c="simple";s.endsWith("*")&&(i=!0,s=s.substring(0,s.length-1)),s.startsWith(".")?(s=s.substring(1),c="label"):s.startsWith(";")&&(s=s.substring(1),c="matrix");let l=t[s];if(l==null)continue;if(Array.isArray(l)){r=r.replace(o,vr({explode:i,name:s,style:c,value:l}));continue}if(typeof l=="object"){r=r.replace(o,Cr({explode:i,name:s,style:c,value:l,valueOnly:!0}));continue}if(c==="matrix"){r=r.replace(o,`;${Ee({name:s,value:l})}`);continue}let p=encodeURIComponent(c==="label"?`.${l}`:l);r=r.replace(o,p)}return r},"defaultPathSerializer"),Pn=u(({baseUrl:t,path:e,query:r,querySerializer:n,url:o})=>{let i=o.startsWith("/")?o:`/${o}`,s=(t??"")+i;e&&(s=Tn({path:e,url:s}));let c=r?n(r):"";return c.startsWith("?")&&(c=c.substring(1)),c&&(s+=`?${c}`),s},"getUrl");function wr(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}a(wr,"G");u(wr,"getValidRequestBody");var Dn=u(async(t,e)=>{let r=typeof e=="function"?await e(t):e;if(r)return t.scheme==="bearer"?`Bearer ${r}`:t.scheme==="basic"?`Basic ${btoa(r)}`:r},"getAuthToken"),Ir=u(({allowReserved:t,array:e,object:r}={})=>u(n=>{let o=[];if(n&&typeof n=="object")for(let i in n){let s=n[i];if(s!=null)if(Array.isArray(s)){let c=vr({allowReserved:t,explode:!0,name:i,style:"form",value:s,...e});c&&o.push(c)}else if(typeof s=="object"){let c=Cr({allowReserved:t,explode:!0,name:i,style:"deepObject",value:s,...r});c&&o.push(c)}else{let c=Ee({allowReserved:t,name:i,value:s});c&&o.push(c)}}return o.join("&")},"querySerializer"),"createQuerySerializer"),xn=u(t=>{var e;if(!t)return"stream";let r=(e=t.split(";")[0])==null?void 0:e.trim();if(r){if(r.startsWith("application/json")||r.endsWith("+json"))return"json";if(r==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some(n=>r.startsWith(n)))return"blob";if(r.startsWith("text/"))return"text"}},"getParseAs"),_n=u((t,e)=>{var r,n;return e?!!(t.headers.has(e)||(r=t.query)!=null&&r[e]||(n=t.headers.get("Cookie"))!=null&&n.includes(`${e}=`)):!1},"checkForExistence"),Ln=u(async({security:t,...e})=>{for(let r of t){if(_n(e,r.name))continue;let n=await Dn(r,e.auth);if(!n)continue;let o=r.name??"Authorization";switch(r.in){case"query":e.query||(e.query={}),e.query[o]=n;break;case"cookie":e.headers.append("Cookie",`${o}=${n}`);break;case"header":default:e.headers.set(o,n);break}}},"setAuthParams"),yr=u(t=>Pn({baseUrl:t.baseUrl,path:t.path,query:t.query,querySerializer:typeof t.querySerializer=="function"?t.querySerializer:Ir(t.querySerializer),url:t.url}),"buildUrl"),gr=u((t,e)=>{var r;let n={...t,...e};return(r=n.baseUrl)!=null&&r.endsWith("/")&&(n.baseUrl=n.baseUrl.substring(0,n.baseUrl.length-1)),n.headers=br(t.headers,e.headers),n},"mergeConfigs"),On=u(t=>{let e=[];return t.forEach((r,n)=>{e.push([n,r])}),e},"headersEntries"),br=u((...t)=>{let e=new Headers;for(let r of t){if(!r)continue;let n=r instanceof Headers?On(r):Object.entries(r);for(let[o,i]of n)if(i===null)e.delete(o);else if(Array.isArray(i))for(let s of i)e.append(o,s);else i!==void 0&&e.set(o,typeof i=="object"?JSON.stringify(i):i)}return e},"mergeHeaders"),Er=class{static{a(this,"$")}constructor(){this.fns=[]}clear(){this.fns=[]}eject(e){let r=this.getInterceptorIndex(e);this.fns[r]&&(this.fns[r]=null)}exists(e){let r=this.getInterceptorIndex(e);return!!this.fns[r]}getInterceptorIndex(e){return typeof e=="number"?this.fns[e]?e:-1:this.fns.indexOf(e)}update(e,r){let n=this.getInterceptorIndex(e);return this.fns[n]?(this.fns[n]=r,e):!1}use(e){return this.fns.push(e),this.fns.length-1}};u(Er,"Interceptors");var it=Er,$n=u(()=>({error:new it,request:new it,response:new it}),"createInterceptors"),Vn=Ir({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Nn={"Content-Type":"application/json"},st=u((t={})=>({...wn,headers:Nn,parseAs:"auto",querySerializer:Vn,...t}),"createConfig"),Sr=u((t={})=>{let e=gr(st(),t),r=u(()=>({...e}),"getConfig"),n=u(p=>(e=gr(e,p),r()),"setConfig"),o=$n(),i=u(async p=>{let d={...e,...p,fetch:p.fetch??e.fetch??globalThis.fetch,headers:br(e.headers,p.headers),serializedBody:void 0};d.security&&await Ln({...d,security:d.security}),d.requestValidator&&await d.requestValidator(d),d.body!==void 0&&d.bodySerializer&&(d.serializedBody=d.bodySerializer(d.body)),(d.body===void 0||d.serializedBody==="")&&d.headers.delete("Content-Type");let h=yr(d);return{opts:d,url:h}},"beforeRequest"),s=u(async p=>{let{opts:d,url:h}=await i(p),C={redirect:"follow",...d,body:wr(d)},m=new Request(h,C);for(let y of o.request.fns)y&&(m=await y(m,d));let I=d.fetch,g=await I(m);for(let y of o.response.fns)y&&(g=await y(g,m,d));let A={request:m,response:g};if(g.ok){let y=(d.parseAs==="auto"?xn(g.headers.get("Content-Type")):d.parseAs)??"json";if(g.status===204||g.headers.get("Content-Length")==="0"){let E;switch(y){case"arrayBuffer":case"blob":case"text":E=await g[y]();break;case"formData":E=new FormData;break;case"stream":E=g.body;break;case"json":default:E={};break}return d.responseStyle==="data"?E:{data:E,...A}}let w;switch(y){case"arrayBuffer":case"blob":case"formData":case"json":case"text":w=await g[y]();break;case"stream":return d.responseStyle==="data"?g.body:{data:g.body,...A}}return y==="json"&&(d.responseValidator&&await d.responseValidator(w),d.responseTransformer&&(w=await d.responseTransformer(w))),d.responseStyle==="data"?w:{data:w,...A}}let P=await g.text(),T;try{T=JSON.parse(P)}catch{}let _=T??P,N=_;for(let y of o.error.fns)y&&(N=await y(_,g,m,d));if(N=N||{},d.throwOnError)throw N;return d.responseStyle==="data"?void 0:{error:N,...A}},"request"),c=u(p=>d=>s({...d,method:p}),"makeMethodFn"),l=u(p=>async d=>{let{opts:h,url:C}=await i(d);return bn({...h,body:h.body,headers:h.headers,method:p,onRequest:u(async(m,I)=>{let g=new Request(m,I);for(let A of o.request.fns)A&&(g=await A(g,h));return g},"onRequest"),url:C})},"makeSseFn");return{buildUrl:yr,connect:c("CONNECT"),delete:c("DELETE"),get:c("GET"),getConfig:r,head:c("HEAD"),interceptors:o,options:c("OPTIONS"),patch:c("PATCH"),post:c("POST"),put:c("PUT"),request:s,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:c("TRACE")}},"createClient"),S=Sr(st({baseUrl:"https://swish.app/api/2025-10"})),Un=u(t=>(t?.client??S).get({security:[{scheme:"bearer",type:"http"}],url:"/lists",...t}),"listControllerFind"),qn=u(t=>(t.client??S).post({security:[{scheme:"bearer",type:"http"}],url:"/lists",...t,headers:{"Content-Type":"application/json",...t.headers}}),"listControllerCreate"),Bn=u(t=>(t.client??S).delete({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...t}),"listControllerDeleteById"),Gn=u(t=>(t.client??S).get({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...t}),"listControllerFindById"),Hn=u(t=>(t.client??S).patch({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...t,headers:{"Content-Type":"application/json",...t.headers}}),"listControllerUpdateById"),Fn=u(t=>(t.client??S).put({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items/order",...t,headers:{"Content-Type":"application/json",...t.headers}}),"listControllerSetListItemsOrder"),Mn=u(t=>(t.client??S).post({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items",...t,headers:{"Content-Type":"application/json",...t.headers}}),"listControllerAddItemsToList"),kn=u(t=>(t.client??S).delete({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items/{itemId}",...t}),"listControllerRemoveItemFromList"),jn=u(t=>(t.client??S).delete({security:[{scheme:"bearer",type:"http"}],url:"/items",...t,headers:{"Content-Type":"application/json",...t.headers}}),"itemControllerDelete"),Qn=u(t=>(t?.client??S).get({security:[{scheme:"bearer",type:"http"}],url:"/items",...t}),"itemControllerFind"),zn=u(t=>(t.client??S).post({security:[{scheme:"bearer",type:"http"}],url:"/items",...t,headers:{"Content-Type":"application/json",...t.headers}}),"itemControllerCreate"),Wn=u(t=>(t?.client??S).get({security:[{scheme:"bearer",type:"http"}],url:"/items/count",...t}),"itemControllerCount"),Yn=u(t=>(t.client??S).delete({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...t}),"itemControllerDeleteById"),Kn=u(t=>(t.client??S).get({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...t}),"itemControllerFindById"),Jn=u(t=>(t.client??S).patch({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...t,headers:{"Content-Type":"application/json",...t.headers}}),"itemControllerUpdateById"),Xn=u(t=>(t.client??S).put({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}/lists",...t,headers:{"Content-Type":"application/json",...t.headers}}),"itemControllerSetListsById"),Zn=u(t=>(t?.client??S).get({security:[{scheme:"bearer",type:"http"}],url:"/profiles/accounts-version",...t}),"profileControllerCustomerAccountsVersion"),eo=u(t=>(t.client??S).post({security:[{scheme:"bearer",type:"http"}],url:"/profiles/identify",...t,headers:{"Content-Type":"application/json",...t.headers}}),"profileControllerIdentify"),to=u(t=>(t.client??S).post({security:[{scheme:"bearer",type:"http"}],url:"/profiles/token",...t,headers:{"Content-Type":"application/json",...t.headers}}),"profileControllerCreateToken"),Se="2025-10",ro=`https://swish.app/api/${Se}`,Ar=u(t=>new no(t),"createApiClient"),Rr=class{static{a(this,"H")}constructor(e){this.client=Sr(st({baseUrl:ro})),this.items={list:u(r=>this.handlePaginatedRequest(Qn({query:r,client:this.client})),"list"),create:u(r=>this.handleRequest(zn({body:r,client:this.client})),"create"),delete:u(r=>this.handleRequest(jn({body:{itemIds:r},client:this.client})),"delete"),findById:u(r=>this.handleRequest(Kn({path:{itemId:r},client:this.client})),"findById"),updateById:u((r,n)=>this.handleRequest(Jn({body:n,path:{itemId:r},client:this.client})),"updateById"),deleteById:u(r=>this.handleRequest(Yn({path:{itemId:r},client:this.client})),"deleteById"),setListsById:u((r,n)=>this.handleRequest(Xn({body:{listIds:n},path:{itemId:r},client:this.client})),"setListsById"),count:u(()=>this.handleRequest(Wn({client:this.client})),"count")},this.lists={list:u(r=>this.handlePaginatedRequest(Un({query:r,client:this.client})),"list"),create:u(r=>this.handleRequest(qn({body:r,client:this.client})),"create"),findById:u(r=>this.handleRequest(Gn({path:{listId:r},client:this.client})),"findById"),updateById:u((r,n)=>this.handleRequest(Hn({body:n,path:{listId:r},client:this.client})),"updateById"),deleteById:u(r=>this.handleRequest(Bn({path:{listId:r},client:this.client})),"deleteById"),orderItems:u((r,n)=>this.handleRequest(Fn({body:{itemIds:n},path:{listId:r},client:this.client})),"orderItems"),addItemsToList:u((r,n)=>this.handleRequest(Mn({body:{itemIds:n},path:{listId:r},client:this.client})),"addItemsToList"),removeItemFromList:u((r,n)=>this.handleRequest(kn({path:{listId:r,itemId:n},client:this.client})),"removeItemFromList")},this.profiles={customerAccountsVersion:u(()=>this.handleRequest(Zn({client:this.client})),"customerAccountsVersion"),createToken:u((r={})=>this.handleRequest(to({body:r,client:this.client})),"createToken"),identify:u(r=>this.handleRequest(eo({body:r,client:this.client})),"identify")},this.handleRequest=u(async r=>{let{data:n,error:o}=await r;return o!=null&&o.error?{error:o.error}:{data:n?.data}},"handleRequest"),this.handlePaginatedRequest=u(async r=>{var n;let{data:o,error:i}=await r;return i!=null&&i.error?{error:i.error}:{data:o?.data??[],pageInfo:o?.pageInfo??{next:null,previous:null,totalCount:((n=o?.data)==null?void 0:n.length)??0}}},"handlePaginatedRequest"),this.profile=e.profile,e.authToken&&(this.authToken=e.authToken),e.config&&this.client.setConfig(e.config),this.client.interceptors.request.use(this.requestInterceptor.bind(this)),e.requestInterceptor&&this.client.interceptors.request.use(e.requestInterceptor),e.responseInterceptor&&this.client.interceptors.response.use(e.responseInterceptor)}setProfile(e){this.profile=e}getProfile(){return this.profile}setAuthToken(e){this.authToken=e}setConfig(e){this.client.setConfig(e)}requestInterceptor(e){return this.authToken&&e.headers.set("Authorization",`Bearer ${this.authToken}`),this.profile&&e.headers.set("Profile",this.profile),e}};u(Rr,"SwishClient");var no=Rr;var xr=Xr(Dr(),1);var _r=a(t=>new xr.default(async e=>{let r=[...new Set(e)].sort((o,i)=>o.localeCompare(i)),n=await t.items.list({query:r.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(o=>{let i=n.data.find(s=>o===`variant:${s.variantId}`||o===`product:${s.productId}`);return{data:i?[i]:[],pageInfo:{next:null,previous:null,totalCount:i?1:0}}})},{batchScheduleFn:a(e=>setTimeout(e,50),"batchScheduleFn"),cache:!1,maxBatchSize:200}),"createItemsBatchLoader");var Ae=class{static{a(this,"SwishApi")}constructor(e,r){this.config=e,this.cache=new M("swish-api","max-age=60, stale-while-revalidate=3600",r+Se),this.cache.cleanupExpiredEntries().catch(o=>{console.warn("Swish API cache initialization cleanup error:",o)});let n=this.config.loadProfile?.();this.apiClient=Ar({profile:n,config:{...e,fetch:a((o,i)=>(o instanceof Request?o.method:i?.method??"GET")==="GET"?this.cache.fetchWithCache(o,i):fetch(o,i),"fetch")},requestInterceptor:a(async o=>(o.headers.set("Swish-Api-Version",Se),o),"requestInterceptor"),responseInterceptor:a(async(o,i)=>(this.processProfileHeader(o),i.method!=="GET"&&await this.cache.clear(),await this.config.responseInterceptor?.(o,i),o),"responseInterceptor")}),this.itemsLoader=_r(this)}processProfileHeader(e){let r=e.headers.get("Set-Profile");r?(this.apiClient.setProfile(r),this.config.storeProfile?.(r)):r===""&&this.config.deleteProfile?.()}get items(){return{...this.apiClient.items,list:a(async(e,r)=>{if(!f.customer.id&&!this.apiClient.getProfile())return{data:[],pageInfo:{next:null,previous:null,totalCount:0}};if(r?.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 o=n[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)},"list"),findById:a(async e=>!f.customer.id&&!this.apiClient.getProfile()?{data:null}:this.apiClient.items.findById(e),"findById")}}get lists(){return{...this.apiClient.lists,list:a(async e=>!f.customer.id&&!this.apiClient.getProfile()?{data:[],pageInfo:{next:null,previous:null,totalCount:0}}:this.apiClient.lists.list(e),"list"),findById:a(async e=>!f.customer.id&&!this.apiClient.getProfile()?{data:null}:this.apiClient.lists.findById(e),"findById")}}get profiles(){return this.apiClient.profiles}async clearCache(){await this.cache.clear()}};var Re=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{a(this,"SwishApiPublisher")}async processFetchResponse(e,r){try{let n=this.getEventName(r.method,e.status,r.url);if(!n)return;let o=await e.clone().text();if(e.headers.get("Content-Type")?.includes("application/json"))try{o=JSON.parse(o).data}catch(i){console.warn(i)}this.eventBus.publish(n,o)}catch(n){console.warn(n)}}getEventName(e,r,n){e=e.toUpperCase();let o=new URL(n).pathname;return e==="GET"||r<200||r>=300?void 0:Object.entries(this.eventMap).find(([s])=>{let[c,l]=s.split(" ");return c!==e?!1:new RegExp(l).test(o)})?.[1]}};var Te=class extends HTMLElement{constructor(){super();this.getComponentRef=a(()=>this.componentRef,"getComponentRef");this.setComponentRef=a(r=>{this.componentRef=r},"setComponentRef");this.shadowRoot||this.attachShadow({mode:"open"});let r=this.querySelector("template");r&&this.shadowRoot&&(this.shadowRoot.appendChild(r.content),r.remove())}static{a(this,"SwishUiElement")}};var fo=".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}",mo=`<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=${window.location.pathname}></form>`,ut=class extends HTMLElement{constructor(){super();this.swish=window.swish;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=`
|
|
394
394
|
<style>${fo}</style>
|
|
395
395
|
${mo}
|
|
396
|
-
`,this.emailInput=this.querySelector("#customer_login_email")),this.shopModalObserver=new MutationObserver(r=>{r.forEach(n=>{n.attributeName==="style"&&document.documentElement.style.overflow==="hidden"&&this.dispatchEvent(new CustomEvent("shop-modal-open"))})}),this.shopModalObserver.observe(document.documentElement,{attributes:!0,attributeFilter:["style"]})}static{a(this,"ShopBridge")}disconnectedCallback(){this.shopModalObserver?.disconnect()}async load(){try{(window.Shopify?.featureAssets?.["shop-js"]?.["init-customer-accounts"]?.[0]??"").includes("init-customer-accounts")&&(await Promise.all(window.Shopify?.featureAssets?.["shop-js"]?.["init-customer-accounts"]?.map(n=>import(`/cdn/shopifycloud/shop-js/${n}`))??[]),window.Shopify?.SignInWithShop?.initCustomerAccounts?.(!0,{fedCMEnabled:!0,windoidEnabled:!1}))}catch(r){console.warn("Failed to initialize Shop JS",r)}}update(r){if(r.email&&(this.emailInput.value=r.email,this.emailInput.dispatchEvent(new Event("input"))),r.returnTo){let n=this.querySelector("input[name='return_url']");n&&(n.value=r.returnTo)}}};customElements.define("swish-shop-bridge",ut);var oe={baseUrl:"/apps/wishlist",version:"0.0.0"},Pe,De,xe,Or=a(t=>{oe=t},"setConfig"),Y=new Map,$r=a(async t=>{if(Y.has(t))return Y.get(t);let e=(async()=>{typeof t=="string"&&(t=await V(t)),!(!t||t.getAttribute("open")!=="true")&&t.setAttribute("open","false")})().finally(()=>{Y.delete(t)});return Co(),Y.set(t,e),e},"hideModal"),G=a(async t=>{if(Y.has(t))return Y.get(t);let e=(async()=>{typeof t=="string"&&(t=await V(t)),!(!t||t.getAttribute("open")==="true")&&t.setAttribute("open","true")})().finally(()=>{Y.delete(t)});return vo(),Y.set(t,e),e},"showModal"),Vr=a(async t=>{let e=await V("sign-in");e.setAttribute("return-to",t?.returnTo??window.location.pathname),await G(e)},"showSignIn"),Nr=a(async t=>{if(!t.itemId)throw new Error("An itemId is required to show the unsave alert");K();let e=await V("unsave-alert",{listeners:{submit:a(r=>{r instanceof CustomEvent?t.onSubmit?.(r.detail):console.warn("Unsave alert submitted without detail",r)},"submit"),cancel:a(()=>{t.onCancel?.()},"cancel")}});e.setAttribute("item-id",t.itemId),await G(e)},"showUnsaveAlert"),Ur=a(async t=>{if(!t.listId)throw new Error("A listId is required to show the delete list alert");K();let e=await V("delete-list-alert",{listeners:{submit:a(()=>{t.onSubmit?.()},"submit"),cancel:a(()=>{t.onCancel?.()},"cancel")}});e.setAttribute("list-id",t.listId),await G(e)},"showDeleteListAlert"),qr=a(async()=>{K();let t=await V("drawer");t.setAttribute("account-url",f.routes.accountUrl),f.customer.id&&t.setAttribute("customer-id",f.customer.id),await G(t)},"showDrawer"),Br=a(async t=>{if(!t.listId)throw new Error("listId is required");K();let e=await V("list-menu",{listeners:{close:a(r=>{"detail"in r&&r.detail?t.onClose?.(r.detail):(console.warn("List menu closed without detail",r),t.onClose?.({reason:"unknown"}))},"close")}});e.setAttribute("list-id",t.listId),await G(e)},"showListMenu"),Gr=a(async t=>{if(!t.itemId)throw new Error("itemId is required");K();let e=await V("list-select",{listeners:{submit:a(async r=>{"detail"in r&&r.detail?t?.onSubmit?.(r.detail):console.warn("List select form submitted without detail",r)},"submit"),close:a(()=>{t.onClose?.()},"close"),unsave:a(r=>{r instanceof CustomEvent?t.onUnsave?.(r.detail):console.warn("List select unsave without detail",r)},"unsave")}});e.setAttribute("item-id",t.itemId),await G(e)},"showListSelect"),Hr=a(async t=>{await V("notifications",{onHydrated:a(e=>{e.current.pushNotification(t)},"onHydrated")})},"showNotification"),K=a(async()=>{pt("notifications")&&await V("notifications",{onHydrated:a(t=>{t.current.clearAllNotifications()},"onHydrated")})},"hideAllNotifications"),Fr=a(async t=>{K();let e=await V("variant-select",{listeners:{submit:a(async r=>{"detail"in r&&r.detail?t?.onSubmit?.(r.detail):console.warn("Variant select form submitted without detail",r)},"submit")}});if(t?.productId)e.setAttribute("product-id",t.productId);else if(t?.productHandle)e.setAttribute("product-handle",t.productHandle);else throw new Error("Either productId or productHandle must be provided");t?.variantId&&e.setAttribute("variant-id",t.variantId),t?.action&&e.setAttribute("action",t.action),e.setAttribute("display-type",t
|
|
396
|
+
`,this.emailInput=this.querySelector("#customer_login_email")),this.shopModalObserver=new MutationObserver(r=>{r.forEach(n=>{n.attributeName==="style"&&document.documentElement.style.overflow==="hidden"&&this.dispatchEvent(new CustomEvent("shop-modal-open"))})}),this.shopModalObserver.observe(document.documentElement,{attributes:!0,attributeFilter:["style"]})}static{a(this,"ShopBridge")}disconnectedCallback(){this.shopModalObserver?.disconnect()}async load(){try{(window.Shopify?.featureAssets?.["shop-js"]?.["init-customer-accounts"]?.[0]??"").includes("init-customer-accounts")&&(await Promise.all(window.Shopify?.featureAssets?.["shop-js"]?.["init-customer-accounts"]?.map(n=>import(`/cdn/shopifycloud/shop-js/${n}`))??[]),window.Shopify?.SignInWithShop?.initCustomerAccounts?.(!0,{fedCMEnabled:!0,windoidEnabled:!1}))}catch(r){console.warn("Failed to initialize Shop JS",r)}}update(r){if(r.email&&(this.emailInput.value=r.email,this.emailInput.dispatchEvent(new Event("input"))),r.returnTo){let n=this.querySelector("input[name='return_url']");n&&(n.value=r.returnTo)}}};customElements.define("swish-shop-bridge",ut);var oe={baseUrl:"/apps/wishlist",version:"0.0.0"},Pe,De,xe,Or=a(t=>{oe=t},"setConfig"),Y=new Map,$r=a(async t=>{if(Y.has(t))return Y.get(t);let e=(async()=>{typeof t=="string"&&(t=await V(t)),!(!t||t.getAttribute("open")!=="true")&&t.setAttribute("open","false")})().finally(()=>{Y.delete(t)});return Co(),Y.set(t,e),e},"hideModal"),G=a(async t=>{if(Y.has(t))return Y.get(t);let e=(async()=>{typeof t=="string"&&(t=await V(t)),!(!t||t.getAttribute("open")==="true")&&t.setAttribute("open","true")})().finally(()=>{Y.delete(t)});return vo(),Y.set(t,e),e},"showModal"),Vr=a(async t=>{let e=await V("sign-in");e.setAttribute("return-to",t?.returnTo??window.location.pathname),await G(e)},"showSignIn"),Nr=a(async t=>{if(!t.itemId)throw new Error("An itemId is required to show the unsave alert");K();let e=await V("unsave-alert",{listeners:{submit:a(r=>{r instanceof CustomEvent?t.onSubmit?.(r.detail):console.warn("Unsave alert submitted without detail",r)},"submit"),cancel:a(()=>{t.onCancel?.()},"cancel")}});e.setAttribute("item-id",t.itemId),await G(e)},"showUnsaveAlert"),Ur=a(async t=>{if(!t.listId)throw new Error("A listId is required to show the delete list alert");K();let e=await V("delete-list-alert",{listeners:{submit:a(()=>{t.onSubmit?.()},"submit"),cancel:a(()=>{t.onCancel?.()},"cancel")}});e.setAttribute("list-id",t.listId),await G(e)},"showDeleteListAlert"),qr=a(async()=>{K();let t=await V("drawer");t.setAttribute("account-url",f.routes.accountUrl),f.customer.id&&t.setAttribute("customer-id",f.customer.id),await G(t)},"showDrawer"),Br=a(async t=>{if(!t.listId)throw new Error("listId is required");K();let e=await V("list-menu",{listeners:{close:a(r=>{"detail"in r&&r.detail?t.onClose?.(r.detail):(console.warn("List menu closed without detail",r),t.onClose?.({reason:"unknown"}))},"close")}});e.setAttribute("list-id",t.listId),await G(e)},"showListMenu"),Gr=a(async t=>{if(!t.itemId)throw new Error("itemId is required");K();let e=await V("list-select",{listeners:{submit:a(async r=>{"detail"in r&&r.detail?t?.onSubmit?.(r.detail):console.warn("List select form submitted without detail",r)},"submit"),close:a(()=>{t.onClose?.()},"close"),unsave:a(r=>{r instanceof CustomEvent?t.onUnsave?.(r.detail):console.warn("List select unsave without detail",r)},"unsave")}});e.setAttribute("item-id",t.itemId),await G(e)},"showListSelect"),Hr=a(async t=>{await V("notifications",{onHydrated:a(e=>{e.current.pushNotification(t)},"onHydrated")})},"showNotification"),K=a(async()=>{pt("notifications")&&await V("notifications",{onHydrated:a(t=>{t.current.clearAllNotifications()},"onHydrated")})},"hideAllNotifications"),Fr=a(async t=>{K();let e=await V("variant-select",{listeners:{submit:a(async r=>{"detail"in r&&r.detail?t?.onSubmit?.(r.detail):console.warn("Variant select form submitted without detail",r)},"submit")}});if(t?.productId)e.setAttribute("product-id",t.productId);else if(t?.productHandle)e.setAttribute("product-handle",t.productHandle);else throw new Error("Either productId or productHandle must be provided");t?.variantId&&e.setAttribute("variant-id",t.variantId),t?.action&&e.setAttribute("action",t.action),t?.displayType&&e.setAttribute("display-type",t.displayType),await G(e)},"showVariantSelect"),Mr=a(async t=>{let e=await V("list-editor",{listeners:{submit:a(async r=>{"detail"in r&&r.detail?t?.onSubmit?.(r.detail):console.warn("List editor form submitted without detail",r)},"submit")}});t?.listId&&e.setAttribute("list-id",t.listId),await G(e)},"showListEditor"),kr=a(async({onShopModalOpen:t})=>{let e=document.querySelector("swish-shop-bridge");if(e||(document.body.insertAdjacentHTML("beforeend","<swish-shop-bridge></swish-shop-bridge>"),e=document.querySelector("swish-shop-bridge")),!e)throw new Error("Failed to initialize Shop Bridge");return e.addEventListener("shop-modal-open",()=>t(),{once:!0}),await e.load(),e},"initShopBridge"),le=a(async()=>xe||(xe=fetch(`${oe?.baseUrl??""}/ui@${oe.version}/manifest.json`).then(t=>t.json()),xe),"loadManifest"),Lr=new Map,V=a(async(t,e)=>{let r=await le(),n=r.prerender[t],o=`${oe?.baseUrl??""}/ui@${oe?.version}/${r.scripts[t]}`,i=e?.instance,s=e?.listeners,c=pt(t,i)??await go({name:t,template:n,refElement:document.body,position:"beforeend",instance:i});c.shadowRoot&&!c.hasAttribute("hydrated")?Promise.all([yo(),import(o)]).then(([l,{hydrate:p}])=>{c.shadowRoot&&l&&(c.shadowRoot.adoptedStyleSheets=[...c.shadowRoot.adoptedStyleSheets,l]),p(c),c.setAttribute("hydrated",""),e?.onHydrated?.(c.getComponentRef())}):c.hasAttribute("hydrated")&&e?.onHydrated?.(c.getComponentRef());for(let{event:l,listener:p}of Lr.values())c.removeEventListener(l,p);for(let[l,p]of Object.entries(s??{}))Lr.set(`${t}-${i}-${l}`,{event:l,listener:p}),c.addEventListener(l,p);return c},"requireUiComponent");async function yo(){return De||(De=new Promise((t,e)=>le().then(r=>r.stylesheets.nonCritical?fetch(`${oe?.baseUrl??""}/ui@${oe?.version}/${r.stylesheets.nonCritical}`):new Response("")).then(r=>r.text()).then(r=>{let n=new CSSStyleSheet;n.replaceSync(r),t(n)}).catch(e)),De)}a(yo,"loadNonCriticalStylesheet");var go=a(async({name:t,instance:e,template:r,position:n,refElement:o})=>{o.insertAdjacentHTML(n,r.replace(' shadowrootmode="open"',""));let i=pt(t,e);if(!i)throw new Error(`Element ${t} not found in DOM`);if(!Pe){let s=await le();Pe=new CSSStyleSheet,Pe.replaceSync(s.css.critical)}return i.shadowRoot&&(i.shadowRoot.adoptedStyleSheets=[Pe]),i},"insertComponent"),pt=a((t,e)=>{let r=`swish-ui[ref="${t}${e?`-${e}`:""}"]`;return document.querySelector(r)},"queryComponent"),ie,ce=0,_e=0,vo=a(()=>{ce++,ce===1&&(_e=window.scrollY,ie||(ie=new CSSStyleSheet,document.adoptedStyleSheets=[...document.adoptedStyleSheets,ie]),ie.replaceSync(`
|
|
397
397
|
html[locked] body {
|
|
398
398
|
overflow: hidden;
|
|
399
399
|
position: fixed;
|
|
@@ -401,4 +401,4 @@ Values:
|
|
|
401
401
|
left: 0px;
|
|
402
402
|
right: 0px;
|
|
403
403
|
}
|
|
404
|
-
`),document.documentElement.setAttribute("locked",""))},"lockScroll"),Co=a(()=>{ce>0&&ce--,ce===0&&(ie&&ie.replaceSync(""),window.scrollTo({top:_e,behavior:"instant"}),_e=0,document.documentElement.removeAttribute("locked"))},"unlockScroll");typeof requestIdleCallback=="function"?requestIdleCallback(()=>{le()}):setTimeout(()=>{le()},1e3);var wo="0.
|
|
404
|
+
`),document.documentElement.setAttribute("locked",""))},"lockScroll"),Co=a(()=>{ce>0&&ce--,ce===0&&(ie&&ie.replaceSync(""),window.scrollTo({top:_e,behavior:"instant"}),_e=0,document.documentElement.removeAttribute("locked"))},"unlockScroll");typeof requestIdleCallback=="function"?requestIdleCallback(()=>{le()}):setTimeout(()=>{le()},1e3);var wo="0.54.0",f={customer:{id:null,email:null,firstName:null,lastName:null,b2b:null},localization:{country:"",language:"",market:0},routes:{accountUrl:"/account",accountLoginUrl:"/account/login",rootUrl:"/"}},Gs=a(async t=>{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})}try{let n=document.getElementById("swishEmbedData");if(!n)throw new Error("Swish embed data not found");Object.assign(f,JSON.parse(n.innerText))}catch(n){console.warn("Could not read Swish embed data.",{cause:n})}let e=t.proxy?.baseUrl??"/apps/wishlist",r=new ht({loadProfile:a(()=>localStorage.getItem("swish-profile")??void 0,"loadProfile"),storeProfile:a(n=>localStorage.setItem("swish-profile",n),"storeProfile"),deleteProfile:a(()=>localStorage.removeItem("swish-profile"),"deleteProfile"),proxy:{baseUrl:e},ui:t.ui,storefront:t.storefront});try{let n=localStorage.getItem("swish-profile");n&&f.customer.id?await r.api.clearCache():!n&&!f.customer.id&&await r.api.clearCache()}catch(n){console.warn("Could not check if customer logged out.",{cause:n})}return window.swish=r,document.dispatchEvent(new Event("swish-ready")),r},"swishApp"),ht=class{constructor(e){this.ui={showSignIn:Vr,showVariantSelect:Fr,initShopBridge:kr,showNotification:Hr,hideAllNotifications:K,showListSelect:Gr,showDrawer:qr,showListEditor:Mr,showUnsaveAlert:Nr,hideModal:$r,showModal:G,showListMenu:Br,showDeleteListAlert:Ur};this.dom={createElementLocator:gt,createQueryParamsObserver:he};this.state={itemContext:Rt(this),itemState:Tt(this),itemCount:Pt(this),swishQuery:Dt(this),effect:$,signal:b};this.options=e,this.events=new fe;let r={baseUrl:`${this.options.proxy.baseUrl}/api`,...this.options.swishApi??{}};this.swishApiPublisher=new Re(this.events);let n=[wo,e.ui?.version].join("-");this.swishApi=new Ae({...r,responseInterceptor:this.swishApiPublisher.processFetchResponse,loadProfile:e.loadProfile,storeProfile:e.storeProfile,deleteProfile:e.deleteProfile},n),this.ajaxApiPublisher=new pe(this.events),this.ajaxApi=new ue({storeDomain:this.options.storefront.storeDomain,responseInterceptor:this.ajaxApiPublisher.processFetchResponse}),this.storefrontApi=new be(this.options.storefront),this.options.ui&&Or(this.options.ui),this.events.subscribe(["cart-add","cart-update","cart-change","cart-clear"],()=>{this.ajaxApi.clearCache()}),customElements.get("swish-ui")||customElements.define("swish-ui",Te)}static{a(this,"SwishApp")}get customer(){return f.customer}get localization(){return f.localization}get shopifyRoutes(){return f.routes}get api(){return this.swishApi}get storefront(){return this.storefrontApi}get ajax(){return this.ajaxApi}get shopUrl(){return`https://${this.options.storefront.storeDomain}`}};export{ht as SwishApp,wo as VERSION,Gs as swishApp,f as swishEmbedData};
|