UNPKG

@swishapp/browser

Version:

JS library to integrate Swish into a browser environment.

288 lines (287 loc) 40.3 kB
var ht=Object.defineProperty;var d=(t,e)=>ht(t,"name",{value:e,configurable:!0});var ft=Object.defineProperty,c=d((t,e)=>ft(t,"name",{value:e,configurable:!0}),"o"),mt=c(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},"A"),yt={bodySerializer:c(t=>JSON.stringify(t,(e,r)=>typeof r=="bigint"?r.toString():r),"bodySerializer")},gt=c(t=>{switch(t){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},"U"),It=c(t=>{switch(t){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},"_"),Tt=c(t=>{switch(t){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},"D"),Te=c(({allowReserved:t,explode:e,name:r,style:a,value:o})=>{if(!e){let i=(t?o:o.map(l=>encodeURIComponent(l))).join(It(a));switch(a){case"label":return`.${i}`;case"matrix":return`;${r}=${i}`;case"simple":return i;default:return`${r}=${i}`}}let s=gt(a),n=o.map(i=>a==="label"||a==="simple"?t?i:encodeURIComponent(i):G({allowReserved:t,name:r,value:i})).join(s);return a==="label"||a==="matrix"?s+n:n},"O"),G=c(({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)}`},"y"),Re=c(({allowReserved:t,explode:e,name:r,style:a,value:o})=>{if(o instanceof Date)return`${r}=${o.toISOString()}`;if(a!=="deepObject"&&!e){let i=[];Object.entries(o).forEach(([h,f])=>{i=[...i,h,t?f:encodeURIComponent(f)]});let l=i.join(",");switch(a){case"form":return`${r}=${l}`;case"label":return`.${l}`;case"matrix":return`;${r}=${l}`;default:return l}}let s=Tt(a),n=Object.entries(o).map(([i,l])=>G({allowReserved:t,name:a==="deepObject"?`${r}[${i}]`:i,value:l})).join(s);return a==="label"||a==="matrix"?s+n:n},"q"),Rt=/\{[^{}]+\}/g,Et=c(({path:t,url:e})=>{let r=e,a=e.match(Rt);if(a)for(let o of a){let s=!1,n=o.substring(1,o.length-1),i="simple";n.endsWith("*")&&(s=!0,n=n.substring(0,n.length-1)),n.startsWith(".")?(n=n.substring(1),i="label"):n.startsWith(";")&&(n=n.substring(1),i="matrix");let l=t[n];if(l==null)continue;if(Array.isArray(l)){r=r.replace(o,Te({explode:s,name:n,style:i,value:l}));continue}if(typeof l=="object"){r=r.replace(o,Re({explode:s,name:n,style:i,value:l}));continue}if(i==="matrix"){r=r.replace(o,`;${G({name:n,value:l})}`);continue}let h=encodeURIComponent(i==="label"?`.${l}`:l);r=r.replace(o,h)}return r},"B"),Ee=c(({allowReserved:t,array:e,object:r}={})=>a=>{let o=[];if(a&&typeof a=="object")for(let s in a){let n=a[s];if(n!=null){if(Array.isArray(n)){o=[...o,Te({allowReserved:t,explode:!0,name:s,style:"form",value:n,...e})];continue}if(typeof n=="object"){o=[...o,Re({allowReserved:t,explode:!0,name:s,style:"deepObject",value:n,...r})];continue}o=[...o,G({allowReserved:t,name:s,value:n})]}}return o.join("&")},"E"),At=c(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(a=>r.startsWith(a)))return"blob";if(r.startsWith("text/"))return"text"}},"P"),Ct=c(async({security:t,...e})=>{for(let r of t){let a=await mt(r,e.auth);if(!a)continue;let o=r.name??"Authorization";switch(r.in){case"query":e.query||(e.query={}),e.query[o]=a;break;case"header":default:e.headers.set(o,a);break}return}},"I"),ge=c(t=>_t({baseUrl:t.baseUrl,path:t.path,query:t.query,querySerializer:typeof t.querySerializer=="function"?t.querySerializer:Ee(t.querySerializer),url:t.url}),"S"),_t=c(({baseUrl:t,path:e,query:r,querySerializer:a,url:o})=>{let s=o.startsWith("/")?o:`/${o}`,n=(t??"")+s;e&&(n=Et({path:e,url:n}));let i=r?a(r):"";return i.startsWith("?")&&(i=i.substring(1)),i&&(n+=`?${i}`),n},"W"),Ie=c((t,e)=>{var r;let a={...t,...e};return(r=a.baseUrl)!=null&&r.endsWith("/")&&(a.baseUrl=a.baseUrl.substring(0,a.baseUrl.length-1)),a.headers=Ae(t.headers,e.headers),a},"C"),Ae=c((...t)=>{let e=new Headers;for(let r of t){if(!r||typeof r!="object")continue;let a=r instanceof Headers?r.entries():Object.entries(r);for(let[o,s]of a)if(s===null)e.delete(o);else if(Array.isArray(s))for(let n of s)e.append(o,n);else s!==void 0&&e.set(o,typeof s=="object"?JSON.stringify(s):s)}return e},"x"),Y,K=(Y=class{static{d(this,"C")}_fns;constructor(){this._fns=[]}clear(){this._fns=[]}exists(t){return this._fns.indexOf(t)!==-1}eject(t){let e=this._fns.indexOf(t);e!==-1&&(this._fns=[...this._fns.slice(0,e),...this._fns.slice(e+1)])}use(t){this._fns=[...this._fns,t]}},c(Y,"m"),Y),Dt=c(()=>({error:new K,request:new K,response:new K}),"T"),Pt=Ee({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),bt={"Content-Type":"application/json"},z=c((t={})=>({...yt,headers:bt,parseAs:"auto",querySerializer:Pt,...t}),"w"),Ce=c((t={})=>{let e=Ie(z(),t),r=c(()=>({...e}),"e"),a=c(n=>(e=Ie(e,n),r()),"a"),o=Dt(),s=c(async n=>{let i={...e,...n,fetch:n.fetch??e.fetch??globalThis.fetch,headers:Ae(e.headers,n.headers)};i.security&&await Ct({...i,security:i.security}),i.body&&i.bodySerializer&&(i.body=i.bodySerializer(i.body)),(i.body===void 0||i.body==="")&&i.headers.delete("Content-Type");let l=ge(i),h={redirect:"follow",...i},f=new Request(l,h);for(let R of o.request._fns)f=await R(f,i);let y=i.fetch,m=await y(f);for(let R of o.response._fns)m=await R(m,f,i);let g={request:f,response:m};if(m.ok){if(m.status===204||m.headers.get("Content-Length")==="0")return{data:{},...g};let R=(i.parseAs==="auto"?At(m.headers.get("Content-Type")):i.parseAs)??"json";if(R==="stream")return{data:m.body,...g};let P=await m[R]();return R==="json"&&(i.responseValidator&&await i.responseValidator(P),i.responseTransformer&&(P=await i.responseTransformer(P))),{data:P,...g}}let S=await m.text();try{S=JSON.parse(S)}catch{}let C=S;for(let R of o.error._fns)C=await R(S,m,f,i);if(C=C||{},i.throwOnError)throw C;return{error:C,...g}},"o");return{buildUrl:ge,connect:c(n=>s({...n,method:"CONNECT"}),"connect"),delete:c(n=>s({...n,method:"DELETE"}),"delete"),get:c(n=>s({...n,method:"GET"}),"get"),getConfig:r,head:c(n=>s({...n,method:"HEAD"}),"head"),interceptors:o,options:c(n=>s({...n,method:"OPTIONS"}),"options"),patch:c(n=>s({...n,method:"PATCH"}),"patch"),post:c(n=>s({...n,method:"POST"}),"post"),put:c(n=>s({...n,method:"PUT"}),"put"),request:s,setConfig:a,trace:c(n=>s({...n,method:"TRACE"}),"trace")}},"J"),I=Ce(z({baseUrl:"https://swish.app/api/2025-07"})),St=c(t=>(t?.client??I).get({url:"/lists",...t}),"listControllerFind"),wt=c(t=>(t.client??I).post({url:"/lists",...t,headers:{"Content-Type":"application/json",...t?.headers}}),"listControllerCreate"),Ot=c(t=>(t.client??I).delete({url:"/lists/{listId}",...t}),"listControllerDeleteById"),vt=c(t=>(t.client??I).get({url:"/lists/{listId}",...t}),"listControllerFindById"),xt=c(t=>(t.client??I).patch({url:"/lists/{listId}",...t,headers:{"Content-Type":"application/json",...t?.headers}}),"listControllerUpdateById"),Vt=c(t=>(t.client??I).put({url:"/lists/{listId}/items/order",...t,headers:{"Content-Type":"application/json",...t?.headers}}),"listControllerSetListItemsOrder"),Nt=c(t=>(t.client??I).post({url:"/lists/{listId}/items",...t,headers:{"Content-Type":"application/json",...t?.headers}}),"listControllerAddItemsToList"),$t=c(t=>(t.client??I).delete({url:"/items",...t,headers:{"Content-Type":"application/json",...t?.headers}}),"itemControllerDelete"),Lt=c(t=>(t?.client??I).get({url:"/items",...t}),"itemControllerFind"),Gt=c(t=>(t.client??I).post({url:"/items",...t,headers:{"Content-Type":"application/json",...t?.headers}}),"itemControllerCreate"),qt=c(t=>(t.client??I).delete({url:"/items/{itemId}",...t}),"itemControllerDeleteById"),Ut=c(t=>(t.client??I).get({url:"/items/{itemId}",...t}),"itemControllerFindById"),Bt=c(t=>(t.client??I).patch({url:"/items/{itemId}",...t,headers:{"Content-Type":"application/json",...t?.headers}}),"itemControllerUpdateById"),Mt=c(t=>(t.client??I).put({url:"/items/{itemId}/lists",...t,headers:{"Content-Type":"application/json",...t?.headers}}),"itemControllerSetListsById"),Ft=c(t=>(t?.client??I).get({url:"/profiles/accounts-version",...t}),"profileControllerCustomerAccountsVersion"),jt=c(t=>(t.client??I).post({url:"/profiles/identify",...t,headers:{"Content-Type":"application/json",...t?.headers}}),"profileControllerIdentify"),kt=c(t=>(t.client??I).post({url:"/profiles/token",...t,headers:{"Content-Type":"application/json",...t?.headers}}),"profileControllerCreateToken"),_e=c(t=>new Ht(t),"createApiClient"),De=class{static{d(this,"D")}constructor(e){this.client=Ce(z({baseUrl:"https://swish.app/api/2025-07"})),this.items={list:c(r=>this.handleRequest(Lt({query:r,client:this.client})),"list"),create:c(r=>this.handleRequest(Gt({body:r,client:this.client})),"create"),delete:c(r=>this.handleRequest($t({body:{itemIds:r},client:this.client})),"delete"),findById:c(r=>this.handleRequest(Ut({path:{itemId:r},client:this.client})),"findById"),updateById:c((r,a)=>this.handleRequest(Bt({body:a,path:{itemId:r},client:this.client})),"updateById"),deleteById:c(r=>this.handleRequest(qt({path:{itemId:r},client:this.client})),"deleteById"),setListsById:c((r,a)=>this.handleRequest(Mt({body:{listIds:a},path:{itemId:r},client:this.client})),"setListsById")},this.lists={list:c(r=>this.handleRequest(St({query:r,client:this.client})),"list"),create:c(r=>this.handleRequest(wt({body:r,client:this.client})),"create"),findById:c((r,a)=>this.handleRequest(vt({path:{listId:r},query:a??{sort:"recently_saved"},client:this.client})),"findById"),updateById:c((r,a)=>this.handleRequest(xt({body:a,path:{listId:r},client:this.client})),"updateById"),deleteById:c(r=>this.handleRequest(Ot({path:{listId:r},client:this.client})),"deleteById"),orderItems:c((r,a)=>this.handleRequest(Vt({body:{itemIds:a},path:{listId:r},client:this.client})),"orderItems"),addItemsToList:c((r,a)=>this.handleRequest(Nt({body:{itemIds:a},path:{listId:r},client:this.client})),"addItemsToList")},this.profiles={customerAccountsVersion:c(()=>this.handleRequest(Ft({client:this.client})),"customerAccountsVersion"),createToken:c((r={})=>this.handleRequest(kt({body:r,client:this.client})),"createToken"),identify:c(r=>this.handleRequest(jt({body:r,client:this.client})),"identify")},this.handleRequest=c(async r=>{let{data:a,error:o}=await r;if(o!=null&&o.error)return{data:null,error:o?.error};if(a!=null&&a.data){let s={data:a.data,error:null};return a.pageInfo&&(s.pageInfo=a.pageInfo),s}return{data:null,error:null}},"handleRequest"),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}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}};c(De,"SwishClient");var Ht=De;var Pe=d(t=>t.split("/").pop(),"shopifyGidToId"),T=d((t,e)=>`gid://shopify/${t}/${e}`,"shopifyIdToGid");var q=class{constructor(e){this.config=null;this.fetchConfig=e}static{d(this,"AjaxApi")}setConfig(e){this.config=e}getBaseUrl(){if(!this.config?.storeDomain)throw new Error("Cart API client not initialized - missing store domain");return`https://${this.config.storeDomain}`}async request(e,r={}){let a=`${this.getBaseUrl()}${e}`,n=await(this.fetchConfig.fetch||fetch)(a,{...r,headers:{...{"Content-Type":"application/json",Accept:"application/json"},...r.headers}});if(!n.ok){let i;try{i=await n.json()}catch{i={message:`HTTP ${n.status}: ${n.statusText}`,status:n.status.toString(),description:n.statusText}}throw new Error(i.message||i.description)}return n.json()}async fetchCart(){return this.request("/cart.js")}async addToCart(e){let r={...e,items:e.items.map(a=>{let o=Pe(a.id);if(!o)throw new Error(`Invalid Shopify GID format: ${a.id}`);let s=parseInt(o,10);if(isNaN(s))throw new Error(`Invalid numeric ID extracted from GID: ${a.id}`);return{...a,id:s}})};return this.request("/cart/add.js",{method:"POST",body:JSON.stringify(r)})}};var w="GraphQL Client";var J="An error occurred while fetching from the API. Review 'graphQLErrors' for details.",X="Response returned unexpected Content-Type:",Z="An unknown error has occurred. The API did not return a data object or any errors in its response.",U={json:"application/json",multipart:"multipart/mixed"},ee="X-SDK-Variant",te="X-SDK-Version",Se="shopify-graphql-client",we="1.4.0",B=1e3,Oe=[429,503],re=/@(defer)\b/i,be=`\r `,ve=/boundary="?([^=";]+)"?/i,ae=be+be;function D(t,e=w){return t.startsWith(`${e}`)?t:`${e}: ${t}`}d(D,"formatErrorMessage");function b(t){return t instanceof Error?t.message:JSON.stringify(t)}d(b,"getErrorMessage");function ne(t){return t instanceof Error&&t.cause?t.cause:void 0}d(ne,"getErrorCause");function oe(t){return t.flatMap(({errors:e})=>e??[])}d(oe,"combineErrors");function M({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}`)}d(M,"validateRetries");function E(t,e){return e&&(typeof e!="object"||Array.isArray(e)||typeof e=="object"&&Object.keys(e).length>0)?{[t]:e}:{}}d(E,"getKeyValueIfValid");function se(t,e){if(t.length===0)return e;let a={[t.pop()]:e};return t.length===0?a:se(t,a)}d(se,"buildDataObjectByPath");function Ne(t,e){return Object.keys(e||{}).reduce((r,a)=>(typeof e[a]=="object"||Array.isArray(e[a]))&&t[a]?(r[a]=Ne(t[a],e[a]),r):(r[a]=e[a],r),Array.isArray(t)?[...t]:{...t})}d(Ne,"combineObjects");function ie([t,...e]){return e.reduce(Ne,{...t})}d(ie,"buildCombinedDataObject");function de({clientLogger:t,customFetchApi:e=fetch,client:r=w,defaultRetryWaitTime:a=B,retriableCodes:o=Oe}){let s=d(async(n,i,l)=>{let h=i+1,f=l+1,y;try{if(y=await e(...n),t({type:"HTTP-Response",content:{requestParams:n,response:y}}),!y.ok&&o.includes(y.status)&&h<=f)throw new Error;let m=y?.headers.get("X-Shopify-API-Deprecated-Reason")||"";return m&&t({type:"HTTP-Response-GraphQL-Deprecation-Notice",content:{requestParams:n,deprecationNotice:m}}),y}catch(m){if(h<=f){let g=y?.headers.get("Retry-After");return await Qt(g?parseInt(g,10):a),t({type:"HTTP-Retry",content:{requestParams:n,lastResponse:y,retryAttempt:i,maxRetries:l}}),s(n,h,l)}throw new Error(D(`${l>0?`Attempted maximum number of ${l} network retries. Last message - `:""}${b(m)}`,r))}},"httpFetch");return s}d(de,"generateHttpFetch");async function Qt(t){return new Promise(e=>setTimeout(e,t))}d(Qt,"sleep");function ce({headers:t,url:e,customFetchApi:r=fetch,retries:a=0,logger:o}){M({client:w,retries:a});let s={headers:t,url:e,retries:a},n=Wt(o),i=de({customFetchApi:r,clientLogger:n,defaultRetryWaitTime:B}),l=Yt(i,s),h=Kt(l),f=rr(l);return{config:s,fetch:l,request:h,requestStream:f}}d(ce,"createGraphQLClient");function Wt(t){return e=>{t&&t(e)}}d(Wt,"generateClientLogger");async function $e(t){let{errors:e,data:r,extensions:a}=await t.json();return{...E("data",r),...E("extensions",a),headers:t.headers,...e||!r?{errors:{networkStatusCode:t.status,message:D(e?J:Z),...E("graphQLErrors",e),response:t}}:{}}}d($e,"processJSONResponse");function Yt(t,{url:e,headers:r,retries:a}){return async(o,s={})=>{let{variables:n,headers:i,url:l,retries:h,keepalive:f,signal:y}=s,m=JSON.stringify({query:o,variables:n});M({client:w,retries:h});let g=Object.entries({...r,...i}).reduce((C,[R,P])=>(C[R]=Array.isArray(P)?P.join(", "):P.toString(),C),{});return!g[ee]&&!g[te]&&(g[ee]=Se,g[te]=we),t([l??e,{method:"POST",headers:g,body:m,signal:y,keepalive:f}],1,h??a)}}d(Yt,"generateFetch");function Kt(t){return async(...e)=>{if(re.test(e[0]))throw new Error(D("This operation will result in a streamable response - use requestStream() instead."));try{let r=await t(...e),{status:a,statusText:o}=r,s=r.headers.get("content-type")||"";return r.ok?s.includes(U.json)?$e(r):{errors:{networkStatusCode:a,message:D(`${X} ${s}`),response:r}}:{errors:{networkStatusCode:a,message:D(o),response:r}}}catch(r){return{errors:{message:b(r)}}}}}d(Kt,"generateRequest");async function*zt(t){let e=new TextDecoder;if(t.body[Symbol.asyncIterator])for await(let r of t.body)yield e.decode(r);else{let r=t.body.getReader(),a;try{for(;!(a=await r.read()).done;)yield e.decode(a.value)}finally{r.cancel()}}}d(zt,"getStreamBodyIterator");function Jt(t,e){return{async*[Symbol.asyncIterator](){try{let r="";for await(let a of t)if(r+=a,r.indexOf(e)>-1){let o=r.lastIndexOf(e),n=r.slice(0,o).split(e).filter(i=>i.trim().length>0).map(i=>i.slice(i.indexOf(ae)+ae.length).trim());n.length>0&&(yield n),r=r.slice(o+e.length),r.trim()==="--"&&(r="")}}catch(r){throw new Error(`Error occured while processing stream payload - ${b(r)}`)}}}}d(Jt,"readStreamChunk");function Xt(t){return{async*[Symbol.asyncIterator](){yield{...await $e(t),hasNext:!1}}}}d(Xt,"createJsonResponseAsyncIterator");function Zt(t){return t.map(e=>{try{return JSON.parse(e)}catch(r){throw new Error(`Error in parsing multipart response - ${b(r)}`)}}).map(e=>{let{data:r,incremental:a,hasNext:o,extensions:s,errors:n}=e;if(!a)return{data:r||{},...E("errors",n),...E("extensions",s),hasNext:o};let i=a.map(({data:l,path:h,errors:f})=>({data:l&&h?se(h,l):{},...E("errors",f)}));return{data:i.length===1?i[0].data:ie([...i.map(({data:l})=>l)]),...E("errors",oe(i)),hasNext:o}})}d(Zt,"getResponseDataFromChunkBodies");function er(t,e){if(t.length>0)throw new Error(J,{cause:{graphQLErrors:t}});if(Object.keys(e).length===0)throw new Error(Z)}d(er,"validateResponseData");function tr(t,e){let r=(e??"").match(ve),a=`--${r?r[1]:"-"}`;if(!t.body?.getReader&&!t.body?.[Symbol.asyncIterator])throw new Error("API multipart response did not return an iterable body",{cause:t});let o=zt(t),s={},n;return{async*[Symbol.asyncIterator](){try{let i=!0;for await(let l of Jt(o,a)){let h=Zt(l);n=h.find(y=>y.extensions)?.extensions??n;let f=oe(h);s=ie([s,...h.map(({data:y})=>y)]),i=h.slice(-1)[0].hasNext,er(f,s),yield{...E("data",s),...E("extensions",n),hasNext:i}}if(i)throw new Error("Response stream terminated unexpectedly")}catch(i){let l=ne(i);yield{...E("data",s),...E("extensions",n),errors:{message:D(b(i)),networkStatusCode:t.status,...E("graphQLErrors",l?.graphQLErrors),response:t},hasNext:!1}}}}}d(tr,"createMultipartResponseAsyncInterator");function rr(t){return async(...e)=>{if(!re.test(e[0]))throw new Error(D("This operation does not result in a streamable response - use request() instead."));try{let r=await t(...e),{statusText:a}=r;if(!r.ok)throw new Error(a,{cause:r});let o=r.headers.get("content-type")||"";switch(!0){case o.includes(U.json):return Xt(r);case o.includes(U.multipart):return tr(r,o);default:throw new Error(`${X} ${o}`,{cause:r})}}catch(r){return{async*[Symbol.asyncIterator](){let a=ne(r);yield{errors:{message:D(b(r)),...E("networkStatusCode",a?.status),...E("response",a)},hasNext:!1}}}}}}d(rr,"generateRequestStream");function le({client:t,storeDomain:e}){try{if(!e||typeof e!="string")throw new Error;let r=e.trim(),a=r.match(/^https?:/)?r:`https://${r}`,o=new URL(a);return o.protocol="https",o.origin}catch(r){throw new Error(`${t}: a valid store domain ("${e}") must be provided`,{cause:r})}}d(le,"validateDomainAndGetStoreUrl");function F({client:t,currentSupportedApiVersions:e,apiVersion:r,logger:a}){let o=`${t}: the provided apiVersion ("${r}")`,s=`Currently supported API versions: ${e.join(", ")}`;if(!r||typeof r!="string")throw new Error(`${o} is invalid. ${s}`);let n=r.trim();e.includes(n)||(a?a({type:"Unsupported_Api_Version",content:{apiVersion:r,supportedApiVersions:e}}):console.warn(`${o} is likely deprecated or not supported. ${s}`))}d(F,"validateApiVersion");function j(t){let e=t*3-2;return e===10?e:`0${e}`}d(j,"getQuarterMonth");function ue(t,e,r){let a=e-r;return a<=0?`${t-1}-${j(a+4)}`:`${t}-${j(a)}`}d(ue,"getPrevousVersion");function Le(){let t=new Date,e=t.getUTCMonth(),r=t.getUTCFullYear(),a=Math.floor(e/3+1);return{year:r,quarter:a,version:`${r}-${j(a)}`}}d(Le,"getCurrentApiVersion");function pe(){let{year:t,quarter:e,version:r}=Le(),a=e===4?`${t+1}-01`:`${t}-${j(e+1)}`;return[ue(t,e,3),ue(t,e,2),ue(t,e,1),r,a,"unstable"]}d(pe,"getCurrentSupportedApiVersions");function he(t){return e=>({...e??{},...t.headers})}d(he,"generateGetHeaders");function fe({getHeaders:t,getApiUrl:e}){return(r,a)=>{let o=[r];if(a&&Object.keys(a).length>0){let{variables:s,apiVersion:n,headers:i,retries:l}=a;o.push({...s?{variables:s}:{},...i?{headers:t(i)}:{},...n?{url:e(n)}:{},...l?{retries:l}:{}})}return o}}d(fe,"generateGetGQLClientParams");var me="application/json",Ge="storefront-api-client",qe="1.0.8",Ue="X-Shopify-Storefront-Access-Token",Be="Shopify-Storefront-Private-Token",Me="X-SDK-Variant",Fe="X-SDK-Version",je="X-SDK-Variant-Source",O="Storefront API Client";function ke(t){if(t&&typeof window<"u")throw new Error(`${O}: private access tokens and headers should only be used in a server-to-server implementation. Use the public API access token in nonserver environments.`)}d(ke,"validatePrivateAccessTokenUsage");function He(t,e){if(!t&&!e)throw new Error(`${O}: a public or private access token must be provided`);if(t&&e)throw new Error(`${O}: only provide either a public or private access token`)}d(He,"validateRequiredAccessTokens");function ye({storeDomain:t,apiVersion:e,publicAccessToken:r,privateAccessToken:a,clientName:o,retries:s=0,customFetchApi:n,logger:i}){let l=pe(),h=le({client:O,storeDomain:t}),f={client:O,currentSupportedApiVersions:l,logger:i};F({...f,apiVersion:e}),He(r,a),ke(a);let y=ar(h,e,f),m={storeDomain:h,apiVersion:e,...r?{publicAccessToken:r}:{privateAccessToken:a},headers:{"Content-Type":me,Accept:me,[Me]:Ge,[Fe]:qe,...o?{[je]:o}:{},...r?{[Ue]:r}:{[Be]:a}},apiUrl:y(),clientName:o},g=ce({headers:m.headers,url:m.apiUrl,retries:s,customFetchApi:n,logger:i}),S=he(m),C=nr(m,y),R=fe({getHeaders:S,getApiUrl:C});return Object.freeze({config:m,getHeaders:S,getApiUrl:C,fetch:d((...N)=>g.fetch(...R(...N)),"fetch"),request:d((...N)=>g.request(...R(...N)),"request"),requestStream:d((...N)=>g.requestStream(...R(...N)),"requestStream")})}d(ye,"createStorefrontApiClient");function ar(t,e,r){return a=>{a&&F({...r,apiVersion:a});let o=(a??e).trim();return`${t}/api/${o}/graphql.json`}}d(ar,"generateApiUrlFormatter");function nr(t,e){return r=>r?e(r):t.apiUrl}d(nr,"generateGetApiUrl");var _=` fragment productImageFields on Image { id altText url thumbhash } `,k=` fragment productCardDataFields on Product { id availableForSale category { id name } compareAtPriceRange { maxVariantPrice { amount currencyCode } minVariantPrice { amount currencyCode } } featuredImage { ...productImageFields } isGiftCard onlineStoreUrl handle priceRange { maxVariantPrice { amount currencyCode } minVariantPrice { amount currencyCode } } productType tags title # totalInventory } `,Qe=` fragment productVariantDataFields on ProductVariant { id availableForSale compareAtPrice { amount currencyCode } currentlyNotInStock image { ...productImageFields } price { amount currencyCode } # quantityAvailable selectedOptions { name value } sku title } `,We=` query GetProductCardData($productId: ID!) { product(id: $productId) { ...productCardDataFields } } ${k} ${_} `,Ye=` query GetProductCardDataWithVariant($productId: ID!, $variantId: ID!) { product(id: $productId) { ...productCardDataFields } variant: node(id: $variantId) { ...productVariantDataFields } } ${k} ${Qe} ${_} `,v=` fragment productOptionsFields on Product { id title featuredImage { ...productImageFields } encodedVariantAvailability encodedVariantExistence variantsCount { count precision } options { id name optionValues { name swatch { color image { previewImage { url } } } firstSelectableVariant { id image { ...productImageFields } } } } } `,Ke=` fragment productOptionsVariantFields on ProductVariant { id selectedOptions { name value } } `,ze=` query GetProductOptions($productId: ID!) { product(id: $productId) { ...productOptionsFields } } ${v} ${_} `,Je=` query GetProductOptionsByHandle($handle: String!) { product(handle: $handle) { ...productOptionsFields } } ${v} ${_} `,Xe=` query GetProductOptionsWithVariant($productId: ID!, $variantId: ID!) { product(id: $productId) { ...productOptionsFields } variant: node(id: $variantId) { ...productOptionsVariantFields } } ${v} ${Ke} ${_} `,Ze=` query GetProductOptionsByHandleWithVariant( $handle: String! $variantId: ID! ) { product(handle: $handle) { ...productOptionsFields } variant: node(id: $variantId) { ...productOptionsVariantFields } } ${v} ${Ke} ${_} `,et=` fragment selectedVariantFields on Product { id title handle featuredImage { ...productImageFields } variantBySelectedOptions(selectedOptions: $selectedOptions) { id availableForSale compareAtPrice { amount currencyCode } currentlyNotInStock image { ...productImageFields } price { amount currencyCode } title selectedOptions { name value } } } `,tt=` query GetSelectedVariant( $productId: ID! $selectedOptions: [SelectedOptionInput!]! ) { product(id: $productId) { ...selectedVariantFields } } ${et} ${_} `,rt=` query GetSelectedVariantByHandle( $handle: String! $selectedOptions: [SelectedOptionInput!]! ) { product(handle: $handle) { ...selectedVariantFields } } ${et} ${_} `,at=` fragment productImagesFields on Product { images(first: 20) { nodes { ...productImageFields } } } `,nt=` query GetProductDetailData($productId: ID!) { product(id: $productId) { ...productCardDataFields ...productOptionsFields ...productImagesFields } } ${k} ${v} ${at} ${_} `,ot=` query GetProductDetailDataWithVariant($productId: ID!, $variantId: ID!) { product(id: $productId) { ...productCardDataFields ...productOptionsFields ...productImagesFields } variant: node(id: $variantId) { ...productVariantDataFields } } ${k} ${v} ${Qe} ${at} ${_} `,st=` query GetProductImagesById($ids: [ID!]!) { nodes(ids: $ids) { ... on Product { featuredImage { ...productImageFields } } ... on ProductVariant { image { ...productImageFields } product { featuredImage { ...productImageFields } } } } } ${_} `;var it=d(async(t,{productId:e,variantId:r})=>{if(!e)throw new Error("A productId must be provided");let a=d(()=>{if(e&&!r)return We;if(e&&r)return Ye},"getProductOptionsQuery"),o=d(()=>{if(e&&!r)return{productId:T("Product",e)};if(e&&r)return{productId:T("Product",e),variantId:T("ProductVariant",r)}},"getVariables"),s=a(),n=o();if(!n||!s)throw new Error("Invalid query arguments");return t.query(s,n)},"loadProductCardData");var dt=d(async(t,{productId:e,variantId:r})=>{if(!e)throw new Error("A productId must be provided");let a=d(()=>{if(e&&!r)return nt;if(e&&r)return ot},"getProductOptionsQuery"),o=d(()=>{if(e&&!r)return{productId:T("Product",e)};if(e&&r)return{productId:T("Product",e),variantId:T("ProductVariant",r)}},"getVariables"),s=a(),n=o();if(!n||!s)throw new Error("Invalid query arguments");return t.query(s,n)},"loadProductDetailData");var ct=d(async(t,{items:e})=>{if(!e?.length)throw new Error("A list of items must be provided");let r={ids:e.map(a=>a.variantId?T("ProductVariant",a.variantId.toString()):T("Product",a.productId.toString()))};try{return{data:(await t.query(st,r)).data?.nodes.map(s=>s===null?null:"image"in s?s.image:"featuredImage"in s?s.featuredImage:null).filter(s=>s!==null)??[],error:null}}catch(a){return console.error(a),{data:null,error:a}}},"loadProductImages");var lt=d(async(t,{productId:e,productHandle:r,variantId:a})=>{if(!e&&!r)throw new Error("Either productId or handle must be provided");let o=d(()=>{if(e&&!a)return ze;if(r&&!a)return Je;if(e&&a)return Xe;if(r&&a)return Ze},"getProductOptionsQuery"),s=d(()=>{if(e&&!a)return{productId:T("Product",e)};if(r&&!a)return{handle:r};if(e&&a)return{productId:T("Product",e),variantId:T("ProductVariant",a)};if(r&&a)return{handle:r,variantId:T("ProductVariant",a)}},"getVariables"),n=o(),i=s();if(!i||!n)throw new Error("Invalid query arguments");return t.query(n,i)},"loadProductOptions");var ut=d(async(t,{productId:e,productHandle:r,selectedOptions:a})=>{if(!e&&!r)throw new Error("Either productId or handle must be provided");let o=e?tt:rt,s=e?{productId:`gid://shopify/Product/${e}`,selectedOptions:a}:{handle:r,selectedOptions:a};return t.query(o,s)},"loadSelectedVariant");var or="2025-07",H=class{constructor(e){this.client=null;this.query=d(async(e,r)=>{if(!this.client)throw new Error("Storefront API client not initialized");let a=await this.client.request(e,{variables:r});return{data:a.data,error:a.errors??null}},"query");this.loadProductOptions=d(async e=>lt(this,e),"loadProductOptions");this.loadSelectedVariant=d(async e=>ut(this,e),"loadSelectedVariant");this.loadProductCardData=d(async e=>it(this,e),"loadProductCardData");this.loadProductDetailData=d(async e=>dt(this,e),"loadProductDetailData");this.loadProductImages=d(async e=>ct(this,e),"loadProductImages");this.fetchConfig=e}static{d(this,"StorefrontApi")}setConfig(e){this.client=ye({apiVersion:or,customFetchApi:this.fetchConfig.fetch,publicAccessToken:e.accessToken,storeDomain:e.storeDomain})}};var $=class{constructor(e,r=0){this.worker=e;this.rpcTimeout=r;this.worker=e,this.rpcTimeout=r,this.worker.onmessage=a=>{this.#o(a.data)}}static{d(this,"WorkerRpc")}#t=new Map;#r=new Map;#n=0;call(e,...r){let a=this.#n++;return this.worker.postMessage({type:"RPC",transactionId:a,id:e,payload:r}),new Promise((o,s)=>{let n={id:a,resolve:o,reject:s};this.rpcTimeout>0&&(n.timeoutHandle=setTimeout(()=>this.#d(n),this.rpcTimeout)),this.#r.set(a,n)})}addMethod(e,r){if(this.#t.has(e))throw new Error(`rpc handler for ${e} already registered`);this.#t.set(e,r)}removeMethod(e){this.#t.delete(e)}#o(e){let r=e;switch(r.type){case"RPC":return this.#s(r);case"INTERNAL":return this.#i(r);default:this.#e(`invalid message type ${r.type}`)}}#e(e){console.error(e),this.worker.postMessage({type:"INTERNAL",id:"ERROR",payload:e})}async#s(e){let r=this.#t.get(e.id);if(!r)return this.#e(`invalid rpc ${e.id}`);try{let a=await r(...e.payload);this.worker.postMessage({type:"INTERNAL",id:"RESOLVE_TRANSACTION",transactionId:e.transactionId,payload:a})}catch(a){this.worker.postMessage({type:"INTERNAL",id:"REJECT_TRANSACTION",transactionId:e.transactionId,payload:a})}}#i(e){let r=typeof e.transactionId=="number"?this.#r.get(e.transactionId):void 0;switch(e.id){case"RESOLVE_TRANSACTION":if(!r)return this.#e(`no pending transaction with id ${e.transactionId}`);r.resolve(e.payload),this.#a(r);break;case"REJECT_TRANSACTION":if(!r)return this.#e(`no pending transaction with id ${e.transactionId}`);r.reject(e.payload),this.#a(r);break;case"ERROR":console.error(`remote error: ${e.payload}`);break;default:this.#e(`unhandled internal message ${e.id}`);break}}#d(e){e.reject("transaction timed out"),this.#e(`transaction ${e.id} timed out`),this.#r.delete(e.id)}#a(e){typeof e.timeoutHandle<"u"&&clearTimeout(e.timeoutHandle),this.#r.delete(e.id)}};var x=class{constructor(e,r){this.revalidationPromises=new Map;this.inFlightRequests=new Map;this.cacheName=e,this.defaultCacheControl=r}static{d(this,"Cache")}async get(e){try{let r=await caches.open(this.cacheName),a=await r.match(e);if(a&&this.isExpired(a)){await r.delete(e);return}return a}catch(r){console.warn("Cache get error:",r);return}}async set(e,r,a){try{let o=this.createCacheableResponse(r,a);await(await caches.open(this.cacheName)).put(e,o)}catch(o){console.warn("Cache set error:",o)}}async fetchWithCache(e,r,a){let o=await this.getCacheKey(e,r);if(this.inFlightRequests.has(o))return this.inFlightRequests.get(o).then(n=>n.clone());let s=(async()=>{let n=await this.get(o);if(n)return this.isStaleButRevalidatable(n)&&this.revalidateInBackground(o,e,r,a),n.clone();let i=await fetch(e,r);return i.ok&&await this.set(o,i.clone(),a??this.defaultCacheControl),i})().finally(()=>{this.inFlightRequests.delete(o)});return this.inFlightRequests.set(o,s),s}async delete(e){try{return await(await caches.open(this.cacheName)).delete(e)}catch(r){return console.warn("Cache delete error:",r),!1}}async clear(){try{let e=await caches.open(this.cacheName),r=await e.keys();await Promise.all(r.map(a=>e.delete(a)))}catch(e){console.warn("Cache clear error:",e)}}async keys(){try{return(await(await caches.open(this.cacheName)).keys()).map(a=>a.url)}catch(e){return console.warn("Cache keys error:",e),[]}}async has(e){try{let r=await caches.open(this.cacheName),a=await r.match(e);return a&&this.isExpired(a)?(await r.delete(e),!1):a!==void 0}catch(r){return console.warn("Cache has error:",r),!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),r=await e.keys(),a=0;for(let s of r){let n=await e.match(s);n&&this.isExpired(n)&&(await e.delete(s),a++)}let o=r.length-a;return{removed:a,remaining:o}}catch(e){return console.warn("Cache cleanup error:",e),{removed:0,remaining:0}}}async getCacheKey(e,r){let o=`${this.getInputUrl(e)}/${JSON.stringify(r)}`,n=new TextEncoder().encode(o),i=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(i)).map(f=>f.toString(16).padStart(2,"0")).join("")}getInputUrl(e){return e instanceof URL?e.toString():typeof e=="string"?e:e.url}isExpired(e){let r=e.headers.get("Cache-Control");if(!r)return!1;let a=this.parseMaxAge(r),o=this.parseStaleWhileRevalidate(r);if(a===null)return!1;let s=e.headers.get("Date");if(!s)return!1;let n=new Date(s).getTime(),l=(Date.now()-n)/1e3,h=a+(o??0);return l>h}isStaleButRevalidatable(e){let r=e.headers.get("Cache-Control");if(!r)return!1;let a=this.parseMaxAge(r),o=this.parseStaleWhileRevalidate(r);if(a===null||o===null)return!1;let s=e.headers.get("Date");if(!s)return!1;let n=new Date(s).getTime(),l=(Date.now()-n)/1e3;return l>a&&l<=a+o}async revalidateInBackground(e,r,a,o){if(this.revalidationPromises.has(e))return;let s=(async()=>{try{let n=await fetch(r,a);n.ok&&await this.set(e,n.clone(),o??this.defaultCacheControl)}catch(n){console.warn("Background revalidation error:",n)}finally{this.revalidationPromises.delete(e)}})();this.revalidationPromises.set(e,s)}parseMaxAge(e){let r=new RegExp(/max-age=(\d+)/).exec(e);return r?parseInt(r[1],10):null}parseStaleWhileRevalidate(e){let r=new RegExp(/stale-while-revalidate=(\d+)/).exec(e);return r?parseInt(r[1],10):null}createCacheableResponse(e,r){let a=new Headers(e.headers);return a.set("Cache-Control",r),a.has("Date")||a.set("Date",new Date().toUTCString()),new Response(e.body,{status:e.status,statusText:e.statusText,headers:a})}};var sr={"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"},pt=d((t,e,r)=>{t=t.toUpperCase();let a=new URL(r).pathname;return t==="GET"||e<200||e>=300?void 0:Object.entries(sr).find(([s])=>{let[n,i]=s.split(" ");return n!==t?!1:new RegExp(i).test(a)})?.[1]},"getEventName");var p=new $(self),L=new x("swish-api","max-age=60, stale-while-revalidate=3600");L.cleanupExpiredEntries().catch(t=>{console.warn("Cache initialization cleanup error:",t)});var u=_e({config:{fetch:d((t,e)=>(t instanceof Request?t.method:e?.method??"GET")==="GET"?L.fetchWithCache(t,e):fetch(t,e),"fetch")},responseInterceptor:d(async(t,e)=>(ir(t),await dr(e,t),t),"responseInterceptor")}),Q=new x("storefront-api","max-age=60, stale-while-revalidate=3600");Q.cleanupExpiredEntries().catch(t=>{console.warn("Cache initialization cleanup error:",t)});var A=new H({fetch:d((t,e)=>e?.method==="OPTIONS"?fetch(t,e):(t instanceof Request?t.method:e?.method??"GET")==="GET"?Q.fetchWithCache(t,e):fetch(t,e),"fetch")}),W=new x("ajax-api","max-age=60, stale-while-revalidate=3600");W.cleanupExpiredEntries().catch(t=>{console.warn("Cache initialization cleanup error:",t)});var V=new q({fetch:d((t,e)=>e?.method==="OPTIONS"?fetch(t,e):(t instanceof Request?t.method:e?.method??"GET")==="GET"?W.fetchWithCache(t,e):fetch(t,e),"fetch")});function ir(t){let e=t.headers.get("Set-Profile");e?(u.setProfile(e),p.call("storeProfile",e)):e===""&&p.call("deleteProfile")}d(ir,"processProfileHeader");async function dr(t,e){let r=pt(t.method,e.status,t.url);if(!r)return;await L.clear();let a=await e.clone().text();if(e.headers.get("Content-Type")?.includes("application/json"))try{a=JSON.parse(a).data}catch(o){console.warn(o)}p.call("events.publish",r,a)}d(dr,"processSwishApiEvent");p.addMethod("api.setConfig",u.setConfig.bind(u));p.addMethod("api.setProfile",u.setProfile.bind(u));p.addMethod("api.items.list",u.items.list.bind(u));p.addMethod("api.items.create",u.items.create.bind(u));p.addMethod("api.items.delete",u.items.delete.bind(u));p.addMethod("api.items.findById",u.items.findById.bind(u));p.addMethod("api.items.deleteById",u.items.deleteById.bind(u));p.addMethod("api.items.updateById",u.items.updateById.bind(u));p.addMethod("api.items.setListsById",u.items.setListsById.bind(u));p.addMethod("api.lists.list",u.lists.list.bind(u));p.addMethod("api.lists.findById",u.lists.findById.bind(u));p.addMethod("api.lists.create",u.lists.create.bind(u));p.addMethod("api.lists.deleteById",u.lists.deleteById.bind(u));p.addMethod("api.lists.updateById",u.lists.updateById.bind(u));p.addMethod("api.lists.orderItems",u.lists.orderItems.bind(u));p.addMethod("api.lists.addItemsToList",u.lists.addItemsToList.bind(u));p.addMethod("api.profiles.customerAccountsVersion",u.profiles.customerAccountsVersion.bind(u));p.addMethod("api.profiles.createToken",u.profiles.createToken.bind(u));p.addMethod("api.profiles.identify",u.profiles.identify.bind(u));p.addMethod("storefront.setConfig",A.setConfig.bind(A));p.addMethod("storefront.loadProductOptions",A.loadProductOptions.bind(A));p.addMethod("storefront.loadSelectedVariant",A.loadSelectedVariant.bind(A));p.addMethod("storefront.loadProductCardData",A.loadProductCardData.bind(A));p.addMethod("storefront.loadProductDetailData",A.loadProductDetailData.bind(A));p.addMethod("storefront.loadProductImages",A.loadProductImages.bind(A));p.addMethod("ajax.setConfig",V.setConfig.bind(V));p.addMethod("ajax.fetchCart",V.fetchCart.bind(V));p.addMethod("ajax.addToCart",V.addToCart.bind(V));p.addMethod("cache.clearSwishApi",async()=>{await L.clear()});p.addMethod("cache.clearStorefrontApi",async()=>{await Q.clear()});p.addMethod("cache.clearAjaxApi",async()=>{await W.clear()});p.addMethod("cache.clearAll",async()=>{await Promise.all([L.clear(),Q.clear(),W.clear()])});