b23-lib 3.2.2 → 3.2.4
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.mjs +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 +2 -2
- package/dist/Classes/Charge.d.ts +2 -2
- 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/Coupon.mjs +1 -1
- package/dist/Classes/Inventory.mjs +1 -1
- package/dist/Classes/Invoice.d.mts +32 -5
- package/dist/Classes/Invoice.d.ts +32 -5
- package/dist/Classes/Invoice.js +1 -1
- package/dist/Classes/Invoice.js.map +1 -1
- package/dist/Classes/Invoice.mjs +1 -1
- package/dist/Classes/Invoice.mjs.map +1 -1
- package/dist/Classes/LineItem.mjs +1 -1
- 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/Product.mjs +1 -1
- package/dist/Classes/ShoppingContainer.js +1 -1
- package/dist/Classes/ShoppingContainer.js.map +1 -1
- package/dist/Classes/ShoppingContainer.mjs +1 -1
- package/dist/{chunk-5IRYC2KY.mjs → chunk-B2VFJRLS.mjs} +2 -2
- package/dist/{chunk-5IRYC2KY.mjs.map → chunk-B2VFJRLS.mjs.map} +1 -1
- package/dist/{chunk-XJPFHEW3.mjs → chunk-G6LH7V5B.mjs} +2 -2
- package/dist/{chunk-XJPFHEW3.mjs.map → chunk-G6LH7V5B.mjs.map} +1 -1
- package/dist/{chunk-QGIQ3MH6.mjs → chunk-MHLRJ4IJ.mjs} +2 -2
- package/dist/{chunk-QGIQ3MH6.mjs.map → chunk-MHLRJ4IJ.mjs.map} +1 -1
- package/dist/{chunk-PWWKQNF7.mjs → chunk-RQ2FFWUW.mjs} +2 -2
- package/dist/{chunk-PWWKQNF7.mjs.map → chunk-RQ2FFWUW.mjs.map} +1 -1
- package/dist/{chunk-MJGCYQ53.mjs → chunk-VTBHWXR4.mjs} +2 -2
- package/dist/{chunk-MJGCYQ53.mjs.map → chunk-VTBHWXR4.mjs.map} +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -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-MHLRJ4IJ.mjs';import'../chunk-FCRJAAPY.mjs';import'../chunk-2B2XI6FG.mjs';import'../chunk-LI5JQ6UC.mjs';import'../chunk-QK4XJ3GB.mjs';import'../chunk-R5DM7WCD.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/Cart.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var Lt=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Lt__default=/*#__PURE__*/_interopDefault(Lt);var Q=class extends Error{constructor(t){super(`Line item with ID '${t}' not found in the cart.`),this.name="LineItemNotFoundError";}},W=class extends Error{constructor(t){super(`Invalid line item state: ${t}`),this.name="InvalidLineItemStateError";}},_=class extends Error{constructor(t){super(`InvalidLineItemTaxRule: ${t}`),this.name="InvalidLineItemTaxRuleError";}},tt=class extends Error{constructor(t){super(`Duplicate size found: ${t}`),this.name="DuplicateSizeError";}},et=class extends Error{constructor(t){super(`Duplicate selection attribute found: ${t}`),this.name="DuplicateSelectionAttributeError";}},it=class extends Error{constructor(t="Product and selection attributes do not match."){super(`ProductMismatch: ${t}`),this.name="ProductMismatchError";}},rt=class extends Error{constructor(t="Product is not active."){super(`ProductInactive: ${t}`),this.name="ProductInactiveError";}},w=class extends Error{constructor(t="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${t}`),this.name="SelectionAttributeParseError";}},nt=class extends Error{constructor(t="Size does not match."){super(`SizeMismatch: ${t}`),this.name="SizeMismatchError";}},ot=class extends Error{constructor(t="Pricing details not available for the product"){super(`NotFound: ${t}`),this.name="PricingNotFoundError";}},z=class extends Error{constructor(t="Tax rule category mismatch."){super(`InvalidTaxRule: ${t}`),this.name="InvalidTaxRuleError";}},st=class extends Error{constructor(t="Tax category is not valid."){super(`InvalidTaxCategory: ${t}`),this.name="InvalidTaxCategoryError";}},at=class extends Error{constructor(t="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${t}`),this.name="InvalidMinQuantityError";}},ct=class extends Error{constructor(t){super(`InvalidTieredPrice: ${t}`),this.name="InvalidTieredPriceError";}},lt=class extends Error{constructor(t="Quantity must be greater than zero."){super(`InvalidQuantity: ${t}`),this.name="InvalidQuantityError";}},ut=class extends Error{constructor(t){super(`NoApplicableTier: Quantity ${t} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}};var H=class extends Error{constructor(t="Amount cannot be negative."){super(`InvalidAmount: ${t}`),this.name="InvalidPriceAmountError";}},j=class extends Error{constructor(t="Currency code is required."){super(`InvalidCurrency: ${t}`),this.name="InvalidCurrencyCodeError";}},v=class extends Error{constructor(t="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${t}`),this.name="CurrencyMismatchError";}},P=class extends Error{constructor(t){super(`InvalidArgument: ${t}`),this.name="InvalidArgumentError";}},Z=class extends Error{constructor(t="Invalid image source configuration."){super(`InvalidImageSource: ${t}`),this.name="InvalidImageSourceError";}},Y=class extends Error{constructor(t="Invalid charge data."){super(`InvalidCharge: ${t}`),this.name="InvalidChargeError";}},$=class extends Error{constructor(t="Invalid charge tax rule."){super(`InvalidChargeTaxRule: ${t}`),this.name="InvalidChargeTaxRuleError";}};var gt=new Uint8Array(256),dt=gt.length;function yt(){return dt>gt.length-16&&(Lt__default.default.randomFillSync(gt),dt=0),gt.slice(dt,dt+=16)}var It=/^(?:[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 vt(n){return typeof n=="string"&&It.test(n)}var At=vt;var I=[];for(let n=0;n<256;++n)I.push((n+256).toString(16).slice(1));function pt(n,t=0){return I[n[t+0]]+I[n[t+1]]+I[n[t+2]]+I[n[t+3]]+"-"+I[n[t+4]]+I[n[t+5]]+"-"+I[n[t+6]]+I[n[t+7]]+"-"+I[n[t+8]]+I[n[t+9]]+"-"+I[n[t+10]]+I[n[t+11]]+I[n[t+12]]+I[n[t+13]]+I[n[t+14]]+I[n[t+15]]}function Et(n){if(!At(n))throw TypeError("Invalid UUID");let t,e=new Uint8Array(16);return e[0]=(t=parseInt(n.slice(0,8),16))>>>24,e[1]=t>>>16&255,e[2]=t>>>8&255,e[3]=t&255,e[4]=(t=parseInt(n.slice(9,13),16))>>>8,e[5]=t&255,e[6]=(t=parseInt(n.slice(14,18),16))>>>8,e[7]=t&255,e[8]=(t=parseInt(n.slice(19,23),16))>>>8,e[9]=t&255,e[10]=(t=parseInt(n.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 St=Et;function Bt(n){n=unescape(encodeURIComponent(n));let t=[];for(let e=0;e<n.length;++e)t.push(n.charCodeAt(e));return t}var Rt="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Nt="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function bt(n,t,e){function i(r,o,a,g){var d;if(typeof r=="string"&&(r=Bt(r)),typeof o=="string"&&(o=St(o)),((d=o)===null||d===void 0?void 0:d.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,a){g=g||0;for(let u=0;u<16;++u)a[g+u]=c[u];return a}return pt(c)}try{i.name=n;}catch{}return i.DNS=Rt,i.URL=Nt,i}var Ct={randomUUID:Lt__default.default.randomUUID};function Ot(n,t,e){if(Ct.randomUUID&&!t&&!n)return Ct.randomUUID();n=n||{};let i=n.random||(n.rng||yt)();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 pt(i)}var xt=Ot;function Ft(n){return Array.isArray(n)?n=Buffer.from(n):typeof n=="string"&&(n=Buffer.from(n,"utf8")),Lt__default.default.createHash("sha1").update(n).digest()}var Pt=Ft;var zt=bt("v5",80,Pt),Tt=zt;var jt={isUUID:n=>/^[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(n),isEmail:n=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(n),isURL:n=>/^(http|https):\/\/[^ "]+$/.test(n),generateUUID:(n,t)=>t&&n?Tt(n,t):xt(),generateSearchId:(n,t)=>`${n}#${B.generateSelectionAttributesKey(t)}`,getKeyfromSearchId:n=>{let[t,e]=n.split("#");return {key:t,selectionAttributes:B.parseSelectionAttributesKey(e)}},deepClone(n){return structuredClone(n)}},m=jt;var Dt=n=>structuredClone(n),R=class{customFields;constructor(t,e=new Date){this.customFields={...t.customFields};}getCustomField(t){let e=this.customFields[t];return e==null?e:Dt(e)}setCustomField(t,e){this.customFields[t]=e;}getAllCustomFields(){return Dt(this.customFields)}},L=class extends R{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 D={"en-IN":"en","kn-IN":"kn"};var Mt={INR:"\u20B9"},wt={INR:"en-IN"};var mt=(u=>(u.INITIAL="INITIAL",u.PROCESSING="PROCESSING",u.SHIPPED="SHIPPED",u.DELIVERED="DELIVERED",u.CANCELLED="CANCELLED",u.RETURN_REQUESTED="RETURN_REQUESTED",u.RETURNED="RETURNED",u.REFUND_INITIATED="REFUND_INITIATED",u.REFUNDED="REFUNDED",u.ON_HOLD="ON_HOLD",u))(mt||{});var N=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 Z("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 Z("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 s=class n{#t;amount;currency;constructor(t){if(this.#t="PriceModel",t.amount<0)throw new H("Amount cannot be negative.");if(!t.currency)throw new j("Currency code is required.");this.currency=t.currency,this.amount=parseFloat(t.amount.toFixed(n.getPrecisionPlaces(this.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}}getPreciseAmount(t){return parseFloat(t.toFixed(n.getPrecisionPlaces(this.currency)))}compareTo(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new v("Cannot compare prices in different currencies.")}else throw new P("Must be a PriceModel instance.");return this.getPreciseAmount(this.amount-t.getAmount())}add(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new v("Cannot add prices in different currencies.")}else throw new P("Must be a PriceModel instance.");return new n({amount:this.getPreciseAmount(this.amount+t.getAmount()),currency:this.currency})}subtract(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new v("Cannot subtract prices in different currencies.")}else throw new P("Must be a PriceModel instance.");return new n({amount:this.getPreciseAmount(this.amount-t.getAmount()),currency:this.currency})}multiply(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new v("Cannot multiply prices in different currencies.");return new n({amount:this.getPreciseAmount(this.amount*t.getAmount()),currency:this.currency})}else if(typeof t=="number"&&t>=0)return new n({amount:this.getPreciseAmount(this.amount*t),currency:this.currency});throw new P("Must be a non-negative number.")}divide(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new v("Cannot divide prices in different currencies.");return new n({amount:this.getPreciseAmount(this.amount/t.getAmount()),currency:this.currency})}else if(typeof t=="number"&&t>0)return new n({amount:this.getPreciseAmount(this.amount/t),currency:this.currency});throw new P("Must be a positive number.")}min(...t){if(t.length===0)throw new P("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(n.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new v("Cannot compare prices in different currencies.")}else throw new P("Must be a PriceModel instance.");return e.compareTo(i)<0?e:i},this)}max(...t){if(t.length===0)throw new P("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(n.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new v("Cannot compare prices in different currencies.")}else throw new P("Must be a PriceModel instance.");return e.compareTo(i)>0?e:i},this)}zero(){return new n({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new n({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return n.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return n.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(t,e,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let r=wt[e];if(!e||!r)throw new j("Invalid currency code for formatting.");let o=t,a=i.displayAsInteger?0:n.getDecimalPlaces(e),g={style:i.style??"currency",currency:e,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:a,maximumFractionDigits:a};i.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(r,g).format(o)}catch(d){return console.error(`Error formatting price for currency "${e}" and locale "${r}":`,d),`${Mt[e]??e} ${n.addThousandSeparators(o.toFixed(a))}`}}static getDecimalPlaces(t){switch(t){case"INR":default:return 2}}static getPrecisionPlaces(t){switch(t){case"INR":default:return 6}}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 H("Amount cannot be negative for rounding.");if(e===void 0)throw new j("Invalid currency code for rounding.");let i=n.getDecimalPlaces(e),r=Math.pow(10,i);return Math.round(t*r)/r}};var V=class{baseUnitPrice;taxCategory;tiers;constructor(t){let e=new s(t.baseUnitPrice);if(!t.taxCategory)throw new st;let i=(t.tiers??[]).map(d=>({minQuantity:d.minQuantity,unitPrice:new s(d.unitPrice)})).sort((d,c)=>d.minQuantity-c.minQuantity);if(i.some(d=>d.minQuantity<=0))throw new at;let o=i.some(d=>d.unitPrice.getCurrency()!==e.getCurrency()),a=i.some((d,c)=>c>0&&d.unitPrice.compareTo(i[c-1].unitPrice)>0),g=i[0]?.unitPrice.compareTo(e)>0;if(o||a||g)throw new ct("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 lt;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 ut(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 B=class n extends L{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 w("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,a]=r.split(":");a.startsWith("c+")?e[o]={name:a.slice(2)}:e[o]=a;}return e}catch(e){throw new w(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 V(t.pricing[o])),r),{}),this.targetGender=t.targetGender,this.attributes=m.deepClone(t.attributes),this.specifications=m.deepClone(t.specifications),this.categories=m.deepClone(t.categories);let i=new Set;this.variants=(t.variants||[]).map(r=>{if(!r.selectionAttributes||typeof r.selectionAttributes!="object")throw new w("Selection attributes are required");this.checkSelectionAttributes(r.selectionAttributes);let o=n.generateSelectionAttributesKey(r.selectionAttributes);if(i.has(o))throw new et(o);return i.add(o),{sku:r.sku,selectionAttributes:r.selectionAttributes,images:{primary:new N(r.images.primary),gallery:(r.images.gallery||[]).map(a=>new N(a))}}}),this.isActive=t.isActive,this.searchTags=t.searchTags?m.deepClone(t.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(t){return t?this.name[t]??this.name[D[t]]??this.name.en:m.deepClone(this.name)}getDescription(t){return t?this.description[t]??this.description[D[t]]??this.description.en:m.deepClone(this.description)}getSlug(t){return t?this.slug[t]??this.slug[D[t]]??this.slug.en:m.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(t){return t?this.pricing[t]??null:{...this.pricing}}getAttributes(){return m.deepClone(this.attributes)}getVariants(){return this.variants.map(t=>({sku:t.sku,selectionAttributes:m.deepClone(t.selectionAttributes),images:{primary:t.images.primary,gallery:[...t.images.gallery]}}))}getImagesBySelectionAttributes(t){let e=n.generateSelectionAttributesKey(t),i=this.variants.find(r=>n.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 m.deepClone(this.categories)}getSpecifications(t){return t?m.deepClone(this.specifications[t]??this.specifications[D[t]]??this.specifications.en):m.deepClone(this.specifications)}getSearchTags(t){return t?m.deepClone(this.searchTags[t]??this.searchTags[D[t]]??this.searchTags.en):m.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:m.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 w("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 w(`Selection attribute '${e}' is missing`);if(typeof i=="string"){if(typeof r!="string"||i!==r)throw new w(`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 w(`Selection attribute '${e}' is invalid`)}else if(typeof r!="object"||!("name"in r)||i.findIndex(o=>o.name===r.name)<0)throw new w(`Selection attribute '${e}' is invalid`)}});}validateSelectionAttribute(t){let e=n.generateSelectionAttributesKey(t);return this.variants.some(i=>n.generateSelectionAttributesKey(i.selectionAttributes)===e)}validateSize(t){return this.attributes.size.includes(t)}};var U=class extends L{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 G=class extends R{taxRuleId;taxCategory;taxSystem;taxSubSystem;country;rate;minPrice;maxPrice;excludeMin;excludeMax;effectiveFrom;effectiveTo;constructor(t){super(t),this.taxRuleId=t.taxRuleId,this.taxSystem=t.taxSystem,this.taxSubSystem=t.taxSubSystem,this.taxCategory=t.taxCategory,this.country=t.country,this.rate=t.rate,this.minPrice=new s(t.minPrice),this.maxPrice=t.maxPrice?new s(t.maxPrice):void 0,this.excludeMin=t.excludeMin??!1,this.excludeMax=t.excludeMax??!1,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}getCountry(){return this.country}getRate(){return this.rate}getMinPrice(){return this.minPrice}getMaxPrice(){return this.maxPrice}getExcludeMin(){return this.excludeMin}getExcludeMax(){return this.excludeMax}getEffectiveFrom(){return this.effectiveFrom}getEffectiveTo(){return this.effectiveTo}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxSubSystem:this.getTaxSubSystem(),taxCategory:this.getTaxCategory(),country:this.getCountry(),rate:this.getRate(),minPrice:this.getMinPrice().getDetails(),maxPrice:this.getMaxPrice()?.getDetails(),excludeMin:this.getExcludeMin(),excludeMax:this.getExcludeMax(),effectiveFrom:this.effectiveFrom,effectiveTo:this.effectiveTo?this.effectiveTo:void 0,customFields:this.getAllCustomFields()}}appliesTo(t,e,i,r=new Date){let o=!i||(this.excludeMin?this.minPrice.compareTo(i)<0:this.minPrice.compareTo(i)<=0)&&(this.maxPrice?this.excludeMax?this.maxPrice.compareTo(i)>0:this.maxPrice.compareTo(i)>=0:!0);return this.taxCategory===t&&this.country===e&&o&&Date.parse(this.effectiveFrom)<=r.getTime()&&(this.effectiveTo?Date.parse(this.effectiveTo)>=r.getTime():!0)}getApplicableTaxRate(t){return this.appliesTo(this.taxCategory,this.country,t)?this.rate:0}calculateTax(t){return this.appliesTo(this.taxCategory,this.country,t)?t.multiply(this.rate):t.zero()}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}%`}};var q=class extends R{id;productKey;selectionAttributes;name;specifications;primaryImage;subItems;pricing;state;total;constructor(t){super(t),this.id=t.id,this.productKey=t.productKey,this.selectionAttributes=m.deepClone(t.selectionAttributes),this.name=m.deepClone(t.name),this.specifications=m.deepClone(t.specifications),this.primaryImage=new N(t.primaryImage),this.subItems=m.deepClone(t.subItems);let e=new Set;this.subItems.forEach(i=>{if(e.has(i.size))throw new tt(i.size);e.add(i.size);}),this.pricing={unitPrice:new s(t.pricing.unitPrice),tierPricing:new V(t.pricing.tierPricing),taxCategory:t.pricing.taxCategory,applicableTaxRule:t.pricing.applicableTaxRule.map(i=>new G(i))},this.validateTaxRules(this.pricing.applicableTaxRule),this.state=t.state??"INITIAL",this.total={quantity:t.total.quantity,unitPrice:new s(t.total.unitPrice),subtotal:new s(t.total.subtotal),discountTotal:new s(t.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(t.total.discountBreakdown).map(([i,r])=>[i,new s(r)])),netUnitPrice:new s(t.total.netUnitPrice),netSubtotal:new s(t.total.netSubtotal),taxTotal:new s(t.total.taxTotal),taxBreakdown:Object.fromEntries(Object.entries(t.total.taxBreakdown).map(([i,r])=>[i,{rate:r.rate,taxableUnitPrice:new s(r.taxableUnitPrice),taxPerUnit:new s(r.taxPerUnit),taxAmount:new s(r.taxAmount),system:r.system,subSystem:r.subSystem}])),grandTotal:new s(t.total.grandTotal)};}getId(){return this.id}getProductKey(){return this.productKey}getSelectionAttributes(){return m.deepClone(this.selectionAttributes)}getName(t){return t?m.deepClone(this.name[t]??this.name[D[t]]??this.name.en):m.deepClone(this.name)}getSpecifications(t){return t?m.deepClone(this.specifications[t]??this.specifications[D[t]]??this.specifications.en):m.deepClone(this.specifications)}getImage(){return this.primaryImage}getSubItems(){return m.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,discountTotal:this.total.discountTotal,discountBreakdown:Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([t,e])=>[t,e])),netUnitPrice:this.total.netUnitPrice,netSubtotal:this.total.netSubtotal,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,e])=>[t,{rate:e.rate,taxableUnitPrice:e.taxableUnitPrice,taxPerUnit:e.taxPerUnit,taxAmount:e.taxAmount,system:e.system,subSystem:e.subSystem}])),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(),discountTotal:e.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(e.discountBreakdown).map(([i,r])=>[i,r.getDetails()])),netUnitPrice:e.netUnitPrice.getDetails(),netSubtotal:e.netSubtotal.getDetails(),taxTotal:e.taxTotal.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(e.taxBreakdown).map(([i,r])=>[i,{rate:r.rate,taxableUnitPrice:r.taxableUnitPrice.getDetails(),taxPerUnit:r.taxPerUnit.getDetails(),taxAmount:r.taxAmount.getDetails(),system:r.system,subSystem:r.subSystem}])),grandTotal:e.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}validateTaxRules(t){let e=new Set;for(let i=0;i<t.length;i++){let r=t[i].getTaxRuleId();if(e.has(r))throw new _("Duplicate tax rule ID found: "+r);e.add(r);}}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 it;if(!t.getIsActive())throw new rt;this.subItems.forEach(g=>{if(!t.validateSize(g.size))throw new nt});let r=t.getPriceDetails(e);if(!r||r.getBaseUnitPrice().getCurrency()!==i)throw new ot;this.name=t.getName(),this.specifications=t.getSpecifications(),this.primaryImage=t.getImages(this.selectionAttributes).primary;let o=this.subItems.reduce((g,d)=>g+d.quantity,0),{unitPrice:a}=r.getApplicableTier(o);this.pricing={unitPrice:a,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.discountBreakdown=e,this.calculateTotals();}updateTax(t){t.forEach(e=>{if(!e.appliesTo(this.pricing.taxCategory,e.getCountry()))throw new z}),this.validateTaxRules(t),this.pricing.applicableTaxRule=t,this.calculateTotals();}calculateTotals(){let t=this.pricing.unitPrice.zero(),e=this.subItems.reduce((h,C)=>h+C.quantity,0);if(this.state==="CANCELLED"){this.total={quantity:0,unitPrice:t,subtotal:t,discountTotal:t,discountBreakdown:{},netUnitPrice:t,netSubtotal:t,taxTotal:t,taxBreakdown:{},grandTotal:t};return}let{unitPrice:i}=this.pricing.tierPricing.getApplicableTier(e),r=i.multiply(e),o=Object.values(this.total.discountBreakdown).reduce((h,C)=>h.add(C),t),a=r.subtract(o),g=e>0?a.divide(e):t,d={},c=t;this.pricing.applicableTaxRule.forEach(h=>{let C=h.getApplicableTaxRate(g),T=h.calculateTax(g),A=T.multiply(e).round();d[h.getTaxRuleId()]={rate:C,taxableUnitPrice:g,taxPerUnit:T,taxAmount:A,system:h.getTaxSystem(),subSystem:h.getTaxSubSystem()},c=c.add(A);});let u=a.add(c);this.total={quantity:e,unitPrice:i,subtotal:r,discountTotal:o,discountBreakdown:this.total.discountBreakdown,netUnitPrice:g,netSubtotal:a,taxTotal:c,taxBreakdown:d,grandTotal:u};}updateState(t){if(this.state in mt)this.state!==t&&(this.state=t);else throw new W(t)}clearLineItem(){let t=this.pricing.unitPrice.zero();this.id="",this.productKey="",this.selectionAttributes={color:{name:""}},this.name={en:""},this.primaryImage=new N({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,discountTotal:t,discountBreakdown:{},netUnitPrice:t,netSubtotal:t,taxTotal:t,taxBreakdown:{},grandTotal:t};}};var J=class extends L{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=m.deepClone(t.name),this.description=m.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 s(o)),i},{}),this.maxCartDiscount=Object.keys(t.maxCartDiscount).reduce((i,r)=>{let o=t.maxCartDiscount[r];return o&&(i[r]=new s(o)),i},{}),this.discountMethod=t.discountMethod,this.percentageValue=t.percentageValue??0,this.percentageValue>100)throw new P("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[D[t]]??this.name.en:{...this.name}}getDescription(t){return t?this.description[t]??this.description[D[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 a=new s({amount:0,currency:r}),g;if(o&&!this.isActive())return a;let d=this.getMinCartValue(i),c=this.getMaxCartDiscount(i);if(!d||d.compareTo(t)>0||!c)return a;let u=this.getCategory(),h=this.getDiscountMethod(),C=u==="SHIPPING"?e:t;if(C.getAmount()<=0)return a;switch(h){case"flat":let A=c;g=C.min(A);break;case"percentage":g=C.multiply(this.getPercentageValue()/100).round();break;default:return a}return g.min(c)}};var K=class extends R{id;name;type;category;impact;pricing;lineItemId;total;constructor(t){if(super(t),this.id=t.id,this.name=t.name,this.type=t.type,this.category=t.category,this.impact=t.impact,this.lineItemId=t.lineItemId,this.pricing={baseChargeAmount:new s(t.pricing.baseChargeAmount),taxCategory:t.pricing.taxCategory,applicableTaxRule:t.pricing.applicableTaxRule.map(e=>new G(e))},this.validateTaxRules(this.pricing.applicableTaxRule),this.impact==="SUBTRACT"&&this.type!=="ADJUSTMENT")throw new Y("SUBTRACT impact is only allowed for ADJUSTMENT charge");this.total={chargeAmount:new s(t.total.chargeAmount),discountTotal:new s(t.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(t.total.discountBreakdown).map(([e,i])=>[e,new s(i)])),netChargeAmount:new s(t.total.netChargeAmount),taxBreakdown:Object.fromEntries(Object.entries(t.total.taxBreakdown).map(([e,i])=>[e,{rate:i.rate,taxableAmount:new s(i.taxableAmount),taxAmount:new s(i.taxAmount),system:i.system,subSystem:i.subSystem}])),taxTotal:new s(t.total.taxTotal),grandTotal:new s(t.total.grandTotal)};}getId(){return this.id}getName(t){return t?m.deepClone(this.name[t]??this.name[D[t]]??this.name.en):m.deepClone(this.name)}getCategory(){return this.category}getType(){return this.type}getImpact(){return this.impact}getLineItemId(){return this.lineItemId}getPricing(){return {baseChargeAmount:this.pricing.baseChargeAmount,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule]}}getTotal(){return {chargeAmount:this.total.chargeAmount,discountTotal:this.total.discountTotal,discountBreakdown:{...this.total.discountBreakdown},netChargeAmount:this.total.netChargeAmount,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,e])=>[t,{rate:e.rate,taxableAmount:e.taxableAmount,taxAmount:e.taxAmount,system:e.system,subSystem:e.subSystem}])),grandTotal:this.total.grandTotal}}getApplicableTaxRules(){return [...this.pricing.applicableTaxRule]}updateTax(t){if(this.type==="ADJUSTMENT"&&t.length>0)throw new Y("Adjustment charges cannot apply tax rules.");t.forEach(e=>{if(!e.appliesTo(this.pricing.taxCategory,e.getCountry()))throw new z}),this.validateTaxRules(t),this.pricing.applicableTaxRule=t,this.calculateTotals();}validateTaxRules(t){if(this.impact==="SUBTRACT"&&t.some(i=>i.getRate()>0))throw new $("Subtractive charges cannot have positive tax rates.");let e=new Set;for(let i=0;i<t.length;i++){let r=t[i].getTaxRuleId();if(e.has(r))throw new $("Duplicate tax rule ID found: "+r);e.add(r);for(let o=i+1;o<t.length;o++){let a=t[i],g=t[o],d=a.getMinPrice(),c=a.getMaxPrice(),u=a.getExcludeMin(),h=a.getExcludeMax(),C=g.getMinPrice(),T=g.getMaxPrice(),A=g.getExcludeMin(),M=g.getExcludeMax(),x=(()=>{if(!c)return !1;let S=c.compareTo(C);return S<0||S===0&&(h||A)})(),y=(()=>{if(!T)return !1;let S=T.compareTo(d);return S<0||S===0&&(M||u)})();if(!(x||y)&&!(d.compareTo(C)===0&&u===A&&h===M&&(!c&&!T||c&&T&&c.compareTo(T)===0)))throw new $(`Overlapping rules found: [${a.getTaxRuleId()}: ${u?"(":"["}${d.getAmount()}-${c?.getAmount()??"Infinity"}${h?")":"]"}] and [${g.getTaxRuleId()}: ${A?"(":"["}${C.getAmount()}-${T?.getAmount()??"Infinity"}${M?")":"]"}]`)}}}updateDiscounts(t){let e={};t.forEach(i=>{e[i.coupon.getCode()]=i.amount;}),this.total.discountBreakdown=e,this.calculateTotals();}calculateTotals(){let t=this.pricing.baseChargeAmount.zero(),e=this.pricing.baseChargeAmount,i=Object.values(this.total.discountBreakdown).reduce((x,y)=>x.add(y),t),r=e.subtract(i),o={},a=this.pricing.applicableTaxRule.reduce((x,y)=>x+y.getApplicableTaxRate(r),0);if(a<=0){this.total={chargeAmount:e,discountTotal:i,discountBreakdown:this.total.discountBreakdown,netChargeAmount:r,taxTotal:t,taxBreakdown:{},grandTotal:r};return}let g=e.getCurrency(),d=e.getAmount(),c=1e3,u=s.getRoundedAmount(d/(1+a),g),h=u,C=Number.POSITIVE_INFINITY;for(let x=0;x<c;x++){let y=new s({amount:u,currency:g}),S=this.pricing.applicableTaxRule.sort((l,p)=>p.getApplicableTaxRate(y)-l.getApplicableTaxRate(y)).map(l=>s.getRoundedAmount(u*l.getApplicableTaxRate(y),g)).reduce((l,p)=>l+p,0),E=u+S-d,ht=this.pricing.applicableTaxRule.reduce((l,p)=>l+p.getApplicableTaxRate(y),0);if(Math.abs(E)<Math.abs(C)&&(C=E,h=u),E===0||(u=u-E/(1+ht),u<0||u>d))break}let T=new s({amount:h,currency:g}),A=t;this.pricing.applicableTaxRule.sort((x,y)=>y.getApplicableTaxRate(T)-x.getApplicableTaxRate(T)).forEach(x=>{let y=x.getApplicableTaxRate(T),F=s.getRoundedAmount(h*y,g),S=new s({amount:F,currency:g});o[x.getTaxRuleId()]={rate:y,taxableAmount:T,taxAmount:S,system:x.getTaxSystem(),subSystem:x.getTaxSubSystem()},A=A.add(S);});let M=r;this.total={chargeAmount:e,discountTotal:i,discountBreakdown:this.total.discountBreakdown,netChargeAmount:r,taxBreakdown:o,taxTotal:A,grandTotal:M};}getDetails(){return {id:this.id,name:m.deepClone(this.name),type:this.type,category:this.category,pricing:{baseChargeAmount:this.pricing.baseChargeAmount.getDetails(),taxCategory:this.pricing.taxCategory,applicableTaxRule:this.pricing.applicableTaxRule.map(e=>e.getDetails())},impact:this.impact,lineItemId:this.lineItemId,total:{chargeAmount:this.total.chargeAmount.getDetails(),discountTotal:this.total.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([e,i])=>[e,i.getDetails()])),netChargeAmount:this.total.netChargeAmount.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([e,i])=>[e,{rate:i.rate,taxableAmount:i.taxableAmount.getDetails(),taxAmount:i.taxAmount.getDetails(),system:i.system,subSystem:i.subSystem}])),taxTotal:this.total.taxTotal.getDetails(),grandTotal:this.total.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}};var X=class extends L{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 q(i)),this.charges=(t.charges??[]).map(i=>new K(i)),this.billingAddress=t.billingAddress?new U(t.billingAddress,e):null,this.shippingAddress=t.shippingAddress?new U(t.shippingAddress,e):null,this.coupons=(t.coupons??[]).map(i=>new J(i)),this.shippingDetails=t.shippingDetails?m.deepClone(t.shippingDetails):null,this.total={lineItemSubtotal:new s(t.total.lineItemSubtotal),netLineItemSubtotal:new s(t.total.netLineItemSubtotal),lineItemTaxTotal:new s(t.total.lineItemTaxTotal),lineItemTaxBreakdown:this.mapTaxBreakdown(t.total.lineItemTaxBreakdown),additiveCharges:new s(t.total.additiveCharges),netAdditiveCharges:new s(t.total.netAdditiveCharges),additiveChargesTaxTotal:new s(t.total.additiveChargesTaxTotal),additiveChargesTaxBreakdown:this.mapTaxBreakdown(t.total.additiveChargesTaxBreakdown),adjustmentCharges:new s(t.total.adjustmentCharges),shippingCharges:new s(t.total.shippingCharges),netShippingCharges:new s(t.total.netShippingCharges),discountTotal:new s(t.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(t.total.discountBreakdown).map(([i,r])=>[i,new s(r)])),taxTotal:new s(t.total.taxTotal),taxBreakdown:this.mapTaxBreakdown(t.total.taxBreakdown),grandTotal:new s(t.total.grandTotal)};}mapTaxBreakdown(t){return Object.fromEntries(Object.entries(t||{}).map(([e,i])=>[e,{system:i.system,totalAmount:new s(i.totalAmount),subSystems:Object.fromEntries(Object.entries(i.subSystems).map(([r,o])=>[r,new s(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 q(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getCharges(){return this.charges.map(t=>new K(t.getDetails()))}addCharge(t){this.charges.push(t),this.calculateTotals();}clearCharges(){this.charges=[],this.calculateTotals();}getShippingDetails(){return this.shippingDetails?m.deepClone(this.shippingDetails):null}getShippingAddress(){return this.shippingAddress?new U(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new U(this.billingAddress.getDetails()):null}getCoupons(){return [...this.coupons]}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return {lineItemSubtotal:this.total.lineItemSubtotal,netLineItemSubtotal:this.total.netLineItemSubtotal,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}}])),additiveCharges:this.total.additiveCharges,netAdditiveCharges:this.total.netAdditiveCharges,additiveChargesTaxTotal:this.total.additiveChargesTaxTotal,additiveChargesTaxBreakdown:Object.fromEntries(Object.entries(this.total.additiveChargesTaxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),adjustmentCharges:this.total.adjustmentCharges,shippingCharges:this.total.shippingCharges,netShippingCharges:this.total.netShippingCharges,discountBreakdown:{...this.total.discountBreakdown},discountTotal:this.total.discountTotal,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}}])),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:{lineItemSubtotal:t.lineItemSubtotal.getDetails(),netLineItemSubtotal:t.netLineItemSubtotal.getDetails(),lineItemTaxTotal:t.lineItemTaxTotal.getDetails(),lineItemTaxBreakdown:this.serializeTaxBreakdown(t.lineItemTaxBreakdown),additiveCharges:t.additiveCharges.getDetails(),netAdditiveCharges:t.netAdditiveCharges.getDetails(),additiveChargesTaxTotal:t.additiveChargesTaxTotal.getDetails(),additiveChargesTaxBreakdown:this.serializeTaxBreakdown(t.additiveChargesTaxBreakdown),adjustmentCharges:t.adjustmentCharges.getDetails(),shippingCharges:t.shippingCharges.getDetails(),netShippingCharges:t.netShippingCharges.getDetails(),discountTotal:t.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(t.discountBreakdown).map(([e,i])=>[e,i.getDetails()])),taxTotal:t.taxTotal.getDetails(),taxBreakdown:this.serializeTaxBreakdown(t.taxBreakdown),grandTotal:t.grandTotal.getDetails()},country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}calculateTotals(){let t=new s({amount:0,currency:this.currency}),e=this.lineItems.filter(l=>l.getState()!=="CANCELLED"),i=e.reduce((l,p)=>l.add(p.getTotal().subtotal),t),r=this.charges.filter(l=>l.getType()==="SHIPPING").reduce((l,p)=>l.add(p.getTotal().chargeAmount),t);this.total.lineItemSubtotal=i,this.total.shippingCharges=r;let o=t,a={},g={};this.coupons.forEach(l=>{let p=l.calculateApplicableCouponDiscount(i,r,this.country,this.currency);o=o.add(p),a[l.getCode()]=p,l.getCategory()!=="SHIPPING"&&(g[l.getCode()]=p);}),this.total.discountTotal=o,this.total.discountBreakdown=a,this.applyDiscountsInLineItem(g);let d=this.coupons.find(l=>l.getCategory()==="SHIPPING");d?this.applyDiscountsInShippingCharges({[d.getCode()]:a[d.getCode()]||t}):this.applyDiscountsInShippingCharges({});let c=this.lineItems.reduce((l,p)=>l.add(p.getTotal().netSubtotal),t),u=this.charges.filter(l=>l.getType()==="SHIPPING").reduce((l,p)=>l.add(p.getTotal().grandTotal),t);this.total.netLineItemSubtotal=c,this.total.netShippingCharges=u;let h=this.charges.filter(l=>l.getImpact()==="ADD").reduce((l,p)=>l.add(p.getTotal().chargeAmount),t),C=this.charges.filter(l=>l.getImpact()==="ADD").reduce((l,p)=>l.add(p.getTotal().grandTotal),t),T=this.charges.filter(l=>l.getImpact()==="SUBTRACT").reduce((l,p)=>l.add(p.getTotal().grandTotal),t),A=t,M=t,x=t,y={},F={},S={},E=(l,p)=>{Object.entries(l).forEach(([Kt,k])=>{let f=k.system,O=k.subSystem;p[f]||(p[f]={system:f,totalAmount:t,subSystems:{}}),p[f].subSystems[O]?p[f].subSystems[O]=p[f].subSystems[O].add(k.taxAmount):p[f].subSystems[O]=k.taxAmount,p[f].totalAmount=p[f].totalAmount.add(k.taxAmount),y[f]||(y[f]={system:f,totalAmount:t,subSystems:{}}),y[f].subSystems[O]?y[f].subSystems[O]=y[f].subSystems[O].add(k.taxAmount):y[f].subSystems[O]=k.taxAmount,y[f].totalAmount=y[f].totalAmount.add(k.taxAmount);});};e.forEach(l=>{let p=l.getTotal().taxBreakdown;p&&(E(p,F),E(p,y),M=M.add(l.getTotal().taxTotal));}),this.charges.forEach(l=>{let p=l.getTotal().taxBreakdown;p&&(E(p,S),E(p,y),x=x.add(l.getTotal().taxTotal));}),A=M.add(x);let ht=c.add(M).add(C).subtract(T);this.total={lineItemSubtotal:i,netLineItemSubtotal:c,lineItemTaxTotal:M,lineItemTaxBreakdown:F,additiveCharges:h,netAdditiveCharges:C,additiveChargesTaxTotal:x,additiveChargesTaxBreakdown:S,adjustmentCharges:T,shippingCharges:r,netShippingCharges:u,discountTotal:o,discountBreakdown:a,taxTotal:A,taxBreakdown:y,grandTotal:ht};}updateShippingDetails(t){this.shippingDetails=t;}applyCoupons(t){let e=t.filter(r=>r.getCategory()==="SHIPPING"),i=t.filter(r=>r.getCategory()!=="SHIPPING");this.coupons=[],this.total.discountTotal=this.total.lineItemSubtotal.zero(),this.total.discountBreakdown={},i.length&&this.applyNonShippingCoupons(i),this.applyDiscountsInLineItem(this.total.discountBreakdown),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 a=this.coupons.find(c=>c.getCode()===r);if(!a||o.isZero())return;let g=this.lineItems.filter(c=>c.getState()!=="CANCELLED"&&!c.getTotal().subtotal.isZero()).sort((c,u)=>c.getTotal().subtotal.compareTo(u.getTotal().subtotal)),d=new s({amount:0,currency:this.currency});g.forEach((c,u)=>{let h;u===g.length-1?h=o.subtract(d):h=o.multiply(c.getTotal().subtotal).divide(this.total.lineItemSubtotal).round(),d=d.add(h),i.get(c.getId())?.push({coupon:a,amount:h});});}),this.lineItems.forEach(r=>{r.getState()==="CANCELLED"||this.total.lineItemSubtotal.isZero()?r.updateDiscounts([]):r.updateDiscounts(i.get(r.getId())||[]);});}applyDiscountsInShippingCharges(t){let e=Array.from(Object.entries(t)).filter(o=>!o[1].isZero()),i=this.charges.filter(o=>o.getType()==="SHIPPING"),r=new Map;i.forEach(o=>r.set(o.getId(),[])),e.forEach(([o,a])=>{let g=this.coupons.find(u=>u.getCode()===o);if(!g||a.isZero())return;let d=i.sort((u,h)=>u.getTotal().grandTotal.compareTo(h.getTotal().grandTotal)),c=new s({amount:0,currency:this.currency});d.forEach((u,h)=>{let C;h===d.length-1?C=a.subtract(c):C=a.multiply(u.getTotal().chargeAmount).divide(this.total.shippingCharges).round(),c=c.add(C),r.get(u.getId())?.push({coupon:g,amount:C});});}),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.lineItemSubtotal,this.total.shippingCharges,this.country,this.currency);i.getAmount()>0&&(this.coupons.push(e[0]),this.total.discountTotal=i,this.total.discountBreakdown[e[0].getCode()]=i);}}applyShippingCoupons(t){if(this.total.shippingCharges.getAmount()>0&&t.length>0){let e=this.total.lineItemSubtotal.subtract(this.total.discountTotal),i=t.reduce((o,a)=>{if(!o)return a;let g=a.calculateApplicableCouponDiscount(e,this.total.shippingCharges,this.country,this.currency).min(this.total.shippingCharges),d=o.calculateApplicableCouponDiscount(e,this.total.shippingCharges,this.country,this.currency).min(this.total.shippingCharges);return g.compareTo(d)===0?a.getType()==="coupon"?a:o:g.compareTo(d)>0?a:o}),r=i.calculateApplicableCouponDiscount(e,this.total.shippingCharges,this.country,this.currency).min(this.total.shippingCharges);r.getAmount()>0&&(this.coupons.push(i),this.total.discountTotal=this.total.discountTotal.add(r),this.total.discountBreakdown[i.getCode()]=r);}}};var Gt=(r=>(r.ACTIVE="ACTIVE",r.FROZEN="FROZEN",r.MERGED="MERGED",r.ORDERED="ORDERED",r))(Gt||{}),qt={expiresAtInSeconds:120*24*60*60},ft=class extends X{state;expireAt;config;constructor(t,e=new Date,i=qt){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.charges=[],this.coupons=[],this.shippingDetails=null,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=B.generateSelectionAttributesKey(i),o=this.lineItems.findIndex(a=>a.getProductKey()===e&&B.generateSelectionAttributesKey(a.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(a=>a.getId()===t);if(o<0)throw new Q(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 Q(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=Gt;exports.DEFAULT_CART_CONFIG=qt;exports.default=ft;//# sourceMappingURL=Cart.js.map
|
|
1
|
+
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var Lt=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Lt__default=/*#__PURE__*/_interopDefault(Lt);var Q=class extends Error{constructor(t){super(`Line item with ID '${t}' not found in the cart.`),this.name="LineItemNotFoundError";}},W=class extends Error{constructor(t){super(`Invalid line item state: ${t}`),this.name="InvalidLineItemStateError";}},_=class extends Error{constructor(t){super(`InvalidLineItemTaxRule: ${t}`),this.name="InvalidLineItemTaxRuleError";}},tt=class extends Error{constructor(t){super(`Duplicate size found: ${t}`),this.name="DuplicateSizeError";}},et=class extends Error{constructor(t){super(`Duplicate selection attribute found: ${t}`),this.name="DuplicateSelectionAttributeError";}},it=class extends Error{constructor(t="Product and selection attributes do not match."){super(`ProductMismatch: ${t}`),this.name="ProductMismatchError";}},rt=class extends Error{constructor(t="Product is not active."){super(`ProductInactive: ${t}`),this.name="ProductInactiveError";}},w=class extends Error{constructor(t="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${t}`),this.name="SelectionAttributeParseError";}},nt=class extends Error{constructor(t="Size does not match."){super(`SizeMismatch: ${t}`),this.name="SizeMismatchError";}},ot=class extends Error{constructor(t="Pricing details not available for the product"){super(`NotFound: ${t}`),this.name="PricingNotFoundError";}},z=class extends Error{constructor(t="Tax rule category mismatch."){super(`InvalidTaxRule: ${t}`),this.name="InvalidTaxRuleError";}},st=class extends Error{constructor(t="Tax category is not valid."){super(`InvalidTaxCategory: ${t}`),this.name="InvalidTaxCategoryError";}},at=class extends Error{constructor(t="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${t}`),this.name="InvalidMinQuantityError";}},ct=class extends Error{constructor(t){super(`InvalidTieredPrice: ${t}`),this.name="InvalidTieredPriceError";}},lt=class extends Error{constructor(t="Quantity must be greater than zero."){super(`InvalidQuantity: ${t}`),this.name="InvalidQuantityError";}},ut=class extends Error{constructor(t){super(`NoApplicableTier: Quantity ${t} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}};var H=class extends Error{constructor(t="Amount cannot be negative."){super(`InvalidAmount: ${t}`),this.name="InvalidPriceAmountError";}},j=class extends Error{constructor(t="Currency code is required."){super(`InvalidCurrency: ${t}`),this.name="InvalidCurrencyCodeError";}},v=class extends Error{constructor(t="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${t}`),this.name="CurrencyMismatchError";}},P=class extends Error{constructor(t){super(`InvalidArgument: ${t}`),this.name="InvalidArgumentError";}},Z=class extends Error{constructor(t="Invalid image source configuration."){super(`InvalidImageSource: ${t}`),this.name="InvalidImageSourceError";}},Y=class extends Error{constructor(t="Invalid charge data."){super(`InvalidCharge: ${t}`),this.name="InvalidChargeError";}},$=class extends Error{constructor(t="Invalid charge tax rule."){super(`InvalidChargeTaxRule: ${t}`),this.name="InvalidChargeTaxRuleError";}};var gt=new Uint8Array(256),dt=gt.length;function yt(){return dt>gt.length-16&&(Lt__default.default.randomFillSync(gt),dt=0),gt.slice(dt,dt+=16)}var It=/^(?:[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 vt(n){return typeof n=="string"&&It.test(n)}var At=vt;var I=[];for(let n=0;n<256;++n)I.push((n+256).toString(16).slice(1));function pt(n,t=0){return I[n[t+0]]+I[n[t+1]]+I[n[t+2]]+I[n[t+3]]+"-"+I[n[t+4]]+I[n[t+5]]+"-"+I[n[t+6]]+I[n[t+7]]+"-"+I[n[t+8]]+I[n[t+9]]+"-"+I[n[t+10]]+I[n[t+11]]+I[n[t+12]]+I[n[t+13]]+I[n[t+14]]+I[n[t+15]]}function Et(n){if(!At(n))throw TypeError("Invalid UUID");let t,e=new Uint8Array(16);return e[0]=(t=parseInt(n.slice(0,8),16))>>>24,e[1]=t>>>16&255,e[2]=t>>>8&255,e[3]=t&255,e[4]=(t=parseInt(n.slice(9,13),16))>>>8,e[5]=t&255,e[6]=(t=parseInt(n.slice(14,18),16))>>>8,e[7]=t&255,e[8]=(t=parseInt(n.slice(19,23),16))>>>8,e[9]=t&255,e[10]=(t=parseInt(n.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 St=Et;function Bt(n){n=unescape(encodeURIComponent(n));let t=[];for(let e=0;e<n.length;++e)t.push(n.charCodeAt(e));return t}var Rt="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Nt="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function bt(n,t,e){function i(r,o,a,g){var d;if(typeof r=="string"&&(r=Bt(r)),typeof o=="string"&&(o=St(o)),((d=o)===null||d===void 0?void 0:d.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,a){g=g||0;for(let u=0;u<16;++u)a[g+u]=c[u];return a}return pt(c)}try{i.name=n;}catch{}return i.DNS=Rt,i.URL=Nt,i}var Ct={randomUUID:Lt__default.default.randomUUID};function Ot(n,t,e){if(Ct.randomUUID&&!t&&!n)return Ct.randomUUID();n=n||{};let i=n.random||(n.rng||yt)();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 pt(i)}var xt=Ot;function Ft(n){return Array.isArray(n)?n=Buffer.from(n):typeof n=="string"&&(n=Buffer.from(n,"utf8")),Lt__default.default.createHash("sha1").update(n).digest()}var Pt=Ft;var zt=bt("v5",80,Pt),Tt=zt;var jt={isUUID:n=>/^[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(n),isEmail:n=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(n),isURL:n=>/^(http|https):\/\/[^ "]+$/.test(n),generateUUID:(n,t)=>t&&n?Tt(n,t):xt(),generateSearchId:(n,t)=>`${n}#${B.generateSelectionAttributesKey(t)}`,getKeyfromSearchId:n=>{let[t,e]=n.split("#");return {key:t,selectionAttributes:B.parseSelectionAttributesKey(e)}},deepClone(n){return structuredClone(n)}},m=jt;var Dt=n=>structuredClone(n),R=class{customFields;constructor(t,e=new Date){this.customFields={...t.customFields};}getCustomField(t){let e=this.customFields[t];return e==null?e:Dt(e)}setCustomField(t,e){this.customFields[t]=e;}getAllCustomFields(){return Dt(this.customFields)}},L=class extends R{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 D={"en-IN":"en","kn-IN":"kn"};var Mt={INR:"\u20B9"},wt={INR:"en-IN"};var mt=(u=>(u.INITIAL="INITIAL",u.PROCESSING="PROCESSING",u.SHIPPED="SHIPPED",u.DELIVERED="DELIVERED",u.CANCELLED="CANCELLED",u.RETURN_REQUESTED="RETURN_REQUESTED",u.RETURNED="RETURNED",u.REFUND_INITIATED="REFUND_INITIATED",u.REFUNDED="REFUNDED",u.ON_HOLD="ON_HOLD",u))(mt||{});var N=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 Z("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 Z("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 s=class n{#t;amount;currency;constructor(t){if(this.#t="PriceModel",t.amount<0)throw new H("Amount cannot be negative.");if(!t.currency)throw new j("Currency code is required.");this.currency=t.currency,this.amount=parseFloat(t.amount.toFixed(n.getPrecisionPlaces(this.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}}getPreciseAmount(t){return parseFloat(t.toFixed(n.getPrecisionPlaces(this.currency)))}compareTo(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new v("Cannot compare prices in different currencies.")}else throw new P("Must be a PriceModel instance.");return this.getPreciseAmount(this.amount-t.getAmount())}add(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new v("Cannot add prices in different currencies.")}else throw new P("Must be a PriceModel instance.");return new n({amount:this.getPreciseAmount(this.amount+t.getAmount()),currency:this.currency})}subtract(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new v("Cannot subtract prices in different currencies.")}else throw new P("Must be a PriceModel instance.");return new n({amount:this.getPreciseAmount(this.amount-t.getAmount()),currency:this.currency})}multiply(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new v("Cannot multiply prices in different currencies.");return new n({amount:this.getPreciseAmount(this.amount*t.getAmount()),currency:this.currency})}else if(typeof t=="number"&&t>=0)return new n({amount:this.getPreciseAmount(this.amount*t),currency:this.currency});throw new P("Must be a non-negative number.")}divide(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new v("Cannot divide prices in different currencies.");return new n({amount:this.getPreciseAmount(this.amount/t.getAmount()),currency:this.currency})}else if(typeof t=="number"&&t>0)return new n({amount:this.getPreciseAmount(this.amount/t),currency:this.currency});throw new P("Must be a positive number.")}min(...t){if(t.length===0)throw new P("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(n.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new v("Cannot compare prices in different currencies.")}else throw new P("Must be a PriceModel instance.");return e.compareTo(i)<0?e:i},this)}max(...t){if(t.length===0)throw new P("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(n.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new v("Cannot compare prices in different currencies.")}else throw new P("Must be a PriceModel instance.");return e.compareTo(i)>0?e:i},this)}zero(){return new n({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new n({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return n.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return n.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(t,e,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let r=wt[e];if(!e||!r)throw new j("Invalid currency code for formatting.");let o=t,a=i.displayAsInteger?0:n.getDecimalPlaces(e),g={style:i.style??"currency",currency:e,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:a,maximumFractionDigits:a};i.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(r,g).format(o)}catch(d){return console.error(`Error formatting price for currency "${e}" and locale "${r}":`,d),`${Mt[e]??e} ${n.addThousandSeparators(o.toFixed(a))}`}}static getDecimalPlaces(t){switch(t){case"INR":default:return 2}}static getPrecisionPlaces(t){switch(t){case"INR":default:return 6}}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 H("Amount cannot be negative for rounding.");if(e===void 0)throw new j("Invalid currency code for rounding.");let i=n.getDecimalPlaces(e),r=Math.pow(10,i);return Math.round(t*r)/r}};var V=class{baseUnitPrice;taxCategory;tiers;constructor(t){let e=new s(t.baseUnitPrice);if(!t.taxCategory)throw new st;let i=(t.tiers??[]).map(d=>({minQuantity:d.minQuantity,unitPrice:new s(d.unitPrice)})).sort((d,c)=>d.minQuantity-c.minQuantity);if(i.some(d=>d.minQuantity<=0))throw new at;let o=i.some(d=>d.unitPrice.getCurrency()!==e.getCurrency()),a=i.some((d,c)=>c>0&&d.unitPrice.compareTo(i[c-1].unitPrice)>0),g=i[0]?.unitPrice.compareTo(e)>0;if(o||a||g)throw new ct("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 lt;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 ut(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 B=class n extends L{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 w("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,a]=r.split(":");a.startsWith("c+")?e[o]={name:a.slice(2)}:e[o]=a;}return e}catch(e){throw new w(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 V(t.pricing[o])),r),{}),this.targetGender=t.targetGender,this.attributes=m.deepClone(t.attributes),this.specifications=m.deepClone(t.specifications),this.categories=m.deepClone(t.categories);let i=new Set;this.variants=(t.variants||[]).map(r=>{if(!r.selectionAttributes||typeof r.selectionAttributes!="object")throw new w("Selection attributes are required");this.checkSelectionAttributes(r.selectionAttributes);let o=n.generateSelectionAttributesKey(r.selectionAttributes);if(i.has(o))throw new et(o);return i.add(o),{sku:r.sku,selectionAttributes:r.selectionAttributes,images:{primary:new N(r.images.primary),gallery:(r.images.gallery||[]).map(a=>new N(a))}}}),this.isActive=t.isActive,this.searchTags=t.searchTags?m.deepClone(t.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(t){return t?this.name[t]??this.name[D[t]]??this.name.en:m.deepClone(this.name)}getDescription(t){return t?this.description[t]??this.description[D[t]]??this.description.en:m.deepClone(this.description)}getSlug(t){return t?this.slug[t]??this.slug[D[t]]??this.slug.en:m.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(t){return t?this.pricing[t]??null:{...this.pricing}}getAttributes(){return m.deepClone(this.attributes)}getVariants(){return this.variants.map(t=>({sku:t.sku,selectionAttributes:m.deepClone(t.selectionAttributes),images:{primary:t.images.primary,gallery:[...t.images.gallery]}}))}getImagesBySelectionAttributes(t){let e=n.generateSelectionAttributesKey(t),i=this.variants.find(r=>n.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 m.deepClone(this.categories)}getSpecifications(t){return t?m.deepClone(this.specifications[t]??this.specifications[D[t]]??this.specifications.en):m.deepClone(this.specifications)}getSearchTags(t){return t?m.deepClone(this.searchTags[t]??this.searchTags[D[t]]??this.searchTags.en):m.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:m.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 w("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 w(`Selection attribute '${e}' is missing`);if(typeof i=="string"){if(typeof r!="string"||i!==r)throw new w(`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 w(`Selection attribute '${e}' is invalid`)}else if(typeof r!="object"||!("name"in r)||i.findIndex(o=>o.name===r.name)<0)throw new w(`Selection attribute '${e}' is invalid`)}});}validateSelectionAttribute(t){let e=n.generateSelectionAttributesKey(t);return this.variants.some(i=>n.generateSelectionAttributesKey(i.selectionAttributes)===e)}validateSize(t){return this.attributes.size.includes(t)}};var U=class extends L{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 G=class extends R{taxRuleId;taxCategory;taxSystem;taxSubSystem;country;rate;minPrice;maxPrice;excludeMin;excludeMax;effectiveFrom;effectiveTo;constructor(t){super(t),this.taxRuleId=t.taxRuleId,this.taxSystem=t.taxSystem,this.taxSubSystem=t.taxSubSystem,this.taxCategory=t.taxCategory,this.country=t.country,this.rate=t.rate,this.minPrice=new s(t.minPrice),this.maxPrice=t.maxPrice?new s(t.maxPrice):void 0,this.excludeMin=t.excludeMin??!1,this.excludeMax=t.excludeMax??!1,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}getCountry(){return this.country}getRate(){return this.rate}getMinPrice(){return this.minPrice}getMaxPrice(){return this.maxPrice}getExcludeMin(){return this.excludeMin}getExcludeMax(){return this.excludeMax}getEffectiveFrom(){return this.effectiveFrom}getEffectiveTo(){return this.effectiveTo}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxSubSystem:this.getTaxSubSystem(),taxCategory:this.getTaxCategory(),country:this.getCountry(),rate:this.getRate(),minPrice:this.getMinPrice().getDetails(),maxPrice:this.getMaxPrice()?.getDetails(),excludeMin:this.getExcludeMin(),excludeMax:this.getExcludeMax(),effectiveFrom:this.effectiveFrom,effectiveTo:this.effectiveTo?this.effectiveTo:void 0,customFields:this.getAllCustomFields()}}appliesTo(t,e,i,r=new Date){let o=!i||(this.excludeMin?this.minPrice.compareTo(i)<0:this.minPrice.compareTo(i)<=0)&&(this.maxPrice?this.excludeMax?this.maxPrice.compareTo(i)>0:this.maxPrice.compareTo(i)>=0:!0);return this.taxCategory===t&&this.country===e&&o&&Date.parse(this.effectiveFrom)<=r.getTime()&&(this.effectiveTo?Date.parse(this.effectiveTo)>=r.getTime():!0)}getApplicableTaxRate(t){return this.appliesTo(this.taxCategory,this.country,t)?this.rate:0}calculateTax(t){return this.appliesTo(this.taxCategory,this.country,t)?t.multiply(this.rate):t.zero()}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}%`}};var q=class extends R{id;productKey;selectionAttributes;name;specifications;primaryImage;subItems;pricing;state;total;constructor(t){super(t),this.id=t.id,this.productKey=t.productKey,this.selectionAttributes=m.deepClone(t.selectionAttributes),this.name=m.deepClone(t.name),this.specifications=m.deepClone(t.specifications),this.primaryImage=new N(t.primaryImage),this.subItems=m.deepClone(t.subItems);let e=new Set;this.subItems.forEach(i=>{if(e.has(i.size))throw new tt(i.size);e.add(i.size);}),this.pricing={unitPrice:new s(t.pricing.unitPrice),tierPricing:new V(t.pricing.tierPricing),taxCategory:t.pricing.taxCategory,applicableTaxRule:t.pricing.applicableTaxRule.map(i=>new G(i))},this.validateTaxRules(this.pricing.applicableTaxRule),this.state=t.state??"INITIAL",this.total={quantity:t.total.quantity,unitPrice:new s(t.total.unitPrice),subtotal:new s(t.total.subtotal),discountTotal:new s(t.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(t.total.discountBreakdown).map(([i,r])=>[i,new s(r)])),netUnitPrice:new s(t.total.netUnitPrice),netSubtotal:new s(t.total.netSubtotal),taxTotal:new s(t.total.taxTotal),taxBreakdown:Object.fromEntries(Object.entries(t.total.taxBreakdown).map(([i,r])=>[i,{rate:r.rate,taxableUnitPrice:new s(r.taxableUnitPrice),taxPerUnit:new s(r.taxPerUnit),taxAmount:new s(r.taxAmount),system:r.system,subSystem:r.subSystem}])),grandTotal:new s(t.total.grandTotal)};}getId(){return this.id}getProductKey(){return this.productKey}getSelectionAttributes(){return m.deepClone(this.selectionAttributes)}getName(t){return t?m.deepClone(this.name[t]??this.name[D[t]]??this.name.en):m.deepClone(this.name)}getSpecifications(t){return t?m.deepClone(this.specifications[t]??this.specifications[D[t]]??this.specifications.en):m.deepClone(this.specifications)}getImage(){return this.primaryImage}getSubItems(){return m.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,discountTotal:this.total.discountTotal,discountBreakdown:Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([t,e])=>[t,e])),netUnitPrice:this.total.netUnitPrice,netSubtotal:this.total.netSubtotal,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,e])=>[t,{rate:e.rate,taxableUnitPrice:e.taxableUnitPrice,taxPerUnit:e.taxPerUnit,taxAmount:e.taxAmount,system:e.system,subSystem:e.subSystem}])),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(),discountTotal:e.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(e.discountBreakdown).map(([i,r])=>[i,r.getDetails()])),netUnitPrice:e.netUnitPrice.getDetails(),netSubtotal:e.netSubtotal.getDetails(),taxTotal:e.taxTotal.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(e.taxBreakdown).map(([i,r])=>[i,{rate:r.rate,taxableUnitPrice:r.taxableUnitPrice.getDetails(),taxPerUnit:r.taxPerUnit.getDetails(),taxAmount:r.taxAmount.getDetails(),system:r.system,subSystem:r.subSystem}])),grandTotal:e.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}validateTaxRules(t){let e=new Set;for(let i=0;i<t.length;i++){let r=t[i].getTaxRuleId();if(e.has(r))throw new _("Duplicate tax rule ID found: "+r);e.add(r);}}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 it;if(!t.getIsActive())throw new rt;this.subItems.forEach(g=>{if(!t.validateSize(g.size))throw new nt});let r=t.getPriceDetails(e);if(!r||r.getBaseUnitPrice().getCurrency()!==i)throw new ot;this.name=t.getName(),this.specifications=t.getSpecifications(),this.primaryImage=t.getImages(this.selectionAttributes).primary;let o=this.subItems.reduce((g,d)=>g+d.quantity,0),{unitPrice:a}=r.getApplicableTier(o);this.pricing={unitPrice:a,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.discountBreakdown=e,this.calculateTotals();}updateTax(t){t.forEach(e=>{if(!e.appliesTo(this.pricing.taxCategory,e.getCountry()))throw new z}),this.validateTaxRules(t),this.pricing.applicableTaxRule=t,this.calculateTotals();}calculateTotals(){let t=this.pricing.unitPrice.zero(),e=this.subItems.reduce((h,C)=>h+C.quantity,0);if(this.state==="CANCELLED"){this.total={quantity:0,unitPrice:t,subtotal:t,discountTotal:t,discountBreakdown:{},netUnitPrice:t,netSubtotal:t,taxTotal:t,taxBreakdown:{},grandTotal:t};return}let{unitPrice:i}=this.pricing.tierPricing.getApplicableTier(e),r=i.multiply(e),o=Object.values(this.total.discountBreakdown).reduce((h,C)=>h.add(C),t),a=r.subtract(o),g=e>0?a.divide(e):t,d={},c=t;this.pricing.applicableTaxRule.forEach(h=>{let C=h.getApplicableTaxRate(g),T=h.calculateTax(g),A=T.multiply(e).round();d[h.getTaxRuleId()]={rate:C,taxableUnitPrice:g,taxPerUnit:T,taxAmount:A,system:h.getTaxSystem(),subSystem:h.getTaxSubSystem()},c=c.add(A);});let u=a.add(c);this.total={quantity:e,unitPrice:i,subtotal:r,discountTotal:o,discountBreakdown:this.total.discountBreakdown,netUnitPrice:g,netSubtotal:a,taxTotal:c,taxBreakdown:d,grandTotal:u};}updateState(t){if(this.state in mt)this.state!==t&&(this.state=t);else throw new W(t)}clearLineItem(){let t=this.pricing.unitPrice.zero();this.id="",this.productKey="",this.selectionAttributes={color:{name:""}},this.name={en:""},this.primaryImage=new N({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,discountTotal:t,discountBreakdown:{},netUnitPrice:t,netSubtotal:t,taxTotal:t,taxBreakdown:{},grandTotal:t};}};var J=class extends L{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=m.deepClone(t.name),this.description=m.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 s(o)),i},{}),this.maxCartDiscount=Object.keys(t.maxCartDiscount).reduce((i,r)=>{let o=t.maxCartDiscount[r];return o&&(i[r]=new s(o)),i},{}),this.discountMethod=t.discountMethod,this.percentageValue=t.percentageValue??0,this.percentageValue>100)throw new P("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[D[t]]??this.name.en:{...this.name}}getDescription(t){return t?this.description[t]??this.description[D[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 a=new s({amount:0,currency:r}),g;if(o&&!this.isActive())return a;let d=this.getMinCartValue(i),c=this.getMaxCartDiscount(i);if(!d||d.compareTo(t)>0||!c)return a;let u=this.getCategory(),h=this.getDiscountMethod(),C=u==="SHIPPING"?e:t;if(C.getAmount()<=0)return a;switch(h){case"flat":let A=c;g=C.min(A);break;case"percentage":g=C.multiply(this.getPercentageValue()/100).round();break;default:return a}return g.min(c)}};var K=class extends R{id;name;type;category;impact;pricing;lineItemId;total;constructor(t){if(super(t),this.id=t.id,this.name=t.name,this.type=t.type,this.category=t.category,this.impact=t.impact,this.lineItemId=t.lineItemId,this.pricing={baseChargeAmount:new s(t.pricing.baseChargeAmount),taxCategory:t.pricing.taxCategory,applicableTaxRule:t.pricing.applicableTaxRule.map(e=>new G(e))},this.validateTaxRules(this.pricing.applicableTaxRule),this.impact==="SUBTRACT"&&this.type!=="ADJUSTMENT")throw new Y("SUBTRACT impact is only allowed for ADJUSTMENT charge");this.total={chargeAmount:new s(t.total.chargeAmount),discountTotal:new s(t.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(t.total.discountBreakdown).map(([e,i])=>[e,new s(i)])),netChargeAmount:new s(t.total.netChargeAmount),taxBreakdown:Object.fromEntries(Object.entries(t.total.taxBreakdown).map(([e,i])=>[e,{rate:i.rate,taxableAmount:new s(i.taxableAmount),taxAmount:new s(i.taxAmount),system:i.system,subSystem:i.subSystem}])),taxTotal:new s(t.total.taxTotal),grandTotal:new s(t.total.grandTotal)};}getId(){return this.id}getName(t){return t?m.deepClone(this.name[t]??this.name[D[t]]??this.name.en):m.deepClone(this.name)}getCategory(){return this.category}getType(){return this.type}getImpact(){return this.impact}getLineItemId(){return this.lineItemId}getPricing(){return {baseChargeAmount:this.pricing.baseChargeAmount,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule]}}getTotal(){return {chargeAmount:this.total.chargeAmount,discountTotal:this.total.discountTotal,discountBreakdown:{...this.total.discountBreakdown},netChargeAmount:this.total.netChargeAmount,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,e])=>[t,{rate:e.rate,taxableAmount:e.taxableAmount,taxAmount:e.taxAmount,system:e.system,subSystem:e.subSystem}])),grandTotal:this.total.grandTotal}}getApplicableTaxRules(){return [...this.pricing.applicableTaxRule]}updateTax(t){if(this.type==="ADJUSTMENT"&&t.length>0)throw new Y("Adjustment charges cannot apply tax rules.");t.forEach(e=>{if(!e.appliesTo(this.pricing.taxCategory,e.getCountry()))throw new z}),this.validateTaxRules(t),this.pricing.applicableTaxRule=t,this.calculateTotals();}validateTaxRules(t){if(this.impact==="SUBTRACT"&&t.some(i=>i.getRate()>0))throw new $("Subtractive charges cannot have positive tax rates.");let e=new Set;for(let i=0;i<t.length;i++){let r=t[i].getTaxRuleId();if(e.has(r))throw new $("Duplicate tax rule ID found: "+r);e.add(r);for(let o=i+1;o<t.length;o++){let a=t[i],g=t[o],d=a.getMinPrice(),c=a.getMaxPrice(),u=a.getExcludeMin(),h=a.getExcludeMax(),C=g.getMinPrice(),T=g.getMaxPrice(),A=g.getExcludeMin(),M=g.getExcludeMax(),x=(()=>{if(!c)return !1;let S=c.compareTo(C);return S<0||S===0&&(h||A)})(),y=(()=>{if(!T)return !1;let S=T.compareTo(d);return S<0||S===0&&(M||u)})();if(!(x||y)&&!(d.compareTo(C)===0&&u===A&&h===M&&(!c&&!T||c&&T&&c.compareTo(T)===0)))throw new $(`Overlapping rules found: [${a.getTaxRuleId()}: ${u?"(":"["}${d.getAmount()}-${c?.getAmount()??"Infinity"}${h?")":"]"}] and [${g.getTaxRuleId()}: ${A?"(":"["}${C.getAmount()}-${T?.getAmount()??"Infinity"}${M?")":"]"}]`)}}}updateDiscounts(t){let e={};t.forEach(i=>{e[i.coupon.getCode()]=i.amount;}),this.total.discountBreakdown=e,this.calculateTotals();}calculateTotals(){let t=this.pricing.baseChargeAmount.zero(),e=this.pricing.baseChargeAmount,i=Object.values(this.total.discountBreakdown).reduce((x,y)=>x.add(y),t),r=e.subtract(i),o={},a=this.pricing.applicableTaxRule.reduce((x,y)=>x+y.getApplicableTaxRate(r),0);if(a<=0){this.total={chargeAmount:e,discountTotal:i,discountBreakdown:this.total.discountBreakdown,netChargeAmount:r,taxTotal:t,taxBreakdown:{},grandTotal:r};return}let g=r.getCurrency(),d=r.getAmount(),c=1e3,u=s.getRoundedAmount(d/(1+a),g),h=u,C=Number.POSITIVE_INFINITY;for(let x=0;x<c;x++){let y=new s({amount:u,currency:g}),S=this.pricing.applicableTaxRule.sort((l,p)=>p.getApplicableTaxRate(y)-l.getApplicableTaxRate(y)).map(l=>s.getRoundedAmount(u*l.getApplicableTaxRate(y),g)).reduce((l,p)=>l+p,0),E=u+S-d,ht=this.pricing.applicableTaxRule.reduce((l,p)=>l+p.getApplicableTaxRate(y),0);if(Math.abs(E)<Math.abs(C)&&(C=E,h=u),E===0||(u=u-E/(1+ht),u<0||u>d))break}let T=new s({amount:h,currency:g}),A=t;this.pricing.applicableTaxRule.sort((x,y)=>y.getApplicableTaxRate(T)-x.getApplicableTaxRate(T)).forEach(x=>{let y=x.getApplicableTaxRate(T),F=s.getRoundedAmount(h*y,g),S=new s({amount:F,currency:g});o[x.getTaxRuleId()]={rate:y,taxableAmount:T,taxAmount:S,system:x.getTaxSystem(),subSystem:x.getTaxSubSystem()},A=A.add(S);});let M=r;this.total={chargeAmount:e,discountTotal:i,discountBreakdown:this.total.discountBreakdown,netChargeAmount:r,taxBreakdown:o,taxTotal:A,grandTotal:M};}getDetails(){return {id:this.id,name:m.deepClone(this.name),type:this.type,category:this.category,pricing:{baseChargeAmount:this.pricing.baseChargeAmount.getDetails(),taxCategory:this.pricing.taxCategory,applicableTaxRule:this.pricing.applicableTaxRule.map(e=>e.getDetails())},impact:this.impact,lineItemId:this.lineItemId,total:{chargeAmount:this.total.chargeAmount.getDetails(),discountTotal:this.total.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([e,i])=>[e,i.getDetails()])),netChargeAmount:this.total.netChargeAmount.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([e,i])=>[e,{rate:i.rate,taxableAmount:i.taxableAmount.getDetails(),taxAmount:i.taxAmount.getDetails(),system:i.system,subSystem:i.subSystem}])),taxTotal:this.total.taxTotal.getDetails(),grandTotal:this.total.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}};var X=class extends L{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 q(i)),this.charges=(t.charges??[]).map(i=>new K(i)),this.billingAddress=t.billingAddress?new U(t.billingAddress,e):null,this.shippingAddress=t.shippingAddress?new U(t.shippingAddress,e):null,this.coupons=(t.coupons??[]).map(i=>new J(i)),this.shippingDetails=t.shippingDetails?m.deepClone(t.shippingDetails):null,this.total={lineItemSubtotal:new s(t.total.lineItemSubtotal),netLineItemSubtotal:new s(t.total.netLineItemSubtotal),lineItemTaxTotal:new s(t.total.lineItemTaxTotal),lineItemTaxBreakdown:this.mapTaxBreakdown(t.total.lineItemTaxBreakdown),additiveCharges:new s(t.total.additiveCharges),netAdditiveCharges:new s(t.total.netAdditiveCharges),additiveChargesTaxTotal:new s(t.total.additiveChargesTaxTotal),additiveChargesTaxBreakdown:this.mapTaxBreakdown(t.total.additiveChargesTaxBreakdown),adjustmentCharges:new s(t.total.adjustmentCharges),shippingCharges:new s(t.total.shippingCharges),netShippingCharges:new s(t.total.netShippingCharges),discountTotal:new s(t.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(t.total.discountBreakdown).map(([i,r])=>[i,new s(r)])),taxTotal:new s(t.total.taxTotal),taxBreakdown:this.mapTaxBreakdown(t.total.taxBreakdown),grandTotal:new s(t.total.grandTotal)};}mapTaxBreakdown(t){return Object.fromEntries(Object.entries(t||{}).map(([e,i])=>[e,{system:i.system,totalAmount:new s(i.totalAmount),subSystems:Object.fromEntries(Object.entries(i.subSystems).map(([r,o])=>[r,new s(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 q(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getCharges(){return this.charges.map(t=>new K(t.getDetails()))}addCharge(t){this.charges.push(t),this.calculateTotals();}clearCharges(){this.charges=[],this.calculateTotals();}getShippingDetails(){return this.shippingDetails?m.deepClone(this.shippingDetails):null}getShippingAddress(){return this.shippingAddress?new U(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new U(this.billingAddress.getDetails()):null}getCoupons(){return [...this.coupons]}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return {lineItemSubtotal:this.total.lineItemSubtotal,netLineItemSubtotal:this.total.netLineItemSubtotal,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}}])),additiveCharges:this.total.additiveCharges,netAdditiveCharges:this.total.netAdditiveCharges,additiveChargesTaxTotal:this.total.additiveChargesTaxTotal,additiveChargesTaxBreakdown:Object.fromEntries(Object.entries(this.total.additiveChargesTaxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),adjustmentCharges:this.total.adjustmentCharges,shippingCharges:this.total.shippingCharges,netShippingCharges:this.total.netShippingCharges,discountBreakdown:{...this.total.discountBreakdown},discountTotal:this.total.discountTotal,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}}])),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:{lineItemSubtotal:t.lineItemSubtotal.getDetails(),netLineItemSubtotal:t.netLineItemSubtotal.getDetails(),lineItemTaxTotal:t.lineItemTaxTotal.getDetails(),lineItemTaxBreakdown:this.serializeTaxBreakdown(t.lineItemTaxBreakdown),additiveCharges:t.additiveCharges.getDetails(),netAdditiveCharges:t.netAdditiveCharges.getDetails(),additiveChargesTaxTotal:t.additiveChargesTaxTotal.getDetails(),additiveChargesTaxBreakdown:this.serializeTaxBreakdown(t.additiveChargesTaxBreakdown),adjustmentCharges:t.adjustmentCharges.getDetails(),shippingCharges:t.shippingCharges.getDetails(),netShippingCharges:t.netShippingCharges.getDetails(),discountTotal:t.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(t.discountBreakdown).map(([e,i])=>[e,i.getDetails()])),taxTotal:t.taxTotal.getDetails(),taxBreakdown:this.serializeTaxBreakdown(t.taxBreakdown),grandTotal:t.grandTotal.getDetails()},country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}calculateTotals(){let t=new s({amount:0,currency:this.currency}),e=this.lineItems.filter(l=>l.getState()!=="CANCELLED"),i=e.reduce((l,p)=>l.add(p.getTotal().subtotal),t),r=this.charges.filter(l=>l.getType()==="SHIPPING").reduce((l,p)=>l.add(p.getTotal().chargeAmount),t);this.total.lineItemSubtotal=i,this.total.shippingCharges=r;let o=t,a={},g={};this.coupons.forEach(l=>{let p=l.calculateApplicableCouponDiscount(i,r,this.country,this.currency);o=o.add(p),a[l.getCode()]=p,l.getCategory()!=="SHIPPING"&&(g[l.getCode()]=p);}),this.total.discountTotal=o,this.total.discountBreakdown=a,this.applyDiscountsInLineItem(g);let d=this.coupons.find(l=>l.getCategory()==="SHIPPING");d?this.applyDiscountsInShippingCharges({[d.getCode()]:a[d.getCode()]||t}):this.applyDiscountsInShippingCharges({});let c=this.lineItems.reduce((l,p)=>l.add(p.getTotal().netSubtotal),t),u=this.charges.filter(l=>l.getType()==="SHIPPING").reduce((l,p)=>l.add(p.getTotal().grandTotal),t);this.total.netLineItemSubtotal=c,this.total.netShippingCharges=u;let h=this.charges.filter(l=>l.getImpact()==="ADD").reduce((l,p)=>l.add(p.getTotal().chargeAmount),t),C=this.charges.filter(l=>l.getImpact()==="ADD").reduce((l,p)=>l.add(p.getTotal().grandTotal),t),T=this.charges.filter(l=>l.getImpact()==="SUBTRACT").reduce((l,p)=>l.add(p.getTotal().grandTotal),t),A=t,M=t,x=t,y={},F={},S={},E=(l,p)=>{Object.entries(l).forEach(([Kt,k])=>{let f=k.system,O=k.subSystem;p[f]||(p[f]={system:f,totalAmount:t,subSystems:{}}),p[f].subSystems[O]?p[f].subSystems[O]=p[f].subSystems[O].add(k.taxAmount):p[f].subSystems[O]=k.taxAmount,p[f].totalAmount=p[f].totalAmount.add(k.taxAmount),y[f]||(y[f]={system:f,totalAmount:t,subSystems:{}}),y[f].subSystems[O]?y[f].subSystems[O]=y[f].subSystems[O].add(k.taxAmount):y[f].subSystems[O]=k.taxAmount,y[f].totalAmount=y[f].totalAmount.add(k.taxAmount);});};e.forEach(l=>{let p=l.getTotal().taxBreakdown;p&&(E(p,F),E(p,y),M=M.add(l.getTotal().taxTotal));}),this.charges.forEach(l=>{let p=l.getTotal().taxBreakdown;p&&(E(p,S),E(p,y),x=x.add(l.getTotal().taxTotal));}),A=M.add(x);let ht=c.add(M).add(C).subtract(T);this.total={lineItemSubtotal:i,netLineItemSubtotal:c,lineItemTaxTotal:M,lineItemTaxBreakdown:F,additiveCharges:h,netAdditiveCharges:C,additiveChargesTaxTotal:x,additiveChargesTaxBreakdown:S,adjustmentCharges:T,shippingCharges:r,netShippingCharges:u,discountTotal:o,discountBreakdown:a,taxTotal:A,taxBreakdown:y,grandTotal:ht};}updateShippingDetails(t){this.shippingDetails=t;}applyCoupons(t){let e=t.filter(r=>r.getCategory()==="SHIPPING"),i=t.filter(r=>r.getCategory()!=="SHIPPING");this.coupons=[],this.total.discountTotal=this.total.lineItemSubtotal.zero(),this.total.discountBreakdown={},i.length&&this.applyNonShippingCoupons(i),this.applyDiscountsInLineItem(this.total.discountBreakdown),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 a=this.coupons.find(c=>c.getCode()===r);if(!a||o.isZero())return;let g=this.lineItems.filter(c=>c.getState()!=="CANCELLED"&&!c.getTotal().subtotal.isZero()).sort((c,u)=>c.getTotal().subtotal.compareTo(u.getTotal().subtotal)),d=new s({amount:0,currency:this.currency});g.forEach((c,u)=>{let h;u===g.length-1?h=o.subtract(d):h=o.multiply(c.getTotal().subtotal).divide(this.total.lineItemSubtotal).round(),d=d.add(h),i.get(c.getId())?.push({coupon:a,amount:h});});}),this.lineItems.forEach(r=>{r.getState()==="CANCELLED"||this.total.lineItemSubtotal.isZero()?r.updateDiscounts([]):r.updateDiscounts(i.get(r.getId())||[]);});}applyDiscountsInShippingCharges(t){let e=Array.from(Object.entries(t)).filter(o=>!o[1].isZero()),i=this.charges.filter(o=>o.getType()==="SHIPPING"),r=new Map;i.forEach(o=>r.set(o.getId(),[])),e.forEach(([o,a])=>{let g=this.coupons.find(u=>u.getCode()===o);if(!g||a.isZero())return;let d=i.sort((u,h)=>u.getTotal().grandTotal.compareTo(h.getTotal().grandTotal)),c=new s({amount:0,currency:this.currency});d.forEach((u,h)=>{let C;h===d.length-1?C=a.subtract(c):C=a.multiply(u.getTotal().chargeAmount).divide(this.total.shippingCharges).round(),c=c.add(C),r.get(u.getId())?.push({coupon:g,amount:C});});}),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.lineItemSubtotal,this.total.shippingCharges,this.country,this.currency);i.getAmount()>0&&(this.coupons.push(e[0]),this.total.discountTotal=i,this.total.discountBreakdown[e[0].getCode()]=i);}}applyShippingCoupons(t){if(this.total.shippingCharges.getAmount()>0&&t.length>0){let e=this.total.lineItemSubtotal.subtract(this.total.discountTotal),i=t.reduce((o,a)=>{if(!o)return a;let g=a.calculateApplicableCouponDiscount(e,this.total.shippingCharges,this.country,this.currency).min(this.total.shippingCharges),d=o.calculateApplicableCouponDiscount(e,this.total.shippingCharges,this.country,this.currency).min(this.total.shippingCharges);return g.compareTo(d)===0?a.getType()==="coupon"?a:o:g.compareTo(d)>0?a:o}),r=i.calculateApplicableCouponDiscount(e,this.total.shippingCharges,this.country,this.currency).min(this.total.shippingCharges);r.getAmount()>0&&(this.coupons.push(i),this.total.discountTotal=this.total.discountTotal.add(r),this.total.discountBreakdown[i.getCode()]=r);}}};var Gt=(r=>(r.ACTIVE="ACTIVE",r.FROZEN="FROZEN",r.MERGED="MERGED",r.ORDERED="ORDERED",r))(Gt||{}),qt={expiresAtInSeconds:120*24*60*60},ft=class extends X{state;expireAt;config;constructor(t,e=new Date,i=qt){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.charges=[],this.coupons=[],this.shippingDetails=null,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=B.generateSelectionAttributesKey(i),o=this.lineItems.findIndex(a=>a.getProductKey()===e&&B.generateSelectionAttributesKey(a.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(a=>a.getId()===t);if(o<0)throw new Q(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 Q(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=Gt;exports.DEFAULT_CART_CONFIG=qt;exports.default=ft;//# sourceMappingURL=Cart.js.map
|
|
2
2
|
//# sourceMappingURL=Cart.js.map
|