UNPKG

craft-commerce-headless-sdk

Version:

Craft Commerce Headless SDK provides tools to integrate Craft Commerce in headless environments, focusing on building API-driven checkout experiences.

2 lines (1 loc) 5.86 kB
(function(c,l){typeof exports=="object"&&typeof module<"u"?l(exports):typeof define=="function"&&define.amd?define(["exports"],l):(c=typeof globalThis<"u"?globalThis:c||self,l(c.CraftCommerceHeadlessSdk={}))})(this,function(c){"use strict";var F=Object.defineProperty;var L=(c,l,f)=>l in c?F(c,l,{enumerable:!0,configurable:!0,writable:!0,value:f}):c[l]=f;var b=(c,l,f)=>(L(c,typeof l!="symbol"?l+"":l,f),f);const l=t=>/^[a-zA-Z0-9.-]+$/.test(t),f=(t,o)=>{var e;if(!l(o))return null;const a=`; ${document.cookie}`.split(`; ${t}=`);return a.length===2&&((e=a.pop())==null?void 0:e.split(";").shift())||null};class d extends Error{constructor(m,a,e,s,u,r){super(m);b(this,"status");b(this,"data");b(this,"endpoint");b(this,"method");b(this,"retryCount");this.name="CraftCommerceSdkError",this.status=a,this.data=e,this.endpoint=s,this.method=u,this.retryCount=r,Object.setPrototypeOf(this,d.prototype)}}function g(t,...o){t&&console.log(...o)}function O(t){return t.endsWith("/")?t:t+"/"}async function U(t,o){let a=f("CRAFT_CSRF_TOKEN",t);if(a)return a;const e=await fetch(`${t}actions/users/session-info`,{headers:{Accept:"application/json"},credentials:"include"});if(!e.ok){const u=await e.json().catch(()=>({})),r=u.message||`Failed to fetch CSRF token with status ${e.status}`;throw new d(r,e.status,u,"actions/users/session-info","GET",0)}return(await e.json()).csrfTokenValue}async function $(t,o,m,a){let e="API request failed",s={};try{(t.headers.get("Content-Type")||"").includes("application/json")?(s=await t.json(),s.error?e=s.error:s.errors?e=Object.values(s.errors).flat().join(", "):e=s.message||e):e=await t.text()||t.statusText||e}catch{e=t.statusText||e}return e=`(${t.status}) ${e}`,new d(e,t.status,s,o,m,a)}function x(t){const o=!!t.enableLogging,m=t.maxRetries??1,a=O(t.apiBaseUrl);let e=null;g(o,"Craft Commerce using base URL:",a);const s=async(r,y,n={},p=0)=>{try{e||(e=await U(a,o));const{accept:w="application/json",contentType:P="application/json",...h}=n,S=y!==void 0?JSON.stringify(y):void 0;g(o,"Craft Commerce POST request:",r,{retryCount:p,body:S});const i=await fetch(`${a}${r}`,{method:"POST",headers:{"Content-Type":P,Accept:w,"X-CSRF-Token":e,"X-Requested-With":"XMLHttpRequest",...h},body:S,credentials:"include"});if(!i.ok){let T={};if((i.headers.get("Content-Type")||"").includes("application/json")?T=await i.json().catch(()=>({})):T={message:await i.text()},g(o,"Craft Commerce POST error data:",T),p<m&&i.status===400&&T.message==="Unable to verify your data submission.")return console.warn("CSRF token invalid. Retrying request..."),e=null,s(r,y,n,p+1);throw new d(T.message||`API request failed with status ${i.status}`,i.status,T,r,"POST",p)}if(w==="application/pdf")return await i.blob();const v=await i.text();if(!v)throw new d(`(${i.status}) Empty response`,i.status,{},r,"POST",p);try{return JSON.parse(v)}catch{return v}}catch(w){throw g(o,"Craft Commerce POST caught error:",w),w instanceof d?w:new d(w.message||"Unknown error",0,{},r,"POST",p)}};return{post:s,get:async(r,y={},n={})=>{try{const{accept:p="application/json",...w}=n,P=new URL(r,a);Object.keys(y).forEach(i=>{y[i]!==void 0&&y[i]!==null&&P.searchParams.append(i,String(y[i]))}),g(o,"Craft Commerce GET request:",P.toString());const h=await fetch(P.toString(),{method:"GET",headers:{Accept:p,"X-Requested-With":"XMLHttpRequest",...w},credentials:"include"});if(!h.ok)throw console.error(`API GET error (${r}):`,await h.text()),await $(h,r,"GET",0);if(p==="application/pdf")return await h.blob();const S=await h.text();if(!S)throw new d(`(${h.status}) Empty response`,h.status,{},r,"GET",0);try{return JSON.parse(S)}catch{return S}}catch(p){throw g(o,"Craft Commerce GET caught error:",p),p instanceof d?p:new d(p.message||"Unknown error",0,{},r,"GET",0)}}}}const C=t=>({loginUser:async n=>await t.post("actions/users/login",n),saveUser:async n=>await t.post("actions/users/save-user",n),uploadUserPhoto:async n=>await t.post("actions/users/upload-user-photo",n),sendPasswordResetEmail:async n=>await t.post("actions/users/send-password-reset-email",n),setPassword:async n=>await t.post("actions/users/set-password",n),saveAddress:async n=>await t.post("actions/users/save-address",n),deleteAddress:async n=>await t.post("actions/users/delete-address",n),getSessionInfo:async()=>await t.get("actions/users/session-info")}),k=t=>({completeCart:async u=>await t.post("actions/commerce/cart/complete",u),getCart:async()=>await t.get("actions/commerce/cart/get-cart"),loadCart:async u=>await t.post("actions/commerce/cart/load-cart",u),forgetCart:async()=>await t.post("actions/commerce/cart/forget-cart",void 0,{accept:"text/html"}),updateCart:async u=>await t.post("actions/commerce/cart/update-cart",u)}),E=t=>({addPaymentSource:async e=>await t.post("actions/commerce/payment-sources/add",e),setPrimaryPaymentSource:async e=>await t.post("actions/commerce/payment-sources/set-primary-payment-source",e),deletePaymentSource:async e=>await t.post("actions/commerce/payment-sources/delete",e)}),R=t=>({completePayment:async a=>await t.get("actions/commerce/payments/complete-payment",a),pay:async a=>await t.post("actions/commerce/payments/pay",a)}),j=t=>({subscribe:async s=>await t.post("actions/commerce/subscriptions/subscribe",s),cancel:async s=>await t.post("actions/commerce/subscriptions/cancel",s),switchPlan:async s=>await t.post("actions/commerce/subscriptions/switch",s),reactivate:async s=>await t.post("actions/commerce/subscriptions/reactivate",s)}),A=({apiBaseUrl:t,enableLogging:o=!1,maxRetries:m})=>{const e=x({apiBaseUrl:t,enableLogging:!!o,maxRetries:m}),s=C(e),u=k(e),r=E(e),y=R(e),n=j(e);return{client:e,users:s,cart:u,paymentSources:r,payment:y,subscriptions:n}};c.cart=k,c.craftCommerceHeadlessSdk=A,c.payment=R,c.paymentSources=E,c.subscriptions=j,c.users=C,Object.defineProperty(c,Symbol.toStringTag,{value:"Module"})});