b23-lib 3.0.6 → 3.0.8
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/Auth/index.js +1 -1
- package/dist/Auth/index.js.map +1 -1
- package/dist/Auth/index.mjs +1 -1
- package/dist/Classes/Address.d.mts +1 -1
- package/dist/Classes/Address.d.ts +1 -1
- package/dist/Classes/Address.js +1 -1
- package/dist/Classes/Address.js.map +1 -1
- package/dist/Classes/Address.mjs +1 -1
- package/dist/Classes/Base.d.mts +1 -1
- package/dist/Classes/Base.d.ts +1 -1
- package/dist/Classes/Base.js +1 -1
- package/dist/Classes/Base.js.map +1 -1
- package/dist/Classes/Base.mjs +1 -1
- package/dist/Classes/Cart.d.mts +1 -1
- package/dist/Classes/Cart.d.ts +1 -1
- package/dist/Classes/Cart.js +1 -1
- package/dist/Classes/Cart.js.map +1 -1
- package/dist/Classes/Cart.mjs +1 -1
- package/dist/Classes/Charge.d.mts +46 -1
- package/dist/Classes/Charge.d.ts +46 -1
- package/dist/Classes/Charge.js +1 -1
- package/dist/Classes/Charge.js.map +1 -1
- package/dist/Classes/Charge.mjs +1 -1
- package/dist/Classes/Common.d.mts +1 -1
- package/dist/Classes/Common.d.ts +1 -1
- package/dist/Classes/Coupon.d.mts +1 -1
- package/dist/Classes/Coupon.d.ts +1 -1
- package/dist/Classes/Coupon.js +1 -1
- package/dist/Classes/Coupon.js.map +1 -1
- package/dist/Classes/Coupon.mjs +1 -1
- package/dist/Classes/Customer.d.mts +1 -1
- package/dist/Classes/Customer.d.ts +1 -1
- package/dist/Classes/Customer.js +1 -1
- package/dist/Classes/Customer.js.map +1 -1
- package/dist/Classes/Customer.mjs +1 -1
- package/dist/Classes/CustomerAddress.d.mts +1 -1
- package/dist/Classes/CustomerAddress.d.ts +1 -1
- package/dist/Classes/CustomerAddress.js +1 -1
- package/dist/Classes/CustomerAddress.js.map +1 -1
- package/dist/Classes/CustomerAddress.mjs +1 -1
- package/dist/Classes/CustomerAddress.mjs.map +1 -1
- package/dist/Classes/Inventory.d.mts +1 -1
- package/dist/Classes/Inventory.d.ts +1 -1
- package/dist/Classes/Inventory.js +1 -1
- package/dist/Classes/Inventory.js.map +1 -1
- package/dist/Classes/Inventory.mjs +1 -1
- package/dist/Classes/Inventory.mjs.map +1 -1
- package/dist/Classes/LineItem.d.mts +1 -1
- package/dist/Classes/LineItem.d.ts +1 -1
- package/dist/Classes/LineItem.js +1 -1
- package/dist/Classes/LineItem.js.map +1 -1
- package/dist/Classes/LineItem.mjs +1 -1
- package/dist/Classes/Order.d.mts +5 -5
- package/dist/Classes/Order.d.ts +5 -5
- package/dist/Classes/Order.js +1 -1
- package/dist/Classes/Order.js.map +1 -1
- package/dist/Classes/Order.mjs +1 -1
- package/dist/Classes/Order.mjs.map +1 -1
- package/dist/Classes/Payment.d.mts +1 -1
- package/dist/Classes/Payment.d.ts +1 -1
- package/dist/Classes/Payment.js +1 -1
- package/dist/Classes/Payment.js.map +1 -1
- package/dist/Classes/Payment.mjs +1 -1
- package/dist/Classes/Price.d.mts +1 -1
- package/dist/Classes/Price.d.ts +1 -1
- package/dist/Classes/Product.d.mts +1 -1
- package/dist/Classes/Product.d.ts +1 -1
- package/dist/Classes/Product.js +1 -1
- package/dist/Classes/Product.js.map +1 -1
- package/dist/Classes/Product.mjs +1 -1
- package/dist/Classes/ShoppingContainer.d.mts +43 -2
- package/dist/Classes/ShoppingContainer.d.ts +43 -2
- package/dist/Classes/ShoppingContainer.js +1 -1
- package/dist/Classes/ShoppingContainer.js.map +1 -1
- package/dist/Classes/ShoppingContainer.mjs +1 -1
- package/dist/Classes/TaxRule.d.mts +1 -1
- package/dist/Classes/TaxRule.d.ts +1 -1
- package/dist/Classes/TaxRule.js +1 -1
- package/dist/Classes/TaxRule.js.map +1 -1
- package/dist/Classes/TaxRule.mjs +1 -1
- package/dist/Classes/TieredPrice.d.mts +1 -1
- package/dist/Classes/TieredPrice.d.ts +1 -1
- package/dist/Classes/TieredPrice.js +1 -1
- package/dist/Classes/TieredPrice.js.map +1 -1
- package/dist/Classes/TieredPrice.mjs +1 -1
- package/dist/{Common-Bd8Xv8x4.d.mts → Common-XM4zQpWC.d.mts} +1 -1
- package/dist/{Common-CXp_zjft.d.ts → Common-uAn7Sunn.d.ts} +1 -1
- package/dist/chunk-3RTEHBPX.mjs +2 -0
- package/dist/chunk-3RTEHBPX.mjs.map +1 -0
- package/dist/chunk-EB5IQLSA.mjs +2 -0
- package/dist/chunk-EB5IQLSA.mjs.map +1 -0
- package/dist/chunk-FSAVZRS6.mjs +2 -0
- package/dist/chunk-FSAVZRS6.mjs.map +1 -0
- package/dist/{chunk-YSUBOEFT.mjs → chunk-HX32EJ3F.mjs} +2 -2
- package/dist/{chunk-YSUBOEFT.mjs.map → chunk-HX32EJ3F.mjs.map} +1 -1
- package/dist/{chunk-6VRUVGN3.mjs → chunk-L3CNGDFJ.mjs} +2 -2
- package/dist/chunk-L3CNGDFJ.mjs.map +1 -0
- package/dist/chunk-NNMLXCUS.mjs +2 -0
- package/dist/chunk-NNMLXCUS.mjs.map +1 -0
- package/dist/chunk-UMVN5K5M.mjs +2 -0
- package/dist/chunk-UMVN5K5M.mjs.map +1 -0
- package/dist/chunk-UXZBULDS.mjs +2 -0
- package/dist/chunk-UXZBULDS.mjs.map +1 -0
- package/dist/chunk-XBFSNBKL.mjs +2 -0
- package/dist/chunk-XBFSNBKL.mjs.map +1 -0
- package/dist/index.d.mts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-2ZQIRKRB.mjs +0 -2
- package/dist/chunk-2ZQIRKRB.mjs.map +0 -1
- package/dist/chunk-52Y5EI7O.mjs +0 -2
- package/dist/chunk-52Y5EI7O.mjs.map +0 -1
- package/dist/chunk-6KCJVEZD.mjs +0 -2
- package/dist/chunk-6KCJVEZD.mjs.map +0 -1
- package/dist/chunk-6VRUVGN3.mjs.map +0 -1
- package/dist/chunk-DLLGHKS5.mjs +0 -2
- package/dist/chunk-DLLGHKS5.mjs.map +0 -1
- package/dist/chunk-HR5HHV6O.mjs +0 -2
- package/dist/chunk-HR5HHV6O.mjs.map +0 -1
- package/dist/chunk-Y5D6RHTJ.mjs +0 -2
- package/dist/chunk-Y5D6RHTJ.mjs.map +0 -1
- package/dist/chunk-YKRWZ24N.mjs +0 -2
- package/dist/chunk-YKRWZ24N.mjs.map +0 -1
package/dist/Auth/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a as a$1,b,d,c as c$1}from'../chunk-AMIRIUMH.mjs';import {a as a$2}from'../chunk-
|
|
1
|
+
import {a as a$1,b,d,c as c$1}from'../chunk-AMIRIUMH.mjs';import {a as a$2}from'../chunk-EB5IQLSA.mjs';import'../chunk-XBFSNBKL.mjs';import'../chunk-XHGUVYQO.mjs';import'../chunk-FC4P26U3.mjs';import'../chunk-RSTZJZSQ.mjs';import'../chunk-XPKK6DFA.mjs';import'../chunk-UXZBULDS.mjs';import {importPKCS8,SignJWT,importSPKI,jwtVerify,decodeJwt}from'jose';import a from'assert';var c=class l{static instance=null;id;type;token;initializedAt;lambdaName;requestId;constructor(e,t,i,r){this.id=e,this.type=t,this.token=i,this.lambdaName=process.env.AWS_LAMBDA_FUNCTION_NAME,this.initializedAt=new Date;}static getInstance(){return a(l.instance,a$1.AUTH_CONTEXT_NOT_INITIALIZED),l.instance}static init(e,t,i,r){return l.instance=new l(e,t,i,r),l.instance}static uninit(){l.instance=null;}getId(){return this.id}getType(){return this.type}getToken(){return this.token}getLambdaName(){return this.lambdaName}getRequestId(){return this.requestId}getInitializedAt(){return this.initializedAt}getSystemID(e){let t=this.lambdaName||e;return this.requestId?`${t} - ${this.requestId}`:t}};var K={userTokenAge:"30 days",userPrivateKeys:"[]",userPublicKeys:"[]",anonymousTokenAge:"30 days",anonymousPrivateKeys:"[]",anonymousPublicKeys:"[]",systemTokenAge:"5 min",systemPrivateKeys:"[]",systemPublicKeys:"[]",adminTokenAge:"30 days",adminPrivateKeys:"[]",adminPublicKeys:"[]",cdnKeys:"[]"},U=(n=>(n.ANON="Anon",n.USER="User",n.SYSTEM="System",n.ADMIN="Admin",n.CDN="CDN",n))(U||{}),v={allowAnonymous:!1,allowSystem:!0,allowUser:!0,allowCDN:!1},N=class{userTokenAge;userPrivateKeys;userPublicKeys;anonymousTokenAge;anonymousPrivateKeys;anonymousPublicKeys;systemTokenAge;systemPrivateKeys;systemPublicKeys;adminTokenAge;adminPrivateKeys;adminPublicKeys;cdnKeys;constructor(e=K){let{userTokenAge:t,userPrivateKeys:i,userPublicKeys:r,anonymousTokenAge:n,anonymousPrivateKeys:g,anonymousPublicKeys:h,systemTokenAge:m,systemPrivateKeys:T,systemPublicKeys:A,adminTokenAge:u,adminPrivateKeys:d,adminPublicKeys:S,cdnKeys:f}={...K,...e};this.userTokenAge=t,this.userPrivateKeys=this.parseKeyArray(i,"user private"),this.userPublicKeys=this.parseKeyArray(r,"user public"),this.anonymousTokenAge=n,this.anonymousPrivateKeys=this.parseKeyArray(g,"anonymous private"),this.anonymousPublicKeys=this.parseKeyArray(h,"anonymous public"),this.systemTokenAge=m,this.systemPrivateKeys=this.parseKeyArray(T,"system private"),this.systemPublicKeys=this.parseKeyArray(A,"system public"),this.adminTokenAge=u,this.adminPrivateKeys=this.parseKeyArray(d,"admin private"),this.adminPublicKeys=this.parseKeyArray(S,"admin public"),this.cdnKeys=this.parseKeyArray(f,"cdn"),this.logWarnings();}parseKeyArray(e,t){try{let i=JSON.parse(e);return !Array.isArray(i)||!i.every(r=>typeof r=="string")?(b.logError("AuthUtility",`Invalid format for ${t} keys in config: Expected stringified array of strings.`),[]):i}catch(i){return b.logError("AuthUtility",`Failed to parse ${t} keys from config: ${i}`),[]}}logWarnings(){let e=(t,i,r)=>i.length>r&&b.logWarning("AuthUtility",`More than ${r} ${t} keys provided. This is not recommended.`);e("user private",this.userPrivateKeys,3),e("user public",this.userPublicKeys,3),e("anonymous private",this.anonymousPrivateKeys,1),e("anonymous public",this.anonymousPublicKeys,3),e("system private",this.systemPrivateKeys,1),e("system public",this.systemPublicKeys,3),e("admin private",this.adminPrivateKeys,1),e("admin public",this.adminPublicKeys,3);}async createSignedJWT(e,t,i){let r=await importPKCS8(t,"RS256");return await new SignJWT(e).setProtectedHeader({alg:"RS256"}).setExpirationTime(i).setIssuedAt().sign(r)}async verifySignedJWT(e,t,i){for(let r=t.length-1;r>=0;r--)try{let n=await importSPKI(t[r],"RS256");return (await jwtVerify(e,n,{clockTolerance:30,maxTokenAge:i})).payload}catch(n){if(r===0)throw n;continue}throw new Error(a$1.INVALID_TOKEN)}async createAnonymousToken(e,t){a(this.anonymousPrivateKeys.length,a$1.ANONYMOUS_PRIVATE_KEY_NOT_FOUND),a(a$2.isUUID(e),a$1.INVALID_UUID);let i={id:e,type:"Anon",...t};return await this.createSignedJWT(i,this.anonymousPrivateKeys[this.anonymousPrivateKeys.length-1],this.anonymousTokenAge)}async verifyAnonymousToken(e){a(this.anonymousPublicKeys.length,a$1.ANONYMOUS_PUBLIC_KEY_NOT_FOUND);let t=await this.verifySignedJWT(e,this.anonymousPublicKeys,this.anonymousTokenAge);return a(t.type==="Anon",a$1.INVALID_AUTH_TYPE),t}async createUserToken(e,t){a(this.userPrivateKeys.length,a$1.USER_PRIVATE_KEY_NOT_FOUND),a(a$2.isUUID(e),a$1.INVALID_UUID);let i={id:e,type:"User",...t};return await this.createSignedJWT(i,this.userPrivateKeys[this.userPrivateKeys.length-1],this.userTokenAge)}async verifyUserToken(e){a(this.userPublicKeys.length,a$1.USER_PUBLIC_KEY_NOT_FOUND);let t=await this.verifySignedJWT(e,this.userPublicKeys,this.userTokenAge);return a(t.type==="User",a$1.INVALID_AUTH_TYPE),t}async createSystemToken(e,t){a(this.systemPrivateKeys.length,a$1.SYSTEM_PRIVATE_KEY_NOT_FOUND);let i={id:e,type:"System",...t};return await this.createSignedJWT(i,this.systemPrivateKeys[this.systemPrivateKeys.length-1],this.systemTokenAge)}async verifySystemToken(e){a(this.systemPublicKeys.length,a$1.USER_PUBLIC_KEY_NOT_FOUND);let t=await this.verifySignedJWT(e,this.systemPublicKeys,this.systemTokenAge);return a(t.type==="System",a$1.INVALID_AUTH_TYPE),t}async createAdminToken(e,t,i){a(this.adminPrivateKeys.length,a$1.ADMIN_PRIVATE_KEY_NOT_FOUND),a(a$2.isEmail(e),a$1.INVALID_EMAIL),a(a$2.isURL(t),a$1.INVALID_VERIFIER);let r={id:e,type:"Admin",verifier:t,...i};return await this.createSignedJWT(r,this.adminPrivateKeys[this.adminPrivateKeys.length-1],this.adminTokenAge)}async verifyAdminToken(e,t,i){a(this.adminPublicKeys.length,a$1.ADMIN_PUBLIC_KEY_NOT_FOUND);let r=await this.verifySignedJWT(e,this.adminPublicKeys,this.adminTokenAge);if(a(r.type==="Admin",a$1.INVALID_AUTH_TYPE),i){let n=await d(r.verifier,"","POST",{},{token:e,permissions:t});if(a(n.data.isTokenValid===!0,a$1.INVALID_TOKEN),n.data.hasPermissions!==!0)throw c$1.generateError(403,a$1.INVALID_PERMISSIONS)}return r}async verifyCDNToken(e){return a(this.cdnKeys.includes(e),a$1.INVALID_TOKEN),{id:e,type:"CDN"}}AuthMiddleware(e=v,t=[]){let{allowAnonymous:i,allowSystem:r,allowUser:n,allowCDN:g}={...v,...e};return async(h,m,T)=>{try{let[A,u]=h.get("Authorization")?.split(" ")||[];if(!u)throw new Error(a$1.INVALID_TOKEN);let d;switch(A){case"Anon":if(!i)throw c$1.generateError(403,a$1.ANONYMOUS_SESSION_NOT_ALLOWED);d=await this.verifyAnonymousToken(u);break;case"User":if(!n)throw c$1.generateError(403,a$1.USER_SESSION_NOT_ALLOWED);d=await this.verifyUserToken(u);break;case"System":if(!r)throw c$1.generateError(403,a$1.SYSTEM_SESSION_NOT_ALLOWED);d=await this.verifySystemToken(u);break;case"Admin":d=await this.verifyAdminToken(u,t,!0);break;case"CDN":if(!g)throw c$1.generateError(403,a$1.CDN_SESSION_NOT_ALLOWED);d=await this.verifyCDNToken(u);break;default:throw c$1.generateError(403,a$1.INVALID_AUTH_TYPE)}T();}catch(A){b.logError("AuthMiddleware",A),c$1.handleException("AuthMiddleware",c$1.generateError(401,A.error||a$1.TOKEN_EXPIRED,!0),m);}}}decodeJWTPayloadWithJose(e){if(!e||typeof e!="string")return b.logError("AuthContextMiddleware","Invalid token provided for decoding."),null;try{return decodeJwt(e)}catch(t){return b.logError("AuthContextMiddleware",`Failed to decode JWT payload: ${t}`),null}}AuthContextMiddleware(){return async(e,t,i)=>{try{let[r,n]=e.get("Authorization")?.split(" ")||[],g=r==="CDN"?{id:n,type:"CDN"}:r?this.decodeJWTPayloadWithJose(n):{},h=c.init(g?.id||n,g?.type||r,n,e.get("x-request-id"));b.logMessage("AuthContextMiddleware",`AuthContext initialized: ${h.getType()||"No-Type"} - ${h.getId()||"No-Id"}`),t.on("finish",()=>{b.logMessage("AuthContextMiddleware","Uninitializing AuthContext"),c.uninit();}),i();}catch(r){b.logError("AuthContextMiddleware",r),c$1.handleException("AuthContextMiddleware",c$1.generateError(500,r.error||a$1.INTERNAL_SERVER_ERROR,!0),t);}}}},j=N;export{c as AuthContext,U as AuthType,v as DefaultAuthMiddlewareConfig,K as DefaultAuthUtilityConfig,j as default};//# sourceMappingURL=index.mjs.map
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
package/dist/Classes/Address.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var r=class{customFields;constructor(e,t=new Date){this.customFields={...e.customFields};}getCustomField(e){
|
|
1
|
+
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var o=r=>structuredClone(r),d=class{customFields;constructor(e,t=new Date){this.customFields={...e.customFields};}getCustomField(e){let t=this.customFields[e];return t==null?t:o(t)}setCustomField(e,t){this.customFields[e]=t;}getAllCustomFields(){return o(this.customFields)}},s=class extends d{version;createdAt;modifiedAt;modifiedBy;constructor(e,t=new Date){super(e),this.version=e.version??1,this.createdAt=e.createdAt&&!isNaN(Date.parse(e.createdAt))?new Date(e.createdAt).toISOString():t.toISOString(),this.modifiedAt=e.modifiedAt&&!isNaN(Date.parse(e.modifiedAt))?new Date(e.modifiedAt).toISOString():t.toISOString(),this.modifiedBy={...e.modifiedBy};}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return {...this.modifiedBy}}setModifiedBy(e,t,g,i){this.modifiedBy={id:e,authType:t,requestId:g,lambdaName:i};}};var a=(i=>(i.BILLING="billing",i.SHIPPING="shipping",i.BILLING_AND_SHIPPING="billing&shipping",i.NONE="none",i))(a||{}),n=class extends s{id;firstName;lastName;company;phone;email;addressLine1;addressLine2;city;postalCode;state;country;isBillingAddress;isShippingAddress;constructor(e,t=new Date){super(e,t),this.id=e.id,this.firstName=e.firstName,this.lastName=e.lastName||"",this.company=e.company||"",this.phone=e.phone,this.email=e.email,this.addressLine1=e.addressLine1,this.addressLine2=e.addressLine2||"",this.city=e.city,this.postalCode=e.postalCode,this.state=e.state,this.country=e.country,this.isBillingAddress=e.isBillingAddress,this.isShippingAddress=e.isShippingAddress;}getDetails(){return {...super.getDetails(),id:this.getId(),firstName:this.getFirstName(),lastName:this.getLastName(),company:this.getCompany(),phone:this.getPhone(),email:this.getEmail(),addressLine1:this.getAddressLine1(),addressLine2:this.getAddressLine2(),city:this.getCity(),postalCode:this.getPostalCode(),state:this.getState(),country:this.getCountry(),isBillingAddress:this.getIsBillingAddress(),isShippingAddress:this.getIsShippingAddress()}}getId(){return this.id}getFirstName(){return this.firstName}getLastName(){return this.lastName}getCompany(){return this.company}getPhone(){return this.phone}getEmail(){return this.email}getAddressLine1(){return this.addressLine1}getAddressLine2(){return this.addressLine2}getCity(){return this.city}getPostalCode(){return this.postalCode}getState(){return this.state}getCountry(){return this.country}getIsBillingAddress(){return this.isBillingAddress}getIsShippingAddress(){return this.isShippingAddress}getAddressType(){return this.isBillingAddress&&this.isShippingAddress?"billing&shipping":this.isBillingAddress?"billing":this.isShippingAddress?"shipping":"none"}static checkIfShippingAddress(e){return e==="shipping"||e==="billing&shipping"}static checkIfBillingAddress(e){return e==="billing"||e==="billing&shipping"}};exports.AddressType=a;exports.default=n;//# sourceMappingURL=Address.js.map
|
|
2
2
|
//# sourceMappingURL=Address.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/Classes/Base.ts","../../src/Classes/Address.ts"],"names":["CustomFieldModel","data","date","fieldName","value","BaseModel","id","authType","requestId","lambdaName","AddressType","AddressModel","addressType"],"mappings":"sEAWO,IAAMA,CAAAA,CAAN,KAAuB,CAClB,YACV,CAAA,WAAA,CAAYC,CAA6BC,CAAAA,CAAAA,CAAa,IAAI,IAAA,CAAQ,CAChE,IAAA,CAAK,YAAe,CAAA,CAAE,GAAGD,CAAAA,CAAK,YAAa,EAC7C,CAOA,cAAA,CAAeE,CAAwB,CAAA,CACrC,OAAO,IAAA,CAAK,YAAaA,CAAAA,CAAS,CAAK,EAAA,IACzC,CAQA,cAAA,CAAeA,CAAmBC,CAAAA,CAAAA,CAAkB,CAClD,IAAA,CAAK,YAAaD,CAAAA,CAAS,CAAIC,CAAAA,EACjC,CAMA,kBAAA,EAAmC,CACjC,OAAO,CAAE,GAAG,IAAK,CAAA,YAAa,CAChC,CACF,CAsBqBC,CAAAA,CAAAA,CAArB,cAAuCL,CAAiB,CAC5C,OAAA,CACA,SACA,CAAA,UAAA,CACA,UAQV,CAAA,WAAA,CAAYC,CAAsBC,CAAAA,CAAAA,CAAa,IAAI,IAAA,CAAQ,CACzD,KAAA,CAAMD,CAAI,CAAA,CACV,IAAK,CAAA,OAAA,CAAUA,CAAK,CAAA,OAAA,EAAW,CAC/B,CAAA,IAAA,CAAK,SAAYA,CAAAA,CAAAA,CAAK,SAAa,EAAA,CAAC,KAAM,CAAA,IAAA,CAAK,KAAMA,CAAAA,CAAAA,CAAK,SAAS,CAAC,CAElE,CAAA,IAAI,IAAKA,CAAAA,CAAAA,CAAK,SAAS,CAAA,CAAE,WAAY,EAAA,CAErCC,CAAK,CAAA,WAAA,EACP,CAAA,IAAA,CAAK,UAAaD,CAAAA,CAAAA,CAAK,UAAc,EAAA,CAAC,KAAM,CAAA,IAAA,CAAK,KAAMA,CAAAA,CAAAA,CAAK,UAAU,CAAC,CACnE,CAAA,IAAI,IAAKA,CAAAA,CAAAA,CAAK,UAAU,CAAA,CAAE,WAAY,EAAA,CACtCC,CAAK,CAAA,WAAA,EAET,CAAA,IAAA,CAAK,UAAa,CAAA,CAAE,GAAGD,CAAAA,CAAK,UAAW,EACzC,CAMA,UAAA,EAAuB,CACrB,OAAO,CACL,YAAA,CAAc,IAAK,CAAA,kBAAA,EACnB,CAAA,OAAA,CAAS,IAAK,CAAA,UAAA,EACd,CAAA,SAAA,CAAW,IAAK,CAAA,YAAA,EAChB,CAAA,UAAA,CAAY,IAAK,CAAA,aAAA,EACjB,CAAA,UAAA,CAAY,IAAK,CAAA,aAAA,EACnB,CACF,CAMA,UAAA,EAAqB,CACnB,OAAO,IAAK,CAAA,OACd,CAMA,YAAA,EAAuB,CACrB,OAAO,IAAK,CAAA,SACd,CAMA,gBAAA,EAA2B,CACzB,OAAO,IAAI,IAAA,CAAK,IAAK,CAAA,SAAS,CAAE,CAAA,OAAA,EAClC,CAOA,aAAwB,EAAA,CACtB,OAAO,IAAA,CAAK,UACd,CAMA,iBAA4B,EAAA,CAC1B,OAAO,IAAI,IAAK,CAAA,IAAA,CAAK,UAAU,CAAA,CAAE,OAAQ,EAC3C,CAMA,aAAA,EAA4B,CAC1B,OAAO,CAAE,GAAG,IAAK,CAAA,UAAW,CAC9B,CAMA,aAAcK,CAAAA,CAAAA,CAAaC,CAAqBC,CAAAA,CAAAA,CAAoBC,CAA2B,CAAA,CAC7F,IAAK,CAAA,UAAA,CAAa,CAChB,EAAA,CAAAH,CACA,CAAA,QAAA,CAAAC,CACA,CAAA,SAAA,CAAAC,CACA,CAAA,UAAA,CAAAC,CACF,EACF,CACF,CAAA,CCrKYC,IAAAA,CAAAA,CAAAA,CAAAA,CAAAA,GACVA,CAAA,CAAA,OAAA,CAAU,SACVA,CAAAA,CAAAA,CAAA,QAAW,CAAA,UAAA,CACXA,CAAA,CAAA,oBAAA,CAAuB,kBACvBA,CAAAA,CAAAA,CAAA,IAAO,CAAA,MAAA,CAJGA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA,CAAA,CA8BSC,CAArB,CAAA,cAA0CN,CAAU,CACxC,EACA,CAAA,SAAA,CACA,QACA,CAAA,OAAA,CACA,KACA,CAAA,KAAA,CACA,YACA,CAAA,YAAA,CACA,IACA,CAAA,UAAA,CACA,KACA,CAAA,OAAA,CACA,gBACA,CAAA,iBAAA,CAOV,WAAYJ,CAAAA,CAAAA,CAAyBC,EAAa,IAAI,IAAA,CAAQ,CAC5D,KAAA,CAAMD,CAAMC,CAAAA,CAAI,CAChB,CAAA,IAAA,CAAK,EAAKD,CAAAA,CAAAA,CAAK,EACf,CAAA,IAAA,CAAK,SAAYA,CAAAA,CAAAA,CAAK,SACtB,CAAA,IAAA,CAAK,QAAWA,CAAAA,CAAAA,CAAK,QAAY,EAAA,EAAA,CACjC,IAAK,CAAA,OAAA,CAAUA,CAAK,CAAA,OAAA,EAAW,EAC/B,CAAA,IAAA,CAAK,KAAQA,CAAAA,CAAAA,CAAK,KAClB,CAAA,IAAA,CAAK,KAAQA,CAAAA,CAAAA,CAAK,KAClB,CAAA,IAAA,CAAK,YAAeA,CAAAA,CAAAA,CAAK,YACzB,CAAA,IAAA,CAAK,YAAeA,CAAAA,CAAAA,CAAK,YAAgB,EAAA,EAAA,CACzC,IAAK,CAAA,IAAA,CAAOA,CAAK,CAAA,IAAA,CACjB,IAAK,CAAA,UAAA,CAAaA,CAAK,CAAA,UAAA,CACvB,IAAK,CAAA,KAAA,CAAQA,CAAK,CAAA,KAAA,CAClB,IAAK,CAAA,OAAA,CAAUA,CAAK,CAAA,OAAA,CACpB,IAAK,CAAA,gBAAA,CAAmBA,CAAK,CAAA,gBAAA,CAC7B,IAAK,CAAA,iBAAA,CAAoBA,CAAK,CAAA,kBAChC,CAOA,UAAA,EAA0B,CACxB,OAAO,CACL,GAAG,KAAM,CAAA,UAAA,EACT,CAAA,EAAA,CAAI,IAAK,CAAA,KAAA,EACT,CAAA,SAAA,CAAW,IAAK,CAAA,YAAA,EAChB,CAAA,QAAA,CAAU,IAAK,CAAA,WAAA,EACf,CAAA,OAAA,CAAS,IAAK,CAAA,UAAA,EACd,CAAA,KAAA,CAAO,IAAK,CAAA,QAAA,EACZ,CAAA,KAAA,CAAO,IAAK,CAAA,QAAA,EACZ,CAAA,YAAA,CAAc,IAAK,CAAA,eAAA,EACnB,CAAA,YAAA,CAAc,IAAK,CAAA,eAAA,EACnB,CAAA,IAAA,CAAM,IAAK,CAAA,OAAA,EACX,CAAA,UAAA,CAAY,IAAK,CAAA,aAAA,EACjB,CAAA,KAAA,CAAO,IAAK,CAAA,QAAA,EACZ,CAAA,OAAA,CAAS,IAAK,CAAA,UAAA,EACd,CAAA,gBAAA,CAAkB,IAAK,CAAA,mBAAA,EACvB,CAAA,iBAAA,CAAmB,IAAK,CAAA,oBAAA,EAC1B,CACF,CAMA,KAAA,EAAgB,CACd,OAAO,IAAK,CAAA,EACd,CAMA,YAAA,EAAuB,CACrB,OAAO,IAAK,CAAA,SACd,CAMA,WAAA,EAAsB,CACpB,OAAO,IAAK,CAAA,QACd,CAMA,UAAA,EAAqB,CACnB,OAAO,IAAK,CAAA,OACd,CAMA,QAAA,EAAmB,CACjB,OAAO,IAAK,CAAA,KACd,CAMA,QAAA,EAAmB,CACjB,OAAO,IAAK,CAAA,KACd,CAMA,eAAA,EAA0B,CACxB,OAAO,IAAK,CAAA,YACd,CAOA,eAAA,EAA0B,CACxB,OAAO,IAAK,CAAA,YACd,CAMA,OAAA,EAAkB,CAChB,OAAO,IAAK,CAAA,IACd,CAMA,aAAA,EAAwB,CACtB,OAAO,IAAK,CAAA,UACd,CAMA,QAAA,EAAmB,CACjB,OAAO,IAAK,CAAA,KACd,CAMA,UAAA,EAAqB,CACnB,OAAO,IAAK,CAAA,OACd,CAMA,mBAAA,EAA+B,CAC7B,OAAO,IAAK,CAAA,gBACd,CAMA,oBAAA,EAAgC,CAC9B,OAAO,IAAK,CAAA,iBACd,CAMA,cAAA,EAA8B,CAC5B,OAAI,IAAK,CAAA,gBAAA,EAAoB,IAAK,CAAA,iBAAA,CACzB,kBACE,CAAA,IAAA,CAAK,gBACP,CAAA,SAAA,CACE,IAAK,CAAA,iBAAA,CACP,UAEA,CAAA,MAEX,CAOA,OAAO,sBAAuBW,CAAAA,CAAAA,CAAmC,CAC/D,OAAOA,CAAgB,GAAA,UAAA,EAAwBA,CAAgB,GAAA,kBACjE,CAOA,OAAO,qBAAsBA,CAAAA,CAAAA,CAAmC,CAC9D,OAAOA,CAAgB,GAAA,SAAA,EAAuBA,CAAgB,GAAA,kBAChE,CACF","file":"Address.js","sourcesContent":["import { AuthType } from \"../Auth\";\r\nimport { ISODateTimeUTC, Prettify } from \"./Common\";\r\n\r\nexport interface CustomFields {\r\n [key: string]: any;\r\n}\r\n\r\nexport type CustomFieldAttributes = {\r\n customFields?: CustomFields;\r\n}\r\n\r\nexport class CustomFieldModel {\r\n protected customFields: CustomFields;\r\n constructor(data: CustomFieldAttributes, date: Date = new Date()) {\r\n this.customFields = { ...data.customFields };\r\n }\r\n\r\n /**\r\n * Retrieves the value of a specific custom field.\r\n * @param fieldName - The name (key) of the custom field to retrieve.\r\n * @returns The value of the custom field, or null if the field does not exist.\r\n */\r\n getCustomField(fieldName: string): any {\r\n return this.customFields[fieldName] ?? null;\r\n }\r\n\r\n /**\r\n * Sets the value of a specific custom field.\r\n * Also updates the modification timestamp and increments the version.\r\n * @param fieldName - The name (key) of the custom field to set.\r\n * @param value - The value to assign to the custom field.\r\n */\r\n setCustomField(fieldName: string, value: any): void {\r\n this.customFields[fieldName] = value;\r\n }\r\n\r\n /**\r\n * Retrieves a shallow copy of all custom fields associated with the instance.\r\n * @returns An object containing all custom fields.\r\n */\r\n getAllCustomFields(): CustomFields {\r\n return { ...this.customFields };\r\n }\r\n}\r\n\r\nexport type ModifiedBy = {\r\n id?: string;\r\n authType?: string;\r\n requestId?: string;\r\n lambdaName?: string;\r\n}\r\n\r\nexport type BaseAttributes = Prettify<CustomFieldAttributes & {\r\n version?: number;\r\n createdAt?: ISODateTimeUTC;\r\n modifiedAt?: ISODateTimeUTC;\r\n modifiedBy?: ModifiedBy;\r\n}>;\r\n\r\nexport type BaseData = Required<BaseAttributes>;\r\n\r\n/**\r\n * Provides common foundational properties and methods for other data models.\r\n * Handles tracking of custom fields, versioning, and timestamps.\r\n */\r\nexport default class BaseModel extends CustomFieldModel {\r\n protected version: number;\r\n protected createdAt: ISODateTimeUTC;\r\n protected modifiedAt: ISODateTimeUTC;\r\n protected modifiedBy: ModifiedBy;\r\n\r\n /**\r\n * Creates an instance of BaseModel.\r\n * Initializes common properties like timestamps, version, and custom fields.\r\n * @param data - Optional initial attributes for the base model.\r\n * @param date - Optional date object to use for default timestamps (defaults to current time).\r\n */\r\n constructor(data: BaseAttributes, date: Date = new Date()) {\r\n super(data);\r\n this.version = data.version ?? 1;\r\n this.createdAt = data.createdAt && !isNaN(Date.parse(data.createdAt))\r\n ?\r\n new Date(data.createdAt).toISOString()\r\n :\r\n date.toISOString();\r\n this.modifiedAt = data.modifiedAt && !isNaN(Date.parse(data.modifiedAt))\r\n ? new Date(data.modifiedAt).toISOString()\r\n : date.toISOString();\r\n\r\n this.modifiedBy = { ...data.modifiedBy };\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the base model's current state.\r\n * @returns BaseData object containing common properties.\r\n */\r\n getDetails(): BaseData {\r\n return {\r\n customFields: this.getAllCustomFields(), // Use getter to return a copy\r\n version: this.getVersion(),\r\n createdAt: this.getCreatedAt(),\r\n modifiedAt: this.getModifiedAt(),\r\n modifiedBy: this.getModifiedBy(),\r\n }\r\n }\r\n\r\n /**\r\n * Gets the current version number of the model instance.\r\n * @returns The version number.\r\n */\r\n getVersion(): number {\r\n return this.version;\r\n }\r\n\r\n /**\r\n * Gets the creation timestamp as an ISO 8601 string.\r\n * @returns The creation timestamp string.\r\n */\r\n getCreatedAt(): string {\r\n return this.createdAt;\r\n }\r\n\r\n /**\r\n * Gets the creation timestamp as a Unix epoch time (milliseconds).\r\n * @returns The creation time in milliseconds since the epoch.\r\n */\r\n getCreatedAtTime(): number {\r\n return new Date(this.createdAt).getTime();\r\n }\r\n\r\n\r\n /**\r\n * Gets the last modification timestamp as an ISO 8601 string.\r\n * @returns The last modification timestamp string.\r\n */\r\n getModifiedAt(): string {\r\n return this.modifiedAt;\r\n }\r\n\r\n /**\r\n * Gets the last modification timestamp as a Unix epoch time (milliseconds).\r\n * @returns The last modification time in milliseconds since the epoch.\r\n */\r\n getModifiedAtTime(): number {\r\n return new Date(this.modifiedAt).getTime();\r\n }\r\n\r\n /**\r\n * Gets the identifier of the user or process that last modified the instance.\r\n * @returns\r\n */\r\n getModifiedBy(): ModifiedBy {\r\n return { ...this.modifiedBy };\r\n }\r\n\r\n /**\r\n * Sets the identifier of the user or process that last modified the instance.\r\n * @param modifiedBy - The identifier string.\r\n */\r\n setModifiedBy(id?: string, authType?: AuthType, requestId?: string, lambdaName?: string): void {\r\n this.modifiedBy = {\r\n id,\r\n authType,\r\n requestId,\r\n lambdaName,\r\n };\r\n }\r\n}\r\n","import BaseModel, { BaseAttributes } from \"./Base\";\r\n\r\nexport enum AddressType {\r\n BILLING = \"billing\",\r\n SHIPPING = \"shipping\",\r\n BILLING_AND_SHIPPING = \"billing&shipping\",\r\n NONE = \"none\",\r\n}\r\n\r\nexport type AddressAttributes = BaseAttributes & {\r\n id: string;\r\n firstName: string;\r\n lastName?: string;\r\n company?: string;\r\n phone: string;\r\n email: string;\r\n addressLine1: string;\r\n addressLine2?: string;\r\n city: string;\r\n postalCode: string\r\n state: string;\r\n country: string;\r\n isBillingAddress: boolean;\r\n isShippingAddress: boolean;\r\n};\r\n\r\nexport type AddressData = Required<AddressAttributes>;\r\n\r\n/**\r\n * Represents a physical address associated with a customer or order.\r\n * Handles both billing and shipping address types.\r\n */\r\nexport default class AddressModel extends BaseModel {\r\n protected id: string;\r\n protected firstName: string;\r\n protected lastName: string;\r\n protected company: string;\r\n protected phone: string;\r\n protected email: string;\r\n protected addressLine1: string;\r\n protected addressLine2: string;\r\n protected city: string;\r\n protected postalCode: string\r\n protected state: string;\r\n protected country: string;\r\n protected isBillingAddress: boolean;\r\n protected isShippingAddress: boolean;\r\n\r\n /**\r\n * Creates an instance of AddressModel.\r\n * @param data - The initial address attributes.\r\n * @param date - Optional date for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: AddressAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n this.id = data.id;\r\n this.firstName = data.firstName;\r\n this.lastName = data.lastName || '';\r\n this.company = data.company || '';\r\n this.phone = data.phone;\r\n this.email = data.email;\r\n this.addressLine1 = data.addressLine1;\r\n this.addressLine2 = data.addressLine2 || '';\r\n this.city = data.city;\r\n this.postalCode = data.postalCode;\r\n this.state = data.state;\r\n this.country = data.country;\r\n this.isBillingAddress = data.isBillingAddress;\r\n this.isShippingAddress = data.isShippingAddress;\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the address's current state.\r\n * Includes all address fields and base model fields.\r\n * @returns AddressData object suitable for serialization or API responses.\r\n */\r\n getDetails(): AddressData {\r\n return {\r\n ...super.getDetails(),\r\n id: this.getId(),\r\n firstName: this.getFirstName(),\r\n lastName: this.getLastName(),\r\n company: this.getCompany(),\r\n phone: this.getPhone(),\r\n email: this.getEmail(),\r\n addressLine1: this.getAddressLine1(),\r\n addressLine2: this.getAddressLine2(),\r\n city: this.getCity(),\r\n postalCode: this.getPostalCode(),\r\n state: this.getState(),\r\n country: this.getCountry(),\r\n isBillingAddress: this.getIsBillingAddress(),\r\n isShippingAddress: this.getIsShippingAddress(),\r\n }\r\n }\r\n\r\n /**\r\n * Gets the unique identifier for the address.\r\n * @returns The address ID.\r\n */\r\n getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the first name associated with the address.\r\n * @returns The first name.\r\n */\r\n getFirstName(): string {\r\n return this.firstName;\r\n }\r\n\r\n /**\r\n * Gets the last name associated with the address.\r\n * @returns The last name.\r\n */\r\n getLastName(): string {\r\n return this.lastName;\r\n }\r\n\r\n /**\r\n * Gets the company name associated with the address.\r\n * @returns The company name.\r\n */\r\n getCompany(): string {\r\n return this.company;\r\n }\r\n\r\n /**\r\n * Gets the phone number associated with the address.\r\n * @returns The phone number.\r\n */\r\n getPhone(): string {\r\n return this.phone;\r\n }\r\n\r\n /**\r\n * Gets the email address associated with the address.\r\n * @returns The email address.\r\n */\r\n getEmail(): string {\r\n return this.email;\r\n }\r\n\r\n /**\r\n * Gets the primary address line (e.g., street address).\r\n * @returns The first address line.\r\n */\r\n getAddressLine1(): string {\r\n return this.addressLine1;\r\n }\r\n\r\n /**\r\n * Gets the secondary address line (e.g., apartment, suite).\r\n * Returns an empty string if not provided.\r\n * @returns The second address line or an empty string.\r\n */\r\n getAddressLine2(): string {\r\n return this.addressLine2;\r\n }\r\n\r\n /**\r\n * Gets the city name.\r\n * @returns The city.\r\n */\r\n getCity(): string {\r\n return this.city;\r\n }\r\n\r\n /**\r\n * Gets the postal code (e.g., ZIP code).\r\n * @returns The postal code.\r\n */\r\n getPostalCode(): string {\r\n return this.postalCode;\r\n }\r\n\r\n /**\r\n * Gets the state, province, or region.\r\n * @returns The state.\r\n */\r\n getState(): string {\r\n return this.state;\r\n }\r\n\r\n /**\r\n * Gets the country name or code.\r\n * @returns The country.\r\n */\r\n getCountry(): string {\r\n return this.country;\r\n }\r\n\r\n /**\r\n * Checks if this address is designated as a billing address.\r\n * @returns True if it's a billing address, false otherwise.\r\n */\r\n getIsBillingAddress(): boolean {\r\n return this.isBillingAddress;\r\n }\r\n\r\n /**\r\n * Checks if this address is designated as a shipping address.\r\n * @returns True if it's a shipping address, false otherwise.\r\n */\r\n getIsShippingAddress(): boolean {\r\n return this.isShippingAddress;\r\n }\r\n\r\n /**\r\n * Determines the type of the address based on its billing and shipping flags.\r\n * @returns The AddressType enum value representing the address's role.\r\n */\r\n getAddressType(): AddressType {\r\n if (this.isBillingAddress && this.isShippingAddress) {\r\n return AddressType.BILLING_AND_SHIPPING;\r\n } else if (this.isBillingAddress) {\r\n return AddressType.BILLING;\r\n } else if (this.isShippingAddress) {\r\n return AddressType.SHIPPING;\r\n } else {\r\n return AddressType.NONE;\r\n }\r\n }\r\n\r\n /**\r\n * Static method to check if a given AddressType includes shipping.\r\n * @param addressType - The address type to check.\r\n * @returns True if the type is SHIPPING or BILLING_AND_SHIPPING.\r\n */\r\n static checkIfShippingAddress(addressType: AddressType): boolean {\r\n return addressType === AddressType.SHIPPING || addressType === AddressType.BILLING_AND_SHIPPING;\r\n }\r\n\r\n /**\r\n * Static method to check if a given AddressType includes billing.\r\n * @param addressType - The address type to check.\r\n * @returns True if the type is BILLING or BILLING_AND_SHIPPING.\r\n */\r\n static checkIfBillingAddress(addressType: AddressType): boolean {\r\n return addressType === AddressType.BILLING || addressType === AddressType.BILLING_AND_SHIPPING;\r\n }\r\n}"]}
|
|
1
|
+
{"version":3,"sources":["../../src/Classes/Base.ts","../../src/Classes/Address.ts"],"names":["deepClone","obj","CustomFieldModel","data","date","fieldName","value","BaseModel","id","authType","requestId","lambdaName","AddressType","AddressModel","addressType"],"mappings":"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","file":"Address.js","sourcesContent":["import { AuthType } from \"../Auth\";\nimport { ISODateTimeUTC, Prettify } from \"./Common\";\n\nconst deepClone = <T>(obj: T): T => structuredClone(obj);\n\r\nexport interface CustomFields {\r\n [key: string]: any;\r\n}\r\n\r\nexport type CustomFieldAttributes = {\r\n customFields?: CustomFields;\r\n}\r\n\r\nexport class CustomFieldModel {\r\n protected customFields: CustomFields;\r\n constructor(data: CustomFieldAttributes, date: Date = new Date()) {\r\n this.customFields = { ...data.customFields };\r\n }\r\n\r\n /**\r\n * Retrieves the value of a specific custom field.\r\n * @param fieldName - The name (key) of the custom field to retrieve.\r\n * @returns The value of the custom field, or null if the field does not exist.\r\n */\r\n getCustomField(fieldName: string): any {\n const value = this.customFields[fieldName];\n if (value === undefined || value === null) return value;\n return deepClone(value);\n }\n\r\n /**\r\n * Sets the value of a specific custom field.\r\n * Also updates the modification timestamp and increments the version.\r\n * @param fieldName - The name (key) of the custom field to set.\r\n * @param value - The value to assign to the custom field.\r\n */\r\n setCustomField(fieldName: string, value: any): void {\r\n this.customFields[fieldName] = value;\r\n }\r\n\r\n /**\r\n * Retrieves a shallow copy of all custom fields associated with the instance.\r\n * @returns An object containing all custom fields.\r\n */\r\n getAllCustomFields(): CustomFields {\n return deepClone(this.customFields);\n }\n}\r\n\r\nexport type ModifiedBy = {\r\n id?: string;\r\n authType?: string;\r\n requestId?: string;\r\n lambdaName?: string;\r\n}\r\n\r\nexport type BaseAttributes = Prettify<CustomFieldAttributes & {\r\n version?: number;\r\n createdAt?: ISODateTimeUTC;\r\n modifiedAt?: ISODateTimeUTC;\r\n modifiedBy?: ModifiedBy;\r\n}>;\r\n\r\nexport type BaseData = Required<BaseAttributes>;\r\n\r\n/**\r\n * Provides common foundational properties and methods for other data models.\r\n * Handles tracking of custom fields, versioning, and timestamps.\r\n */\r\nexport default class BaseModel extends CustomFieldModel {\r\n protected version: number;\r\n protected createdAt: ISODateTimeUTC;\r\n protected modifiedAt: ISODateTimeUTC;\r\n protected modifiedBy: ModifiedBy;\r\n\r\n /**\r\n * Creates an instance of BaseModel.\r\n * Initializes common properties like timestamps, version, and custom fields.\r\n * @param data - Optional initial attributes for the base model.\r\n * @param date - Optional date object to use for default timestamps (defaults to current time).\r\n */\r\n constructor(data: BaseAttributes, date: Date = new Date()) {\r\n super(data);\r\n this.version = data.version ?? 1;\r\n this.createdAt = data.createdAt && !isNaN(Date.parse(data.createdAt))\r\n ?\r\n new Date(data.createdAt).toISOString()\r\n :\r\n date.toISOString();\r\n this.modifiedAt = data.modifiedAt && !isNaN(Date.parse(data.modifiedAt))\r\n ? new Date(data.modifiedAt).toISOString()\r\n : date.toISOString();\r\n\r\n this.modifiedBy = { ...data.modifiedBy };\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the base model's current state.\r\n * @returns BaseData object containing common properties.\r\n */\r\n getDetails(): BaseData {\r\n return {\r\n customFields: this.getAllCustomFields(), // Use getter to return a copy\r\n version: this.getVersion(),\r\n createdAt: this.getCreatedAt(),\r\n modifiedAt: this.getModifiedAt(),\r\n modifiedBy: this.getModifiedBy(),\r\n }\r\n }\r\n\r\n /**\r\n * Gets the current version number of the model instance.\r\n * @returns The version number.\r\n */\r\n getVersion(): number {\r\n return this.version;\r\n }\r\n\r\n /**\r\n * Gets the creation timestamp as an ISO 8601 string.\r\n * @returns The creation timestamp string.\r\n */\r\n getCreatedAt(): string {\r\n return this.createdAt;\r\n }\r\n\r\n /**\r\n * Gets the creation timestamp as a Unix epoch time (milliseconds).\r\n * @returns The creation time in milliseconds since the epoch.\r\n */\r\n getCreatedAtTime(): number {\r\n return new Date(this.createdAt).getTime();\r\n }\r\n\r\n\r\n /**\r\n * Gets the last modification timestamp as an ISO 8601 string.\r\n * @returns The last modification timestamp string.\r\n */\r\n getModifiedAt(): string {\r\n return this.modifiedAt;\r\n }\r\n\r\n /**\r\n * Gets the last modification timestamp as a Unix epoch time (milliseconds).\r\n * @returns The last modification time in milliseconds since the epoch.\r\n */\r\n getModifiedAtTime(): number {\r\n return new Date(this.modifiedAt).getTime();\r\n }\r\n\r\n /**\r\n * Gets the identifier of the user or process that last modified the instance.\r\n * @returns\r\n */\r\n getModifiedBy(): ModifiedBy {\r\n return { ...this.modifiedBy };\r\n }\r\n\r\n /**\r\n * Sets the identifier of the user or process that last modified the instance.\r\n * @param modifiedBy - The identifier string.\r\n */\r\n setModifiedBy(id?: string, authType?: AuthType, requestId?: string, lambdaName?: string): void {\r\n this.modifiedBy = {\r\n id,\r\n authType,\r\n requestId,\r\n lambdaName,\r\n };\r\n }\r\n}\r\n","import BaseModel, { BaseAttributes } from \"./Base\";\r\n\r\nexport enum AddressType {\r\n BILLING = \"billing\",\r\n SHIPPING = \"shipping\",\r\n BILLING_AND_SHIPPING = \"billing&shipping\",\r\n NONE = \"none\",\r\n}\r\n\r\nexport type AddressAttributes = BaseAttributes & {\r\n id: string;\r\n firstName: string;\r\n lastName?: string;\r\n company?: string;\r\n phone: string;\r\n email: string;\r\n addressLine1: string;\r\n addressLine2?: string;\r\n city: string;\r\n postalCode: string\r\n state: string;\r\n country: string;\r\n isBillingAddress: boolean;\r\n isShippingAddress: boolean;\r\n};\r\n\r\nexport type AddressData = Required<AddressAttributes>;\r\n\r\n/**\r\n * Represents a physical address associated with a customer or order.\r\n * Handles both billing and shipping address types.\r\n */\r\nexport default class AddressModel extends BaseModel {\r\n protected id: string;\r\n protected firstName: string;\r\n protected lastName: string;\r\n protected company: string;\r\n protected phone: string;\r\n protected email: string;\r\n protected addressLine1: string;\r\n protected addressLine2: string;\r\n protected city: string;\r\n protected postalCode: string\r\n protected state: string;\r\n protected country: string;\r\n protected isBillingAddress: boolean;\r\n protected isShippingAddress: boolean;\r\n\r\n /**\r\n * Creates an instance of AddressModel.\r\n * @param data - The initial address attributes.\r\n * @param date - Optional date for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: AddressAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n this.id = data.id;\r\n this.firstName = data.firstName;\r\n this.lastName = data.lastName || '';\r\n this.company = data.company || '';\r\n this.phone = data.phone;\r\n this.email = data.email;\r\n this.addressLine1 = data.addressLine1;\r\n this.addressLine2 = data.addressLine2 || '';\r\n this.city = data.city;\r\n this.postalCode = data.postalCode;\r\n this.state = data.state;\r\n this.country = data.country;\r\n this.isBillingAddress = data.isBillingAddress;\r\n this.isShippingAddress = data.isShippingAddress;\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the address's current state.\r\n * Includes all address fields and base model fields.\r\n * @returns AddressData object suitable for serialization or API responses.\r\n */\r\n getDetails(): AddressData {\r\n return {\r\n ...super.getDetails(),\r\n id: this.getId(),\r\n firstName: this.getFirstName(),\r\n lastName: this.getLastName(),\r\n company: this.getCompany(),\r\n phone: this.getPhone(),\r\n email: this.getEmail(),\r\n addressLine1: this.getAddressLine1(),\r\n addressLine2: this.getAddressLine2(),\r\n city: this.getCity(),\r\n postalCode: this.getPostalCode(),\r\n state: this.getState(),\r\n country: this.getCountry(),\r\n isBillingAddress: this.getIsBillingAddress(),\r\n isShippingAddress: this.getIsShippingAddress(),\r\n }\r\n }\r\n\r\n /**\r\n * Gets the unique identifier for the address.\r\n * @returns The address ID.\r\n */\r\n getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the first name associated with the address.\r\n * @returns The first name.\r\n */\r\n getFirstName(): string {\r\n return this.firstName;\r\n }\r\n\r\n /**\r\n * Gets the last name associated with the address.\r\n * @returns The last name.\r\n */\r\n getLastName(): string {\r\n return this.lastName;\r\n }\r\n\r\n /**\r\n * Gets the company name associated with the address.\r\n * @returns The company name.\r\n */\r\n getCompany(): string {\r\n return this.company;\r\n }\r\n\r\n /**\r\n * Gets the phone number associated with the address.\r\n * @returns The phone number.\r\n */\r\n getPhone(): string {\r\n return this.phone;\r\n }\r\n\r\n /**\r\n * Gets the email address associated with the address.\r\n * @returns The email address.\r\n */\r\n getEmail(): string {\r\n return this.email;\r\n }\r\n\r\n /**\r\n * Gets the primary address line (e.g., street address).\r\n * @returns The first address line.\r\n */\r\n getAddressLine1(): string {\r\n return this.addressLine1;\r\n }\r\n\r\n /**\r\n * Gets the secondary address line (e.g., apartment, suite).\r\n * Returns an empty string if not provided.\r\n * @returns The second address line or an empty string.\r\n */\r\n getAddressLine2(): string {\r\n return this.addressLine2;\r\n }\r\n\r\n /**\r\n * Gets the city name.\r\n * @returns The city.\r\n */\r\n getCity(): string {\r\n return this.city;\r\n }\r\n\r\n /**\r\n * Gets the postal code (e.g., ZIP code).\r\n * @returns The postal code.\r\n */\r\n getPostalCode(): string {\r\n return this.postalCode;\r\n }\r\n\r\n /**\r\n * Gets the state, province, or region.\r\n * @returns The state.\r\n */\r\n getState(): string {\r\n return this.state;\r\n }\r\n\r\n /**\r\n * Gets the country name or code.\r\n * @returns The country.\r\n */\r\n getCountry(): string {\r\n return this.country;\r\n }\r\n\r\n /**\r\n * Checks if this address is designated as a billing address.\r\n * @returns True if it's a billing address, false otherwise.\r\n */\r\n getIsBillingAddress(): boolean {\r\n return this.isBillingAddress;\r\n }\r\n\r\n /**\r\n * Checks if this address is designated as a shipping address.\r\n * @returns True if it's a shipping address, false otherwise.\r\n */\r\n getIsShippingAddress(): boolean {\r\n return this.isShippingAddress;\r\n }\r\n\r\n /**\r\n * Determines the type of the address based on its billing and shipping flags.\r\n * @returns The AddressType enum value representing the address's role.\r\n */\r\n getAddressType(): AddressType {\r\n if (this.isBillingAddress && this.isShippingAddress) {\r\n return AddressType.BILLING_AND_SHIPPING;\r\n } else if (this.isBillingAddress) {\r\n return AddressType.BILLING;\r\n } else if (this.isShippingAddress) {\r\n return AddressType.SHIPPING;\r\n } else {\r\n return AddressType.NONE;\r\n }\r\n }\r\n\r\n /**\r\n * Static method to check if a given AddressType includes shipping.\r\n * @param addressType - The address type to check.\r\n * @returns True if the type is SHIPPING or BILLING_AND_SHIPPING.\r\n */\r\n static checkIfShippingAddress(addressType: AddressType): boolean {\r\n return addressType === AddressType.SHIPPING || addressType === AddressType.BILLING_AND_SHIPPING;\r\n }\r\n\r\n /**\r\n * Static method to check if a given AddressType includes billing.\r\n * @param addressType - The address type to check.\r\n * @returns True if the type is BILLING or BILLING_AND_SHIPPING.\r\n */\r\n static checkIfBillingAddress(addressType: AddressType): boolean {\r\n return addressType === AddressType.BILLING || addressType === AddressType.BILLING_AND_SHIPPING;\r\n }\r\n}"]}
|
package/dist/Classes/Address.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as AddressType,b as default}from'../chunk-
|
|
1
|
+
export{a as AddressType,b as default}from'../chunk-HX32EJ3F.mjs';import'../chunk-UXZBULDS.mjs';//# sourceMappingURL=Address.mjs.map
|
|
2
2
|
//# sourceMappingURL=Address.mjs.map
|
package/dist/Classes/Base.d.mts
CHANGED
package/dist/Classes/Base.d.ts
CHANGED
package/dist/Classes/Base.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var i=class{customFields;constructor(e,t=new Date){this.customFields={...e.customFields};}getCustomField(e){
|
|
1
|
+
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var d=i=>structuredClone(i),s=class{customFields;constructor(e,t=new Date){this.customFields={...e.customFields};}getCustomField(e){let t=this.customFields[e];return t==null?t:d(t)}setCustomField(e,t){this.customFields[e]=t;}getAllCustomFields(){return d(this.customFields)}},r=class extends s{version;createdAt;modifiedAt;modifiedBy;constructor(e,t=new Date){super(e),this.version=e.version??1,this.createdAt=e.createdAt&&!isNaN(Date.parse(e.createdAt))?new Date(e.createdAt).toISOString():t.toISOString(),this.modifiedAt=e.modifiedAt&&!isNaN(Date.parse(e.modifiedAt))?new Date(e.modifiedAt).toISOString():t.toISOString(),this.modifiedBy={...e.modifiedBy};}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return {...this.modifiedBy}}setModifiedBy(e,t,o,n){this.modifiedBy={id:e,authType:t,requestId:o,lambdaName:n};}};exports.CustomFieldModel=s;exports.default=r;//# sourceMappingURL=Base.js.map
|
|
2
2
|
//# sourceMappingURL=Base.js.map
|
package/dist/Classes/Base.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/Classes/Base.ts"],"names":["CustomFieldModel","data","date","fieldName","value","BaseModel","id","authType","requestId","lambdaName"],"mappings":"
|
|
1
|
+
{"version":3,"sources":["../../src/Classes/Base.ts"],"names":["deepClone","obj","CustomFieldModel","data","date","fieldName","value","BaseModel","id","authType","requestId","lambdaName"],"mappings":"sEAGMA,IAAAA,CAAAA,CAAgBC,CAAc,EAAA,eAAA,CAAgBA,CAAG,CAAA,CAU1CC,EAAN,KAAuB,CAClB,YACV,CAAA,WAAA,CAAYC,CAA6BC,CAAAA,CAAAA,CAAa,IAAI,IAAQ,CAAA,CAChE,IAAK,CAAA,YAAA,CAAe,CAAE,GAAGD,EAAK,YAAa,EAC7C,CAOA,cAAA,CAAeE,CAAwB,CAAA,CACrC,IAAMC,CAAQ,CAAA,IAAA,CAAK,YAAaD,CAAAA,CAAS,CACzC,CAAA,OAA2BC,GAAU,IAAaA,CAAAA,CAAAA,CAC3CN,CAAUM,CAAAA,CAAK,CACxB,CAQA,eAAeD,CAAmBC,CAAAA,CAAAA,CAAkB,CAClD,IAAA,CAAK,YAAaD,CAAAA,CAAS,CAAIC,CAAAA,EACjC,CAMA,kBAAA,EAAmC,CACjC,OAAON,CAAU,CAAA,IAAA,CAAK,YAAY,CACpC,CACF,CAsBqBO,CAAAA,CAAAA,CAArB,cAAuCL,CAAiB,CAC5C,OACA,CAAA,SAAA,CACA,UACA,CAAA,UAAA,CAQV,WAAYC,CAAAA,CAAAA,CAAsBC,EAAa,IAAI,IAAA,CAAQ,CACzD,KAAA,CAAMD,CAAI,CAAA,CACV,IAAK,CAAA,OAAA,CAAUA,CAAK,CAAA,OAAA,EAAW,CAC/B,CAAA,IAAA,CAAK,SAAYA,CAAAA,CAAAA,CAAK,WAAa,CAAC,KAAA,CAAM,IAAK,CAAA,KAAA,CAAMA,CAAK,CAAA,SAAS,CAAC,CAElE,CAAA,IAAI,IAAKA,CAAAA,CAAAA,CAAK,SAAS,CAAA,CAAE,aAEzBC,CAAAA,CAAAA,CAAK,WAAY,EAAA,CACnB,IAAK,CAAA,UAAA,CAAaD,CAAK,CAAA,UAAA,EAAc,CAAC,KAAA,CAAM,IAAK,CAAA,KAAA,CAAMA,CAAK,CAAA,UAAU,CAAC,CACnE,CAAA,IAAI,IAAKA,CAAAA,CAAAA,CAAK,UAAU,CAAA,CAAE,aAC1BC,CAAAA,CAAAA,CAAK,WAAY,EAAA,CAErB,IAAK,CAAA,UAAA,CAAa,CAAE,GAAGD,CAAAA,CAAK,UAAW,EACzC,CAMA,UAAA,EAAuB,CACrB,OAAO,CACL,YAAc,CAAA,IAAA,CAAK,kBAAmB,EAAA,CACtC,QAAS,IAAK,CAAA,UAAA,EACd,CAAA,SAAA,CAAW,IAAK,CAAA,YAAA,GAChB,UAAY,CAAA,IAAA,CAAK,aAAc,EAAA,CAC/B,UAAY,CAAA,IAAA,CAAK,eACnB,CACF,CAMA,UAAA,EAAqB,CACnB,OAAO,IAAK,CAAA,OACd,CAMA,YAAA,EAAuB,CACrB,OAAO,IAAK,CAAA,SACd,CAMA,gBAA2B,EAAA,CACzB,OAAO,IAAI,IAAK,CAAA,IAAA,CAAK,SAAS,CAAE,CAAA,OAAA,EAClC,CAOA,aAAwB,EAAA,CACtB,OAAO,IAAK,CAAA,UACd,CAMA,iBAAA,EAA4B,CAC1B,OAAO,IAAI,IAAA,CAAK,IAAK,CAAA,UAAU,CAAE,CAAA,OAAA,EACnC,CAMA,eAA4B,CAC1B,OAAO,CAAE,GAAG,IAAK,CAAA,UAAW,CAC9B,CAMA,aAAA,CAAcK,CAAaC,CAAAA,CAAAA,CAAqBC,CAAoBC,CAAAA,CAAAA,CAA2B,CAC7F,IAAK,CAAA,UAAA,CAAa,CAChB,EAAA,CAAAH,CACA,CAAA,QAAA,CAAAC,CACA,CAAA,SAAA,CAAAC,CACA,CAAA,UAAA,CAAAC,CACF,EACF,CACF","file":"Base.js","sourcesContent":["import { AuthType } from \"../Auth\";\nimport { ISODateTimeUTC, Prettify } from \"./Common\";\n\nconst deepClone = <T>(obj: T): T => structuredClone(obj);\n\r\nexport interface CustomFields {\r\n [key: string]: any;\r\n}\r\n\r\nexport type CustomFieldAttributes = {\r\n customFields?: CustomFields;\r\n}\r\n\r\nexport class CustomFieldModel {\r\n protected customFields: CustomFields;\r\n constructor(data: CustomFieldAttributes, date: Date = new Date()) {\r\n this.customFields = { ...data.customFields };\r\n }\r\n\r\n /**\r\n * Retrieves the value of a specific custom field.\r\n * @param fieldName - The name (key) of the custom field to retrieve.\r\n * @returns The value of the custom field, or null if the field does not exist.\r\n */\r\n getCustomField(fieldName: string): any {\n const value = this.customFields[fieldName];\n if (value === undefined || value === null) return value;\n return deepClone(value);\n }\n\r\n /**\r\n * Sets the value of a specific custom field.\r\n * Also updates the modification timestamp and increments the version.\r\n * @param fieldName - The name (key) of the custom field to set.\r\n * @param value - The value to assign to the custom field.\r\n */\r\n setCustomField(fieldName: string, value: any): void {\r\n this.customFields[fieldName] = value;\r\n }\r\n\r\n /**\r\n * Retrieves a shallow copy of all custom fields associated with the instance.\r\n * @returns An object containing all custom fields.\r\n */\r\n getAllCustomFields(): CustomFields {\n return deepClone(this.customFields);\n }\n}\r\n\r\nexport type ModifiedBy = {\r\n id?: string;\r\n authType?: string;\r\n requestId?: string;\r\n lambdaName?: string;\r\n}\r\n\r\nexport type BaseAttributes = Prettify<CustomFieldAttributes & {\r\n version?: number;\r\n createdAt?: ISODateTimeUTC;\r\n modifiedAt?: ISODateTimeUTC;\r\n modifiedBy?: ModifiedBy;\r\n}>;\r\n\r\nexport type BaseData = Required<BaseAttributes>;\r\n\r\n/**\r\n * Provides common foundational properties and methods for other data models.\r\n * Handles tracking of custom fields, versioning, and timestamps.\r\n */\r\nexport default class BaseModel extends CustomFieldModel {\r\n protected version: number;\r\n protected createdAt: ISODateTimeUTC;\r\n protected modifiedAt: ISODateTimeUTC;\r\n protected modifiedBy: ModifiedBy;\r\n\r\n /**\r\n * Creates an instance of BaseModel.\r\n * Initializes common properties like timestamps, version, and custom fields.\r\n * @param data - Optional initial attributes for the base model.\r\n * @param date - Optional date object to use for default timestamps (defaults to current time).\r\n */\r\n constructor(data: BaseAttributes, date: Date = new Date()) {\r\n super(data);\r\n this.version = data.version ?? 1;\r\n this.createdAt = data.createdAt && !isNaN(Date.parse(data.createdAt))\r\n ?\r\n new Date(data.createdAt).toISOString()\r\n :\r\n date.toISOString();\r\n this.modifiedAt = data.modifiedAt && !isNaN(Date.parse(data.modifiedAt))\r\n ? new Date(data.modifiedAt).toISOString()\r\n : date.toISOString();\r\n\r\n this.modifiedBy = { ...data.modifiedBy };\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the base model's current state.\r\n * @returns BaseData object containing common properties.\r\n */\r\n getDetails(): BaseData {\r\n return {\r\n customFields: this.getAllCustomFields(), // Use getter to return a copy\r\n version: this.getVersion(),\r\n createdAt: this.getCreatedAt(),\r\n modifiedAt: this.getModifiedAt(),\r\n modifiedBy: this.getModifiedBy(),\r\n }\r\n }\r\n\r\n /**\r\n * Gets the current version number of the model instance.\r\n * @returns The version number.\r\n */\r\n getVersion(): number {\r\n return this.version;\r\n }\r\n\r\n /**\r\n * Gets the creation timestamp as an ISO 8601 string.\r\n * @returns The creation timestamp string.\r\n */\r\n getCreatedAt(): string {\r\n return this.createdAt;\r\n }\r\n\r\n /**\r\n * Gets the creation timestamp as a Unix epoch time (milliseconds).\r\n * @returns The creation time in milliseconds since the epoch.\r\n */\r\n getCreatedAtTime(): number {\r\n return new Date(this.createdAt).getTime();\r\n }\r\n\r\n\r\n /**\r\n * Gets the last modification timestamp as an ISO 8601 string.\r\n * @returns The last modification timestamp string.\r\n */\r\n getModifiedAt(): string {\r\n return this.modifiedAt;\r\n }\r\n\r\n /**\r\n * Gets the last modification timestamp as a Unix epoch time (milliseconds).\r\n * @returns The last modification time in milliseconds since the epoch.\r\n */\r\n getModifiedAtTime(): number {\r\n return new Date(this.modifiedAt).getTime();\r\n }\r\n\r\n /**\r\n * Gets the identifier of the user or process that last modified the instance.\r\n * @returns\r\n */\r\n getModifiedBy(): ModifiedBy {\r\n return { ...this.modifiedBy };\r\n }\r\n\r\n /**\r\n * Sets the identifier of the user or process that last modified the instance.\r\n * @param modifiedBy - The identifier string.\r\n */\r\n setModifiedBy(id?: string, authType?: AuthType, requestId?: string, lambdaName?: string): void {\r\n this.modifiedBy = {\r\n id,\r\n authType,\r\n requestId,\r\n lambdaName,\r\n };\r\n }\r\n}\r\n"]}
|
package/dist/Classes/Base.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as CustomFieldModel,b as default}from'../chunk-
|
|
1
|
+
export{a as CustomFieldModel,b as default}from'../chunk-UXZBULDS.mjs';//# sourceMappingURL=Base.mjs.map
|
|
2
2
|
//# sourceMappingURL=Base.mjs.map
|
package/dist/Classes/Cart.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import LineItemModel from './LineItem.mjs';
|
|
2
2
|
import ProductModel from './Product.mjs';
|
|
3
3
|
import BaseShoppingContainerModel, { BaseShoppingContainerAttributes, BaseShoppingContainerData } from './ShoppingContainer.mjs';
|
|
4
|
-
import '../Common-
|
|
4
|
+
import '../Common-XM4zQpWC.mjs';
|
|
5
5
|
import './Enum.mjs';
|
|
6
6
|
import './Coupon.mjs';
|
|
7
7
|
import './Base.mjs';
|
package/dist/Classes/Cart.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import LineItemModel from './LineItem.js';
|
|
2
2
|
import ProductModel from './Product.js';
|
|
3
3
|
import BaseShoppingContainerModel, { BaseShoppingContainerAttributes, BaseShoppingContainerData } from './ShoppingContainer.js';
|
|
4
|
-
import '../Common-
|
|
4
|
+
import '../Common-uAn7Sunn.js';
|
|
5
5
|
import './Enum.js';
|
|
6
6
|
import './Coupon.js';
|
|
7
7
|
import './Base.js';
|
package/dist/Classes/Cart.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var At=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var At__default=/*#__PURE__*/_interopDefault(At);var G=class extends Error{constructor(t){super(`Line item with ID '${t}' not found in the cart.`),this.name="LineItemNotFoundError";}},Q=class extends Error{constructor(t){super(`Invalid line item state: ${t}`),this.name="InvalidLineItemStateError";}},Z=class extends Error{constructor(t){super(`Duplicate size found: ${t}`),this.name="DuplicateSizeError";}},Y=class extends Error{constructor(t){super(`Duplicate selection attribute found: ${t}`),this.name="DuplicateSelectionAttributeError";}},J=class extends Error{constructor(t="Product and selection attributes do not match."){super(`ProductMismatch: ${t}`),this.name="ProductMismatchError";}},W=class extends Error{constructor(t="Product is not active."){super(`ProductInactive: ${t}`),this.name="ProductInactiveError";}},A=class extends Error{constructor(t="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${t}`),this.name="SelectionAttributeParseError";}},X=class extends Error{constructor(t="Size does not match."){super(`SizeMismatch: ${t}`),this.name="SizeMismatchError";}},_=class extends Error{constructor(t="Pricing details not available for the product"){super(`NotFound: ${t}`),this.name="PricingNotFoundError";}},U=class extends Error{constructor(t="Tax rule category mismatch."){super(`InvalidTaxRule: ${t}`),this.name="InvalidTaxRuleError";}},tt=class extends Error{constructor(t="Tax category is not valid."){super(`InvalidTaxCategory: ${t}`),this.name="InvalidTaxCategoryError";}},et=class extends Error{constructor(t="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${t}`),this.name="InvalidMinQuantityError";}},it=class extends Error{constructor(t){super(`InvalidTieredPrice: ${t}`),this.name="InvalidTieredPriceError";}},rt=class extends Error{constructor(t="Quantity must be greater than zero."){super(`InvalidQuantity: ${t}`),this.name="InvalidQuantityError";}},st=class extends Error{constructor(t){super(`NoApplicableTier: Quantity ${t} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}},ot=class extends Error{constructor(t="No applicable tax slab or multiple slabs found for the given unit price."){super(`TaxSlabNotFound: ${t}`),this.name="TaxSlabNotFoundError";}},$=class extends Error{constructor(t="Amount cannot be negative."){super(`InvalidAmount: ${t}`),this.name="InvalidPriceAmountError";}},O=class extends Error{constructor(t="Currency code is required."){super(`InvalidCurrency: ${t}`),this.name="InvalidCurrencyCodeError";}},w=class extends Error{constructor(t="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${t}`),this.name="CurrencyMismatchError";}},C=class extends Error{constructor(t){super(`InvalidArgument: ${t}`),this.name="InvalidArgumentError";}},j=class extends Error{constructor(t="Invalid image source configuration."){super(`InvalidImageSource: ${t}`),this.name="InvalidImageSourceError";}};var at=new Uint8Array(256),nt=at.length;function pt(){return nt>at.length-16&&(At__default.default.randomFillSync(at),nt=0),at.slice(nt,nt+=16)}var Tt=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function Mt(s){return typeof s=="string"&&Tt.test(s)}var ft=Mt;var f=[];for(let s=0;s<256;++s)f.push((s+256).toString(16).slice(1));function ct(s,t=0){return f[s[t+0]]+f[s[t+1]]+f[s[t+2]]+f[s[t+3]]+"-"+f[s[t+4]]+f[s[t+5]]+"-"+f[s[t+6]]+f[s[t+7]]+"-"+f[s[t+8]]+f[s[t+9]]+"-"+f[s[t+10]]+f[s[t+11]]+f[s[t+12]]+f[s[t+13]]+f[s[t+14]]+f[s[t+15]]}function wt(s){if(!ft(s))throw TypeError("Invalid UUID");let t,e=new Uint8Array(16);return e[0]=(t=parseInt(s.slice(0,8),16))>>>24,e[1]=t>>>16&255,e[2]=t>>>8&255,e[3]=t&255,e[4]=(t=parseInt(s.slice(9,13),16))>>>8,e[5]=t&255,e[6]=(t=parseInt(s.slice(14,18),16))>>>8,e[7]=t&255,e[8]=(t=parseInt(s.slice(19,23),16))>>>8,e[9]=t&255,e[10]=(t=parseInt(s.slice(24,36),16))/1099511627776&255,e[11]=t/4294967296&255,e[12]=t>>>24&255,e[13]=t>>>16&255,e[14]=t>>>8&255,e[15]=t&255,e}var Ct=wt;function Lt(s){s=unescape(encodeURIComponent(s));let t=[];for(let e=0;e<s.length;++e)t.push(s.charCodeAt(e));return t}var Rt="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Et="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function mt(s,t,e){function i(r,o,n,u){var l;if(typeof r=="string"&&(r=Lt(r)),typeof o=="string"&&(o=Ct(o)),((l=o)===null||l===void 0?void 0:l.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+r.length);if(c.set(o),c.set(r,o.length),c=e(c),c[6]=c[6]&15|t,c[8]=c[8]&63|128,n){u=u||0;for(let d=0;d<16;++d)n[u+d]=c[d];return n}return ct(c)}try{i.name=s;}catch{}return i.DNS=Rt,i.URL=Et,i}var ht={randomUUID:At__default.default.randomUUID};function Bt(s,t,e){if(ht.randomUUID&&!t&&!s)return ht.randomUUID();s=s||{};let i=s.random||(s.rng||pt)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){e=e||0;for(let r=0;r<16;++r)t[e+r]=i[r];return t}return ct(i)}var yt=Bt;function Ut(s){return Array.isArray(s)?s=Buffer.from(s):typeof s=="string"&&(s=Buffer.from(s,"utf8")),At__default.default.createHash("sha1").update(s).digest()}var It=Ut;var Ot=mt("v5",80,It),bt=Ot;var kt={isUUID:s=>/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(s),isEmail:s=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(s),isURL:s=>/^(http|https):\/\/[^ "]+$/.test(s),generateUUID:(s,t)=>t&&s?bt(s,t):yt(),generateSearchId:(s,t)=>`${s}#${L.generateSelectionAttributesKey(t)}`,getKeyfromSearchId:s=>{let[t,e]=s.split("#");return {key:t,selectionAttributes:L.parseSelectionAttributesKey(e)}},deepClone(s){return structuredClone(s)}},g=kt;var N=class{customFields;constructor(t,e=new Date){this.customFields={...t.customFields};}getCustomField(t){return this.customFields[t]??null}setCustomField(t,e){this.customFields[t]=e;}getAllCustomFields(){return {...this.customFields}}},M=class extends N{version;createdAt;modifiedAt;modifiedBy;constructor(t,e=new Date){super(t),this.version=t.version??1,this.createdAt=t.createdAt&&!isNaN(Date.parse(t.createdAt))?new Date(t.createdAt).toISOString():e.toISOString(),this.modifiedAt=t.modifiedAt&&!isNaN(Date.parse(t.modifiedAt))?new Date(t.modifiedAt).toISOString():e.toISOString(),this.modifiedBy={...t.modifiedBy};}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return {...this.modifiedBy}}setModifiedBy(t,e,i,r){this.modifiedBy={id:t,authType:e,requestId:i,lambdaName:r};}};var S={"en-IN":"en","kn-IN":"kn"};var St={INR:"\u20B9"},Pt={INR:"en-IN"};var lt=(d=>(d.INITIAL="INITIAL",d.PROCESSING="PROCESSING",d.SHIPPED="SHIPPED",d.DELIVERED="DELIVERED",d.CANCELLED="CANCELLED",d.RETURN_REQUESTED="RETURN_REQUESTED",d.RETURNED="RETURNED",d.REFUND_INITIATED="REFUND_INITIATED",d.REFUNDED="REFUNDED",d.ON_HOLD="ON_HOLD",d))(lt||{});var R=class{sources;alt;order;label;constructor(t){if(this.sources={...t.sources},this.alt=t.alt,this.order=t.order,this.label=t.label,!this.sources.original)throw new j("ImageInfoModel cannot be created without an 'original' source URL.")}getSources(){return {...this.sources}}getSource(t){return this.sources[t]||this.sources.original}getAlt(){return this.alt}getOrder(){return this.order}getLabel(){return this.label}setAlt(t){this.alt=t;}setOrder(t){this.order=t;}setLabel(t){this.label=t;}setSource(t,e){if(e===void 0){if(t==="original")throw new j("Cannot remove the 'original' image source.");delete this.sources[t];}else this.sources[t]=e;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var a=class s{#t;amount;currency;constructor(t){if(this.#t="PriceModel",t.amount<0)throw new $("Amount cannot be negative.");if(!t.currency)throw new O("Currency code is required.");this.amount=t.amount,this.currency=t.currency;}get kind(){return this.#t}static isPriceModel(t){return typeof t=="object"&&t!==null&&t.kind==="PriceModel"}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}compareTo(t){if(s.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new w("Cannot compare prices in different currencies.")}else throw new C("Must be a PriceModel instance.");return this.amount-t.getAmount()}add(t){if(s.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new w("Cannot add prices in different currencies.")}else throw new C("Must be a PriceModel instance.");return new s({amount:this.amount+t.getAmount(),currency:this.currency})}subtract(t){if(s.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new w("Cannot subtract prices in different currencies.")}else throw new C("Must be a PriceModel instance.");return new s({amount:this.amount-t.getAmount(),currency:this.currency})}multiply(t){if(s.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new w("Cannot multiply prices in different currencies.");return new s({amount:this.amount*t.getAmount(),currency:this.currency})}else if(typeof t=="number"&&t>=0)return new s({amount:this.amount*t,currency:this.currency});throw new C("Must be a non-negative number.")}divide(t){if(s.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new w("Cannot divide prices in different currencies.");return new s({amount:this.amount/t.getAmount(),currency:this.currency})}else if(typeof t=="number"&&t>0)return new s({amount:this.amount/t,currency:this.currency});throw new C("Must be a positive number.")}min(...t){if(t.length===0)throw new C("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(s.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new w("Cannot compare prices in different currencies.")}else throw new C("Must be a PriceModel instance.");return e.compareTo(i)<0?e:i},this)}max(...t){if(t.length===0)throw new C("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(s.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new w("Cannot compare prices in different currencies.")}else throw new C("Must be a PriceModel instance.");return e.compareTo(i)>0?e:i},this)}zero(){return new s({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new s({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return s.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return s.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(t,e,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let r=Pt[e];if(!e||!r)throw new O("Invalid currency code for formatting.");let o=t,n=i.displayAsInteger?0:s.getDecimalPlaces(e),u={style:i.style??"currency",currency:e,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:n,maximumFractionDigits:n};i.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(r,u).format(o)}catch(l){return console.error(`Error formatting price for currency "${e}" and locale "${r}":`,l),`${St[e]??e} ${s.addThousandSeparators(o.toFixed(n))}`}}static getDecimalPlaces(t){switch(t){case"INR":default:return 2}}static addThousandSeparators(t){let e=t.split("."),i=e[0],r=e.length>1?"."+e[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+r}static getRoundedAmount(t,e){if(t<0)throw new $("Amount cannot be negative for rounding.");if(e===void 0)throw new O("Invalid currency code for rounding.");let i=s.getDecimalPlaces(e),r=Math.pow(10,i);return Math.round(t*r)/r}};var k=class{baseUnitPrice;taxCategory;tiers;constructor(t){let e=new a(t.baseUnitPrice);if(!t.taxCategory)throw new tt;let i=(t.tiers??[]).map(l=>({minQuantity:l.minQuantity,unitPrice:new a(l.unitPrice)})).sort((l,c)=>l.minQuantity-c.minQuantity);if(i.some(l=>l.minQuantity<=0))throw new et;let o=i.some(l=>l.unitPrice.getCurrency()!==e.getCurrency()),n=i.some((l,c)=>c>0&&l.unitPrice.compareTo(i[c-1].unitPrice)>0),u=i[0]?.unitPrice.compareTo(e)>0;if(o||n||u)throw new it("Tiers must share the same currency and must not increase in unit price.");this.baseUnitPrice=e,this.taxCategory=t.taxCategory,this.tiers=i;}getBaseUnitPrice(){return this.baseUnitPrice}getTaxCategory(){return this.taxCategory}getTiers(){return this.tiers}getDetails(){return {baseUnitPrice:this.baseUnitPrice.getDetails(),taxCategory:this.taxCategory,tiers:this.tiers.map(t=>({minQuantity:t.minQuantity,unitPrice:t.unitPrice.getDetails()}))}}getApplicableTier(t){if(t<=0)throw new rt;for(let e=this.tiers.length-1;e>=0;e--)if(t>=this.tiers[e].minQuantity)return this.tiers[e];throw new st(t)}getMinQuantity(){return this.tiers[0]?.minQuantity??1}getMaxDiscountPercent(){if(!this.tiers.length)return 0;let t=this.tiers[this.tiers.length-1].unitPrice.getAmount(),e=this.baseUnitPrice.getAmount();return (e-t)/e*100}};var L=class s extends M{id;key;name;description;slug;brand;pricing;variants;targetGender;attributes;specifications;categories;isActive;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static productSKURegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static generateSelectionAttributesKey(t){if(typeof t!="object")throw new A("Selection attributes must be an object");return Object.keys(t).filter(i=>t[i]!==void 0&&i.toLowerCase()!=="size").sort().map(i=>t[i].name?`${i}:c+${t[i].name}`:`${i}:${t[i]}`).join("|").toLowerCase()}static parseSelectionAttributesKey(t){try{let e={},i=t.split("|");for(let r of i){let[o,n]=r.split(":");n.startsWith("c+")?e[o]={name:n.slice(2)}:e[o]=n;}return e}catch(e){throw new A(e?.message)}}constructor(t,e=new Date){super(t,e),this.id=t.id,this.key=t.key,this.name={...t.name},this.description={...t.description},this.slug={...t.slug},this.brand=t.brand,this.pricing=Object.keys(t.pricing).reduce((r,o)=>(t.pricing[o]&&(r[o]=new k(t.pricing[o])),r),{}),this.targetGender=t.targetGender,this.attributes=g.deepClone(t.attributes),this.specifications=g.deepClone(t.specifications),this.categories=g.deepClone(t.categories);let i=new Set;this.variants=(t.variants||[]).map(r=>{if(!r.selectionAttributes||typeof r.selectionAttributes!="object")throw new A("Selection attributes are required");this.checkSelectionAttributes(r.selectionAttributes);let o=s.generateSelectionAttributesKey(r.selectionAttributes);if(i.has(o))throw new Y(o);return i.add(o),{sku:r.sku,selectionAttributes:r.selectionAttributes,images:{primary:new R(r.images.primary),gallery:(r.images.gallery||[]).map(n=>new R(n))}}}),this.isActive=t.isActive,this.searchTags=t.searchTags?g.deepClone(t.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(t){return t?this.name[t]??this.name[S[t]]??this.name.en:g.deepClone(this.name)}getDescription(t){return t?this.description[t]??this.description[S[t]]??this.description.en:g.deepClone(this.description)}getSlug(t){return t?this.slug[t]??this.slug[S[t]]??this.slug.en:g.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(t){return t?this.pricing[t]??null:this.pricing}getAttributes(){return g.deepClone(this.attributes)}getVariants(){return this.variants.map(t=>({sku:t.sku,selectionAttributes:t.selectionAttributes,images:{primary:t.images.primary,gallery:t.images.gallery}}))}getImagesBySelectionAttributes(t){let e=s.generateSelectionAttributesKey(t),i=this.variants.find(r=>s.generateSelectionAttributesKey(r.selectionAttributes)===e);return i?i.images:null}getImages(t,e){switch(e){case"PRIMARY":return this.getImagesBySelectionAttributes(t)?.primary??this.variants[0]?.images?.primary;case"GALLERY":return this.getImagesBySelectionAttributes(t)?.gallery??[];default:return this.getImagesBySelectionAttributes(t)??{primary:this.variants[0]?.images?.primary,gallery:[]}}}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return g.deepClone(this.categories)}getSpecifications(t){return t?g.deepClone(this.specifications[t]??this.specifications[S[t]]??this.specifications.en):g.deepClone(this.specifications)}getSearchTags(t){return t?g.deepClone(this.searchTags[t]??this.searchTags[S[t]]??this.searchTags.en):g.deepClone(this.searchTags)}getDetails(){let t=super.getDetails();return {id:this.getId(),key:this.getKey(),name:this.getName(),description:this.getDescription(),slug:this.getSlug(),brand:this.getBrand(),pricing:Object.keys(this.pricing).reduce((e,i)=>(this.pricing[i]&&(e[i]=this.pricing[i]?.getDetails()),e),{}),attributes:this.getAttributes(),variants:this.variants.map(e=>({sku:e.sku,selectionAttributes:g.deepClone(e.selectionAttributes),images:{primary:e.images.primary.getDetails(),gallery:e.images.gallery.map(i=>i.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...t}}checkSelectionAttributes(t){if(!t||typeof t!="object")throw new A("Selection attributes are required");Object.keys(this.attributes).forEach(e=>{if(e.toLowerCase()==="size")return;let i=this.attributes[e],r=t[e];if(r===void 0)throw new A(`Selection attribute '${e}' is missing`);if(typeof i=="string"){if(typeof r!="string"||i!==r)throw new A(`Selection attribute '${e}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof r!="string"||!i.includes(r))throw new A(`Selection attribute '${e}' is invalid`)}else if(typeof r!="object"||!("name"in r)||i.findIndex(o=>o.name===r.name)<0)throw new A(`Selection attribute '${e}' is invalid`)}});}validateSelectionAttribute(t){let e=s.generateSelectionAttributesKey(t);return this.variants.some(i=>s.generateSelectionAttributesKey(i.selectionAttributes)===e)}validateSize(t){return this.attributes.size.includes(t)}};var B=class extends M{id;firstName;lastName;company;phone;email;addressLine1;addressLine2;city;postalCode;state;country;isBillingAddress;isShippingAddress;constructor(t,e=new Date){super(t,e),this.id=t.id,this.firstName=t.firstName,this.lastName=t.lastName||"",this.company=t.company||"",this.phone=t.phone,this.email=t.email,this.addressLine1=t.addressLine1,this.addressLine2=t.addressLine2||"",this.city=t.city,this.postalCode=t.postalCode,this.state=t.state,this.country=t.country,this.isBillingAddress=t.isBillingAddress,this.isShippingAddress=t.isShippingAddress;}getDetails(){return {...super.getDetails(),id:this.getId(),firstName:this.getFirstName(),lastName:this.getLastName(),company:this.getCompany(),phone:this.getPhone(),email:this.getEmail(),addressLine1:this.getAddressLine1(),addressLine2:this.getAddressLine2(),city:this.getCity(),postalCode:this.getPostalCode(),state:this.getState(),country:this.getCountry(),isBillingAddress:this.getIsBillingAddress(),isShippingAddress:this.getIsShippingAddress()}}getId(){return this.id}getFirstName(){return this.firstName}getLastName(){return this.lastName}getCompany(){return this.company}getPhone(){return this.phone}getEmail(){return this.email}getAddressLine1(){return this.addressLine1}getAddressLine2(){return this.addressLine2}getCity(){return this.city}getPostalCode(){return this.postalCode}getState(){return this.state}getCountry(){return this.country}getIsBillingAddress(){return this.isBillingAddress}getIsShippingAddress(){return this.isShippingAddress}getAddressType(){return this.isBillingAddress&&this.isShippingAddress?"billing&shipping":this.isBillingAddress?"billing":this.isShippingAddress?"shipping":"none"}static checkIfShippingAddress(t){return t==="shipping"||t==="billing&shipping"}static checkIfBillingAddress(t){return t==="billing"||t==="billing&shipping"}};var ut=class{taxRuleId;taxCategory;taxSystem;taxSubSystem;taxCountry;effectiveFrom;effectiveTo;constructor(t){this.taxRuleId=t.taxRuleId,this.taxSystem=t.taxSystem,this.taxSubSystem=t.taxSubSystem,this.taxCategory=t.taxCategory,this.taxCountry=t.taxCountry,this.effectiveFrom=new Date(t.effectiveFrom).toISOString(),this.effectiveTo=t.effectiveTo?new Date(t.effectiveTo).toISOString():void 0;}getTaxRuleId(){return this.taxRuleId}getTaxSystem(){return this.taxSystem}getTaxSubSystem(){return this.taxSubSystem}getTaxCategory(){return this.taxCategory}getTaxCountry(){return this.taxCountry}getEffectiveFrom(){return this.effectiveFrom}getEffectiveTo(){return this.effectiveTo}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxSubSystem:this.getTaxSubSystem(),taxCategory:this.getTaxCategory(),taxCountry:this.getTaxCountry(),effectiveFrom:this.effectiveFrom,effectiveTo:this.effectiveTo?this.effectiveTo:void 0}}appliesTo(t,e,i=new Date){return this.taxCategory===t&&this.taxCountry===e&&Date.parse(this.effectiveFrom)<=i.getTime()&&(this.effectiveTo?Date.parse(this.effectiveTo)>=i.getTime():!0)}static getTaxRateDisplayString(t,e,i){let r=e*100,o=r%1===0?r.toString():r.toFixed(2).replace(/\.?0+$/,"");return i?.percentageOnly?`${o}%`:t.getTaxSystem()==="GST"?`${t.getTaxSubSystem()} ${o}%`:`${t.getTaxSystem()} ${o}%`}},dt=class s extends ut{slabs;constructor(t){super(t),this.slabs=t.slabs.map(e=>({rate:e.rate,minUnitPrice:new a(e.minUnitPrice),maxUnitPrice:e.maxUnitPrice?new a(e.maxUnitPrice):void 0}));}getSlabs(){return this.slabs}getDetails(){return {...super.getDetails(),slabs:this.getSlabs().map(t=>({rate:t.rate,minUnitPrice:t.minUnitPrice.getDetails(),maxUnitPrice:t.maxUnitPrice?t.maxUnitPrice.getDetails():void 0}))}}getApplicableTaxRate(t){return s.getApplicableTaxRate(t,this.slabs)}calculateTax(t){let e=this.getApplicableTaxRate(t);return t.multiply(e)}static getApplicableTaxRate(t,e){let i=e.filter(r=>(r.minUnitPrice===void 0||t.compareTo(r.minUnitPrice)>=0)&&(r.maxUnitPrice===void 0||t.compareTo(r.maxUnitPrice)<0));if(i.length!==1)throw new ot;return i[0].rate}},gt=class extends ut{rate;constructor(t){super(t),this.rate=t.rate;}getApplicableTaxRate(){return this.rate}calculateTax(t){let e=this.getApplicableTaxRate();return t.multiply(e)}getDetails(){return {...super.getDetails(),rate:this.getApplicableTaxRate()}}};var F=class extends N{id;productKey;selectionAttributes;name;specifications;primaryImage;subItems;pricing;state;total;constructor(t){super(t),this.id=t.id,this.productKey=t.productKey,this.selectionAttributes=g.deepClone(t.selectionAttributes),this.name=g.deepClone(t.name),this.specifications=g.deepClone(t.specifications),this.primaryImage=new R(t.primaryImage),this.subItems=g.deepClone(t.subItems);let e=new Set;this.subItems.forEach(i=>{if(e.has(i.size))throw new Z(i.size);e.add(i.size);}),this.pricing={unitPrice:new a(t.pricing.unitPrice),tierPricing:new k(t.pricing.tierPricing),taxCategory:t.pricing.taxCategory,applicableTaxRule:t.pricing.applicableTaxRule.map(i=>new dt(i))},this.state=t.state??"INITIAL",this.total={quantity:t.total.quantity,unitPrice:new a(t.total.unitPrice),subtotal:new a(t.total.subtotal),discounts:Object.fromEntries(Object.entries(t.total.discounts).map(([i,r])=>[i,new a(r)])),totalDiscount:new a(t.total.totalDiscount),netUnitPrice:new a(t.total.netUnitPrice),netSubtotal:new a(t.total.netSubtotal),taxBreakdown:Object.fromEntries(Object.entries(t.total.taxBreakdown).map(([i,r])=>[i,{rate:r.rate,taxableUnitPrice:new a(r.taxableUnitPrice),taxPerUnit:new a(r.taxPerUnit),amount:new a(r.amount),system:r.system,subSystem:r.subSystem}])),taxTotal:new a(t.total.taxTotal),grandTotal:new a(t.total.grandTotal)};}getId(){return this.id}getProductKey(){return this.productKey}getSelectionAttributes(){return g.deepClone(this.selectionAttributes)}getName(t){return t?g.deepClone(this.name[t]??this.name[S[t]]??this.name.en):g.deepClone(this.name)}getSpecifications(t){return t?g.deepClone(this.specifications[t]??this.specifications[S[t]]??this.specifications.en):g.deepClone(this.specifications)}getImage(){return this.primaryImage}getSubItems(){return g.deepClone(this.subItems)}getTotalQuantity(){return this.total.quantity}getPricing(){return {unitPrice:this.pricing.unitPrice,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,applicableTaxRule:this.pricing.applicableTaxRule}}getState(){return this.state}getTotal(){return {quantity:this.total.quantity,unitPrice:this.total.unitPrice,subtotal:this.total.subtotal,discounts:Object.fromEntries(Object.entries(this.total.discounts).map(([t,e])=>[t,e])),totalDiscount:this.total.totalDiscount,netUnitPrice:this.total.netUnitPrice,netSubtotal:this.total.netSubtotal,taxBreakdown:this.total.taxBreakdown,taxTotal:this.total.taxTotal,grandTotal:this.total.grandTotal}}getDetails(){let t=this.getPricing(),e=this.getTotal();return {id:this.getId(),productKey:this.getProductKey(),selectionAttributes:this.getSelectionAttributes(),name:this.getName(),specifications:this.getSpecifications(),primaryImage:this.getImage().getDetails(),subItems:this.getSubItems(),pricing:{unitPrice:t.unitPrice.getDetails(),tierPricing:t.tierPricing.getDetails(),taxCategory:t.taxCategory,applicableTaxRule:t.applicableTaxRule.map(i=>i.getDetails())},state:this.getState(),total:{quantity:e.quantity,unitPrice:e.unitPrice.getDetails(),subtotal:e.subtotal.getDetails(),discounts:Object.fromEntries(Object.entries(e.discounts).map(([i,r])=>[i,r.getDetails()])),totalDiscount:e.totalDiscount.getDetails(),netUnitPrice:e.netUnitPrice.getDetails(),netSubtotal:e.netSubtotal.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(e.taxBreakdown).map(([i,r])=>[i,{rate:r.rate,taxableUnitPrice:r.taxableUnitPrice.getDetails(),taxPerUnit:r.taxPerUnit.getDetails(),amount:r.amount.getDetails(),system:r.system,subSystem:r.subSystem}])),taxTotal:e.taxTotal.getDetails(),grandTotal:e.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}addSubItems(t,e){t.forEach(i=>{let r=this.subItems.find(o=>o.size===i.size);r?r.quantity=e?r.quantity+i.quantity:i.quantity:this.subItems.push(i);}),this.subItems=this.subItems.filter(i=>i.quantity>0),this.calculateTotals();}updateProductData(t,e,i){if(this.productKey!==t.getKey()||!t.validateSelectionAttribute(this.selectionAttributes))throw new J;if(!t.getIsActive())throw new W;this.subItems.forEach(u=>{if(!t.validateSize(u.size))throw new X});let r=t.getPriceDetails(e);if(!r||r.getBaseUnitPrice().getCurrency()!==i)throw new _;this.name=t.getName(),this.specifications=t.getSpecifications(),this.primaryImage=t.getImages(this.selectionAttributes).primary;let o=this.subItems.reduce((u,l)=>u+l.quantity,0),{unitPrice:n}=r.getApplicableTier(o);this.pricing={unitPrice:n,tierPricing:r,taxCategory:r.getTaxCategory(),applicableTaxRule:this.pricing.applicableTaxRule},this.calculateTotals();}updateDiscounts(t){let e={};t.forEach(i=>{e[i.coupon.getCode()]=i.amount;}),this.total.discounts=e,this.calculateTotals();}updateTax(t){t.forEach(e=>{if(!e.appliesTo(this.pricing.taxCategory,e.getTaxCountry()))throw new U}),this.pricing.applicableTaxRule=t,this.calculateTotals();}calculateTotals(){let t=this.pricing.unitPrice.zero(),e=this.subItems.reduce((h,x)=>h+x.quantity,0);if(this.state==="CANCELLED"){this.total={quantity:0,unitPrice:t,subtotal:t,discounts:{},totalDiscount:t,netUnitPrice:t,netSubtotal:t,taxBreakdown:{},taxTotal:t,grandTotal:t};return}let{unitPrice:i}=this.pricing.tierPricing.getApplicableTier(e),r=i.multiply(e),o=Object.values(this.total.discounts).reduce((h,x)=>h.add(x),t),n=r.subtract(o),u=e>0?n.divide(e):t,l={},c=t;this.pricing.applicableTaxRule.forEach(h=>{let x=h.getApplicableTaxRate(u),P=h.calculateTax(u),D=P.multiply(e).round();l[h.getTaxRuleId()]={rate:x,taxableUnitPrice:u,taxPerUnit:P,amount:D,system:h.getTaxSystem(),subSystem:h.getTaxSubSystem()},c=c.add(D);});let d=n.add(c);this.total={quantity:e,unitPrice:i,subtotal:r,discounts:this.total.discounts,totalDiscount:o,netUnitPrice:u,netSubtotal:n,taxBreakdown:l,taxTotal:c,grandTotal:d};}updateState(t){if(this.state in lt)this.state!==t&&(this.state=t);else throw new Q(t)}clearLineItem(){let t=this.pricing.unitPrice.zero();this.id="",this.productKey="",this.selectionAttributes={color:{name:""}},this.name={en:""},this.primaryImage=new R({sources:{original:""}}),this.subItems=[],this.pricing={unitPrice:t,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,applicableTaxRule:[]},this.total={quantity:0,unitPrice:t,subtotal:t,discounts:{},totalDiscount:t,netUnitPrice:t,netSubtotal:t,taxBreakdown:{},taxTotal:t,grandTotal:t};}};var K=class extends M{couponCode;name;description;type;customerId;validFrom;validTo;minCartValue;maxCartDiscount;discountMethod;percentageValue;applicableTo;category;constructor(t,e=new Date){if(super(t,e),this.couponCode=t.couponCode,this.name=g.deepClone(t.name),this.description=g.deepClone(t.description),this.type=t.type,this.customerId=t.customerId,this.validFrom=t.validFrom&&Date.parse(t.validFrom)?new Date(t.validFrom).toISOString():e.toISOString(),this.validTo=t.validTo&&Date.parse(t.validTo)?new Date(t.validTo).toISOString():e.toISOString(),this.minCartValue=Object.keys(t.minCartValue).reduce((i,r)=>{let o=t.minCartValue[r];return o&&(i[r]=new a(o)),i},{}),this.maxCartDiscount=Object.keys(t.maxCartDiscount).reduce((i,r)=>{let o=t.maxCartDiscount[r];return o&&(i[r]=new a(o)),i},{}),this.discountMethod=t.discountMethod,this.percentageValue=t.percentageValue??0,this.percentageValue>100)throw new C("Percentage value cannot be greater than 100");this.applicableTo=t.applicableTo,this.category=t.category;}getCode(){return this.couponCode}getName(t){return t?this.name[t]??this.name[S[t]]??this.name.en:{...this.name}}getDescription(t){return t?this.description[t]??this.description[S[t]]??this.description.en:{...this.description}}getType(){return this.type}getCustomerId(){return this.customerId??""}getValidFrom(){return this.validFrom}getValidTo(){return this.validTo}getMinCartValue(t){return t?this.minCartValue[t]:this.minCartValue}getMaxCartDiscount(t){return t?this.maxCartDiscount[t]:this.maxCartDiscount}getDiscountMethod(){return this.discountMethod}getPercentageValue(){return this.percentageValue}getApplicableTo(){return this.applicableTo}getCategory(){return this.category}getDetails(){return {...super.getDetails(),couponCode:this.getCode(),name:this.getName(),description:this.getDescription(),type:this.getType(),customerId:this.getCustomerId(),validFrom:this.getValidFrom(),validTo:this.getValidTo(),minCartValue:Object.keys(this.getMinCartValue()).reduce((t,e)=>{let i=this.getMinCartValue(e);return i&&(t[e]=i.getDetails()),t},{}),maxCartDiscount:Object.keys(this.getMaxCartDiscount()).reduce((t,e)=>{let i=this.getMaxCartDiscount(e);return i&&(t[e]=i.getDetails()),t},{}),discountMethod:this.getDiscountMethod(),percentageValue:this.getPercentageValue(),applicableTo:this.getApplicableTo(),category:this.getCategory()}}isActive(){return new Date(this.validFrom)<=new Date&&new Date(this.validTo)>=new Date}isApplicableTo(t){return this.applicableTo==="all"||this.applicableTo==="ftb"&&t}calculateApplicableCouponDiscount(t,e,i,r,o=!0){let n=new a({amount:0,currency:r}),u;if(o&&!this.isActive())return n;let l=this.getMinCartValue(i),c=this.getMaxCartDiscount(i);if(!l||l.compareTo(t)>0||!c)return n;let d=this.getCategory(),h=this.getDiscountMethod(),x=d==="SHIPPING"?e:t;if(x.getAmount()<=0)return n;switch(h){case"flat":let D=c;u=x.min(D);break;case"percentage":u=x.multiply(this.getPercentageValue()/100).round();break;default:return n}return u.min(c)}};var z=class extends N{id;name;category;lineItemId;chargeType;pricing;total;constructor(t){super(t),this.id=t.id,this.name=t.name,this.category=t.category,this.lineItemId=t.lineItemId,this.chargeType=t.chargeType,this.pricing={price:new a(t.pricing.price),taxCategory:t.pricing.taxCategory,applicableTaxRule:t.pricing.applicableTaxRule.map(e=>new gt(e))},this.total={price:new a(t.total.price),discounts:Object.fromEntries(Object.entries(t.total.discounts).map(([e,i])=>[e,new a(i)])),totalDiscount:new a(t.total.totalDiscount),netPrice:new a(t.total.netPrice),taxBreakdown:Object.fromEntries(Object.entries(t.total.taxBreakdown).map(([e,i])=>[e,{rate:i.rate,taxablePrice:new a(i.taxablePrice),amount:new a(i.amount),system:i.system,subSystem:i.subSystem}])),taxTotal:new a(t.total.taxTotal),grandTotal:new a(t.total.grandTotal)};}getId(){return this.id}getName(){return this.name}getCategory(){return this.category}getChargeType(){return this.chargeType}getLineItemId(){return this.lineItemId}getPricing(){return this.pricing}getTotal(){return this.total}getApplicableTaxRules(){return this.pricing.applicableTaxRule}updateTax(t){t.forEach(e=>{if(!e.appliesTo(this.pricing.taxCategory,e.getTaxCountry()))throw new U}),this.pricing.applicableTaxRule=t,this.calculateTotals();}updateDiscounts(t){let e={};t.forEach(i=>{e[i.coupon.getCode()]=i.amount;}),this.total.discounts=e,this.calculateTotals();}calculateTotals(){let t=this.pricing.price.zero(),e=this.pricing.price,i=Object.values(this.total.discounts).reduce((b,I)=>b.add(I),t),r=e.subtract(i),o={},n=this.pricing.applicableTaxRule.reduce((b,I)=>b+I.getApplicableTaxRate(),0),u=r.divide(1+n).round(),l=n>0?r.subtract(u):t,c=t,d=this.pricing.applicableTaxRule.reduce((b,I)=>I.getApplicableTaxRate()>b.getApplicableTaxRate()?I:b),h=d.getTaxRuleId();this.pricing.applicableTaxRule.forEach(b=>{if(b.getTaxRuleId()===h)return;let I=b.getApplicableTaxRate(),V=n>0?l.multiply(I).divide(n).round():t;o[b.getTaxRuleId()]={rate:I,taxablePrice:u,amount:V,system:b.getTaxSystem(),subSystem:b.getTaxSubSystem()},c=c.add(V);});let x=l.subtract(c);o[h]={rate:d.getApplicableTaxRate(),taxablePrice:u,amount:x,system:d.getTaxSystem(),subSystem:d.getTaxSubSystem()};let P=u,D=r;this.total={price:e,discounts:this.total.discounts,netPrice:P,totalDiscount:i,taxBreakdown:o,taxTotal:l,grandTotal:D};}getDetails(){return {id:this.id,name:g.deepClone(this.name),category:this.category,lineItemId:this.lineItemId,chargeType:this.chargeType,pricing:{price:this.pricing.price.getDetails(),taxCategory:this.pricing.taxCategory,applicableTaxRule:this.pricing.applicableTaxRule.map(e=>e.getDetails())},total:{price:this.total.price.getDetails(),discounts:Object.fromEntries(Object.entries(this.total.discounts).map(([e,i])=>[e,i.getDetails()])),totalDiscount:this.total.totalDiscount.getDetails(),netPrice:this.total.netPrice.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([e,i])=>[e,{rate:i.rate,taxablePrice:i.taxablePrice.getDetails(),amount:i.amount.getDetails(),system:i.system,subSystem:i.subSystem}])),taxTotal:this.total.taxTotal.getDetails(),grandTotal:this.total.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}};var q=class extends M{id;customerId;customerEmail;anonymousId;lineItems;charges;shippingDetails;shippingAddress;billingAddress;coupons;total;country;currency;locale;constructor(t,e=new Date){super(t,e),this.id=t.id,this.customerId=t.customerId,this.customerEmail=t.customerEmail,this.anonymousId=t.anonymousId,this.country=t.country,this.currency=t.currency,this.locale=t.locale,this.lineItems=(t.lineItems??[]).map(i=>new F(i)),this.charges=(t.charges??[]).map(i=>new z(i)),this.billingAddress=t.billingAddress?new B(t.billingAddress,e):null,this.shippingAddress=t.shippingAddress?new B(t.shippingAddress,e):null,this.coupons=(t.coupons??[]).map(i=>new K(i)),this.shippingDetails=t.shippingDetails?g.deepClone(t.shippingDetails):null,this.total={subtotal:new a(t.total.subtotal),netSubtotal:new a(t.total.netSubtotal),lineItemTaxTotal:new a(t.total.lineItemTaxTotal||{amount:0,currency:t.currency}),lineItemTaxBreakdown:this.mapTaxBreakdown(t.total.lineItemTaxBreakdown||{}),chargesTotal:new a(t.total.chargesTotal||{amount:0,currency:t.currency}),shippingCharge:new a(t.total.shippingCharge),netShippingCharge:new a(t.total.netShippingCharge),chargeTaxTotal:new a(t.total.chargeTaxTotal||{amount:0,currency:t.currency}),chargeTaxBreakdown:this.mapTaxBreakdown(t.total.chargeTaxBreakdown||{}),taxTotal:new a(t.total.taxTotal),taxBreakdown:this.mapTaxBreakdown(t.total.taxBreakdown),discounts:Object.fromEntries(Object.entries(t.total.discounts).map(([i,r])=>[i,new a(r)])),totalDiscount:new a(t.total.totalDiscount),grandTotal:new a(t.total.grandTotal)};}mapTaxBreakdown(t){return Object.fromEntries(Object.entries(t||{}).map(([e,i])=>[e,{system:i.system,totalAmount:new a(i.totalAmount),subSystems:Object.fromEntries(Object.entries(i.subSystems).map(([r,o])=>[r,new a(o)]))}]))}serializeTaxBreakdown(t){return Object.fromEntries(Object.entries(t||{}).map(([e,i])=>[e,{system:i.system,totalAmount:i.totalAmount.getDetails(),subSystems:Object.fromEntries(Object.entries(i.subSystems).map(([r,o])=>[r,o.getDetails()]))}]))}getId(){return this.id}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getAnonymousId(){return this.anonymousId}getLineItems(){return this.lineItems.map(t=>new F(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getCharges(){return this.charges.map(t=>new z(t.getDetails()))}addCharge(t){this.charges.push(t),this.calculateTotals();}clearCharges(){this.charges=[],this.calculateTotals();}getShippingDetails(){return this.shippingDetails?{...this.shippingDetails}:null}getShippingAddress(){return this.shippingAddress?new B(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new B(this.billingAddress.getDetails()):null}getCoupons(){return this.coupons}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return this.total}getDetails(){let t=this.getTotal();return {...super.getDetails(),id:this.getId(),customerId:this.getCustomerId(),customerEmail:this.getCustomerEmail(),anonymousId:this.getAnonymousId(),lineItems:this.getLineItems().map(e=>e.getDetails()),charges:this.getCharges().map(e=>e.getDetails()),shippingDetails:this.getShippingDetails(),shippingAddress:this.getShippingAddress()?.getDetails()||null,billingAddress:this.getBillingAddress()?.getDetails()||null,coupons:this.getCoupons().map(e=>e.getDetails()),total:{subtotal:t.subtotal.getDetails(),netSubtotal:t.netSubtotal.getDetails(),lineItemTaxTotal:t.lineItemTaxTotal.getDetails(),lineItemTaxBreakdown:this.serializeTaxBreakdown(t.lineItemTaxBreakdown),chargesTotal:t.chargesTotal.getDetails(),shippingCharge:t.shippingCharge.getDetails(),netShippingCharge:t.netShippingCharge.getDetails(),chargeTaxTotal:t.chargeTaxTotal.getDetails(),chargeTaxBreakdown:this.serializeTaxBreakdown(t.chargeTaxBreakdown),taxTotal:t.taxTotal.getDetails(),taxBreakdown:this.serializeTaxBreakdown(t.taxBreakdown),discounts:Object.fromEntries(Object.entries(t.discounts).map(([e,i])=>[e,i.getDetails()])),totalDiscount:t.totalDiscount.getDetails(),grandTotal:t.grandTotal.getDetails()},country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}calculateTotals(){let t=new a({amount:0,currency:this.currency}),e=this.lineItems.filter(p=>p.getState()!=="CANCELLED"),i=e.reduce((p,m)=>p.add(m.getTotal().subtotal),t),r=e.reduce((p,m)=>p.add(m.getTotal().netSubtotal),t),o=this.charges.filter(p=>p.getChargeType()==="SHIPPING").reduce((p,m)=>p.add(m.getTotal().price),t),n=t,u={},l={};this.coupons.forEach(p=>{let m=p.calculateApplicableCouponDiscount(i,o,this.country,this.currency);n=n.add(m),u[p.getCode()]=m,p.getCategory()!=="SHIPPING"&&(l[p.getCode()]=m);}),this.applyDiscountsInLineItem(l);let c=this.coupons.find(p=>p.getCategory()==="SHIPPING");c?this.applyDiscuountsInShippingCharges({[c.getCode()]:u[c.getCode()]||t}):this.applyDiscuountsInShippingCharges({});let d=this.charges.reduce((p,m)=>p.add(m.getTotal().grandTotal),t),h=this.charges.filter(p=>p.getChargeType()==="SHIPPING").reduce((p,m)=>p.add(m.getTotal().grandTotal),t),x=t,P=t,D=t,b={},I={},V={},H=(p,m)=>{Object.entries(p).forEach(([Vt,E])=>{let T=E.system,v=E.subSystem;m[T]||(m[T]={system:T,totalAmount:t,subSystems:{}}),m[T].subSystems[v]?m[T].subSystems[v]=m[T].subSystems[v].add(E.amount):m[T].subSystems[v]=E.amount,m[T].totalAmount=m[T].totalAmount.add(E.amount),b[T]||(b[T]={system:T,totalAmount:t,subSystems:{}}),b[T].subSystems[v]?b[T].subSystems[v]=b[T].subSystems[v].add(E.amount):b[T].subSystems[v]=E.amount,b[T].totalAmount=b[T].totalAmount.add(E.amount);});};e.forEach(p=>{let m=p.getTotal().taxBreakdown;m&&(H(m,I),H(m,b),P=P.add(p.getTotal().taxTotal));}),this.charges.forEach(p=>{let m=p.getTotal().taxBreakdown;m&&(H(m,V),H(m,b),D=D.add(p.getTotal().taxTotal));}),x=P.add(D);let Dt=r.add(P).add(d);this.total={subtotal:i,netSubtotal:r,lineItemTaxTotal:P,lineItemTaxBreakdown:I,chargesTotal:d,shippingCharge:o,netShippingCharge:h,chargeTaxTotal:D,chargeTaxBreakdown:V,taxTotal:x,taxBreakdown:b,discounts:u,totalDiscount:n,grandTotal:Dt};}updateShippingDetails(t){this.shippingDetails=t,this.calculateTotals();}applyCoupons(t){let e=t.filter(r=>r.getCategory()==="SHIPPING"),i=t.filter(r=>r.getCategory()!=="SHIPPING");this.coupons=[],this.total.totalDiscount=this.total.subtotal.zero(),this.total.discounts={},i.length&&this.applyNonShippingCoupons(i),this.applyDiscountsInLineItem(this.total.discounts),e.length&&this.applyShippingCoupons(e),this.calculateTotals();}applyDiscountsInLineItem(t){let e=Array.from(Object.entries(t)).filter(r=>!r[1].isZero()),i=new Map;this.lineItems.forEach(r=>i.set(r.getId(),[])),e.forEach(([r,o])=>{let n=this.coupons.find(c=>c.getCode()===r);if(!n||o.isZero())return;let u=this.lineItems.filter(c=>c.getState()!=="CANCELLED"&&!c.getTotal().subtotal.isZero()).sort((c,d)=>c.getTotal().subtotal.compareTo(d.getTotal().subtotal)),l=new a({amount:0,currency:this.currency});u.forEach((c,d)=>{let h;d===u.length-1?h=o.subtract(l):h=o.multiply(c.getTotal().subtotal).divide(this.total.subtotal).round(),l=l.add(h),i.get(c.getId())?.push({coupon:n,amount:h});});}),this.lineItems.forEach(r=>{r.getState()==="CANCELLED"||this.total.subtotal.isZero()?r.updateDiscounts([]):r.updateDiscounts(i.get(r.getId())||[]);});}applyDiscuountsInShippingCharges(t){let e=Array.from(Object.entries(t)).filter(o=>!o[1].isZero()),i=this.charges.filter(o=>o.getChargeType()==="SHIPPING"),r=new Map;i.forEach(o=>r.set(o.getId(),[])),e.forEach(([o,n])=>{let u=this.coupons.find(d=>d.getCode()===o);if(!u||n.isZero())return;let l=i.sort((d,h)=>d.getTotal().grandTotal.compareTo(h.getTotal().grandTotal)),c=new a({amount:0,currency:this.currency});l.forEach((d,h)=>{let x;h===l.length-1?x=n.subtract(c):x=n.multiply(d.getTotal().grandTotal).divide(this.total.subtotal).round(),c=c.add(x),r.get(d.getId())?.push({coupon:u,amount:x});});}),i.forEach(o=>{o.updateDiscounts(r.get(o.getId())||[]);});}applyNonShippingCoupons(t){let e=t.filter(i=>i.getType()==="coupon");if(e.length===1){let i=e[0].calculateApplicableCouponDiscount(this.total.subtotal,this.total.shippingCharge,this.country,this.currency);i.getAmount()>0&&(this.coupons.push(e[0]),this.total.discounts[e[0].getCode()]=i,this.total.totalDiscount=i);}}applyShippingCoupons(t){if(this.total.shippingCharge.getAmount()>0&&t.length>0){let e=this.total.subtotal.subtract(this.total.totalDiscount),i=t.reduce((o,n)=>{if(!o)return n;let u=n.calculateApplicableCouponDiscount(e,this.total.shippingCharge,this.country,this.currency).min(this.total.shippingCharge),l=o.calculateApplicableCouponDiscount(e,this.total.shippingCharge,this.country,this.currency).min(this.total.shippingCharge);return u===l?n.getType()==="coupon"?n:o:u.compareTo(l)>0?n:o}),r=i.calculateApplicableCouponDiscount(e,this.total.shippingCharge,this.country,this.currency).min(this.total.shippingCharge);r.getAmount()>0&&(this.coupons.push(i),this.total.discounts[i.getCode()]=r,this.total.totalDiscount=this.total.totalDiscount.add(r),this.total.netShippingCharge=this.total.shippingCharge.subtract(r));}}};var Ft=(r=>(r.ACTIVE="ACTIVE",r.FROZEN="FROZEN",r.MERGED="MERGED",r.ORDERED="ORDERED",r))(Ft||{}),zt={expiresAtInSeconds:120*24*60*60},xt=class extends q{state;expireAt;config;constructor(t,e=new Date,i=zt){super(t,e),this.state=t.state,this.expireAt=t.expireAt&&typeof t.expireAt=="number"?t.expireAt:Math.floor(e.getTime()/1e3)+i.expiresAtInSeconds,this.config=i;}getState(){return this.state}getExpireAt(){return this.expireAt}isActive(){let t=Math.ceil(Date.now()/1e3);return this.state==="ACTIVE"&&this.expireAt>t}clearCartItems(){this.lineItems=[],this.coupons=[],this.shippingDetails=null,this.total.discounts={},this.calculateTotals();}validateLineItems(t){this.lineItems=this.lineItems.map(e=>{try{e.updateProductData(t[e.getProductKey()],this.country,this.currency);}catch(i){console.error(`Error recalculating line item ${e.getId()}:`,i),e.clearLineItem();}return e}).filter(e=>e.getId()),this.calculateTotals();}addLineItem(t){let e=t.getProductKey(),i=t.getSelectionAttributes(),r=L.generateSelectionAttributesKey(i),o=this.lineItems.findIndex(n=>n.getProductKey()===e&&L.generateSelectionAttributesKey(n.getSelectionAttributes())===r);return o>=0?this.lineItems[o].addSubItems(t.getSubItems(),!0):this.lineItems.push(t),this.calculateTotals(),o>=0?o:this.lineItems.length-1}updateLineItem(t,e,i){let r=this.lineItems,o=r.findIndex(n=>n.getId()===t);if(o<0)throw new G(t);return r[o].addSubItems([{size:e,quantity:i}],!1),this.calculateTotals(),o}removeLineItem(t){let i=this.lineItems.findIndex(r=>r.getId()===t);if(i<0)throw new G(t);return this.lineItems.splice(i,1),this.charges=this.charges.filter(r=>r.getLineItemId()!==t),this.calculateTotals(),i}getDetails(){return {...super.getDetails(),state:this.getState(),expireAt:this.getExpireAt()}}};exports.CartState=Ft;exports.DEFAULT_CART_CONFIG=zt;exports.default=xt;//# sourceMappingURL=Cart.js.map
|
|
1
|
+
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var Mt=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Mt__default=/*#__PURE__*/_interopDefault(Mt);var V=class extends Error{constructor(t){super(`Line item with ID '${t}' not found in the cart.`),this.name="LineItemNotFoundError";}},H=class extends Error{constructor(t){super(`Invalid line item state: ${t}`),this.name="InvalidLineItemStateError";}},Z=class extends Error{constructor(t){super(`Duplicate size found: ${t}`),this.name="DuplicateSizeError";}},Y=class extends Error{constructor(t){super(`Duplicate selection attribute found: ${t}`),this.name="DuplicateSelectionAttributeError";}},J=class extends Error{constructor(t="Product and selection attributes do not match."){super(`ProductMismatch: ${t}`),this.name="ProductMismatchError";}},W=class extends Error{constructor(t="Product is not active."){super(`ProductInactive: ${t}`),this.name="ProductInactiveError";}},A=class extends Error{constructor(t="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${t}`),this.name="SelectionAttributeParseError";}},X=class extends Error{constructor(t="Size does not match."){super(`SizeMismatch: ${t}`),this.name="SizeMismatchError";}},_=class extends Error{constructor(t="Pricing details not available for the product"){super(`NotFound: ${t}`),this.name="PricingNotFoundError";}},U=class extends Error{constructor(t="Tax rule category mismatch."){super(`InvalidTaxRule: ${t}`),this.name="InvalidTaxRuleError";}},tt=class extends Error{constructor(t="Tax category is not valid."){super(`InvalidTaxCategory: ${t}`),this.name="InvalidTaxCategoryError";}},et=class extends Error{constructor(t="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${t}`),this.name="InvalidMinQuantityError";}},it=class extends Error{constructor(t){super(`InvalidTieredPrice: ${t}`),this.name="InvalidTieredPriceError";}},rt=class extends Error{constructor(t="Quantity must be greater than zero."){super(`InvalidQuantity: ${t}`),this.name="InvalidQuantityError";}},st=class extends Error{constructor(t){super(`NoApplicableTier: Quantity ${t} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}},ot=class extends Error{constructor(t="No applicable tax slab or multiple slabs found for the given unit price."){super(`TaxSlabNotFound: ${t}`),this.name="TaxSlabNotFoundError";}},G=class extends Error{constructor(t="Amount cannot be negative."){super(`InvalidAmount: ${t}`),this.name="InvalidPriceAmountError";}},O=class extends Error{constructor(t="Currency code is required."){super(`InvalidCurrency: ${t}`),this.name="InvalidCurrencyCodeError";}},w=class extends Error{constructor(t="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${t}`),this.name="CurrencyMismatchError";}},C=class extends Error{constructor(t){super(`InvalidArgument: ${t}`),this.name="InvalidArgumentError";}},$=class extends Error{constructor(t="Invalid image source configuration."){super(`InvalidImageSource: ${t}`),this.name="InvalidImageSourceError";}};var at=new Uint8Array(256),nt=at.length;function pt(){return nt>at.length-16&&(Mt__default.default.randomFillSync(at),nt=0),at.slice(nt,nt+=16)}var Tt=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function wt(s){return typeof s=="string"&&Tt.test(s)}var ft=wt;var f=[];for(let s=0;s<256;++s)f.push((s+256).toString(16).slice(1));function ct(s,t=0){return f[s[t+0]]+f[s[t+1]]+f[s[t+2]]+f[s[t+3]]+"-"+f[s[t+4]]+f[s[t+5]]+"-"+f[s[t+6]]+f[s[t+7]]+"-"+f[s[t+8]]+f[s[t+9]]+"-"+f[s[t+10]]+f[s[t+11]]+f[s[t+12]]+f[s[t+13]]+f[s[t+14]]+f[s[t+15]]}function Lt(s){if(!ft(s))throw TypeError("Invalid UUID");let t,e=new Uint8Array(16);return e[0]=(t=parseInt(s.slice(0,8),16))>>>24,e[1]=t>>>16&255,e[2]=t>>>8&255,e[3]=t&255,e[4]=(t=parseInt(s.slice(9,13),16))>>>8,e[5]=t&255,e[6]=(t=parseInt(s.slice(14,18),16))>>>8,e[7]=t&255,e[8]=(t=parseInt(s.slice(19,23),16))>>>8,e[9]=t&255,e[10]=(t=parseInt(s.slice(24,36),16))/1099511627776&255,e[11]=t/4294967296&255,e[12]=t>>>24&255,e[13]=t>>>16&255,e[14]=t>>>8&255,e[15]=t&255,e}var Ct=Lt;function Rt(s){s=unescape(encodeURIComponent(s));let t=[];for(let e=0;e<s.length;++e)t.push(s.charCodeAt(e));return t}var Et="6ba7b810-9dad-11d1-80b4-00c04fd430c8",vt="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function mt(s,t,e){function i(r,o,n,u){var l;if(typeof r=="string"&&(r=Rt(r)),typeof o=="string"&&(o=Ct(o)),((l=o)===null||l===void 0?void 0:l.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+r.length);if(c.set(o),c.set(r,o.length),c=e(c),c[6]=c[6]&15|t,c[8]=c[8]&63|128,n){u=u||0;for(let d=0;d<16;++d)n[u+d]=c[d];return n}return ct(c)}try{i.name=s;}catch{}return i.DNS=Et,i.URL=vt,i}var ht={randomUUID:Mt__default.default.randomUUID};function Nt(s,t,e){if(ht.randomUUID&&!t&&!s)return ht.randomUUID();s=s||{};let i=s.random||(s.rng||pt)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){e=e||0;for(let r=0;r<16;++r)t[e+r]=i[r];return t}return ct(i)}var yt=Nt;function Ot(s){return Array.isArray(s)?s=Buffer.from(s):typeof s=="string"&&(s=Buffer.from(s,"utf8")),Mt__default.default.createHash("sha1").update(s).digest()}var It=Ot;var kt=mt("v5",80,It),bt=kt;var Ft={isUUID:s=>/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(s),isEmail:s=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(s),isURL:s=>/^(http|https):\/\/[^ "]+$/.test(s),generateUUID:(s,t)=>t&&s?bt(s,t):yt(),generateSearchId:(s,t)=>`${s}#${L.generateSelectionAttributesKey(t)}`,getKeyfromSearchId:s=>{let[t,e]=s.split("#");return {key:t,selectionAttributes:L.parseSelectionAttributesKey(e)}},deepClone(s){return structuredClone(s)}},g=Ft;var St=s=>structuredClone(s),N=class{customFields;constructor(t,e=new Date){this.customFields={...t.customFields};}getCustomField(t){let e=this.customFields[t];return e==null?e:St(e)}setCustomField(t,e){this.customFields[t]=e;}getAllCustomFields(){return St(this.customFields)}},M=class extends N{version;createdAt;modifiedAt;modifiedBy;constructor(t,e=new Date){super(t),this.version=t.version??1,this.createdAt=t.createdAt&&!isNaN(Date.parse(t.createdAt))?new Date(t.createdAt).toISOString():e.toISOString(),this.modifiedAt=t.modifiedAt&&!isNaN(Date.parse(t.modifiedAt))?new Date(t.modifiedAt).toISOString():e.toISOString(),this.modifiedBy={...t.modifiedBy};}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return {...this.modifiedBy}}setModifiedBy(t,e,i,r){this.modifiedBy={id:t,authType:e,requestId:i,lambdaName:r};}};var I={"en-IN":"en","kn-IN":"kn"};var Pt={INR:"\u20B9"},Dt={INR:"en-IN"};var lt=(d=>(d.INITIAL="INITIAL",d.PROCESSING="PROCESSING",d.SHIPPED="SHIPPED",d.DELIVERED="DELIVERED",d.CANCELLED="CANCELLED",d.RETURN_REQUESTED="RETURN_REQUESTED",d.RETURNED="RETURNED",d.REFUND_INITIATED="REFUND_INITIATED",d.REFUNDED="REFUNDED",d.ON_HOLD="ON_HOLD",d))(lt||{});var R=class{sources;alt;order;label;constructor(t){if(this.sources={...t.sources},this.alt=t.alt,this.order=t.order,this.label=t.label,!this.sources.original)throw new $("ImageInfoModel cannot be created without an 'original' source URL.")}getSources(){return {...this.sources}}getSource(t){return this.sources[t]||this.sources.original}getAlt(){return this.alt}getOrder(){return this.order}getLabel(){return this.label}setAlt(t){this.alt=t;}setOrder(t){this.order=t;}setLabel(t){this.label=t;}setSource(t,e){if(e===void 0){if(t==="original")throw new $("Cannot remove the 'original' image source.");delete this.sources[t];}else this.sources[t]=e;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var a=class s{#t;amount;currency;constructor(t){if(this.#t="PriceModel",t.amount<0)throw new G("Amount cannot be negative.");if(!t.currency)throw new O("Currency code is required.");this.amount=t.amount,this.currency=t.currency;}get kind(){return this.#t}static isPriceModel(t){return typeof t=="object"&&t!==null&&t.kind==="PriceModel"}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}compareTo(t){if(s.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new w("Cannot compare prices in different currencies.")}else throw new C("Must be a PriceModel instance.");return this.amount-t.getAmount()}add(t){if(s.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new w("Cannot add prices in different currencies.")}else throw new C("Must be a PriceModel instance.");return new s({amount:this.amount+t.getAmount(),currency:this.currency})}subtract(t){if(s.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new w("Cannot subtract prices in different currencies.")}else throw new C("Must be a PriceModel instance.");return new s({amount:this.amount-t.getAmount(),currency:this.currency})}multiply(t){if(s.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new w("Cannot multiply prices in different currencies.");return new s({amount:this.amount*t.getAmount(),currency:this.currency})}else if(typeof t=="number"&&t>=0)return new s({amount:this.amount*t,currency:this.currency});throw new C("Must be a non-negative number.")}divide(t){if(s.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new w("Cannot divide prices in different currencies.");return new s({amount:this.amount/t.getAmount(),currency:this.currency})}else if(typeof t=="number"&&t>0)return new s({amount:this.amount/t,currency:this.currency});throw new C("Must be a positive number.")}min(...t){if(t.length===0)throw new C("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(s.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new w("Cannot compare prices in different currencies.")}else throw new C("Must be a PriceModel instance.");return e.compareTo(i)<0?e:i},this)}max(...t){if(t.length===0)throw new C("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(s.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new w("Cannot compare prices in different currencies.")}else throw new C("Must be a PriceModel instance.");return e.compareTo(i)>0?e:i},this)}zero(){return new s({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new s({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return s.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return s.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(t,e,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let r=Dt[e];if(!e||!r)throw new O("Invalid currency code for formatting.");let o=t,n=i.displayAsInteger?0:s.getDecimalPlaces(e),u={style:i.style??"currency",currency:e,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:n,maximumFractionDigits:n};i.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(r,u).format(o)}catch(l){return console.error(`Error formatting price for currency "${e}" and locale "${r}":`,l),`${Pt[e]??e} ${s.addThousandSeparators(o.toFixed(n))}`}}static getDecimalPlaces(t){switch(t){case"INR":default:return 2}}static addThousandSeparators(t){let e=t.split("."),i=e[0],r=e.length>1?"."+e[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+r}static getRoundedAmount(t,e){if(t<0)throw new G("Amount cannot be negative for rounding.");if(e===void 0)throw new O("Invalid currency code for rounding.");let i=s.getDecimalPlaces(e),r=Math.pow(10,i);return Math.round(t*r)/r}};var k=class{baseUnitPrice;taxCategory;tiers;constructor(t){let e=new a(t.baseUnitPrice);if(!t.taxCategory)throw new tt;let i=(t.tiers??[]).map(l=>({minQuantity:l.minQuantity,unitPrice:new a(l.unitPrice)})).sort((l,c)=>l.minQuantity-c.minQuantity);if(i.some(l=>l.minQuantity<=0))throw new et;let o=i.some(l=>l.unitPrice.getCurrency()!==e.getCurrency()),n=i.some((l,c)=>c>0&&l.unitPrice.compareTo(i[c-1].unitPrice)>0),u=i[0]?.unitPrice.compareTo(e)>0;if(o||n||u)throw new it("Tiers must share the same currency and must not increase in unit price.");this.baseUnitPrice=e,this.taxCategory=t.taxCategory,this.tiers=i;}getBaseUnitPrice(){return this.baseUnitPrice}getTaxCategory(){return this.taxCategory}getTiers(){return this.tiers.map(t=>({minQuantity:t.minQuantity,unitPrice:t.unitPrice}))}getDetails(){return {baseUnitPrice:this.baseUnitPrice.getDetails(),taxCategory:this.taxCategory,tiers:this.tiers.map(t=>({minQuantity:t.minQuantity,unitPrice:t.unitPrice.getDetails()}))}}getApplicableTier(t){if(t<=0)throw new rt;for(let e=this.tiers.length-1;e>=0;e--)if(t>=this.tiers[e].minQuantity){let i=this.tiers[e];return {minQuantity:i.minQuantity,unitPrice:i.unitPrice}}throw new st(t)}getMinQuantity(){return this.tiers[0]?.minQuantity??1}getMaxDiscountPercent(){if(!this.tiers.length)return 0;let t=this.tiers[this.tiers.length-1].unitPrice.getAmount(),e=this.baseUnitPrice.getAmount();return (e-t)/e*100}};var L=class s extends M{id;key;name;description;slug;brand;pricing;variants;targetGender;attributes;specifications;categories;isActive;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static productSKURegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static generateSelectionAttributesKey(t){if(typeof t!="object")throw new A("Selection attributes must be an object");return Object.keys(t).filter(i=>t[i]!==void 0&&i.toLowerCase()!=="size").sort().map(i=>t[i].name?`${i}:c+${t[i].name}`:`${i}:${t[i]}`).join("|").toLowerCase()}static parseSelectionAttributesKey(t){try{let e={},i=t.split("|");for(let r of i){let[o,n]=r.split(":");n.startsWith("c+")?e[o]={name:n.slice(2)}:e[o]=n;}return e}catch(e){throw new A(e?.message)}}constructor(t,e=new Date){super(t,e),this.id=t.id,this.key=t.key,this.name={...t.name},this.description={...t.description},this.slug={...t.slug},this.brand=t.brand,this.pricing=Object.keys(t.pricing).reduce((r,o)=>(t.pricing[o]&&(r[o]=new k(t.pricing[o])),r),{}),this.targetGender=t.targetGender,this.attributes=g.deepClone(t.attributes),this.specifications=g.deepClone(t.specifications),this.categories=g.deepClone(t.categories);let i=new Set;this.variants=(t.variants||[]).map(r=>{if(!r.selectionAttributes||typeof r.selectionAttributes!="object")throw new A("Selection attributes are required");this.checkSelectionAttributes(r.selectionAttributes);let o=s.generateSelectionAttributesKey(r.selectionAttributes);if(i.has(o))throw new Y(o);return i.add(o),{sku:r.sku,selectionAttributes:r.selectionAttributes,images:{primary:new R(r.images.primary),gallery:(r.images.gallery||[]).map(n=>new R(n))}}}),this.isActive=t.isActive,this.searchTags=t.searchTags?g.deepClone(t.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(t){return t?this.name[t]??this.name[I[t]]??this.name.en:g.deepClone(this.name)}getDescription(t){return t?this.description[t]??this.description[I[t]]??this.description.en:g.deepClone(this.description)}getSlug(t){return t?this.slug[t]??this.slug[I[t]]??this.slug.en:g.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(t){return t?this.pricing[t]??null:{...this.pricing}}getAttributes(){return g.deepClone(this.attributes)}getVariants(){return this.variants.map(t=>({sku:t.sku,selectionAttributes:g.deepClone(t.selectionAttributes),images:{primary:t.images.primary,gallery:[...t.images.gallery]}}))}getImagesBySelectionAttributes(t){let e=s.generateSelectionAttributesKey(t),i=this.variants.find(r=>s.generateSelectionAttributesKey(r.selectionAttributes)===e);return i?{primary:i.images.primary,gallery:[...i.images.gallery]}:null}getImages(t,e){switch(e){case"PRIMARY":return this.getImagesBySelectionAttributes(t)?.primary??this.variants[0]?.images?.primary;case"GALLERY":return this.getImagesBySelectionAttributes(t)?.gallery??[];default:return this.getImagesBySelectionAttributes(t)??{primary:this.variants[0]?.images?.primary,gallery:[]}}}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return g.deepClone(this.categories)}getSpecifications(t){return t?g.deepClone(this.specifications[t]??this.specifications[I[t]]??this.specifications.en):g.deepClone(this.specifications)}getSearchTags(t){return t?g.deepClone(this.searchTags[t]??this.searchTags[I[t]]??this.searchTags.en):g.deepClone(this.searchTags)}getDetails(){let t=super.getDetails();return {id:this.getId(),key:this.getKey(),name:this.getName(),description:this.getDescription(),slug:this.getSlug(),brand:this.getBrand(),pricing:Object.keys(this.pricing).reduce((e,i)=>(this.pricing[i]&&(e[i]=this.pricing[i]?.getDetails()),e),{}),attributes:this.getAttributes(),variants:this.variants.map(e=>({sku:e.sku,selectionAttributes:g.deepClone(e.selectionAttributes),images:{primary:e.images.primary.getDetails(),gallery:e.images.gallery.map(i=>i.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...t}}checkSelectionAttributes(t){if(!t||typeof t!="object")throw new A("Selection attributes are required");Object.keys(this.attributes).forEach(e=>{if(e.toLowerCase()==="size")return;let i=this.attributes[e],r=t[e];if(r===void 0)throw new A(`Selection attribute '${e}' is missing`);if(typeof i=="string"){if(typeof r!="string"||i!==r)throw new A(`Selection attribute '${e}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof r!="string"||!i.includes(r))throw new A(`Selection attribute '${e}' is invalid`)}else if(typeof r!="object"||!("name"in r)||i.findIndex(o=>o.name===r.name)<0)throw new A(`Selection attribute '${e}' is invalid`)}});}validateSelectionAttribute(t){let e=s.generateSelectionAttributesKey(t);return this.variants.some(i=>s.generateSelectionAttributesKey(i.selectionAttributes)===e)}validateSize(t){return this.attributes.size.includes(t)}};var B=class extends M{id;firstName;lastName;company;phone;email;addressLine1;addressLine2;city;postalCode;state;country;isBillingAddress;isShippingAddress;constructor(t,e=new Date){super(t,e),this.id=t.id,this.firstName=t.firstName,this.lastName=t.lastName||"",this.company=t.company||"",this.phone=t.phone,this.email=t.email,this.addressLine1=t.addressLine1,this.addressLine2=t.addressLine2||"",this.city=t.city,this.postalCode=t.postalCode,this.state=t.state,this.country=t.country,this.isBillingAddress=t.isBillingAddress,this.isShippingAddress=t.isShippingAddress;}getDetails(){return {...super.getDetails(),id:this.getId(),firstName:this.getFirstName(),lastName:this.getLastName(),company:this.getCompany(),phone:this.getPhone(),email:this.getEmail(),addressLine1:this.getAddressLine1(),addressLine2:this.getAddressLine2(),city:this.getCity(),postalCode:this.getPostalCode(),state:this.getState(),country:this.getCountry(),isBillingAddress:this.getIsBillingAddress(),isShippingAddress:this.getIsShippingAddress()}}getId(){return this.id}getFirstName(){return this.firstName}getLastName(){return this.lastName}getCompany(){return this.company}getPhone(){return this.phone}getEmail(){return this.email}getAddressLine1(){return this.addressLine1}getAddressLine2(){return this.addressLine2}getCity(){return this.city}getPostalCode(){return this.postalCode}getState(){return this.state}getCountry(){return this.country}getIsBillingAddress(){return this.isBillingAddress}getIsShippingAddress(){return this.isShippingAddress}getAddressType(){return this.isBillingAddress&&this.isShippingAddress?"billing&shipping":this.isBillingAddress?"billing":this.isShippingAddress?"shipping":"none"}static checkIfShippingAddress(t){return t==="shipping"||t==="billing&shipping"}static checkIfBillingAddress(t){return t==="billing"||t==="billing&shipping"}};var ut=class{taxRuleId;taxCategory;taxSystem;taxSubSystem;taxCountry;effectiveFrom;effectiveTo;constructor(t){this.taxRuleId=t.taxRuleId,this.taxSystem=t.taxSystem,this.taxSubSystem=t.taxSubSystem,this.taxCategory=t.taxCategory,this.taxCountry=t.taxCountry,this.effectiveFrom=new Date(t.effectiveFrom).toISOString(),this.effectiveTo=t.effectiveTo?new Date(t.effectiveTo).toISOString():void 0;}getTaxRuleId(){return this.taxRuleId}getTaxSystem(){return this.taxSystem}getTaxSubSystem(){return this.taxSubSystem}getTaxCategory(){return this.taxCategory}getTaxCountry(){return this.taxCountry}getEffectiveFrom(){return this.effectiveFrom}getEffectiveTo(){return this.effectiveTo}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxSubSystem:this.getTaxSubSystem(),taxCategory:this.getTaxCategory(),taxCountry:this.getTaxCountry(),effectiveFrom:this.effectiveFrom,effectiveTo:this.effectiveTo?this.effectiveTo:void 0}}appliesTo(t,e,i=new Date){return this.taxCategory===t&&this.taxCountry===e&&Date.parse(this.effectiveFrom)<=i.getTime()&&(this.effectiveTo?Date.parse(this.effectiveTo)>=i.getTime():!0)}static getTaxRateDisplayString(t,e,i){let r=e*100,o=r%1===0?r.toString():r.toFixed(2).replace(/\.?0+$/,"");return i?.percentageOnly?`${o}%`:t.getTaxSystem()==="GST"?`${t.getTaxSubSystem()} ${o}%`:`${t.getTaxSystem()} ${o}%`}},dt=class s extends ut{slabs;constructor(t){super(t),this.slabs=t.slabs.map(e=>({rate:e.rate,minUnitPrice:new a(e.minUnitPrice),maxUnitPrice:e.maxUnitPrice?new a(e.maxUnitPrice):void 0}));}getSlabs(){return this.slabs.map(t=>({rate:t.rate,minUnitPrice:t.minUnitPrice,maxUnitPrice:t.maxUnitPrice}))}getDetails(){return {...super.getDetails(),slabs:this.getSlabs().map(t=>({rate:t.rate,minUnitPrice:t.minUnitPrice.getDetails(),maxUnitPrice:t.maxUnitPrice?t.maxUnitPrice.getDetails():void 0}))}}getApplicableTaxRate(t){return s.getApplicableTaxRate(t,this.slabs)}calculateTax(t){let e=this.getApplicableTaxRate(t);return t.multiply(e)}static getApplicableTaxRate(t,e){let i=e.filter(r=>(r.minUnitPrice===void 0||t.compareTo(r.minUnitPrice)>=0)&&(r.maxUnitPrice===void 0||t.compareTo(r.maxUnitPrice)<0));if(i.length!==1)throw new ot;return i[0].rate}},gt=class extends ut{rate;constructor(t){super(t),this.rate=t.rate;}getApplicableTaxRate(){return this.rate}calculateTax(t){let e=this.getApplicableTaxRate();return t.multiply(e)}getDetails(){return {...super.getDetails(),rate:this.getApplicableTaxRate()}}};var F=class extends N{id;productKey;selectionAttributes;name;specifications;primaryImage;subItems;pricing;state;total;constructor(t){super(t),this.id=t.id,this.productKey=t.productKey,this.selectionAttributes=g.deepClone(t.selectionAttributes),this.name=g.deepClone(t.name),this.specifications=g.deepClone(t.specifications),this.primaryImage=new R(t.primaryImage),this.subItems=g.deepClone(t.subItems);let e=new Set;this.subItems.forEach(i=>{if(e.has(i.size))throw new Z(i.size);e.add(i.size);}),this.pricing={unitPrice:new a(t.pricing.unitPrice),tierPricing:new k(t.pricing.tierPricing),taxCategory:t.pricing.taxCategory,applicableTaxRule:t.pricing.applicableTaxRule.map(i=>new dt(i))},this.state=t.state??"INITIAL",this.total={quantity:t.total.quantity,unitPrice:new a(t.total.unitPrice),subtotal:new a(t.total.subtotal),discounts:Object.fromEntries(Object.entries(t.total.discounts).map(([i,r])=>[i,new a(r)])),totalDiscount:new a(t.total.totalDiscount),netUnitPrice:new a(t.total.netUnitPrice),netSubtotal:new a(t.total.netSubtotal),taxBreakdown:Object.fromEntries(Object.entries(t.total.taxBreakdown).map(([i,r])=>[i,{rate:r.rate,taxableUnitPrice:new a(r.taxableUnitPrice),taxPerUnit:new a(r.taxPerUnit),amount:new a(r.amount),system:r.system,subSystem:r.subSystem}])),taxTotal:new a(t.total.taxTotal),grandTotal:new a(t.total.grandTotal)};}getId(){return this.id}getProductKey(){return this.productKey}getSelectionAttributes(){return g.deepClone(this.selectionAttributes)}getName(t){return t?g.deepClone(this.name[t]??this.name[I[t]]??this.name.en):g.deepClone(this.name)}getSpecifications(t){return t?g.deepClone(this.specifications[t]??this.specifications[I[t]]??this.specifications.en):g.deepClone(this.specifications)}getImage(){return this.primaryImage}getSubItems(){return g.deepClone(this.subItems)}getTotalQuantity(){return this.total.quantity}getPricing(){return {unitPrice:this.pricing.unitPrice,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule]}}getState(){return this.state}getTotal(){return {quantity:this.total.quantity,unitPrice:this.total.unitPrice,subtotal:this.total.subtotal,discounts:Object.fromEntries(Object.entries(this.total.discounts).map(([t,e])=>[t,e])),totalDiscount:this.total.totalDiscount,netUnitPrice:this.total.netUnitPrice,netSubtotal:this.total.netSubtotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,e])=>[t,{rate:e.rate,taxableUnitPrice:e.taxableUnitPrice,taxPerUnit:e.taxPerUnit,amount:e.amount,system:e.system,subSystem:e.subSystem}])),taxTotal:this.total.taxTotal,grandTotal:this.total.grandTotal}}getDetails(){let t=this.getPricing(),e=this.getTotal();return {id:this.getId(),productKey:this.getProductKey(),selectionAttributes:this.getSelectionAttributes(),name:this.getName(),specifications:this.getSpecifications(),primaryImage:this.getImage().getDetails(),subItems:this.getSubItems(),pricing:{unitPrice:t.unitPrice.getDetails(),tierPricing:t.tierPricing.getDetails(),taxCategory:t.taxCategory,applicableTaxRule:t.applicableTaxRule.map(i=>i.getDetails())},state:this.getState(),total:{quantity:e.quantity,unitPrice:e.unitPrice.getDetails(),subtotal:e.subtotal.getDetails(),discounts:Object.fromEntries(Object.entries(e.discounts).map(([i,r])=>[i,r.getDetails()])),totalDiscount:e.totalDiscount.getDetails(),netUnitPrice:e.netUnitPrice.getDetails(),netSubtotal:e.netSubtotal.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(e.taxBreakdown).map(([i,r])=>[i,{rate:r.rate,taxableUnitPrice:r.taxableUnitPrice.getDetails(),taxPerUnit:r.taxPerUnit.getDetails(),amount:r.amount.getDetails(),system:r.system,subSystem:r.subSystem}])),taxTotal:e.taxTotal.getDetails(),grandTotal:e.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}addSubItems(t,e){t.forEach(i=>{let r=this.subItems.find(o=>o.size===i.size);r?r.quantity=e?r.quantity+i.quantity:i.quantity:this.subItems.push(i);}),this.subItems=this.subItems.filter(i=>i.quantity>0),this.calculateTotals();}updateProductData(t,e,i){if(this.productKey!==t.getKey()||!t.validateSelectionAttribute(this.selectionAttributes))throw new J;if(!t.getIsActive())throw new W;this.subItems.forEach(u=>{if(!t.validateSize(u.size))throw new X});let r=t.getPriceDetails(e);if(!r||r.getBaseUnitPrice().getCurrency()!==i)throw new _;this.name=t.getName(),this.specifications=t.getSpecifications(),this.primaryImage=t.getImages(this.selectionAttributes).primary;let o=this.subItems.reduce((u,l)=>u+l.quantity,0),{unitPrice:n}=r.getApplicableTier(o);this.pricing={unitPrice:n,tierPricing:r,taxCategory:r.getTaxCategory(),applicableTaxRule:this.pricing.applicableTaxRule},this.calculateTotals();}updateDiscounts(t){let e={};t.forEach(i=>{e[i.coupon.getCode()]=i.amount;}),this.total.discounts=e,this.calculateTotals();}updateTax(t){t.forEach(e=>{if(!e.appliesTo(this.pricing.taxCategory,e.getTaxCountry()))throw new U}),this.pricing.applicableTaxRule=t,this.calculateTotals();}calculateTotals(){let t=this.pricing.unitPrice.zero(),e=this.subItems.reduce((h,x)=>h+x.quantity,0);if(this.state==="CANCELLED"){this.total={quantity:0,unitPrice:t,subtotal:t,discounts:{},totalDiscount:t,netUnitPrice:t,netSubtotal:t,taxBreakdown:{},taxTotal:t,grandTotal:t};return}let{unitPrice:i}=this.pricing.tierPricing.getApplicableTier(e),r=i.multiply(e),o=Object.values(this.total.discounts).reduce((h,x)=>h.add(x),t),n=r.subtract(o),u=e>0?n.divide(e):t,l={},c=t;this.pricing.applicableTaxRule.forEach(h=>{let x=h.getApplicableTaxRate(u),P=h.calculateTax(u),D=P.multiply(e).round();l[h.getTaxRuleId()]={rate:x,taxableUnitPrice:u,taxPerUnit:P,amount:D,system:h.getTaxSystem(),subSystem:h.getTaxSubSystem()},c=c.add(D);});let d=n.add(c);this.total={quantity:e,unitPrice:i,subtotal:r,discounts:this.total.discounts,totalDiscount:o,netUnitPrice:u,netSubtotal:n,taxBreakdown:l,taxTotal:c,grandTotal:d};}updateState(t){if(this.state in lt)this.state!==t&&(this.state=t);else throw new H(t)}clearLineItem(){let t=this.pricing.unitPrice.zero();this.id="",this.productKey="",this.selectionAttributes={color:{name:""}},this.name={en:""},this.primaryImage=new R({sources:{original:""}}),this.subItems=[],this.pricing={unitPrice:t,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,applicableTaxRule:[]},this.total={quantity:0,unitPrice:t,subtotal:t,discounts:{},totalDiscount:t,netUnitPrice:t,netSubtotal:t,taxBreakdown:{},taxTotal:t,grandTotal:t};}};var K=class extends M{couponCode;name;description;type;customerId;validFrom;validTo;minCartValue;maxCartDiscount;discountMethod;percentageValue;applicableTo;category;constructor(t,e=new Date){if(super(t,e),this.couponCode=t.couponCode,this.name=g.deepClone(t.name),this.description=g.deepClone(t.description),this.type=t.type,this.customerId=t.customerId,this.validFrom=t.validFrom&&Date.parse(t.validFrom)?new Date(t.validFrom).toISOString():e.toISOString(),this.validTo=t.validTo&&Date.parse(t.validTo)?new Date(t.validTo).toISOString():e.toISOString(),this.minCartValue=Object.keys(t.minCartValue).reduce((i,r)=>{let o=t.minCartValue[r];return o&&(i[r]=new a(o)),i},{}),this.maxCartDiscount=Object.keys(t.maxCartDiscount).reduce((i,r)=>{let o=t.maxCartDiscount[r];return o&&(i[r]=new a(o)),i},{}),this.discountMethod=t.discountMethod,this.percentageValue=t.percentageValue??0,this.percentageValue>100)throw new C("Percentage value cannot be greater than 100");this.applicableTo=t.applicableTo,this.category=t.category;}getCode(){return this.couponCode}getName(t){return t?this.name[t]??this.name[I[t]]??this.name.en:{...this.name}}getDescription(t){return t?this.description[t]??this.description[I[t]]??this.description.en:{...this.description}}getType(){return this.type}getCustomerId(){return this.customerId??""}getValidFrom(){return this.validFrom}getValidTo(){return this.validTo}getMinCartValue(t){return t?this.minCartValue[t]:{...this.minCartValue}}getMaxCartDiscount(t){return t?this.maxCartDiscount[t]:{...this.maxCartDiscount}}getDiscountMethod(){return this.discountMethod}getPercentageValue(){return this.percentageValue}getApplicableTo(){return this.applicableTo}getCategory(){return this.category}getDetails(){return {...super.getDetails(),couponCode:this.getCode(),name:this.getName(),description:this.getDescription(),type:this.getType(),customerId:this.getCustomerId(),validFrom:this.getValidFrom(),validTo:this.getValidTo(),minCartValue:Object.keys(this.getMinCartValue()).reduce((t,e)=>{let i=this.getMinCartValue(e);return i&&(t[e]=i.getDetails()),t},{}),maxCartDiscount:Object.keys(this.getMaxCartDiscount()).reduce((t,e)=>{let i=this.getMaxCartDiscount(e);return i&&(t[e]=i.getDetails()),t},{}),discountMethod:this.getDiscountMethod(),percentageValue:this.getPercentageValue(),applicableTo:this.getApplicableTo(),category:this.getCategory()}}isActive(){return new Date(this.validFrom)<=new Date&&new Date(this.validTo)>=new Date}isApplicableTo(t){return this.applicableTo==="all"||this.applicableTo==="ftb"&&t}calculateApplicableCouponDiscount(t,e,i,r,o=!0){let n=new a({amount:0,currency:r}),u;if(o&&!this.isActive())return n;let l=this.getMinCartValue(i),c=this.getMaxCartDiscount(i);if(!l||l.compareTo(t)>0||!c)return n;let d=this.getCategory(),h=this.getDiscountMethod(),x=d==="SHIPPING"?e:t;if(x.getAmount()<=0)return n;switch(h){case"flat":let D=c;u=x.min(D);break;case"percentage":u=x.multiply(this.getPercentageValue()/100).round();break;default:return n}return u.min(c)}};var z=class extends N{id;name;category;lineItemId;chargeType;pricing;total;constructor(t){super(t),this.id=t.id,this.name=t.name,this.category=t.category,this.lineItemId=t.lineItemId,this.chargeType=t.chargeType,this.pricing={price:new a(t.pricing.price),taxCategory:t.pricing.taxCategory,applicableTaxRule:t.pricing.applicableTaxRule.map(e=>new gt(e))},this.total={price:new a(t.total.price),discounts:Object.fromEntries(Object.entries(t.total.discounts).map(([e,i])=>[e,new a(i)])),totalDiscount:new a(t.total.totalDiscount),netPrice:new a(t.total.netPrice),taxBreakdown:Object.fromEntries(Object.entries(t.total.taxBreakdown).map(([e,i])=>[e,{rate:i.rate,taxablePrice:new a(i.taxablePrice),amount:new a(i.amount),system:i.system,subSystem:i.subSystem}])),taxTotal:new a(t.total.taxTotal),grandTotal:new a(t.total.grandTotal)};}getId(){return this.id}getName(t){return t?g.deepClone(this.name[t]??this.name[I[t]]??this.name.en):g.deepClone(this.name)}getCategory(){return this.category}getChargeType(){return this.chargeType}getLineItemId(){return this.lineItemId}getPricing(){return {price:this.pricing.price,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule]}}getTotal(){return {price:this.total.price,discounts:{...this.total.discounts},netPrice:this.total.netPrice,totalDiscount:this.total.totalDiscount,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,e])=>[t,{rate:e.rate,taxablePrice:e.taxablePrice,amount:e.amount,system:e.system,subSystem:e.subSystem}])),taxTotal:this.total.taxTotal,grandTotal:this.total.grandTotal}}getApplicableTaxRules(){return [...this.pricing.applicableTaxRule]}updateTax(t){t.forEach(e=>{if(!e.appliesTo(this.pricing.taxCategory,e.getTaxCountry()))throw new U}),this.pricing.applicableTaxRule=t,this.calculateTotals();}updateDiscounts(t){let e={};t.forEach(i=>{e[i.coupon.getCode()]=i.amount;}),this.total.discounts=e,this.calculateTotals();}calculateTotals(){let t=this.pricing.price.zero(),e=this.pricing.price,i=Object.values(this.total.discounts).reduce((b,S)=>b.add(S),t),r=e.subtract(i),o={},n=this.pricing.applicableTaxRule.reduce((b,S)=>b+S.getApplicableTaxRate(),0),u=r.divide(1+n).round(),l=n>0?r.subtract(u):t,c=t,d=this.pricing.applicableTaxRule.reduce((b,S)=>S.getApplicableTaxRate()>b.getApplicableTaxRate()?S:b),h=d.getTaxRuleId();this.pricing.applicableTaxRule.forEach(b=>{if(b.getTaxRuleId()===h)return;let S=b.getApplicableTaxRate(),j=n>0?l.multiply(S).divide(n).round():t;o[b.getTaxRuleId()]={rate:S,taxablePrice:u,amount:j,system:b.getTaxSystem(),subSystem:b.getTaxSubSystem()},c=c.add(j);});let x=l.subtract(c);o[h]={rate:d.getApplicableTaxRate(),taxablePrice:u,amount:x,system:d.getTaxSystem(),subSystem:d.getTaxSubSystem()};let P=u,D=r;this.total={price:e,discounts:this.total.discounts,netPrice:P,totalDiscount:i,taxBreakdown:o,taxTotal:l,grandTotal:D};}getDetails(){return {id:this.id,name:g.deepClone(this.name),category:this.category,lineItemId:this.lineItemId,chargeType:this.chargeType,pricing:{price:this.pricing.price.getDetails(),taxCategory:this.pricing.taxCategory,applicableTaxRule:this.pricing.applicableTaxRule.map(e=>e.getDetails())},total:{price:this.total.price.getDetails(),discounts:Object.fromEntries(Object.entries(this.total.discounts).map(([e,i])=>[e,i.getDetails()])),totalDiscount:this.total.totalDiscount.getDetails(),netPrice:this.total.netPrice.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([e,i])=>[e,{rate:i.rate,taxablePrice:i.taxablePrice.getDetails(),amount:i.amount.getDetails(),system:i.system,subSystem:i.subSystem}])),taxTotal:this.total.taxTotal.getDetails(),grandTotal:this.total.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}};var q=class extends M{id;customerId;customerEmail;anonymousId;lineItems;charges;shippingDetails;shippingAddress;billingAddress;coupons;total;country;currency;locale;constructor(t,e=new Date){super(t,e),this.id=t.id,this.customerId=t.customerId,this.customerEmail=t.customerEmail,this.anonymousId=t.anonymousId,this.country=t.country,this.currency=t.currency,this.locale=t.locale,this.lineItems=(t.lineItems??[]).map(i=>new F(i)),this.charges=(t.charges??[]).map(i=>new z(i)),this.billingAddress=t.billingAddress?new B(t.billingAddress,e):null,this.shippingAddress=t.shippingAddress?new B(t.shippingAddress,e):null,this.coupons=(t.coupons??[]).map(i=>new K(i)),this.shippingDetails=t.shippingDetails?g.deepClone(t.shippingDetails):null,this.total={subtotal:new a(t.total.subtotal),netSubtotal:new a(t.total.netSubtotal),lineItemTaxTotal:new a(t.total.lineItemTaxTotal||{amount:0,currency:t.currency}),lineItemTaxBreakdown:this.mapTaxBreakdown(t.total.lineItemTaxBreakdown||{}),chargesTotal:new a(t.total.chargesTotal||{amount:0,currency:t.currency}),shippingCharge:new a(t.total.shippingCharge),netShippingCharge:new a(t.total.netShippingCharge),chargeTaxTotal:new a(t.total.chargeTaxTotal||{amount:0,currency:t.currency}),chargeTaxBreakdown:this.mapTaxBreakdown(t.total.chargeTaxBreakdown||{}),taxTotal:new a(t.total.taxTotal),taxBreakdown:this.mapTaxBreakdown(t.total.taxBreakdown),discounts:Object.fromEntries(Object.entries(t.total.discounts).map(([i,r])=>[i,new a(r)])),totalDiscount:new a(t.total.totalDiscount),grandTotal:new a(t.total.grandTotal)};}mapTaxBreakdown(t){return Object.fromEntries(Object.entries(t||{}).map(([e,i])=>[e,{system:i.system,totalAmount:new a(i.totalAmount),subSystems:Object.fromEntries(Object.entries(i.subSystems).map(([r,o])=>[r,new a(o)]))}]))}serializeTaxBreakdown(t){return Object.fromEntries(Object.entries(t||{}).map(([e,i])=>[e,{system:i.system,totalAmount:i.totalAmount.getDetails(),subSystems:Object.fromEntries(Object.entries(i.subSystems).map(([r,o])=>[r,o.getDetails()]))}]))}getId(){return this.id}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getAnonymousId(){return this.anonymousId}getLineItems(){return this.lineItems.map(t=>new F(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getCharges(){return this.charges.map(t=>new z(t.getDetails()))}addCharge(t){this.charges.push(t),this.calculateTotals();}clearCharges(){this.charges=[],this.calculateTotals();}getShippingDetails(){return this.shippingDetails?g.deepClone(this.shippingDetails):null}getShippingAddress(){return this.shippingAddress?new B(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new B(this.billingAddress.getDetails()):null}getCoupons(){return [...this.coupons]}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return {subtotal:this.total.subtotal,netSubtotal:this.total.netSubtotal,lineItemTaxTotal:this.total.lineItemTaxTotal,lineItemTaxBreakdown:Object.fromEntries(Object.entries(this.total.lineItemTaxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),chargesTotal:this.total.chargesTotal,shippingCharge:this.total.shippingCharge,netShippingCharge:this.total.netShippingCharge,chargeTaxTotal:this.total.chargeTaxTotal,chargeTaxBreakdown:Object.fromEntries(Object.entries(this.total.chargeTaxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),discounts:{...this.total.discounts},totalDiscount:this.total.totalDiscount,grandTotal:this.total.grandTotal}}getDetails(){let t=this.getTotal();return {...super.getDetails(),id:this.getId(),customerId:this.getCustomerId(),customerEmail:this.getCustomerEmail(),anonymousId:this.getAnonymousId(),lineItems:this.getLineItems().map(e=>e.getDetails()),charges:this.getCharges().map(e=>e.getDetails()),shippingDetails:this.getShippingDetails(),shippingAddress:this.getShippingAddress()?.getDetails()||null,billingAddress:this.getBillingAddress()?.getDetails()||null,coupons:this.getCoupons().map(e=>e.getDetails()),total:{subtotal:t.subtotal.getDetails(),netSubtotal:t.netSubtotal.getDetails(),lineItemTaxTotal:t.lineItemTaxTotal.getDetails(),lineItemTaxBreakdown:this.serializeTaxBreakdown(t.lineItemTaxBreakdown),chargesTotal:t.chargesTotal.getDetails(),shippingCharge:t.shippingCharge.getDetails(),netShippingCharge:t.netShippingCharge.getDetails(),chargeTaxTotal:t.chargeTaxTotal.getDetails(),chargeTaxBreakdown:this.serializeTaxBreakdown(t.chargeTaxBreakdown),taxTotal:t.taxTotal.getDetails(),taxBreakdown:this.serializeTaxBreakdown(t.taxBreakdown),discounts:Object.fromEntries(Object.entries(t.discounts).map(([e,i])=>[e,i.getDetails()])),totalDiscount:t.totalDiscount.getDetails(),grandTotal:t.grandTotal.getDetails()},country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}calculateTotals(){let t=new a({amount:0,currency:this.currency}),e=this.lineItems.filter(p=>p.getState()!=="CANCELLED"),i=e.reduce((p,m)=>p.add(m.getTotal().subtotal),t),r=e.reduce((p,m)=>p.add(m.getTotal().netSubtotal),t),o=this.charges.filter(p=>p.getChargeType()==="SHIPPING").reduce((p,m)=>p.add(m.getTotal().price),t),n=t,u={},l={};this.coupons.forEach(p=>{let m=p.calculateApplicableCouponDiscount(i,o,this.country,this.currency);n=n.add(m),u[p.getCode()]=m,p.getCategory()!=="SHIPPING"&&(l[p.getCode()]=m);}),this.applyDiscountsInLineItem(l);let c=this.coupons.find(p=>p.getCategory()==="SHIPPING");c?this.applyDiscuountsInShippingCharges({[c.getCode()]:u[c.getCode()]||t}):this.applyDiscuountsInShippingCharges({});let d=this.charges.reduce((p,m)=>p.add(m.getTotal().grandTotal),t),h=this.charges.filter(p=>p.getChargeType()==="SHIPPING").reduce((p,m)=>p.add(m.getTotal().grandTotal),t),x=t,P=t,D=t,b={},S={},j={},Q=(p,m)=>{Object.entries(p).forEach(([Vt,E])=>{let T=E.system,v=E.subSystem;m[T]||(m[T]={system:T,totalAmount:t,subSystems:{}}),m[T].subSystems[v]?m[T].subSystems[v]=m[T].subSystems[v].add(E.amount):m[T].subSystems[v]=E.amount,m[T].totalAmount=m[T].totalAmount.add(E.amount),b[T]||(b[T]={system:T,totalAmount:t,subSystems:{}}),b[T].subSystems[v]?b[T].subSystems[v]=b[T].subSystems[v].add(E.amount):b[T].subSystems[v]=E.amount,b[T].totalAmount=b[T].totalAmount.add(E.amount);});};e.forEach(p=>{let m=p.getTotal().taxBreakdown;m&&(Q(m,S),Q(m,b),P=P.add(p.getTotal().taxTotal));}),this.charges.forEach(p=>{let m=p.getTotal().taxBreakdown;m&&(Q(m,j),Q(m,b),D=D.add(p.getTotal().taxTotal));}),x=P.add(D);let At=r.add(P).add(d);this.total={subtotal:i,netSubtotal:r,lineItemTaxTotal:P,lineItemTaxBreakdown:S,chargesTotal:d,shippingCharge:o,netShippingCharge:h,chargeTaxTotal:D,chargeTaxBreakdown:j,taxTotal:x,taxBreakdown:b,discounts:u,totalDiscount:n,grandTotal:At};}updateShippingDetails(t){this.shippingDetails=t,this.calculateTotals();}applyCoupons(t){let e=t.filter(r=>r.getCategory()==="SHIPPING"),i=t.filter(r=>r.getCategory()!=="SHIPPING");this.coupons=[],this.total.totalDiscount=this.total.subtotal.zero(),this.total.discounts={},i.length&&this.applyNonShippingCoupons(i),this.applyDiscountsInLineItem(this.total.discounts),e.length&&this.applyShippingCoupons(e),this.calculateTotals();}applyDiscountsInLineItem(t){let e=Array.from(Object.entries(t)).filter(r=>!r[1].isZero()),i=new Map;this.lineItems.forEach(r=>i.set(r.getId(),[])),e.forEach(([r,o])=>{let n=this.coupons.find(c=>c.getCode()===r);if(!n||o.isZero())return;let u=this.lineItems.filter(c=>c.getState()!=="CANCELLED"&&!c.getTotal().subtotal.isZero()).sort((c,d)=>c.getTotal().subtotal.compareTo(d.getTotal().subtotal)),l=new a({amount:0,currency:this.currency});u.forEach((c,d)=>{let h;d===u.length-1?h=o.subtract(l):h=o.multiply(c.getTotal().subtotal).divide(this.total.subtotal).round(),l=l.add(h),i.get(c.getId())?.push({coupon:n,amount:h});});}),this.lineItems.forEach(r=>{r.getState()==="CANCELLED"||this.total.subtotal.isZero()?r.updateDiscounts([]):r.updateDiscounts(i.get(r.getId())||[]);});}applyDiscuountsInShippingCharges(t){let e=Array.from(Object.entries(t)).filter(o=>!o[1].isZero()),i=this.charges.filter(o=>o.getChargeType()==="SHIPPING"),r=new Map;i.forEach(o=>r.set(o.getId(),[])),e.forEach(([o,n])=>{let u=this.coupons.find(d=>d.getCode()===o);if(!u||n.isZero())return;let l=i.sort((d,h)=>d.getTotal().grandTotal.compareTo(h.getTotal().grandTotal)),c=new a({amount:0,currency:this.currency});l.forEach((d,h)=>{let x;h===l.length-1?x=n.subtract(c):x=n.multiply(d.getTotal().grandTotal).divide(this.total.subtotal).round(),c=c.add(x),r.get(d.getId())?.push({coupon:u,amount:x});});}),i.forEach(o=>{o.updateDiscounts(r.get(o.getId())||[]);});}applyNonShippingCoupons(t){let e=t.filter(i=>i.getType()==="coupon");if(e.length===1){let i=e[0].calculateApplicableCouponDiscount(this.total.subtotal,this.total.shippingCharge,this.country,this.currency);i.getAmount()>0&&(this.coupons.push(e[0]),this.total.discounts[e[0].getCode()]=i,this.total.totalDiscount=i);}}applyShippingCoupons(t){if(this.total.shippingCharge.getAmount()>0&&t.length>0){let e=this.total.subtotal.subtract(this.total.totalDiscount),i=t.reduce((o,n)=>{if(!o)return n;let u=n.calculateApplicableCouponDiscount(e,this.total.shippingCharge,this.country,this.currency).min(this.total.shippingCharge),l=o.calculateApplicableCouponDiscount(e,this.total.shippingCharge,this.country,this.currency).min(this.total.shippingCharge);return u===l?n.getType()==="coupon"?n:o:u.compareTo(l)>0?n:o}),r=i.calculateApplicableCouponDiscount(e,this.total.shippingCharge,this.country,this.currency).min(this.total.shippingCharge);r.getAmount()>0&&(this.coupons.push(i),this.total.discounts[i.getCode()]=r,this.total.totalDiscount=this.total.totalDiscount.add(r),this.total.netShippingCharge=this.total.shippingCharge.subtract(r));}}};var zt=(r=>(r.ACTIVE="ACTIVE",r.FROZEN="FROZEN",r.MERGED="MERGED",r.ORDERED="ORDERED",r))(zt||{}),jt={expiresAtInSeconds:120*24*60*60},xt=class extends q{state;expireAt;config;constructor(t,e=new Date,i=jt){super(t,e),this.state=t.state,this.expireAt=t.expireAt&&typeof t.expireAt=="number"?t.expireAt:Math.floor(e.getTime()/1e3)+i.expiresAtInSeconds,this.config=i;}getState(){return this.state}getExpireAt(){return this.expireAt}isActive(){let t=Math.ceil(Date.now()/1e3);return this.state==="ACTIVE"&&this.expireAt>t}clearCartItems(){this.lineItems=[],this.coupons=[],this.shippingDetails=null,this.total.discounts={},this.calculateTotals();}validateLineItems(t){this.lineItems=this.lineItems.map(e=>{try{e.updateProductData(t[e.getProductKey()],this.country,this.currency);}catch(i){console.error(`Error recalculating line item ${e.getId()}:`,i),e.clearLineItem();}return e}).filter(e=>e.getId()),this.calculateTotals();}addLineItem(t){let e=t.getProductKey(),i=t.getSelectionAttributes(),r=L.generateSelectionAttributesKey(i),o=this.lineItems.findIndex(n=>n.getProductKey()===e&&L.generateSelectionAttributesKey(n.getSelectionAttributes())===r);return o>=0?this.lineItems[o].addSubItems(t.getSubItems(),!0):this.lineItems.push(t),this.calculateTotals(),o>=0?o:this.lineItems.length-1}updateLineItem(t,e,i){let r=this.lineItems,o=r.findIndex(n=>n.getId()===t);if(o<0)throw new V(t);return r[o].addSubItems([{size:e,quantity:i}],!1),this.calculateTotals(),o}removeLineItem(t){let i=this.lineItems.findIndex(r=>r.getId()===t);if(i<0)throw new V(t);return this.lineItems.splice(i,1),this.charges=this.charges.filter(r=>r.getLineItemId()!==t),this.calculateTotals(),i}getDetails(){return {...super.getDetails(),state:this.getState(),expireAt:this.getExpireAt()}}};exports.CartState=zt;exports.DEFAULT_CART_CONFIG=jt;exports.default=xt;//# sourceMappingURL=Cart.js.map
|
|
2
2
|
//# sourceMappingURL=Cart.js.map
|