b23-lib 2.1.2 → 2.1.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.
@@ -1,2 +1,2 @@
1
- import {a,b as b$1,c}from'../chunk-OIR5JBJY.mjs';import {a as a$1}from'../chunk-AWZ6KRLF.mjs';import'../chunk-SFUOYZ3L.mjs';import'../chunk-TJ7AZBND.mjs';import'../chunk-72DR3HF2.mjs';import'../chunk-WSUPVXRZ.mjs';import'../chunk-JHELVQYY.mjs';import'../chunk-6KCJVEZD.mjs';import {importPKCS8,SignJWT,importSPKI,jwtVerify,decodeJwt}from'jose';import o from'assert';var b=async(d,e,t="GET",i={},r)=>{let n={method:t,headers:{"Content-Type":"application/json",...i}};t!=="GET"&&r&&(n.body=JSON.stringify(r));let u=`${d}${e?"/"+e:""}`,h=u.includes("api.xetile.com")||u.includes("localhost");try{let a=await fetch(u,n);if(!a.ok){let c,l=await a.text();try{c=JSON.parse(l);}catch{c={status:a.status,error:l||a.statusText},b$1.logWarning("Fetch",`Failed to parse error response body as JSON for URL-${u}. Raw text: ${l}`);}throw {status:a.status,statusText:a.statusText,error:c}}let A=await a.json();return b$1.logMessage("Fetch",`API call successful: URL-${u}, Status- ${a.status}`),{status:a.status,statusText:a.statusText,data:h?A.data:A}}catch(a$1){throw b$1.logError("Fetch",`API call failed: URL-${u}, Status- ${a$1.status||500}, Error- ${b$1.inspect(a$1.error||a$1)}`),{status:a$1.status||500,statusText:a$1.statusText||a.INTERNAL_SERVER_ERROR,error:a$1.error||{status:a$1.status||500,error:a$1.statusText||a.SOMETHING_WENT_WRONG}}}},E=b;var T=class d{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 o(d.instance,a.AUTH_CONTEXT_NOT_INITIALIZED),d.instance}static init(e,t,i,r){return d.instance=new d(e,t,i,r),d.instance}static uninit(){d.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 S={userTokenAge:"30 days",userPrivateKeys:"[]",userPublicKeys:"[]",anonymousTokenAge:"30 days",anonymousPrivateKeys:"[]",anonymousPublicKeys:"[]",systemTokenAge:"5 min",systemPrivateKeys:"[]",systemPublicKeys:"[]",adminTokenAge:"30 days",adminPrivateKeys:"[]",adminPublicKeys:"[]",cdnKeys:"[]"},x=(n=>(n.ANON="Anon",n.USER="User",n.SYSTEM="System",n.ADMIN="Admin",n.CDN="CDN",n))(x||{}),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=S){let{userTokenAge:t,userPrivateKeys:i,userPublicKeys:r,anonymousTokenAge:n,anonymousPrivateKeys:u,anonymousPublicKeys:h,systemTokenAge:a,systemPrivateKeys:A,systemPublicKeys:c,adminTokenAge:l,adminPrivateKeys:p,adminPublicKeys:f,cdnKeys:I}={...S,...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(u,"anonymous private"),this.anonymousPublicKeys=this.parseKeyArray(h,"anonymous public"),this.systemTokenAge=a,this.systemPrivateKeys=this.parseKeyArray(A,"system private"),this.systemPublicKeys=this.parseKeyArray(c,"system public"),this.adminTokenAge=l,this.adminPrivateKeys=this.parseKeyArray(p,"admin private"),this.adminPublicKeys=this.parseKeyArray(f,"admin public"),this.cdnKeys=this.parseKeyArray(I,"cdn"),this.logWarnings();}parseKeyArray(e,t){try{let i=JSON.parse(e);return !Array.isArray(i)||!i.every(r=>typeof r=="string")?(b$1.logError("AuthUtility",`Invalid format for ${t} keys in config: Expected stringified array of strings.`),[]):i}catch(i){return b$1.logError("AuthUtility",`Failed to parse ${t} keys from config: ${i}`),[]}}logWarnings(){let e=(t,i,r)=>i.length>r&&b$1.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.INVALID_TOKEN)}async createAnonymousToken(e,t){o(this.anonymousPrivateKeys.length,a.ANONYMOUS_PRIVATE_KEY_NOT_FOUND),o(a$1.isUUID(e),a.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){o(this.anonymousPublicKeys.length,a.ANONYMOUS_PUBLIC_KEY_NOT_FOUND);let t=await this.verifySignedJWT(e,this.anonymousPublicKeys,this.anonymousTokenAge);return o(t.type==="Anon",a.INVALID_AUTH_TYPE),t}async createUserToken(e,t){o(this.userPrivateKeys.length,a.USER_PRIVATE_KEY_NOT_FOUND),o(a$1.isUUID(e),a.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){o(this.userPublicKeys.length,a.USER_PUBLIC_KEY_NOT_FOUND);let t=await this.verifySignedJWT(e,this.userPublicKeys,this.userTokenAge);return o(t.type==="User",a.INVALID_AUTH_TYPE),t}async createSystemToken(e,t){o(this.systemPrivateKeys.length,a.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){o(this.systemPublicKeys.length,a.USER_PUBLIC_KEY_NOT_FOUND);let t=await this.verifySignedJWT(e,this.systemPublicKeys,this.systemTokenAge);return o(t.type==="System",a.INVALID_AUTH_TYPE),t}async createAdminToken(e,t,i){o(this.adminPrivateKeys.length,a.ADMIN_PRIVATE_KEY_NOT_FOUND),o(a$1.isEmail(e),a.INVALID_EMAIL),o(a$1.isURL(t),a.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){o(this.adminPublicKeys.length,a.ADMIN_PUBLIC_KEY_NOT_FOUND);let r=await this.verifySignedJWT(e,this.adminPublicKeys,this.adminTokenAge);if(o(r.type==="Admin",a.INVALID_AUTH_TYPE),i){let n=await E(r.verifier,"","POST",{},{token:e,permissions:t});if(o(n.data.isTokenValid===!0,a.INVALID_TOKEN),n.data.hasPermissions!==!0)throw c.generateError(403,a.INVALID_PERMISSIONS)}return r}async verifyCDNToken(e){return o(this.cdnKeys.includes(e),a.INVALID_TOKEN),{id:e,type:"CDN"}}AuthMiddleware(e=v,t=[]){let{allowAnonymous:i,allowSystem:r,allowUser:n,allowCDN:u}={...v,...e};return async(h,a$1,A)=>{try{let[c$1,l]=h.get("Authorization")?.split(" ")||[];if(!l)throw new Error(a.INVALID_TOKEN);let p;switch(c$1){case"Anon":if(!i)throw c.generateError(403,a.ANONYMOUS_SESSION_NOT_ALLOWED);p=await this.verifyAnonymousToken(l);break;case"User":if(!n)throw c.generateError(403,a.USER_SESSION_NOT_ALLOWED);p=await this.verifyUserToken(l);break;case"System":if(!r)throw c.generateError(403,a.SYSTEM_SESSION_NOT_ALLOWED);p=await this.verifySystemToken(l);break;case"Admin":p=await this.verifyAdminToken(l,t,!0);break;case"CDN":if(!u)throw c.generateError(403,a.CDN_SESSION_NOT_ALLOWED);p=await this.verifyCDNToken(l);break;default:throw c.generateError(403,a.INVALID_AUTH_TYPE)}A();}catch(c$1){b$1.logError("AuthMiddleware",c$1),c.handleException("AuthMiddleware",c.generateError(401,c$1.error||a.TOKEN_EXPIRED,!0),a$1);}}}decodeJWTPayloadWithJose(e){if(!e||typeof e!="string")return b$1.logError("AuthContextMiddleware","Invalid token provided for decoding."),null;try{return decodeJwt(e)}catch(t){return b$1.logError("AuthContextMiddleware",`Failed to decode JWT payload: ${t}`),null}}AuthContextMiddleware(){return async(e,t,i)=>{try{let[r,n]=e.get("Authorization")?.split(" ")||[],u=r==="CDN"?{id:n,type:"CDN"}:r?this.decodeJWTPayloadWithJose(n):{},h=T.init(u?.id||n,u?.type||r,n,e.get("x-request-id"));b$1.logMessage("AuthContextMiddleware",`AuthContext initialized: ${h.getType()||"No-Type"} - ${h.getId()||"No-Id"}`),t.on("finish",()=>{b$1.logMessage("AuthContextMiddleware","Uninitializing AuthContext"),T.uninit();}),i();}catch(r){b$1.logError("AuthContextMiddleware",r),c.handleException("AuthContextMiddleware",c.generateError(500,r.error||a.INTERNAL_SERVER_ERROR,!0),t);}}}},X=N;export{T as AuthContext,x as AuthType,v as DefaultAuthMiddlewareConfig,S as DefaultAuthUtilityConfig,X as default};//# sourceMappingURL=index.mjs.map
1
+ import {a as a$1,b,d,c as c$1}from'../chunk-AMIRIUMH.mjs';import {a as a$2}from'../chunk-AWZ6KRLF.mjs';import'../chunk-SFUOYZ3L.mjs';import'../chunk-TJ7AZBND.mjs';import'../chunk-72DR3HF2.mjs';import'../chunk-WSUPVXRZ.mjs';import'../chunk-JHELVQYY.mjs';import'../chunk-6KCJVEZD.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
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/Utils/fetch.ts","../../src/Auth/AuthContext.ts","../../src/Auth/index.ts"],"names":["Fetch","baseURL","endpoint","method","headers","payload","options","completeURL","isInternalAPI","response","errorBody","errorText","Logger_default","body","err","ErrorTypes_default","fetch_default","AuthContext","_AuthContext","id","type","token","requestId","assert","fallbackLambdaName","baseId","DefaultAuthUtilityConfig","AuthType","DefaultAuthMiddlewareConfig","AuthUtility","config","userTokenAge","userPrivateKeys","userPublicKeys","anonymousTokenAge","anonymousPrivateKeys","anonymousPublicKeys","systemTokenAge","systemPrivateKeys","systemPublicKeys","adminTokenAge","adminPrivateKeys","adminPublicKeys","cdnKeys","jsonString","keyType","parsed","item","error","warn","keys","limit","privateKeyString","expiration","privateKey","importPKCS8","SignJWT","publicKeyString","i","publicKey","importSPKI","jwtVerify","additionalData","Utils_default","email","verifier","permissions","authenticate","response_default","allowAnonymous","allowSystem","allowUser","allowCDN","req","res","next","authType","decodeJwt","authContext","Auth_default"],"mappings":"8WA4BA,IAAMA,CAAQ,CAAA,MACZC,EACAC,CACAC,CAAAA,CAAAA,CAA8C,KAC9CC,CAAAA,CAAAA,CAAkC,EAClCC,CAAAA,CAAAA,GACyB,CACzB,IAAMC,CAAAA,CAAuB,CAC3B,MAAAH,CAAAA,CAAAA,CACA,QAAS,CACP,cAAA,CAAgB,mBAChB,GAAGC,CACL,CACF,CAEID,CAAAA,CAAAA,GAAW,OAASE,CACtBC,GAAAA,CAAAA,CAAQ,IAAO,CAAA,IAAA,CAAK,UAAUD,C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AAA,CACd,wBACAA,CAAgB,CAAA,aAAA,CAAc,IAAKpB,CAAM,CAAA,KAAA,EAASjC,EAAW,qBAAuB,CAAA,CAAA,CAAI,EACxF2D,CACF,EACF,CACF,CACF,CACF,EAEOK,CAAQlD,CAAAA","file":"index.mjs","sourcesContent":["\"use client\";\r\n\r\nimport ErrorTypes from \"../enums/ErrorTypes\";\r\nimport Logger from \"../Logger\";\r\n\r\nexport type ErrorType = {\r\n status: number;\r\n statusText: string;\r\n error: any;\r\n};\r\n\r\nexport type SuccessType = {\r\n status: number;\r\n statusText: string;\r\n data: any;\r\n};\r\n\r\n/**\r\n * Makes an HTTP request to the specified endpoint using the provided parameters.\r\n *\r\n * @param {string} baseURL - The base URL of the API.\r\n * @param {string} endpoint - The specific endpoint to call.\r\n * @param {'GET' | 'POST' | 'PATCH' | 'DELETE'} [method='GET'] - The HTTP method to use for the request.\r\n * @param {Record<string, string>} [headers={}] - Additional headers to include in the request.\r\n * @param {any} [payload] - The payload to send with the request, if applicable.\r\n * @returns {Promise<SuccessType>} - A promise that resolves to the response data if the request is successful.\r\n * @throws {ErrorType} - Throws an error if the request fails.\r\n */\r\nconst Fetch = async (\r\n baseURL: string,\r\n endpoint: string,\r\n method: 'GET' | 'POST' | 'PATCH' | 'DELETE' = 'GET',\r\n headers: Record<string, string> = {},\r\n payload?: any,\r\n): Promise<SuccessType> => {\r\n const options: RequestInit = {\r\n method,\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n ...headers,\r\n },\r\n };\r\n\r\n if (method !== 'GET' && payload) {\r\n options.body = JSON.stringify(payload);\r\n }\r\n\r\n const completeURL = `${baseURL}${endpoint ? ('/' + endpoint) : ''}`;\r\n const isInternalAPI = completeURL.includes('api.xetile.com') || completeURL.includes('localhost');\r\n \r\n try {\r\n const response: any = await fetch(completeURL, options);\r\n\r\n if (!response.ok) {\r\n let errorBody: any;\r\n const errorText = await response.text();\r\n\r\n try {\r\n errorBody = JSON.parse(errorText);\r\n } catch (parseError) {\r\n errorBody = {\r\n status: response.status,\r\n error: errorText || response.statusText\r\n };\r\n Logger.logWarning('Fetch', `Failed to parse error response body as JSON for URL-${completeURL}. Raw text: ${errorText}`);\r\n }\r\n\r\n throw {\r\n status: response.status,\r\n statusText: response.statusText,\r\n error: errorBody\r\n } as ErrorType;\r\n }\r\n\r\n const body = await response.json();\r\n\r\n Logger.logMessage('Fetch', `API call successful: URL-${completeURL}, Status- ${response.status}`);\r\n return {\r\n status: response.status,\r\n statusText: response.statusText,\r\n data: isInternalAPI ? body.data : body,\r\n } as SuccessType;\r\n } catch (err: any) {\r\n \r\n Logger.logError('Fetch', `API call failed: URL-${completeURL}, Status- ${err.status || 500}, Error- ${Logger.inspect(err.error || err)}`);\r\n throw {\r\n status: err.status || 500,\r\n statusText: err.statusText || ErrorTypes.INTERNAL_SERVER_ERROR,\r\n error: err.error || {\r\n status: err.status || 500,\r\n error: err.statusText || ErrorTypes.SOMETHING_WENT_WRONG,\r\n }\r\n } as ErrorType;\r\n }\r\n};\r\n\r\nexport default Fetch;\r\n","import assert from \"assert\";\r\nimport ErrorTypes from \"../enums/ErrorTypes\";\r\nimport { AuthType } from \"./index\";\r\n\r\nexport default class AuthContext {\r\n private static instance: AuthContext | null = null;\r\n private id: string;\r\n private type: AuthType;\r\n private token?: string;\r\n private initializedAt: Date;\r\n private lambdaName?: string;\r\n private requestId?: string;\r\n\r\n private constructor(id: string, type: AuthType, token: string, requestId: string) {\r\n this.id = id;\r\n this.type = type;\r\n this.token = token;\r\n this.lambdaName = process.env.AWS_LAMBDA_FUNCTION_NAME;\r\n this.initializedAt = new Date();\r\n }\r\n\r\n public static getInstance(): AuthContext {\r\n assert(AuthContext.instance, ErrorTypes.AUTH_CONTEXT_NOT_INITIALIZED);\r\n return AuthContext.instance;\r\n }\r\n\r\n public static init(id: string, type: AuthType, token: string, requestId: string): AuthContext {\r\n AuthContext.instance = new AuthContext(id, type, token, requestId);\r\n return AuthContext.instance;\r\n }\r\n\r\n public static uninit() {\r\n AuthContext.instance = null;\r\n }\r\n\r\n public getId(): string {\r\n return this.id;\r\n }\r\n\r\n public getType(): AuthType {\r\n return this.type;\r\n }\r\n\r\n public getToken(): string | undefined {\r\n return this.token;\r\n }\r\n \r\n public getLambdaName(): string | undefined{\r\n return this.lambdaName;\r\n }\r\n\r\n public getRequestId(): string | undefined {\r\n return this.requestId;\r\n }\r\n\r\n public getInitializedAt(): Date {\r\n return this.initializedAt;\r\n }\r\n\r\n public getSystemID(fallbackLambdaName: string): string {\r\n let baseId = this.lambdaName || fallbackLambdaName;\r\n if (this.requestId) {\r\n return `${baseId} - ${this.requestId}`;\r\n }\r\n return baseId;\r\n }\r\n}","import { decodeJwt, importPKCS8, importSPKI, jwtVerify, SignJWT} from 'jose';\r\nimport ErrorTypes from '../enums/ErrorTypes';\r\nimport Logger from '../Logger';\r\nimport Utils from '../Utils';\r\nimport ResponseUtility from '../Utils/response';\r\nimport assert from 'assert';\r\nimport Fetch from '../Utils/fetch';\r\nimport AuthContext from './AuthContext';\r\n\r\ntype StringifiedJSONArray = string;\r\n\r\nexport type AuthPayloadData = {\r\n id: string;\r\n type: AuthType;\r\n verifier?: string;\r\n [key: string]: any;\r\n}\r\n\r\nexport interface AuthUtilityConfig {\r\n userTokenAge: string;\r\n userPrivateKeys: StringifiedJSONArray;\r\n userPublicKeys: StringifiedJSONArray;\r\n anonymousTokenAge: string;\r\n anonymousPrivateKeys: StringifiedJSONArray;\r\n anonymousPublicKeys: StringifiedJSONArray;\r\n systemTokenAge: string;\r\n systemPrivateKeys: StringifiedJSONArray;\r\n systemPublicKeys: StringifiedJSONArray;\r\n adminTokenAge: string;\r\n adminPrivateKeys: StringifiedJSONArray;\r\n adminPublicKeys: StringifiedJSONArray;\r\n cdnKeys: StringifiedJSONArray;\r\n}\r\n\r\nexport const DefaultAuthUtilityConfig: Readonly<AuthUtilityConfig> = {\r\n userTokenAge: '30 days',\r\n userPrivateKeys: '[]',\r\n userPublicKeys: '[]',\r\n anonymousTokenAge: '30 days',\r\n anonymousPrivateKeys: '[]',\r\n anonymousPublicKeys: '[]',\r\n systemTokenAge: '5 min',\r\n systemPrivateKeys: '[]',\r\n systemPublicKeys: '[]',\r\n adminTokenAge: '30 days',\r\n adminPrivateKeys: '[]',\r\n adminPublicKeys: '[]',\r\n cdnKeys: '[]',\r\n};\r\n\r\nexport enum AuthType {\r\n ANON = 'Anon',\r\n USER = 'User',\r\n SYSTEM = 'System',\r\n ADMIN = 'Admin',\r\n CDN = 'CDN'\r\n}\r\n\r\nexport interface AuthMiddlewareConfig {\r\n allowAnonymous: boolean;\r\n allowSystem: boolean;\r\n allowUser: boolean;\r\n allowCDN: boolean;\r\n}\r\n\r\nexport const DefaultAuthMiddlewareConfig: Readonly<AuthMiddlewareConfig> = {\r\n allowAnonymous: false,\r\n allowSystem: true,\r\n allowUser: true,\r\n allowCDN: false\r\n};\r\n\r\n/**\r\n * A utility class for JWT authentication and authorization.\r\n */\r\nclass AuthUtility {\r\n private userTokenAge: string;\r\n private userPrivateKeys: string[];\r\n private userPublicKeys: string[];\r\n\r\n private anonymousTokenAge: string;\r\n private anonymousPrivateKeys: string[];\r\n private anonymousPublicKeys: string[];\r\n\r\n private systemTokenAge: string;\r\n private systemPrivateKeys: string[];\r\n private systemPublicKeys: string[];\r\n\r\n private adminTokenAge: string;\r\n private adminPrivateKeys: string[];\r\n private adminPublicKeys: string[];\r\n\r\n private cdnKeys: string[];\r\n\r\n /**\r\n * Initializes the AuthUtility class with a configuration.\r\n * @param config The configuration for the utility (optional).\r\n */\r\n constructor(config: Partial<AuthUtilityConfig> = DefaultAuthUtilityConfig) {\r\n const {\r\n userTokenAge,\r\n userPrivateKeys,\r\n userPublicKeys,\r\n anonymousTokenAge,\r\n anonymousPrivateKeys,\r\n anonymousPublicKeys,\r\n systemTokenAge,\r\n systemPrivateKeys,\r\n systemPublicKeys,\r\n adminTokenAge,\r\n adminPrivateKeys,\r\n adminPublicKeys,\r\n cdnKeys\r\n } = { ...DefaultAuthUtilityConfig, ...config };\r\n\r\n this.userTokenAge = userTokenAge;\r\n this.userPrivateKeys = this.parseKeyArray(userPrivateKeys, 'user private');\r\n this.userPublicKeys = this.parseKeyArray(userPublicKeys, 'user public');\r\n\r\n this.anonymousTokenAge = anonymousTokenAge;\r\n this.anonymousPrivateKeys = this.parseKeyArray(anonymousPrivateKeys, 'anonymous private');\r\n this.anonymousPublicKeys = this.parseKeyArray(anonymousPublicKeys, 'anonymous public');\r\n\r\n this.systemTokenAge = systemTokenAge;\r\n this.systemPrivateKeys = this.parseKeyArray(systemPrivateKeys, 'system private');\r\n this.systemPublicKeys = this.parseKeyArray(systemPublicKeys, 'system public');\r\n\r\n this.adminTokenAge = adminTokenAge;\r\n this.adminPrivateKeys = this.parseKeyArray(adminPrivateKeys, 'admin private');\r\n this.adminPublicKeys = this.parseKeyArray(adminPublicKeys, 'admin public');\r\n\r\n this.cdnKeys = this.parseKeyArray(cdnKeys, 'cdn');\r\n\r\n this.logWarnings();\r\n }\r\n\r\n private parseKeyArray(jsonString: string, keyType: string): string[] {\r\n try {\r\n const parsed = JSON.parse(jsonString);\r\n if (!Array.isArray(parsed) || !parsed.every(item => typeof item === 'string')) {\r\n Logger.logError('AuthUtility', `Invalid format for ${keyType} keys in config: Expected stringified array of strings.`);\r\n return [];\r\n }\r\n return parsed;\r\n } catch (error) {\r\n Logger.logError('AuthUtility', `Failed to parse ${keyType} keys from config: ${error}`);\r\n return [];\r\n }\r\n }\r\n\r\n /**\r\n * Logs warnings if the number of keys exceeds recommended limits.\r\n */\r\n private logWarnings() {\r\n const warn = (type: string, keys: string[], limit: number) =>\r\n keys.length > limit &&\r\n Logger.logWarning(\r\n 'AuthUtility',\r\n `More than ${limit} ${type} keys provided. This is not recommended.`\r\n );\r\n\r\n warn('user private', this.userPrivateKeys, 3);\r\n warn('user public', this.userPublicKeys, 3);\r\n warn('anonymous private', this.anonymousPrivateKeys, 1);\r\n warn('anonymous public', this.anonymousPublicKeys, 3);\r\n warn('system private', this.systemPrivateKeys, 1);\r\n warn('system public', this.systemPublicKeys, 3);\r\n warn('admin private', this.adminPrivateKeys, 1);\r\n warn('admin public', this.adminPublicKeys, 3);\r\n }\r\n\r\n private async createSignedJWT(payload: AuthPayloadData, privateKeyString: string, expiration: string){\r\n const privateKey = await importPKCS8(privateKeyString, 'RS256');\r\n const token = await new SignJWT(payload)\r\n .setProtectedHeader({ alg: 'RS256' })\r\n .setExpirationTime(expiration)\r\n .setIssuedAt()\r\n .sign(privateKey);\r\n\r\n return token;\r\n }\r\n\r\n private async verifySignedJWT(token: string, publicKeyString: string[], expiration: string): Promise<AuthPayloadData> {\r\n for(let i = publicKeyString.length - 1; i >= 0 ; i--){\r\n try { \r\n const publicKey = await importSPKI(publicKeyString[i], 'RS256')\r\n const jwt = await jwtVerify(token, publicKey, { clockTolerance: 30, maxTokenAge: expiration });\r\n return jwt.payload as AuthPayloadData;\r\n } catch (error) {\r\n if (i === 0) {\r\n throw error;\r\n }\r\n // Try with the next oldest key\r\n continue;\r\n }\r\n }\r\n throw new Error(ErrorTypes.INVALID_TOKEN);\r\n }\r\n\r\n \r\n /**\r\n * Creates an anonymous token with the given ID and additional data.\r\n *\r\n * @param id - The unique identifier for the token. Must be a valid UUID.\r\n * @param additionalData - Optional additional data to include in the token payload.\r\n * @returns A promise that resolves to the signed JWT as a string.\r\n * @throws Will throw an error if no anonymous private keys are found or if the ID is not a valid UUID.\r\n */\r\n async createAnonymousToken(id: string, additionalData?: object): Promise<string> {\r\n assert(this.anonymousPrivateKeys.length, ErrorTypes.ANONYMOUS_PRIVATE_KEY_NOT_FOUND);\r\n\r\n assert(Utils.isUUID(id), ErrorTypes.INVALID_UUID);\r\n const payload = {\r\n id,\r\n type: AuthType.ANON,\r\n ...additionalData\r\n };\r\n\r\n return await this.createSignedJWT(payload, this.anonymousPrivateKeys[this.anonymousPrivateKeys.length - 1], this.anonymousTokenAge);\r\n }\r\n\r\n /**\r\n * Verifies an anonymous token by checking its signature and payload type.\r\n *\r\n * @param token - The JWT token to be verified.\r\n * @returns The payload of the verified token.\r\n * @throws Will throw an error if no anonymous public keys are found or if the token type is invalid.\r\n */\r\n async verifyAnonymousToken(token: string){\r\n assert(this.anonymousPublicKeys.length, ErrorTypes.ANONYMOUS_PUBLIC_KEY_NOT_FOUND);\r\n const payload = await this.verifySignedJWT(token, this.anonymousPublicKeys, this.anonymousTokenAge);\r\n assert(payload.type === AuthType.ANON, ErrorTypes.INVALID_AUTH_TYPE);\r\n return payload;\r\n }\r\n\r\n /**\r\n * Creates a signed JWT token for a user.\r\n *\r\n * @param id - The UUID of the user.\r\n * @param additionalData - Optional additional data to include in the token payload.\r\n * @returns A promise that resolves to the signed JWT token as a string.\r\n * @throws Will throw an error if no user private keys are found or if the provided id is not a valid UUID.\r\n */\r\n async createUserToken(id: string, additionalData?: object): Promise<string> {\r\n assert(this.userPrivateKeys.length, ErrorTypes.USER_PRIVATE_KEY_NOT_FOUND);\r\n assert(Utils.isUUID(id), ErrorTypes.INVALID_UUID);\r\n\r\n const payload = {\r\n id,\r\n type: AuthType.USER,\r\n ...additionalData\r\n };\r\n return await this.createSignedJWT(payload, this.userPrivateKeys[this.userPrivateKeys.length - 1], this.userTokenAge);\r\n }\r\n\r\n /**\r\n * Verifies the provided user token by checking its signature and payload.\r\n *\r\n * @param token - The JWT token to be verified.\r\n * @returns The payload of the verified token if valid.\r\n * @throws Will throw an error if no user public keys are found or if the token type is invalid.\r\n */\r\n async verifyUserToken(token: string){\r\n assert(this.userPublicKeys.length, ErrorTypes.USER_PUBLIC_KEY_NOT_FOUND);\r\n const payload = await this.verifySignedJWT(token, this.userPublicKeys, this.userTokenAge);\r\n assert(payload.type === AuthType.USER, ErrorTypes.INVALID_AUTH_TYPE);\r\n return payload;\r\n }\r\n\r\n /**\r\n * Creates a signed JWT (JSON Web Token) for a system with the given ID and optional additional data.\r\n *\r\n * @param id - The unique identifier for the system.\r\n * @param additionalData - Optional additional data to include in the token payload.\r\n * @returns A promise that resolves to the signed JWT as a string.\r\n * @throws Will throw an error if no system private keys are found.\r\n */\r\n async createSystemToken(id: string, additionalData?: object): Promise<string> {\r\n assert(this.systemPrivateKeys.length, ErrorTypes.SYSTEM_PRIVATE_KEY_NOT_FOUND);\r\n\r\n const payload = {\r\n id,\r\n type: AuthType.SYSTEM,\r\n ...additionalData\r\n };\r\n return await this.createSignedJWT(payload, this.systemPrivateKeys[this.systemPrivateKeys.length - 1], this.systemTokenAge);\r\n }\r\n\r\n /**\r\n * Verifies a system token by checking its signature and payload type.\r\n *\r\n * @param token - The JWT token to be verified.\r\n * @returns The payload of the verified token.\r\n * @throws Will throw an error if no system public keys are found or if the token type is not 'System'.\r\n */\r\n async verifySystemToken(token: string){\r\n assert(this.systemPublicKeys.length, ErrorTypes.USER_PUBLIC_KEY_NOT_FOUND);\r\n const payload = await this.verifySignedJWT(token, this.systemPublicKeys, this.systemTokenAge);\r\n assert(payload.type === AuthType.SYSTEM, ErrorTypes.INVALID_AUTH_TYPE);\r\n return payload;\r\n }\r\n\r\n /**\r\n * Creates a signed JWT token for an admin user.\r\n *\r\n * @param email - The email of the admin user.\r\n * @param additionalData - Optional additional data to include in the token payload.\r\n * @returns A promise that resolves to the signed JWT token string.\r\n * @throws Will throw an error if no admin private keys are found or if the provided id is not a valid UUID.\r\n */\r\n async createAdminToken(email: string, verifier: string, additionalData?: object): Promise<string> {\r\n assert(this.adminPrivateKeys.length, ErrorTypes.ADMIN_PRIVATE_KEY_NOT_FOUND);\r\n\r\n assert(Utils.isEmail(email), ErrorTypes.INVALID_EMAIL);\r\n assert(Utils.isURL(verifier), ErrorTypes.INVALID_VERIFIER);\r\n const payload = {\r\n id: email,\r\n type: AuthType.ADMIN,\r\n verifier: verifier,\r\n ...additionalData\r\n };\r\n return await this.createSignedJWT(payload, this.adminPrivateKeys[this.adminPrivateKeys.length - 1], this.adminTokenAge);\r\n }\r\n\r\n /**\r\n * Verifies the provided admin token by checking its signature and payload.\r\n * Ensures that the token is signed with one of the known admin public keys\r\n * and that the payload type is 'Admin'.\r\n *\r\n * @param token - The JWT token to be verified.\r\n * @param permissions - The permissions required for the admin user.\r\n * @param authenticate - Whether to authenticate the token with the verifier.\r\n * @returns The payload of the verified token.\r\n * @throws Will throw an error if no admin public keys are found or if the token is invalid or if the admin doesn't have proper permissions.\r\n */\r\n async verifyAdminToken(token: string, permissions: string[], authenticate: boolean){\r\n assert(this.adminPublicKeys.length, ErrorTypes.ADMIN_PUBLIC_KEY_NOT_FOUND);\r\n const payload = await this.verifySignedJWT(token, this.adminPublicKeys, this.adminTokenAge);\r\n assert(payload.type === AuthType.ADMIN, ErrorTypes.INVALID_AUTH_TYPE);\r\n\r\n if(authenticate) {\r\n const response = await Fetch(payload.verifier as string, '', 'POST', {}, { token, permissions });\r\n assert(response.data.isTokenValid === true, ErrorTypes.INVALID_TOKEN);\r\n \r\n if(response.data.hasPermissions !== true){\r\n throw ResponseUtility.generateError(403, ErrorTypes.INVALID_PERMISSIONS)\r\n }\r\n }\r\n\r\n return payload;\r\n }\r\n\r\n async verifyCDNToken(token: string) {\r\n assert(this.cdnKeys.includes(token), ErrorTypes.INVALID_TOKEN);\r\n\r\n const payload: AuthPayloadData = {\r\n id: token,\r\n type: AuthType.CDN,\r\n };\r\n\r\n return payload;\r\n }\r\n\r\n /**\r\n * Middleware function to handle authentication based on different token types.\r\n * It verifies the token and sets the authentication details in the response locals.\r\n *\r\n * @param {Partial<AuthMiddlewareConfig>} [config=DefaultAuthMiddlewareConfig] - Configuration object to customize the middleware behavior.\r\n * @returns Middleware function to handle authentication.\r\n */\r\n AuthMiddleware(config: Partial<AuthMiddlewareConfig> = DefaultAuthMiddlewareConfig, permissions: string[] = []) {\r\n const { allowAnonymous, allowSystem, allowUser, allowCDN } = { ...DefaultAuthMiddlewareConfig, ...config };\r\n return async (req: any, res: any, next: any) => {\r\n try {\r\n const [authType, token] = req.get('Authorization')?.split(' ') || [];\r\n if (!token) throw new Error(ErrorTypes.INVALID_TOKEN);\r\n\r\n let payload;\r\n switch (authType as AuthType) {\r\n case AuthType.ANON:\r\n if (!allowAnonymous) throw ResponseUtility.generateError(403, ErrorTypes.ANONYMOUS_SESSION_NOT_ALLOWED);\r\n payload = await this.verifyAnonymousToken(token);\r\n break;\r\n case AuthType.USER:\r\n if (!allowUser) throw ResponseUtility.generateError(403, ErrorTypes.USER_SESSION_NOT_ALLOWED);\r\n payload = await this.verifyUserToken(token);\r\n break;\r\n case AuthType.SYSTEM:\r\n if (!allowSystem) throw ResponseUtility.generateError(403, ErrorTypes.SYSTEM_SESSION_NOT_ALLOWED);\r\n payload = await this.verifySystemToken(token);\r\n break;\r\n case AuthType.ADMIN:\r\n payload = await this.verifyAdminToken(token, permissions, true);\r\n break;\r\n case AuthType.CDN:\r\n if (!allowCDN) throw ResponseUtility.generateError(403, ErrorTypes.CDN_SESSION_NOT_ALLOWED);\r\n payload = await this.verifyCDNToken(token);\r\n\r\n break;\r\n default:\r\n throw ResponseUtility.generateError(403, ErrorTypes.INVALID_AUTH_TYPE);\r\n }\r\n\r\n next();\r\n } catch (error: any) {\r\n Logger.logError('AuthMiddleware', error);\r\n ResponseUtility.handleException(\r\n 'AuthMiddleware',\r\n ResponseUtility.generateError(401, error.error || ErrorTypes.TOKEN_EXPIRED, true),\r\n res\r\n );\r\n }\r\n };\r\n }\r\n\r\n /**\r\n * Decodes the payload of a JWT using jose.decodeJwt without verifying\r\n * the signature or expiration.\r\n * WARNING: This is insecure as it doesn't validate the token's integrity.\r\n * Use only when you understand the risks and have a specific need.\r\n *\r\n * @param token - The JWT string.\r\n * @returns The decoded payload object, or null if the token format is invalid or decoding fails.\r\n */\r\n decodeJWTPayloadWithJose(token: string): Record<string, any> | null {\r\n if (!token || typeof token !== 'string') {\r\n Logger.logError(\"AuthContextMiddleware\", \"Invalid token provided for decoding.\");\r\n return null;\r\n }\r\n\r\n try {\r\n const payload = decodeJwt(token);\r\n return payload;\r\n } catch (error) {\r\n Logger.logError(\"AuthContextMiddleware\", `Failed to decode JWT payload: ${error}`);\r\n return null;\r\n }\r\n }\r\n\r\n AuthContextMiddleware() {\r\n return async (req: any, res: any, next: any) => {\r\n try {\r\n const [authType, token] = req.get('Authorization')?.split(' ') || [];\r\n let payload = authType === AuthType.CDN ? { id: token, type: AuthType.CDN } : (authType ? this.decodeJWTPayloadWithJose(token) : {});\r\n\r\n const authContext = AuthContext.init(payload?.id || token, payload?.type || authType, token, req.get('x-request-id'));\r\n Logger.logMessage('AuthContextMiddleware', `AuthContext initialized: ${authContext.getType() || 'No-Type'} - ${authContext.getId() || 'No-Id'}`);\r\n\r\n res.on('finish', () => {\r\n Logger.logMessage('AuthContextMiddleware', 'Uninitializing AuthContext');\r\n AuthContext.uninit();\r\n });\r\n\r\n next();\r\n } catch (error: any) {\r\n Logger.logError('AuthContextMiddleware', error);\r\n ResponseUtility.handleException(\r\n 'AuthContextMiddleware',\r\n ResponseUtility.generateError(500, error.error || ErrorTypes.INTERNAL_SERVER_ERROR, true),\r\n res\r\n );\r\n }\r\n };\r\n }\r\n}\r\n\r\nexport default AuthUtility;\r\nexport { AuthContext };\r\n\r\n"]}
1
+ {"version":3,"sources":["../../src/Auth/AuthContext.ts","../../src/Auth/index.ts"],"names":["AuthContext","_AuthContext","id","type","token","requestId","assert","ErrorTypes_default","fallbackLambdaName","baseId","DefaultAuthUtilityConfig","AuthType","DefaultAuthMiddlewareConfig","AuthUtility","config","userTokenAge","userPrivateKeys","userPublicKeys","anonymousTokenAge","anonymousPrivateKeys","anonymousPublicKeys","systemTokenAge","systemPrivateKeys","systemPublicKeys","adminTokenAge","adminPrivateKeys","adminPublicKeys","cdnKeys","jsonString","keyType","parsed","item","Logger_default","error","warn","keys","limit","payload","privateKeyString","expiration","privateKey","importPKCS8","SignJWT","publicKeyString","i","publicKey","importSPKI","jwtVerify","additionalData","Utils_default","email","verifier","permissions","authenticate","response","fetch_default","response_default","allowAnonymous","allowSystem","allowUser","allowCDN","req","res","next","authType","decodeJwt","authContext","Auth_default"],"mappings":"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GAAAA,EAAAA,CAAAA,CAAY,KAAM,EAAA,EAAK,OAAO,CAAE,CAAA,CAAA,CAE/IJ,CAAI,CAAA,EAAA,CAAG,SAAU,IAAM,CACrB9B,CAAO,CAAA,UAAA,CAAW,wBAAyB,4BAA4B,CAAA,CACvEhC,CAAY,CAAA,MAAA,GACd,CAAC,CAAA,CAED+D,CAAK,GACP,OAAS9B,CAAY,CAAA,CACnBD,CAAO,CAAA,QAAA,CAAS,wBAAyBC,CAAK,CAAA,CAC9CuB,GAAgB,CAAA,eAAA,CACd,wBACAA,GAAgB,CAAA,aAAA,CAAc,GAAKvB,CAAAA,CAAAA,CAAM,OAAS1B,GAAW,CAAA,qBAAA,CAAuB,CAAI,CAAA,CAAA,CACxFuD,CACF,EACF,CACF,CACF,CACF,EAEOK,CAAQtD,CAAAA","file":"index.mjs","sourcesContent":["import assert from \"assert\";\r\nimport ErrorTypes from \"../enums/ErrorTypes\";\r\nimport { AuthType } from \"./index\";\r\n\r\nexport default class AuthContext {\r\n private static instance: AuthContext | null = null;\r\n private id: string;\r\n private type: AuthType;\r\n private token?: string;\r\n private initializedAt: Date;\r\n private lambdaName?: string;\r\n private requestId?: string;\r\n\r\n private constructor(id: string, type: AuthType, token: string, requestId: string) {\r\n this.id = id;\r\n this.type = type;\r\n this.token = token;\r\n this.lambdaName = process.env.AWS_LAMBDA_FUNCTION_NAME;\r\n this.initializedAt = new Date();\r\n }\r\n\r\n public static getInstance(): AuthContext {\r\n assert(AuthContext.instance, ErrorTypes.AUTH_CONTEXT_NOT_INITIALIZED);\r\n return AuthContext.instance;\r\n }\r\n\r\n public static init(id: string, type: AuthType, token: string, requestId: string): AuthContext {\r\n AuthContext.instance = new AuthContext(id, type, token, requestId);\r\n return AuthContext.instance;\r\n }\r\n\r\n public static uninit() {\r\n AuthContext.instance = null;\r\n }\r\n\r\n public getId(): string {\r\n return this.id;\r\n }\r\n\r\n public getType(): AuthType {\r\n return this.type;\r\n }\r\n\r\n public getToken(): string | undefined {\r\n return this.token;\r\n }\r\n \r\n public getLambdaName(): string | undefined{\r\n return this.lambdaName;\r\n }\r\n\r\n public getRequestId(): string | undefined {\r\n return this.requestId;\r\n }\r\n\r\n public getInitializedAt(): Date {\r\n return this.initializedAt;\r\n }\r\n\r\n public getSystemID(fallbackLambdaName: string): string {\r\n let baseId = this.lambdaName || fallbackLambdaName;\r\n if (this.requestId) {\r\n return `${baseId} - ${this.requestId}`;\r\n }\r\n return baseId;\r\n }\r\n}","import { decodeJwt, importPKCS8, importSPKI, jwtVerify, SignJWT} from 'jose';\r\nimport ErrorTypes from '../enums/ErrorTypes';\r\nimport Logger from '../Logger';\r\nimport Utils from '../Utils';\r\nimport ResponseUtility from '../Utils/response';\r\nimport assert from 'assert';\r\nimport Fetch from '../Utils/fetch';\r\nimport AuthContext from './AuthContext';\r\n\r\ntype StringifiedJSONArray = string;\r\n\r\nexport type AuthPayloadData = {\r\n id: string;\r\n type: AuthType;\r\n verifier?: string;\r\n [key: string]: any;\r\n}\r\n\r\nexport interface AuthUtilityConfig {\r\n userTokenAge: string;\r\n userPrivateKeys: StringifiedJSONArray;\r\n userPublicKeys: StringifiedJSONArray;\r\n anonymousTokenAge: string;\r\n anonymousPrivateKeys: StringifiedJSONArray;\r\n anonymousPublicKeys: StringifiedJSONArray;\r\n systemTokenAge: string;\r\n systemPrivateKeys: StringifiedJSONArray;\r\n systemPublicKeys: StringifiedJSONArray;\r\n adminTokenAge: string;\r\n adminPrivateKeys: StringifiedJSONArray;\r\n adminPublicKeys: StringifiedJSONArray;\r\n cdnKeys: StringifiedJSONArray;\r\n}\r\n\r\nexport const DefaultAuthUtilityConfig: Readonly<AuthUtilityConfig> = {\r\n userTokenAge: '30 days',\r\n userPrivateKeys: '[]',\r\n userPublicKeys: '[]',\r\n anonymousTokenAge: '30 days',\r\n anonymousPrivateKeys: '[]',\r\n anonymousPublicKeys: '[]',\r\n systemTokenAge: '5 min',\r\n systemPrivateKeys: '[]',\r\n systemPublicKeys: '[]',\r\n adminTokenAge: '30 days',\r\n adminPrivateKeys: '[]',\r\n adminPublicKeys: '[]',\r\n cdnKeys: '[]',\r\n};\r\n\r\nexport enum AuthType {\r\n ANON = 'Anon',\r\n USER = 'User',\r\n SYSTEM = 'System',\r\n ADMIN = 'Admin',\r\n CDN = 'CDN'\r\n}\r\n\r\nexport interface AuthMiddlewareConfig {\r\n allowAnonymous: boolean;\r\n allowSystem: boolean;\r\n allowUser: boolean;\r\n allowCDN: boolean;\r\n}\r\n\r\nexport const DefaultAuthMiddlewareConfig: Readonly<AuthMiddlewareConfig> = {\r\n allowAnonymous: false,\r\n allowSystem: true,\r\n allowUser: true,\r\n allowCDN: false\r\n};\r\n\r\n/**\r\n * A utility class for JWT authentication and authorization.\r\n */\r\nclass AuthUtility {\r\n private userTokenAge: string;\r\n private userPrivateKeys: string[];\r\n private userPublicKeys: string[];\r\n\r\n private anonymousTokenAge: string;\r\n private anonymousPrivateKeys: string[];\r\n private anonymousPublicKeys: string[];\r\n\r\n private systemTokenAge: string;\r\n private systemPrivateKeys: string[];\r\n private systemPublicKeys: string[];\r\n\r\n private adminTokenAge: string;\r\n private adminPrivateKeys: string[];\r\n private adminPublicKeys: string[];\r\n\r\n private cdnKeys: string[];\r\n\r\n /**\r\n * Initializes the AuthUtility class with a configuration.\r\n * @param config The configuration for the utility (optional).\r\n */\r\n constructor(config: Partial<AuthUtilityConfig> = DefaultAuthUtilityConfig) {\r\n const {\r\n userTokenAge,\r\n userPrivateKeys,\r\n userPublicKeys,\r\n anonymousTokenAge,\r\n anonymousPrivateKeys,\r\n anonymousPublicKeys,\r\n systemTokenAge,\r\n systemPrivateKeys,\r\n systemPublicKeys,\r\n adminTokenAge,\r\n adminPrivateKeys,\r\n adminPublicKeys,\r\n cdnKeys\r\n } = { ...DefaultAuthUtilityConfig, ...config };\r\n\r\n this.userTokenAge = userTokenAge;\r\n this.userPrivateKeys = this.parseKeyArray(userPrivateKeys, 'user private');\r\n this.userPublicKeys = this.parseKeyArray(userPublicKeys, 'user public');\r\n\r\n this.anonymousTokenAge = anonymousTokenAge;\r\n this.anonymousPrivateKeys = this.parseKeyArray(anonymousPrivateKeys, 'anonymous private');\r\n this.anonymousPublicKeys = this.parseKeyArray(anonymousPublicKeys, 'anonymous public');\r\n\r\n this.systemTokenAge = systemTokenAge;\r\n this.systemPrivateKeys = this.parseKeyArray(systemPrivateKeys, 'system private');\r\n this.systemPublicKeys = this.parseKeyArray(systemPublicKeys, 'system public');\r\n\r\n this.adminTokenAge = adminTokenAge;\r\n this.adminPrivateKeys = this.parseKeyArray(adminPrivateKeys, 'admin private');\r\n this.adminPublicKeys = this.parseKeyArray(adminPublicKeys, 'admin public');\r\n\r\n this.cdnKeys = this.parseKeyArray(cdnKeys, 'cdn');\r\n\r\n this.logWarnings();\r\n }\r\n\r\n private parseKeyArray(jsonString: string, keyType: string): string[] {\r\n try {\r\n const parsed = JSON.parse(jsonString);\r\n if (!Array.isArray(parsed) || !parsed.every(item => typeof item === 'string')) {\r\n Logger.logError('AuthUtility', `Invalid format for ${keyType} keys in config: Expected stringified array of strings.`);\r\n return [];\r\n }\r\n return parsed;\r\n } catch (error) {\r\n Logger.logError('AuthUtility', `Failed to parse ${keyType} keys from config: ${error}`);\r\n return [];\r\n }\r\n }\r\n\r\n /**\r\n * Logs warnings if the number of keys exceeds recommended limits.\r\n */\r\n private logWarnings() {\r\n const warn = (type: string, keys: string[], limit: number) =>\r\n keys.length > limit &&\r\n Logger.logWarning(\r\n 'AuthUtility',\r\n `More than ${limit} ${type} keys provided. This is not recommended.`\r\n );\r\n\r\n warn('user private', this.userPrivateKeys, 3);\r\n warn('user public', this.userPublicKeys, 3);\r\n warn('anonymous private', this.anonymousPrivateKeys, 1);\r\n warn('anonymous public', this.anonymousPublicKeys, 3);\r\n warn('system private', this.systemPrivateKeys, 1);\r\n warn('system public', this.systemPublicKeys, 3);\r\n warn('admin private', this.adminPrivateKeys, 1);\r\n warn('admin public', this.adminPublicKeys, 3);\r\n }\r\n\r\n private async createSignedJWT(payload: AuthPayloadData, privateKeyString: string, expiration: string){\r\n const privateKey = await importPKCS8(privateKeyString, 'RS256');\r\n const token = await new SignJWT(payload)\r\n .setProtectedHeader({ alg: 'RS256' })\r\n .setExpirationTime(expiration)\r\n .setIssuedAt()\r\n .sign(privateKey);\r\n\r\n return token;\r\n }\r\n\r\n private async verifySignedJWT(token: string, publicKeyString: string[], expiration: string): Promise<AuthPayloadData> {\r\n for(let i = publicKeyString.length - 1; i >= 0 ; i--){\r\n try { \r\n const publicKey = await importSPKI(publicKeyString[i], 'RS256')\r\n const jwt = await jwtVerify(token, publicKey, { clockTolerance: 30, maxTokenAge: expiration });\r\n return jwt.payload as AuthPayloadData;\r\n } catch (error) {\r\n if (i === 0) {\r\n throw error;\r\n }\r\n // Try with the next oldest key\r\n continue;\r\n }\r\n }\r\n throw new Error(ErrorTypes.INVALID_TOKEN);\r\n }\r\n\r\n \r\n /**\r\n * Creates an anonymous token with the given ID and additional data.\r\n *\r\n * @param id - The unique identifier for the token. Must be a valid UUID.\r\n * @param additionalData - Optional additional data to include in the token payload.\r\n * @returns A promise that resolves to the signed JWT as a string.\r\n * @throws Will throw an error if no anonymous private keys are found or if the ID is not a valid UUID.\r\n */\r\n async createAnonymousToken(id: string, additionalData?: object): Promise<string> {\r\n assert(this.anonymousPrivateKeys.length, ErrorTypes.ANONYMOUS_PRIVATE_KEY_NOT_FOUND);\r\n\r\n assert(Utils.isUUID(id), ErrorTypes.INVALID_UUID);\r\n const payload = {\r\n id,\r\n type: AuthType.ANON,\r\n ...additionalData\r\n };\r\n\r\n return await this.createSignedJWT(payload, this.anonymousPrivateKeys[this.anonymousPrivateKeys.length - 1], this.anonymousTokenAge);\r\n }\r\n\r\n /**\r\n * Verifies an anonymous token by checking its signature and payload type.\r\n *\r\n * @param token - The JWT token to be verified.\r\n * @returns The payload of the verified token.\r\n * @throws Will throw an error if no anonymous public keys are found or if the token type is invalid.\r\n */\r\n async verifyAnonymousToken(token: string){\r\n assert(this.anonymousPublicKeys.length, ErrorTypes.ANONYMOUS_PUBLIC_KEY_NOT_FOUND);\r\n const payload = await this.verifySignedJWT(token, this.anonymousPublicKeys, this.anonymousTokenAge);\r\n assert(payload.type === AuthType.ANON, ErrorTypes.INVALID_AUTH_TYPE);\r\n return payload;\r\n }\r\n\r\n /**\r\n * Creates a signed JWT token for a user.\r\n *\r\n * @param id - The UUID of the user.\r\n * @param additionalData - Optional additional data to include in the token payload.\r\n * @returns A promise that resolves to the signed JWT token as a string.\r\n * @throws Will throw an error if no user private keys are found or if the provided id is not a valid UUID.\r\n */\r\n async createUserToken(id: string, additionalData?: object): Promise<string> {\r\n assert(this.userPrivateKeys.length, ErrorTypes.USER_PRIVATE_KEY_NOT_FOUND);\r\n assert(Utils.isUUID(id), ErrorTypes.INVALID_UUID);\r\n\r\n const payload = {\r\n id,\r\n type: AuthType.USER,\r\n ...additionalData\r\n };\r\n return await this.createSignedJWT(payload, this.userPrivateKeys[this.userPrivateKeys.length - 1], this.userTokenAge);\r\n }\r\n\r\n /**\r\n * Verifies the provided user token by checking its signature and payload.\r\n *\r\n * @param token - The JWT token to be verified.\r\n * @returns The payload of the verified token if valid.\r\n * @throws Will throw an error if no user public keys are found or if the token type is invalid.\r\n */\r\n async verifyUserToken(token: string){\r\n assert(this.userPublicKeys.length, ErrorTypes.USER_PUBLIC_KEY_NOT_FOUND);\r\n const payload = await this.verifySignedJWT(token, this.userPublicKeys, this.userTokenAge);\r\n assert(payload.type === AuthType.USER, ErrorTypes.INVALID_AUTH_TYPE);\r\n return payload;\r\n }\r\n\r\n /**\r\n * Creates a signed JWT (JSON Web Token) for a system with the given ID and optional additional data.\r\n *\r\n * @param id - The unique identifier for the system.\r\n * @param additionalData - Optional additional data to include in the token payload.\r\n * @returns A promise that resolves to the signed JWT as a string.\r\n * @throws Will throw an error if no system private keys are found.\r\n */\r\n async createSystemToken(id: string, additionalData?: object): Promise<string> {\r\n assert(this.systemPrivateKeys.length, ErrorTypes.SYSTEM_PRIVATE_KEY_NOT_FOUND);\r\n\r\n const payload = {\r\n id,\r\n type: AuthType.SYSTEM,\r\n ...additionalData\r\n };\r\n return await this.createSignedJWT(payload, this.systemPrivateKeys[this.systemPrivateKeys.length - 1], this.systemTokenAge);\r\n }\r\n\r\n /**\r\n * Verifies a system token by checking its signature and payload type.\r\n *\r\n * @param token - The JWT token to be verified.\r\n * @returns The payload of the verified token.\r\n * @throws Will throw an error if no system public keys are found or if the token type is not 'System'.\r\n */\r\n async verifySystemToken(token: string){\r\n assert(this.systemPublicKeys.length, ErrorTypes.USER_PUBLIC_KEY_NOT_FOUND);\r\n const payload = await this.verifySignedJWT(token, this.systemPublicKeys, this.systemTokenAge);\r\n assert(payload.type === AuthType.SYSTEM, ErrorTypes.INVALID_AUTH_TYPE);\r\n return payload;\r\n }\r\n\r\n /**\r\n * Creates a signed JWT token for an admin user.\r\n *\r\n * @param email - The email of the admin user.\r\n * @param additionalData - Optional additional data to include in the token payload.\r\n * @returns A promise that resolves to the signed JWT token string.\r\n * @throws Will throw an error if no admin private keys are found or if the provided id is not a valid UUID.\r\n */\r\n async createAdminToken(email: string, verifier: string, additionalData?: object): Promise<string> {\r\n assert(this.adminPrivateKeys.length, ErrorTypes.ADMIN_PRIVATE_KEY_NOT_FOUND);\r\n\r\n assert(Utils.isEmail(email), ErrorTypes.INVALID_EMAIL);\r\n assert(Utils.isURL(verifier), ErrorTypes.INVALID_VERIFIER);\r\n const payload = {\r\n id: email,\r\n type: AuthType.ADMIN,\r\n verifier: verifier,\r\n ...additionalData\r\n };\r\n return await this.createSignedJWT(payload, this.adminPrivateKeys[this.adminPrivateKeys.length - 1], this.adminTokenAge);\r\n }\r\n\r\n /**\r\n * Verifies the provided admin token by checking its signature and payload.\r\n * Ensures that the token is signed with one of the known admin public keys\r\n * and that the payload type is 'Admin'.\r\n *\r\n * @param token - The JWT token to be verified.\r\n * @param permissions - The permissions required for the admin user.\r\n * @param authenticate - Whether to authenticate the token with the verifier.\r\n * @returns The payload of the verified token.\r\n * @throws Will throw an error if no admin public keys are found or if the token is invalid or if the admin doesn't have proper permissions.\r\n */\r\n async verifyAdminToken(token: string, permissions: string[], authenticate: boolean){\r\n assert(this.adminPublicKeys.length, ErrorTypes.ADMIN_PUBLIC_KEY_NOT_FOUND);\r\n const payload = await this.verifySignedJWT(token, this.adminPublicKeys, this.adminTokenAge);\r\n assert(payload.type === AuthType.ADMIN, ErrorTypes.INVALID_AUTH_TYPE);\r\n\r\n if(authenticate) {\r\n const response = await Fetch(payload.verifier as string, '', 'POST', {}, { token, permissions });\r\n assert(response.data.isTokenValid === true, ErrorTypes.INVALID_TOKEN);\r\n \r\n if(response.data.hasPermissions !== true){\r\n throw ResponseUtility.generateError(403, ErrorTypes.INVALID_PERMISSIONS)\r\n }\r\n }\r\n\r\n return payload;\r\n }\r\n\r\n async verifyCDNToken(token: string) {\r\n assert(this.cdnKeys.includes(token), ErrorTypes.INVALID_TOKEN);\r\n\r\n const payload: AuthPayloadData = {\r\n id: token,\r\n type: AuthType.CDN,\r\n };\r\n\r\n return payload;\r\n }\r\n\r\n /**\r\n * Middleware function to handle authentication based on different token types.\r\n * It verifies the token and sets the authentication details in the response locals.\r\n *\r\n * @param {Partial<AuthMiddlewareConfig>} [config=DefaultAuthMiddlewareConfig] - Configuration object to customize the middleware behavior.\r\n * @returns Middleware function to handle authentication.\r\n */\r\n AuthMiddleware(config: Partial<AuthMiddlewareConfig> = DefaultAuthMiddlewareConfig, permissions: string[] = []) {\r\n const { allowAnonymous, allowSystem, allowUser, allowCDN } = { ...DefaultAuthMiddlewareConfig, ...config };\r\n return async (req: any, res: any, next: any) => {\r\n try {\r\n const [authType, token] = req.get('Authorization')?.split(' ') || [];\r\n if (!token) throw new Error(ErrorTypes.INVALID_TOKEN);\r\n\r\n let payload;\r\n switch (authType as AuthType) {\r\n case AuthType.ANON:\r\n if (!allowAnonymous) throw ResponseUtility.generateError(403, ErrorTypes.ANONYMOUS_SESSION_NOT_ALLOWED);\r\n payload = await this.verifyAnonymousToken(token);\r\n break;\r\n case AuthType.USER:\r\n if (!allowUser) throw ResponseUtility.generateError(403, ErrorTypes.USER_SESSION_NOT_ALLOWED);\r\n payload = await this.verifyUserToken(token);\r\n break;\r\n case AuthType.SYSTEM:\r\n if (!allowSystem) throw ResponseUtility.generateError(403, ErrorTypes.SYSTEM_SESSION_NOT_ALLOWED);\r\n payload = await this.verifySystemToken(token);\r\n break;\r\n case AuthType.ADMIN:\r\n payload = await this.verifyAdminToken(token, permissions, true);\r\n break;\r\n case AuthType.CDN:\r\n if (!allowCDN) throw ResponseUtility.generateError(403, ErrorTypes.CDN_SESSION_NOT_ALLOWED);\r\n payload = await this.verifyCDNToken(token);\r\n\r\n break;\r\n default:\r\n throw ResponseUtility.generateError(403, ErrorTypes.INVALID_AUTH_TYPE);\r\n }\r\n\r\n next();\r\n } catch (error: any) {\r\n Logger.logError('AuthMiddleware', error);\r\n ResponseUtility.handleException(\r\n 'AuthMiddleware',\r\n ResponseUtility.generateError(401, error.error || ErrorTypes.TOKEN_EXPIRED, true),\r\n res\r\n );\r\n }\r\n };\r\n }\r\n\r\n /**\r\n * Decodes the payload of a JWT using jose.decodeJwt without verifying\r\n * the signature or expiration.\r\n * WARNING: This is insecure as it doesn't validate the token's integrity.\r\n * Use only when you understand the risks and have a specific need.\r\n *\r\n * @param token - The JWT string.\r\n * @returns The decoded payload object, or null if the token format is invalid or decoding fails.\r\n */\r\n decodeJWTPayloadWithJose(token: string): Record<string, any> | null {\r\n if (!token || typeof token !== 'string') {\r\n Logger.logError(\"AuthContextMiddleware\", \"Invalid token provided for decoding.\");\r\n return null;\r\n }\r\n\r\n try {\r\n const payload = decodeJwt(token);\r\n return payload;\r\n } catch (error) {\r\n Logger.logError(\"AuthContextMiddleware\", `Failed to decode JWT payload: ${error}`);\r\n return null;\r\n }\r\n }\r\n\r\n AuthContextMiddleware() {\r\n return async (req: any, res: any, next: any) => {\r\n try {\r\n const [authType, token] = req.get('Authorization')?.split(' ') || [];\r\n let payload = authType === AuthType.CDN ? { id: token, type: AuthType.CDN } : (authType ? this.decodeJWTPayloadWithJose(token) : {});\r\n\r\n const authContext = AuthContext.init(payload?.id || token, payload?.type || authType, token, req.get('x-request-id'));\r\n Logger.logMessage('AuthContextMiddleware', `AuthContext initialized: ${authContext.getType() || 'No-Type'} - ${authContext.getId() || 'No-Id'}`);\r\n\r\n res.on('finish', () => {\r\n Logger.logMessage('AuthContextMiddleware', 'Uninitializing AuthContext');\r\n AuthContext.uninit();\r\n });\r\n\r\n next();\r\n } catch (error: any) {\r\n Logger.logError('AuthContextMiddleware', error);\r\n ResponseUtility.handleException(\r\n 'AuthContextMiddleware',\r\n ResponseUtility.generateError(500, error.error || ErrorTypes.INTERNAL_SERVER_ERROR, true),\r\n res\r\n );\r\n }\r\n };\r\n }\r\n}\r\n\r\nexport default AuthUtility;\r\nexport { AuthContext };\r\n\r\n"]}
@@ -1,3 +1,3 @@
1
- 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var ht=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ht__default=/*#__PURE__*/_interopDefault(ht);var L=class extends Error{constructor(t){super(`Line item with ID '${t}' not found in the cart.`),this.name="LineItemNotFoundError";}},O=class extends Error{constructor(t){super(`Invalid line item state: ${t}`),this.name="InvalidLineItemStateError";}},F=class extends Error{constructor(t){super(`Duplicate size found: ${t}`),this.name="DuplicateSizeError";}},B=class extends Error{constructor(t){super(`Duplicate selection attribute found: ${t}`),this.name="DuplicateSelectionAttributeError";}},z=class extends Error{constructor(t="Product and selection attributes do not match."){super(`ProductMismatch: ${t}`),this.name="ProductMismatchError";}},$=class extends Error{constructor(t="Product is not active."){super(`ProductInactive: ${t}`),this.name="ProductInactiveError";}},x=class extends Error{constructor(t="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${t}`),this.name="SelectionAttributeParseError";}},V=class extends Error{constructor(t="Size does not match."){super(`SizeMismatch: ${t}`),this.name="SizeMismatchError";}},G=class extends Error{constructor(t="Pricing details not available for the product"){super(`NotFound: ${t}`),this.name="PricingNotFoundError";}},k=class extends Error{constructor(t="Tax rule category mismatch."){super(`InvalidTaxRule: ${t}`),this.name="InvalidTaxRuleError";}},K=class extends Error{constructor(t="Tax category is not valid."){super(`InvalidTaxCategory: ${t}`),this.name="InvalidTaxCategoryError";}},q=class extends Error{constructor(t="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${t}`),this.name="InvalidMinQuantityError";}},j=class extends Error{constructor(t){super(`InvalidTieredPrice: ${t}`),this.name="InvalidTieredPriceError";}},Q=class extends Error{constructor(t="Quantity must be greater than zero."){super(`InvalidQuantity: ${t}`),this.name="InvalidQuantityError";}},H=class extends Error{constructor(t){super(`NoApplicableTier: Quantity ${t} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}},Z=class extends Error{constructor(t="No applicable tax slab or multiple slabs found for the given unit price."){super(`TaxSlabNotFound: ${t}`),this.name="TaxSlabNotFoundError";}},v=class extends Error{constructor(t="Amount cannot be negative."){super(`InvalidAmount: ${t}`),this.name="InvalidPriceAmountError";}},D=class extends Error{constructor(t="Currency code is required."){super(`InvalidCurrency: ${t}`),this.name="InvalidCurrencyCodeError";}},T=class extends Error{constructor(t="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${t}`),this.name="CurrencyMismatchError";}},f=class extends Error{constructor(t){super(`InvalidArgument: ${t}`),this.name="InvalidArgumentError";}},E=class extends Error{constructor(t="Invalid image source configuration."){super(`InvalidImageSource: ${t}`),this.name="InvalidImageSourceError";}};var X=new Uint8Array(256),Y=X.length;function tt(){return Y>X.length-16&&(ht__default.default.randomFillSync(X),Y=0),X.slice(Y,Y+=16)}var at=/^(?:[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 yt(n){return typeof n=="string"&&at.test(n)}var ct=yt;var h=[];for(let n=0;n<256;++n)h.push((n+256).toString(16).slice(1));function W(n,t=0){return h[n[t+0]]+h[n[t+1]]+h[n[t+2]]+h[n[t+3]]+"-"+h[n[t+4]]+h[n[t+5]]+"-"+h[n[t+6]]+h[n[t+7]]+"-"+h[n[t+8]]+h[n[t+9]]+"-"+h[n[t+10]]+h[n[t+11]]+h[n[t+12]]+h[n[t+13]]+h[n[t+14]]+h[n[t+15]]}function ft(n){if(!ct(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 ut=ft;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 Ct="6ba7b810-9dad-11d1-80b4-00c04fd430c8",xt="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function et(n,t,e){function i(r,o,s,c){var u;if(typeof r=="string"&&(r=bt(r)),typeof o=="string"&&(o=ut(o)),((u=o)===null||u===void 0?void 0:u.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let a=new Uint8Array(16+r.length);if(a.set(o),a.set(r,o.length),a=e(a),a[6]=a[6]&15|t,a[8]=a[8]&63|128,s){c=c||0;for(let g=0;g<16;++g)s[c+g]=a[g];return s}return W(a)}try{i.name=n;}catch{}return i.DNS=Ct,i.URL=xt,i}var it={randomUUID:ht__default.default.randomUUID};function St(n,t,e){if(it.randomUUID&&!t&&!n)return it.randomUUID();n=n||{};let i=n.random||(n.rng||tt)();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 W(i)}var rt=St;function At(n){return Array.isArray(n)?n=Buffer.from(n):typeof n=="string"&&(n=Buffer.from(n,"utf8")),ht__default.default.createHash("sha1").update(n).digest()}var lt=At;var Pt=et("v5",80,lt),nt=Pt;var Dt={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?nt(n,t):rt(),generateSearchId:(n,t)=>`${n}#${S.generateSelectionAttributesKey(t)}`,getKeyfromSearchId:n=>{let[t,e]=n.split("#");return {key:t,selectionAttributes:S.parseSelectionAttributesKey(e)}},deepClone(n){return structuredClone(n)}},d=Dt;var R=class{customFields;constructor(t,e=new Date){this.customFields={...t.customFields};}getCustomField(t){return this.customFields[t]??null}setCustomField(t,e){this.customFields[t]=e;}getAllCustomFields(){return {...this.customFields}}},b=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 C={"en-IN":"en","kn-IN":"kn"};var dt={INR:"\u20B9"},gt={INR:"en-IN"};var J=(g=>(g.INITIAL="INITIAL",g.PROCESSING="PROCESSING",g.SHIPPED="SHIPPED",g.DELIVERED="DELIVERED",g.CANCELLED="CANCELLED",g.RETURN_REQUESTED="RETURN_REQUESTED",g.RETURNED="RETURNED",g.REFUND_INITIATED="REFUND_INITIATED",g.REFUNDED="REFUNDED",g.ON_HOLD="ON_HOLD",g))(J||{});var I=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 E("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 E("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 l=class n{#t;amount;currency;constructor(t){if(this.#t="PriceModel",t.amount<0)throw new v("Amount cannot be negative.");if(!t.currency)throw new D("Currency code is required.");this.amount=t.amount,this.currency=t.currency;}get kind(){return this.#t}static isPriceModel(t){return typeof t=="object"&&t!==null&&t.kind==="PriceModel"}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}compareTo(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new T("Cannot compare prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return this.amount-t.getAmount()}add(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new T("Cannot add prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return new n({amount:this.amount+t.getAmount(),currency:this.currency})}subtract(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new T("Cannot subtract prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return new n({amount:this.amount-t.getAmount(),currency:this.currency})}multiply(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new T("Cannot multiply prices in different currencies.");return new n({amount:this.amount*t.getAmount(),currency:this.currency})}else if(typeof t=="number"&&t>=0)return new n({amount:this.amount*t,currency:this.currency});throw new f("Must be a non-negative number.")}divide(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new T("Cannot divide prices in different currencies.");return new n({amount:this.amount/t.getAmount(),currency:this.currency})}else if(typeof t=="number"&&t>0)return new n({amount:this.amount/t,currency:this.currency});throw new f("Must be a positive number.")}min(...t){if(t.length===0)throw new f("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(n.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new T("Cannot compare prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return e.compareTo(i)<0?e:i})}max(...t){if(t.length===0)throw new f("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(n.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new T("Cannot compare prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return e.compareTo(i)>0?e:i})}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=gt[e];if(!e||!r)throw new D("Invalid currency code for formatting.");let o=t,s=i.displayAsInteger?0:n.getDecimalPlaces(e),c={style:i.style??"currency",currency:e,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:s,maximumFractionDigits:s};i.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(r,c).format(o)}catch(u){return console.error(`Error formatting price for currency "${e}" and locale "${r}":`,u),`${dt[e]??e} ${n.addThousandSeparators(o.toFixed(s))}`}}static getDecimalPlaces(t){switch(t){case"INR":default:return 2}}static addThousandSeparators(t){let e=t.split("."),i=e[0],r=e.length>1?"."+e[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+r}static getRoundedAmount(t,e){if(t<0)throw new v("Amount cannot be negative for rounding.");if(e===void 0)throw new D("Invalid currency code for rounding.");let i=n.getDecimalPlaces(e),r=Math.pow(10,i);return Math.round(t*r)/r}};var M=class{baseUnitPrice;taxCategory;tiers;constructor(t){let e=new l(t.baseUnitPrice);if(!t.taxCategory)throw new K;let i=(t.tiers??[]).map(u=>({minQuantity:u.minQuantity,unitPrice:new l(u.unitPrice)})).sort((u,a)=>u.minQuantity-a.minQuantity);if(i.some(u=>u.minQuantity<=0))throw new q;let o=i.some(u=>u.unitPrice.getCurrency()!==e.getCurrency()),s=i.some((u,a)=>a>0&&u.unitPrice.compareTo(i[a-1].unitPrice)>0),c=i[0]?.unitPrice.compareTo(e)>0;if(o||s||c)throw new j("Tiers must share the same currency and must not increase in unit price.");this.baseUnitPrice=e,this.taxCategory=t.taxCategory,this.tiers=i;}getBaseUnitPrice(){return this.baseUnitPrice}getTaxCategory(){return this.taxCategory}getTiers(){return this.tiers}getDetails(){return {baseUnitPrice:this.baseUnitPrice.getDetails(),taxCategory:this.taxCategory,tiers:this.tiers.map(t=>({minQuantity:t.minQuantity,unitPrice:t.unitPrice.getDetails()}))}}getApplicableTier(t){if(t<=0)throw new Q;for(let e=this.tiers.length-1;e>=0;e--)if(t>=this.tiers[e].minQuantity)return this.tiers[e];throw new H(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 S=class n extends b{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 x("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,s]=r.split(":");s.startsWith("c+")?e[o]={name:s.slice(2)}:e[o]=s;}return e}catch(e){throw new x(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 M(t.pricing[o])),r),{}),this.targetGender=t.targetGender,this.attributes=d.deepClone(t.attributes),this.specifications=d.deepClone(t.specifications),this.categories=d.deepClone(t.categories);let i=new Set;this.variants=(t.variants||[]).map(r=>{if(!r.selectionAttributes||typeof r.selectionAttributes!="object")throw new x("Selection attributes are required");this.checkSelectionAttributes(r.selectionAttributes);let o=n.generateSelectionAttributesKey(r.selectionAttributes);if(i.has(o))throw new B(o);return i.add(o),{sku:r.sku,selectionAttributes:r.selectionAttributes,images:{primary:new I(r.images.primary),gallery:(r.images.gallery||[]).map(s=>new I(s))}}}),this.isActive=t.isActive,this.searchTags=t.searchTags?d.deepClone(t.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(t){return t?this.name[t]??this.name[C[t]]??this.name.en:d.deepClone(this.name)}getDescription(t){return t?this.description[t]??this.description[C[t]]??this.description.en:d.deepClone(this.description)}getSlug(t){return t?this.slug[t]??this.slug[C[t]]??this.slug.en:d.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(t){return t?this.pricing[t]??null:this.pricing}getAttributes(){return d.deepClone(this.attributes)}getVariants(){return this.variants.map(t=>({sku:t.sku,selectionAttributes:t.selectionAttributes,images:{primary:t.images.primary,gallery:t.images.gallery}}))}getImagesBySelectionAttributes(t){let e=n.generateSelectionAttributesKey(t),i=this.variants.find(r=>n.generateSelectionAttributesKey(r.selectionAttributes)===e);return i?i.images:null}getImages(t,e){switch(e){case"PRIMARY":return this.getImagesBySelectionAttributes(t)?.primary??this.variants[0]?.images?.primary;case"GALLERY":return this.getImagesBySelectionAttributes(t)?.gallery??[];default:return this.getImagesBySelectionAttributes(t)??{primary:this.variants[0]?.images?.primary,gallery:[]}}}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return d.deepClone(this.categories)}getSpecifications(t){return t?d.deepClone(this.specifications[t]??this.specifications[C[t]]??this.specifications.en):d.deepClone(this.specifications)}getSearchTags(t){return t?d.deepClone(this.searchTags[t]??this.searchTags[C[t]]??this.searchTags.en):d.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:d.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 x("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 x(`Selection attribute '${e}' is missing`);if(typeof i=="string"){if(typeof r!="string"||i!==r)throw new x(`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 x(`Selection attribute '${e}' is invalid`)}else if(typeof r!="object"||!("name"in r)||i.findIndex(o=>o.name===r.name)<0)throw new x(`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 P=class extends b{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 ot=class{getBreakdown(t,e,i){let r=t*100,o=r%1===0?r.toString():r.toFixed(2).replace(/\.?0+$/,"");if(e==="IN"&&i?.merchantState&&i?.customerState)if(i.merchantState.toLowerCase().trim()===i.customerState.toLowerCase().trim()){let s=r/2%1===0?(r/2).toString():(r/2).toFixed(2).replace(/\.?0+$/,"");return {totalRate:t,label:`${s}% CGST + ${s}% SGST`,components:[{rate:t/2,label:`${s}% CGST`,type:"CGST"},{rate:t/2,label:`${s}% SGST`,type:"SGST"}]}}else return {totalRate:t,label:`${o}% IGST`,components:[{rate:t,label:`${o}% IGST`,type:"IGST"}]};return {totalRate:t,label:`${o}% GST`,components:[{rate:t,label:`${o}% GST`,type:"GST"}]}}getLongName(){return "Goods and Services Tax"}},pt={GST:new ot},_=class n extends b{taxRuleId;taxSystem;taxCategory;country;slabs;effectiveFrom;effectiveTo;constructor(t,e=new Date){super(t,e),this.taxRuleId=t.taxRuleId,this.taxSystem=t.taxSystem,this.taxCategory=t.taxCategory,this.country=t.country,this.slabs=t.slabs.map(i=>({rate:i.rate,minUnitPrice:new l(i.minUnitPrice),maxUnitPrice:i.maxUnitPrice?new l(i.maxUnitPrice):void 0})),this.effectiveFrom=new Date(t.effectiveFrom),this.effectiveTo=t.effectiveTo?new Date(t.effectiveTo):void 0;}getTaxRuleId(){return this.taxRuleId}getTaxSystem(){return this.taxSystem}getTaxCategory(){return this.taxCategory}getCountry(){return this.country}getSlabs(){return this.slabs}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxCategory:this.getTaxCategory(),country:this.getCountry(),slabs:this.getSlabs().map(t=>({rate:t.rate,minUnitPrice:t.minUnitPrice.getDetails(),maxUnitPrice:t.maxUnitPrice?t.maxUnitPrice.getDetails():void 0})),effectiveFrom:this.effectiveFrom.toISOString(),effectiveTo:this.effectiveTo?this.effectiveTo.toISOString():void 0,...super.getDetails()}}appliesTo(t,e,i=new Date){return this.taxCategory===t&&this.country===e&&this.effectiveFrom<=i&&(this.effectiveTo?this.effectiveTo>=i:!0)}getApplicableTaxRate(t){return n.getApplicableTaxRate(t,this.slabs)}getTaxRateDisplayString(t,e){let i=this.getApplicableTaxRate(t);return n.getTaxRateDisplayString(i,{taxSystem:this.taxSystem,merchantState:e?.merchantState,customerState:e?.customerState})}getTaxRateBreakdown(t,e){let i=this.getApplicableTaxRate(t),r=pt[this.taxSystem];if(r)return r.getBreakdown(i,this.country,e);let o=i*100,c=`${o%1===0?o.toString():o.toFixed(2).replace(/\.?0+$/,"")}% ${this.taxSystem}`;return {totalRate:i,label:c,components:[{rate:i,label:c,type:this.taxSystem}]}}getFormattedTaxRate(t,e={}){let r=this.getApplicableTaxRate(t)*100,o=r%1===0?r.toString():r.toFixed(2).replace(/\.?0+$/,""),s=e.variant||"short",c="";switch(s){case"percentageOnly":c=`${o}%`;break;case"detailed":let u=this.getTaxRateBreakdown(t,e),a=e.separator||(e.multiline?`
2
- `:" + ");c=u.components.map(m=>m.label).join(a);break;case"long":let g=pt[this.taxSystem],y=g?g.getLongName(this.country):this.taxSystem.toString();c=`${o}% ${y}`;break;case"short":default:c=`${o}% ${this.taxSystem}`;break}return e.includeTaxesSuffix&&(c+=" (Incl. Taxes)"),c}static getApplicableTaxRate(t,e){let i=e.filter(r=>(r.minUnitPrice===void 0||t.compareTo(r.minUnitPrice)>=0)&&(r.maxUnitPrice===void 0||t.compareTo(r.maxUnitPrice)<0));if(i.length!==1)throw new Z;return i[0].rate}static getTaxRateDisplayString(t,e){let i=t*100,r=i%1===0?i.toString():i.toFixed(2).replace(/\.?0+$/,"");if(e.taxSystem==="GST"&&e.merchantState&&e.customerState)if(e.merchantState.toLowerCase().trim()===e.customerState.toLowerCase().trim()){let o=i/2%1===0?(i/2).toString():(i/2).toFixed(2).replace(/\.?0+$/,"");return `${o}% CGST + ${o}% SGST`}else return `${r}% IGST`;return e.taxSystem?`${r}% ${e.taxSystem}`:`${r}%`}};var w=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=d.deepClone(t.selectionAttributes),this.name=d.deepClone(t.name),this.specifications=d.deepClone(t.specifications),this.primaryImage=new I(t.primaryImage),this.subItems=d.deepClone(t.subItems);let e=new Set;this.subItems.forEach(i=>{if(e.has(i.size))throw new F(i.size);e.add(i.size);}),this.pricing={unitPrice:new l(t.pricing.unitPrice),tierPricing:new M(t.pricing.tierPricing),taxCategory:t.pricing.taxCategory,tax:{taxRuleId:t.pricing.tax.taxRuleId,taxSystem:t.pricing.tax.taxSystem,country:t.pricing.tax.country,rate:t.pricing.tax.rate,taxSlabs:t.pricing.tax.taxSlabs.map(i=>({rate:i.rate,minUnitPrice:new l(i.minUnitPrice),maxUnitPrice:i.maxUnitPrice?new l(i.maxUnitPrice):void 0}))}},this.state=t.state??"INITIAL",this.total={quantity:t.total.quantity,subtotal:new l(t.total.subtotal),discounts:Object.fromEntries(Object.entries(t.total.discounts).map(([i,r])=>[i,new l(r)])),taxableAmount:new l(t.total.taxableAmount),taxTotal:new l(t.total.taxTotal),grandTotal:new l(t.total.grandTotal)};}getId(){return this.id}getProductKey(){return this.productKey}getSelectionAttributes(){return d.deepClone(this.selectionAttributes)}getName(t){return t?d.deepClone(this.name[t]??this.name[C[t]]??this.name.en):d.deepClone(this.name)}getSpecifications(t){return t?d.deepClone(this.specifications[t]??this.specifications[C[t]]??this.specifications.en):d.deepClone(this.specifications)}getImage(){return this.primaryImage}getSubItems(){return d.deepClone(this.subItems)}getTotalQuantity(){return this.total.quantity}getPricing(){return {unitPrice:this.pricing.unitPrice,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,tax:{taxRuleId:this.pricing.tax.taxRuleId,taxSystem:this.pricing.tax.taxSystem,country:this.pricing.tax.country,rate:this.pricing.tax.rate,taxSlabs:this.pricing.tax.taxSlabs}}}getState(){return this.state}getTotal(){return {quantity:this.total.quantity,subtotal:this.total.subtotal,taxableAmount:this.total.taxableAmount,taxTotal:this.total.taxTotal,discounts:Object.fromEntries(Object.entries(this.total.discounts).map(([t,e])=>[t,e])),grandTotal:this.total.grandTotal}}getDetails(){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:this.getPricing().unitPrice.getDetails(),tierPricing:this.getPricing().tierPricing.getDetails(),taxCategory:this.getPricing().taxCategory,tax:{taxRuleId:this.getPricing().tax.taxRuleId,taxSystem:this.getPricing().tax.taxSystem,country:this.getPricing().tax.country,rate:this.getPricing().tax.rate,taxSlabs:this.getPricing().tax.taxSlabs.map(t=>({rate:t.rate,minUnitPrice:t.minUnitPrice.getDetails(),maxUnitPrice:t.maxUnitPrice?t.maxUnitPrice.getDetails():void 0}))}},state:this.getState(),total:{quantity:this.getTotal().quantity,subtotal:this.getTotal().subtotal.getDetails(),taxableAmount:this.getTotal().taxableAmount.getDetails(),taxTotal:this.getTotal().taxTotal.getDetails(),discounts:Object.fromEntries(Object.entries(this.getTotal().discounts).map(([t,e])=>[t,e.getDetails()])),grandTotal:this.getTotal().grandTotal.getDetails()},customFields:this.getAllCustomFields()}}addSubItems(t,e){t.forEach(i=>{let r=this.subItems.find(o=>o.size===i.size);r?r.quantity=e?r.quantity+i.quantity:i.quantity:this.subItems.push(i);}),this.subItems=this.subItems.filter(i=>i.quantity>0),this.calculateTotals();}updateProductData(t,e,i){if(this.productKey!==t.getKey()||!t.validateSelectionAttribute(this.selectionAttributes))throw new z;if(!t.getIsActive())throw new $;this.subItems.forEach(c=>{if(!t.validateSize(c.size))throw new V});let r=t.getPriceDetails(e);if(!r||r.getBaseUnitPrice().getCurrency()!==i)throw new G;this.name=t.getName(),this.specifications=t.getSpecifications(),this.primaryImage=t.getImages(this.selectionAttributes).primary;let o=this.subItems.reduce((c,u)=>c+u.quantity,0),{unitPrice:s}=r.getApplicableTier(o);this.pricing={unitPrice:s,tierPricing:r,taxCategory:r.getTaxCategory(),tax:this.pricing.tax},this.calculateTotals();}updateDiscounts(t){let e={};t.forEach(i=>{e[i.coupon.getCode()]=i.amount;}),this.total.discounts=e,this.calculateTotals();}updateTax(t){if(!t.appliesTo(this.pricing.taxCategory,this.pricing.tax.country))throw new k;let e=this.total.quantity>0?this.total.taxableAmount.divide(this.total.quantity):this.total.taxableAmount.zero();this.pricing.tax={taxRuleId:t.getTaxRuleId(),taxSystem:t.getTaxSystem(),country:t.getCountry(),rate:t.getApplicableTaxRate(e),taxSlabs:t.getSlabs()},this.calculateTotals();}calculateTotals(){let t=this.pricing.unitPrice.zero(),e=this.subItems.reduce((y,m)=>y+m.quantity,0),{unitPrice:i}=this.pricing.tierPricing.getApplicableTier(e),r=i.multiply(e),o=Object.values(this.total.discounts).reduce((y,m)=>y.add(m),t),s=r.subtract(o),c=e>0?s.divide(e):t,u=_.getApplicableTaxRate(c,this.pricing.tax.taxSlabs),a=s.multiply(u).round(),g=r.subtract(o).add(a);this.total={quantity:e,subtotal:r,taxableAmount:s,taxTotal:a,discounts:this.total.discounts,grandTotal:g};}updateState(t){if(this.state in J)this.state!==t&&(this.state=t);else throw new O(t)}clearLineItem(){let t=this.pricing.unitPrice.zero();this.id="",this.productKey="",this.selectionAttributes={color:{name:""}},this.name={en:""},this.primaryImage=new I({sources:{original:""}}),this.subItems=[],this.pricing={unitPrice:t,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,tax:this.pricing.tax},this.total={quantity:0,subtotal:t,taxableAmount:t,taxTotal:t,discounts:{},grandTotal:t};}};var N=class extends b{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=d.deepClone(t.name),this.description=d.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 l(o)),i},{}),this.maxCartDiscount=Object.keys(t.maxCartDiscount).reduce((i,r)=>{let o=t.maxCartDiscount[r];return o&&(i[r]=new l(o)),i},{}),this.discountMethod=t.discountMethod,this.percentageValue=t.percentageValue??0,this.percentageValue>100)throw new f("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[C[t]]??this.name.en:{...this.name}}getDescription(t){return t?this.description[t]??this.description[C[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 s=new l({amount:0,currency:r}),c;if(o&&!this.isActive())return s;let u=this.getMinCartValue(i),a=this.getMaxCartDiscount(i);if(!u||u.compareTo(t)>0||!a)return s;let g=this.getCategory(),y=this.getDiscountMethod(),m=g==="SHIPPING"?e:t;if(m.getAmount()<=0)return s;switch(y){case"flat":let mt=a;c=m.min(mt);break;case"percentage":c=m.multiply(this.getPercentageValue()/100).round();break;default:return s}return c.min(a)}};var U=class extends b{id;customerId;customerEmail;anonymousId;lineItems;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 w(i)),this.billingAddress=t.billingAddress?new P(t.billingAddress,e):null,this.shippingAddress=t.shippingAddress?new P(t.shippingAddress,e):null,this.coupons=(t.coupons??[]).map(i=>new N(i)),this.shippingDetails=t.shippingDetails?d.deepClone(t.shippingDetails):null,this.total={subtotal:new l(t.total.subtotal),shipping:new l(t.total.shipping),effectiveShipping:new l(t.total.effectiveShipping),taxTotal:new l(t.total.taxTotal),couponTotal:Object.fromEntries(Object.entries(t.total.couponTotal).map(([i,r])=>[i,new l(r)])),couponDiscountTotal:new l(t.total.couponDiscountTotal),grandTotal:new l(t.total.grandTotal)};}getId(){return this.id}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getAnonymousId(){return this.anonymousId}getLineItems(){return this.lineItems.map(t=>new w(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getShippingDetails(){return this.shippingDetails?{...this.shippingDetails}:null}getShippingAddress(){return this.shippingAddress?new P(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new P(this.billingAddress.getDetails()):null}getCoupons(){return this.coupons}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return this.total}getDetails(){return {...super.getDetails(),id:this.getId(),customerId:this.getCustomerId(),customerEmail:this.getCustomerEmail(),anonymousId:this.getAnonymousId(),lineItems:this.getLineItems().map(t=>t.getDetails()),shippingDetails:this.getShippingDetails(),shippingAddress:this.getShippingAddress()?.getDetails()||null,billingAddress:this.getBillingAddress()?.getDetails()||null,coupons:this.getCoupons().map(t=>t.getDetails()),total:{subtotal:this.getTotal().subtotal.getDetails(),shipping:this.getTotal().shipping.getDetails(),effectiveShipping:this.getTotal().effectiveShipping.getDetails(),taxTotal:this.getTotal().taxTotal.getDetails(),couponTotal:Object.fromEntries(Object.entries(this.getTotal().couponTotal).map(([t,e])=>[t,e.getDetails()])),couponDiscountTotal:this.getTotal().couponDiscountTotal.getDetails(),grandTotal:this.getTotal().grandTotal.getDetails()},country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}calculateTotals(){let t=new l({amount:0,currency:this.currency}),e=this.lineItems.filter(m=>m.getState()!=="CANCELLED"),i=e.reduce((m,A)=>m.add(A.getTotal().subtotal),t),r=new l({amount:this.shippingDetails?.cost||0,currency:this.currency}).round(),o=t,s={},c={};this.coupons.forEach(m=>{let A=m.calculateApplicableCouponDiscount(i,r,this.country,this.currency);o=o.add(A),s[m.getCode()]=A,m.getCategory()!=="SHIPPING"&&(c[m.getCode()]=A);}),this.applyDiscountsInLineItem(c);let u=e.reduce((m,A)=>m.add(A.getTotal().taxTotal),t),a=this.coupons.find(m=>m.getCategory()==="SHIPPING"),g=a?r.subtract(s[a.getCode()]||t):r,y=i.add(r).add(u).subtract(o);this.total={subtotal:i,shipping:r,effectiveShipping:g,couponTotal:s,couponDiscountTotal:o,taxTotal:u,grandTotal:y};}updateShippingDetails(t){this.shippingDetails=t,this.calculateTotals();}applyCoupons(t){let e=t.filter(r=>r.getCategory()==="SHIPPING"),i=t.filter(r=>r.getCategory()!=="SHIPPING");this.coupons=[],this.total.couponDiscountTotal=this.total.subtotal.zero(),this.total.couponTotal={},i.length&&this.applyNonShippingCoupons(i),this.applyDiscountsInLineItem(this.total.couponTotal),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 s=this.coupons.find(a=>a.getCode()===r);if(!s||o.isZero())return;let c=this.lineItems.filter(a=>a.getState()!=="CANCELLED"&&!a.getTotal().subtotal.isZero()).sort((a,g)=>a.getTotal().subtotal.compareTo(g.getTotal().subtotal)),u=new l({amount:0,currency:this.currency});c.forEach((a,g)=>{let y;g===c.length-1?y=o.subtract(u):y=o.multiply(a.getTotal().subtotal).divide(this.total.subtotal).round(),u=u.add(y),i.get(a.getId())?.push({coupon:s,amount:y});});}),this.lineItems.forEach(r=>{r.getState()==="CANCELLED"||this.total.subtotal.isZero()?r.updateDiscounts([]):r.updateDiscounts(i.get(r.getId())||[]);});}updateTax(t){this.lineItems.forEach(e=>{e.updateTax(t[e.getPricing().taxCategory]);}),this.calculateTotals();}applyNonShippingCoupons(t){let e=t.filter(i=>i.getType()==="coupon");if(e.length===1){let i=e[0].calculateApplicableCouponDiscount(this.total.subtotal,this.total.shipping,this.country,this.currency);i.getAmount()>0&&(this.coupons.push(e[0]),this.total.couponTotal[e[0].getCode()]=i,this.total.couponDiscountTotal=i);}}applyShippingCoupons(t){if(this.total.shipping.getAmount()>0&&t.length>0){let e=this.total.subtotal.subtract(this.total.couponDiscountTotal),i=t.reduce((o,s)=>{if(!o)return s;let c=s.calculateApplicableCouponDiscount(e,this.total.shipping,this.country,this.currency).min(this.total.shipping),u=o.calculateApplicableCouponDiscount(e,this.total.shipping,this.country,this.currency).min(this.total.shipping);return c===u?s.getType()==="coupon"?s:o:c>u?s:o}),r=i.calculateApplicableCouponDiscount(e,this.total.shipping,this.country,this.currency).min(this.total.shipping);r.getAmount()>0&&(this.coupons.push(i),this.total.couponTotal[i.getCode()]=r,this.total.couponDiscountTotal=this.total.couponDiscountTotal.add(r),this.total.effectiveShipping=this.total.shipping.subtract(r));}}};var Mt=(r=>(r.ACTIVE="ACTIVE",r.FROZEN="FROZEN",r.MERGED="MERGED",r.ORDERED="ORDERED",r))(Mt||{}),wt={expiresAtInSeconds:120*24*60*60},st=class extends U{state;expireAt;config;constructor(t,e=new Date,i=wt){super(t,e),this.state=t.state,this.expireAt=t.expireAt&&typeof t.expireAt=="number"?t.expireAt:Math.floor(e.getTime()/1e3)+i.expiresAtInSeconds,this.config=i;}getState(){return this.state}getExpireAt(){return this.expireAt}isActive(){let t=Math.ceil(Date.now()/1e3);return this.state==="ACTIVE"&&this.expireAt>t}clearCartItems(){this.lineItems=[],this.coupons=[],this.shippingDetails=null,this.total.couponTotal={},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=S.generateSelectionAttributesKey(i),o=this.lineItems.findIndex(s=>s.getProductKey()===e&&S.generateSelectionAttributesKey(s.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(s=>s.getId()===t);if(o<0)throw new L(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 L(t);return this.lineItems.splice(i,1),this.calculateTotals(),i}getDetails(){return {...super.getDetails(),state:this.getState(),expireAt:this.getExpireAt()}}};exports.CartState=Mt;exports.DEFAULT_CART_CONFIG=wt;exports.default=st;//# sourceMappingURL=Cart.js.map
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var ht=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ht__default=/*#__PURE__*/_interopDefault(ht);var w=class extends Error{constructor(t){super(`Line item with ID '${t}' not found in the cart.`),this.name="LineItemNotFoundError";}},O=class extends Error{constructor(t){super(`Invalid line item state: ${t}`),this.name="InvalidLineItemStateError";}},F=class extends Error{constructor(t){super(`Duplicate size found: ${t}`),this.name="DuplicateSizeError";}},B=class extends Error{constructor(t){super(`Duplicate selection attribute found: ${t}`),this.name="DuplicateSelectionAttributeError";}},z=class extends Error{constructor(t="Product and selection attributes do not match."){super(`ProductMismatch: ${t}`),this.name="ProductMismatchError";}},$=class extends Error{constructor(t="Product is not active."){super(`ProductInactive: ${t}`),this.name="ProductInactiveError";}},x=class extends Error{constructor(t="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${t}`),this.name="SelectionAttributeParseError";}},V=class extends Error{constructor(t="Size does not match."){super(`SizeMismatch: ${t}`),this.name="SizeMismatchError";}},G=class extends Error{constructor(t="Pricing details not available for the product"){super(`NotFound: ${t}`),this.name="PricingNotFoundError";}},k=class extends Error{constructor(t="Tax rule category mismatch."){super(`InvalidTaxRule: ${t}`),this.name="InvalidTaxRuleError";}},q=class extends Error{constructor(t="Tax category is not valid."){super(`InvalidTaxCategory: ${t}`),this.name="InvalidTaxCategoryError";}},K=class extends Error{constructor(t="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${t}`),this.name="InvalidMinQuantityError";}},j=class extends Error{constructor(t){super(`InvalidTieredPrice: ${t}`),this.name="InvalidTieredPriceError";}},Q=class extends Error{constructor(t="Quantity must be greater than zero."){super(`InvalidQuantity: ${t}`),this.name="InvalidQuantityError";}},H=class extends Error{constructor(t){super(`NoApplicableTier: Quantity ${t} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}},Z=class extends Error{constructor(t="No applicable tax slab or multiple slabs found for the given unit price."){super(`TaxSlabNotFound: ${t}`),this.name="TaxSlabNotFoundError";}},v=class extends Error{constructor(t="Amount cannot be negative."){super(`InvalidAmount: ${t}`),this.name="InvalidPriceAmountError";}},D=class extends Error{constructor(t="Currency code is required."){super(`InvalidCurrency: ${t}`),this.name="InvalidCurrencyCodeError";}},T=class extends Error{constructor(t="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${t}`),this.name="CurrencyMismatchError";}},f=class extends Error{constructor(t){super(`InvalidArgument: ${t}`),this.name="InvalidArgumentError";}},E=class extends Error{constructor(t="Invalid image source configuration."){super(`InvalidImageSource: ${t}`),this.name="InvalidImageSourceError";}};var X=new Uint8Array(256),Y=X.length;function tt(){return Y>X.length-16&&(ht__default.default.randomFillSync(X),Y=0),X.slice(Y,Y+=16)}var at=/^(?:[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 yt(n){return typeof n=="string"&&at.test(n)}var ct=yt;var h=[];for(let n=0;n<256;++n)h.push((n+256).toString(16).slice(1));function W(n,t=0){return h[n[t+0]]+h[n[t+1]]+h[n[t+2]]+h[n[t+3]]+"-"+h[n[t+4]]+h[n[t+5]]+"-"+h[n[t+6]]+h[n[t+7]]+"-"+h[n[t+8]]+h[n[t+9]]+"-"+h[n[t+10]]+h[n[t+11]]+h[n[t+12]]+h[n[t+13]]+h[n[t+14]]+h[n[t+15]]}function ft(n){if(!ct(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 ut=ft;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 Ct="6ba7b810-9dad-11d1-80b4-00c04fd430c8",xt="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function et(n,t,e){function i(r,o,s,c){var u;if(typeof r=="string"&&(r=bt(r)),typeof o=="string"&&(o=ut(o)),((u=o)===null||u===void 0?void 0:u.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let a=new Uint8Array(16+r.length);if(a.set(o),a.set(r,o.length),a=e(a),a[6]=a[6]&15|t,a[8]=a[8]&63|128,s){c=c||0;for(let g=0;g<16;++g)s[c+g]=a[g];return s}return W(a)}try{i.name=n;}catch{}return i.DNS=Ct,i.URL=xt,i}var it={randomUUID:ht__default.default.randomUUID};function St(n,t,e){if(it.randomUUID&&!t&&!n)return it.randomUUID();n=n||{};let i=n.random||(n.rng||tt)();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 W(i)}var rt=St;function At(n){return Array.isArray(n)?n=Buffer.from(n):typeof n=="string"&&(n=Buffer.from(n,"utf8")),ht__default.default.createHash("sha1").update(n).digest()}var lt=At;var Pt=et("v5",80,lt),nt=Pt;var Dt={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?nt(n,t):rt(),generateSearchId:(n,t)=>`${n}#${S.generateSelectionAttributesKey(t)}`,getKeyfromSearchId:n=>{let[t,e]=n.split("#");return {key:t,selectionAttributes:S.parseSelectionAttributesKey(e)}},deepClone(n){return structuredClone(n)}},d=Dt;var R=class{customFields;constructor(t,e=new Date){this.customFields={...t.customFields};}getCustomField(t){return this.customFields[t]??null}setCustomField(t,e){this.customFields[t]=e;}getAllCustomFields(){return {...this.customFields}}},b=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 C={"en-IN":"en","kn-IN":"kn"};var dt={INR:"\u20B9"},gt={INR:"en-IN"};var J=(g=>(g.INITIAL="INITIAL",g.PROCESSING="PROCESSING",g.SHIPPED="SHIPPED",g.DELIVERED="DELIVERED",g.CANCELLED="CANCELLED",g.RETURN_REQUESTED="RETURN_REQUESTED",g.RETURNED="RETURNED",g.REFUND_INITIATED="REFUND_INITIATED",g.REFUNDED="REFUNDED",g.ON_HOLD="ON_HOLD",g))(J||{});var I=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 E("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 E("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 l=class n{#t;amount;currency;constructor(t){if(this.#t="PriceModel",t.amount<0)throw new v("Amount cannot be negative.");if(!t.currency)throw new D("Currency code is required.");this.amount=t.amount,this.currency=t.currency;}get kind(){return this.#t}static isPriceModel(t){return typeof t=="object"&&t!==null&&t.kind==="PriceModel"}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}compareTo(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new T("Cannot compare prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return this.amount-t.getAmount()}add(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new T("Cannot add prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return new n({amount:this.amount+t.getAmount(),currency:this.currency})}subtract(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new T("Cannot subtract prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return new n({amount:this.amount-t.getAmount(),currency:this.currency})}multiply(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new T("Cannot multiply prices in different currencies.");return new n({amount:this.amount*t.getAmount(),currency:this.currency})}else if(typeof t=="number"&&t>=0)return new n({amount:this.amount*t,currency:this.currency});throw new f("Must be a non-negative number.")}divide(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new T("Cannot divide prices in different currencies.");return new n({amount:this.amount/t.getAmount(),currency:this.currency})}else if(typeof t=="number"&&t>0)return new n({amount:this.amount/t,currency:this.currency});throw new f("Must be a positive number.")}min(...t){if(t.length===0)throw new f("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(n.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new T("Cannot compare prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return e.compareTo(i)<0?e:i})}max(...t){if(t.length===0)throw new f("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(n.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new T("Cannot compare prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return e.compareTo(i)>0?e:i})}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=gt[e];if(!e||!r)throw new D("Invalid currency code for formatting.");let o=t,s=i.displayAsInteger?0:n.getDecimalPlaces(e),c={style:i.style??"currency",currency:e,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:s,maximumFractionDigits:s};i.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(r,c).format(o)}catch(u){return console.error(`Error formatting price for currency "${e}" and locale "${r}":`,u),`${dt[e]??e} ${n.addThousandSeparators(o.toFixed(s))}`}}static getDecimalPlaces(t){switch(t){case"INR":default:return 2}}static addThousandSeparators(t){let e=t.split("."),i=e[0],r=e.length>1?"."+e[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+r}static getRoundedAmount(t,e){if(t<0)throw new v("Amount cannot be negative for rounding.");if(e===void 0)throw new D("Invalid currency code for rounding.");let i=n.getDecimalPlaces(e),r=Math.pow(10,i);return Math.round(t*r)/r}};var M=class{baseUnitPrice;taxCategory;tiers;constructor(t){let e=new l(t.baseUnitPrice);if(!t.taxCategory)throw new q;let i=(t.tiers??[]).map(u=>({minQuantity:u.minQuantity,unitPrice:new l(u.unitPrice)})).sort((u,a)=>u.minQuantity-a.minQuantity);if(i.some(u=>u.minQuantity<=0))throw new K;let o=i.some(u=>u.unitPrice.getCurrency()!==e.getCurrency()),s=i.some((u,a)=>a>0&&u.unitPrice.compareTo(i[a-1].unitPrice)>0),c=i[0]?.unitPrice.compareTo(e)>0;if(o||s||c)throw new j("Tiers must share the same currency and must not increase in unit price.");this.baseUnitPrice=e,this.taxCategory=t.taxCategory,this.tiers=i;}getBaseUnitPrice(){return this.baseUnitPrice}getTaxCategory(){return this.taxCategory}getTiers(){return this.tiers}getDetails(){return {baseUnitPrice:this.baseUnitPrice.getDetails(),taxCategory:this.taxCategory,tiers:this.tiers.map(t=>({minQuantity:t.minQuantity,unitPrice:t.unitPrice.getDetails()}))}}getApplicableTier(t){if(t<=0)throw new Q;for(let e=this.tiers.length-1;e>=0;e--)if(t>=this.tiers[e].minQuantity)return this.tiers[e];throw new H(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 S=class n extends b{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 x("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,s]=r.split(":");s.startsWith("c+")?e[o]={name:s.slice(2)}:e[o]=s;}return e}catch(e){throw new x(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 M(t.pricing[o])),r),{}),this.targetGender=t.targetGender,this.attributes=d.deepClone(t.attributes),this.specifications=d.deepClone(t.specifications),this.categories=d.deepClone(t.categories);let i=new Set;this.variants=(t.variants||[]).map(r=>{if(!r.selectionAttributes||typeof r.selectionAttributes!="object")throw new x("Selection attributes are required");this.checkSelectionAttributes(r.selectionAttributes);let o=n.generateSelectionAttributesKey(r.selectionAttributes);if(i.has(o))throw new B(o);return i.add(o),{sku:r.sku,selectionAttributes:r.selectionAttributes,images:{primary:new I(r.images.primary),gallery:(r.images.gallery||[]).map(s=>new I(s))}}}),this.isActive=t.isActive,this.searchTags=t.searchTags?d.deepClone(t.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(t){return t?this.name[t]??this.name[C[t]]??this.name.en:d.deepClone(this.name)}getDescription(t){return t?this.description[t]??this.description[C[t]]??this.description.en:d.deepClone(this.description)}getSlug(t){return t?this.slug[t]??this.slug[C[t]]??this.slug.en:d.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(t){return t?this.pricing[t]??null:this.pricing}getAttributes(){return d.deepClone(this.attributes)}getVariants(){return this.variants.map(t=>({sku:t.sku,selectionAttributes:t.selectionAttributes,images:{primary:t.images.primary,gallery:t.images.gallery}}))}getImagesBySelectionAttributes(t){let e=n.generateSelectionAttributesKey(t),i=this.variants.find(r=>n.generateSelectionAttributesKey(r.selectionAttributes)===e);return i?i.images:null}getImages(t,e){switch(e){case"PRIMARY":return this.getImagesBySelectionAttributes(t)?.primary??this.variants[0]?.images?.primary;case"GALLERY":return this.getImagesBySelectionAttributes(t)?.gallery??[];default:return this.getImagesBySelectionAttributes(t)??{primary:this.variants[0]?.images?.primary,gallery:[]}}}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return d.deepClone(this.categories)}getSpecifications(t){return t?d.deepClone(this.specifications[t]??this.specifications[C[t]]??this.specifications.en):d.deepClone(this.specifications)}getSearchTags(t){return t?d.deepClone(this.searchTags[t]??this.searchTags[C[t]]??this.searchTags.en):d.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:d.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 x("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 x(`Selection attribute '${e}' is missing`);if(typeof i=="string"){if(typeof r!="string"||i!==r)throw new x(`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 x(`Selection attribute '${e}' is invalid`)}else if(typeof r!="object"||!("name"in r)||i.findIndex(o=>o.name===r.name)<0)throw new x(`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 P=class extends b{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 ot=class{getBreakdown(t,e,i){let r=t*100,o=r%1===0?r.toString():r.toFixed(2).replace(/\.?0+$/,"");if(e==="IN"&&i?.merchantState&&i?.customerState)if(i.merchantState.toLowerCase().trim()===i.customerState.toLowerCase().trim()){let s=r/2%1===0?(r/2).toString():(r/2).toFixed(2).replace(/\.?0+$/,"");return {totalRate:t,label:`${s}% CGST + ${s}% SGST`,components:[{rate:t/2,label:`${s}% CGST`,type:"CGST"},{rate:t/2,label:`${s}% SGST`,type:"SGST"}]}}else return {totalRate:t,label:`${o}% IGST`,components:[{rate:t,label:`${o}% IGST`,type:"IGST"}]};return {totalRate:t,label:`${o}% GST`,components:[{rate:t,label:`${o}% GST`,type:"GST"}]}}getLongName(){return "Goods and Services Tax"}},pt={GST:new ot},_=class n extends b{taxRuleId;taxSystem;taxCategory;country;slabs;effectiveFrom;effectiveTo;constructor(t,e=new Date){super(t,e),this.taxRuleId=t.taxRuleId,this.taxSystem=t.taxSystem,this.taxCategory=t.taxCategory,this.country=t.country,this.slabs=t.slabs.map(i=>({rate:i.rate,minUnitPrice:new l(i.minUnitPrice),maxUnitPrice:i.maxUnitPrice?new l(i.maxUnitPrice):void 0})),this.effectiveFrom=new Date(t.effectiveFrom),this.effectiveTo=t.effectiveTo?new Date(t.effectiveTo):void 0;}getTaxRuleId(){return this.taxRuleId}getTaxSystem(){return this.taxSystem}getTaxCategory(){return this.taxCategory}getCountry(){return this.country}getSlabs(){return this.slabs}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxCategory:this.getTaxCategory(),country:this.getCountry(),slabs:this.getSlabs().map(t=>({rate:t.rate,minUnitPrice:t.minUnitPrice.getDetails(),maxUnitPrice:t.maxUnitPrice?t.maxUnitPrice.getDetails():void 0})),effectiveFrom:this.effectiveFrom.toISOString(),effectiveTo:this.effectiveTo?this.effectiveTo.toISOString():void 0,...super.getDetails()}}appliesTo(t,e,i=new Date){return this.taxCategory===t&&this.country===e&&this.effectiveFrom<=i&&(this.effectiveTo?this.effectiveTo>=i:!0)}getApplicableTaxRate(t){return n.getApplicableTaxRate(t,this.slabs)}getTaxRateDisplayString(t,e){let i=this.getApplicableTaxRate(t);return n.getTaxRateDisplayString(i,{taxSystem:this.taxSystem,merchantState:e?.merchantState,customerState:e?.customerState})}getTaxRateBreakdown(t,e){let i=this.getApplicableTaxRate(t),r=pt[this.taxSystem];if(r)return r.getBreakdown(i,this.country,e);let o=i*100,c=`${o%1===0?o.toString():o.toFixed(2).replace(/\.?0+$/,"")}% ${this.taxSystem}`;return {totalRate:i,label:c,components:[{rate:i,label:c,type:this.taxSystem}]}}getFormattedTaxRate(t,e={}){let r=this.getApplicableTaxRate(t)*100,o=r%1===0?r.toString():r.toFixed(2).replace(/\.?0+$/,""),s=e.variant||"short",c="";switch(s){case"percentageOnly":c=`${o}%`;break;case"detailed":let u=this.getTaxRateBreakdown(t,e),a=e.separator||(e.multiline?`
2
+ `:" + ");c=u.components.map(m=>m.label).join(a);break;case"long":let g=pt[this.taxSystem],y=g?g.getLongName(this.country):this.taxSystem.toString();c=`${o}% ${y}`;break;case"short":default:c=`${o}% ${this.taxSystem}`;break}return e.includeTaxesSuffix&&(c+=" (Incl. Taxes)"),c}static getApplicableTaxRate(t,e){let i=e.filter(r=>(r.minUnitPrice===void 0||t.compareTo(r.minUnitPrice)>=0)&&(r.maxUnitPrice===void 0||t.compareTo(r.maxUnitPrice)<0));if(i.length!==1)throw new Z;return i[0].rate}static getTaxRateDisplayString(t,e){let i=t*100,r=i%1===0?i.toString():i.toFixed(2).replace(/\.?0+$/,"");if(e.taxSystem==="GST"&&e.merchantState&&e.customerState)if(e.merchantState.toLowerCase().trim()===e.customerState.toLowerCase().trim()){let o=i/2%1===0?(i/2).toString():(i/2).toFixed(2).replace(/\.?0+$/,"");return `${o}% CGST + ${o}% SGST`}else return `${r}% IGST`;return e.taxSystem?`${r}% ${e.taxSystem}`:`${r}%`}};var L=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=d.deepClone(t.selectionAttributes),this.name=d.deepClone(t.name),this.specifications=d.deepClone(t.specifications),this.primaryImage=new I(t.primaryImage),this.subItems=d.deepClone(t.subItems);let e=new Set;this.subItems.forEach(i=>{if(e.has(i.size))throw new F(i.size);e.add(i.size);}),this.pricing={unitPrice:new l(t.pricing.unitPrice),tierPricing:new M(t.pricing.tierPricing),taxCategory:t.pricing.taxCategory,tax:{taxRuleId:t.pricing.tax.taxRuleId,taxSystem:t.pricing.tax.taxSystem,country:t.pricing.tax.country,rate:t.pricing.tax.rate,taxSlabs:t.pricing.tax.taxSlabs.map(i=>({rate:i.rate,minUnitPrice:new l(i.minUnitPrice),maxUnitPrice:i.maxUnitPrice?new l(i.maxUnitPrice):void 0}))}},this.state=t.state??"INITIAL",this.total={quantity:t.total.quantity,subtotal:new l(t.total.subtotal),discounts:Object.fromEntries(Object.entries(t.total.discounts).map(([i,r])=>[i,new l(r)])),taxableAmount:new l(t.total.taxableAmount),taxTotal:new l(t.total.taxTotal),grandTotal:new l(t.total.grandTotal)};}getId(){return this.id}getProductKey(){return this.productKey}getSelectionAttributes(){return d.deepClone(this.selectionAttributes)}getName(t){return t?d.deepClone(this.name[t]??this.name[C[t]]??this.name.en):d.deepClone(this.name)}getSpecifications(t){return t?d.deepClone(this.specifications[t]??this.specifications[C[t]]??this.specifications.en):d.deepClone(this.specifications)}getImage(){return this.primaryImage}getSubItems(){return d.deepClone(this.subItems)}getTotalQuantity(){return this.total.quantity}getPricing(){return {unitPrice:this.pricing.unitPrice,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,tax:{taxRuleId:this.pricing.tax.taxRuleId,taxSystem:this.pricing.tax.taxSystem,country:this.pricing.tax.country,rate:this.pricing.tax.rate,taxSlabs:this.pricing.tax.taxSlabs}}}getState(){return this.state}getTotal(){return {quantity:this.total.quantity,subtotal:this.total.subtotal,taxableAmount:this.total.taxableAmount,taxTotal:this.total.taxTotal,discounts:Object.fromEntries(Object.entries(this.total.discounts).map(([t,e])=>[t,e])),grandTotal:this.total.grandTotal}}getDetails(){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:this.getPricing().unitPrice.getDetails(),tierPricing:this.getPricing().tierPricing.getDetails(),taxCategory:this.getPricing().taxCategory,tax:{taxRuleId:this.getPricing().tax.taxRuleId,taxSystem:this.getPricing().tax.taxSystem,country:this.getPricing().tax.country,rate:this.getPricing().tax.rate,taxSlabs:this.getPricing().tax.taxSlabs.map(t=>({rate:t.rate,minUnitPrice:t.minUnitPrice.getDetails(),maxUnitPrice:t.maxUnitPrice?t.maxUnitPrice.getDetails():void 0}))}},state:this.getState(),total:{quantity:this.getTotal().quantity,subtotal:this.getTotal().subtotal.getDetails(),taxableAmount:this.getTotal().taxableAmount.getDetails(),taxTotal:this.getTotal().taxTotal.getDetails(),discounts:Object.fromEntries(Object.entries(this.getTotal().discounts).map(([t,e])=>[t,e.getDetails()])),grandTotal:this.getTotal().grandTotal.getDetails()},customFields:this.getAllCustomFields()}}addSubItems(t,e){t.forEach(i=>{let r=this.subItems.find(o=>o.size===i.size);r?r.quantity=e?r.quantity+i.quantity:i.quantity:this.subItems.push(i);}),this.subItems=this.subItems.filter(i=>i.quantity>0),this.calculateTotals();}updateProductData(t,e,i){if(this.productKey!==t.getKey()||!t.validateSelectionAttribute(this.selectionAttributes))throw new z;if(!t.getIsActive())throw new $;this.subItems.forEach(c=>{if(!t.validateSize(c.size))throw new V});let r=t.getPriceDetails(e);if(!r||r.getBaseUnitPrice().getCurrency()!==i)throw new G;this.name=t.getName(),this.specifications=t.getSpecifications(),this.primaryImage=t.getImages(this.selectionAttributes).primary;let o=this.subItems.reduce((c,u)=>c+u.quantity,0),{unitPrice:s}=r.getApplicableTier(o);this.pricing={unitPrice:s,tierPricing:r,taxCategory:r.getTaxCategory(),tax:this.pricing.tax},this.calculateTotals();}updateDiscounts(t){let e={};t.forEach(i=>{e[i.coupon.getCode()]=i.amount;}),this.total.discounts=e,this.calculateTotals();}updateTax(t){if(!t.appliesTo(this.pricing.taxCategory,this.pricing.tax.country))throw new k;let e=this.total.quantity>0?this.total.taxableAmount.divide(this.total.quantity):this.total.taxableAmount.zero();this.pricing.tax={taxRuleId:t.getTaxRuleId(),taxSystem:t.getTaxSystem(),country:t.getCountry(),rate:t.getApplicableTaxRate(e),taxSlabs:t.getSlabs()},this.calculateTotals();}calculateTotals(){let t=this.pricing.unitPrice.zero(),e=this.subItems.reduce((y,m)=>y+m.quantity,0);if(this.state==="CANCELLED"){this.total={quantity:0,subtotal:t,taxableAmount:t,taxTotal:t,discounts:{},grandTotal:t};return}let{unitPrice:i}=this.pricing.tierPricing.getApplicableTier(e),r=i.multiply(e),o=Object.values(this.total.discounts).reduce((y,m)=>y.add(m),t),s=r.subtract(o),c=e>0?s.divide(e):t,u=_.getApplicableTaxRate(c,this.pricing.tax.taxSlabs),a=s.multiply(u).round(),g=r.subtract(o).add(a);this.total={quantity:e,subtotal:r,taxableAmount:s,taxTotal:a,discounts:this.total.discounts,grandTotal:g};}updateState(t){if(this.state in J)this.state!==t&&(this.state=t);else throw new O(t)}clearLineItem(){let t=this.pricing.unitPrice.zero();this.id="",this.productKey="",this.selectionAttributes={color:{name:""}},this.name={en:""},this.primaryImage=new I({sources:{original:""}}),this.subItems=[],this.pricing={unitPrice:t,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,tax:this.pricing.tax},this.total={quantity:0,subtotal:t,taxableAmount:t,taxTotal:t,discounts:{},grandTotal:t};}};var N=class extends b{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=d.deepClone(t.name),this.description=d.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 l(o)),i},{}),this.maxCartDiscount=Object.keys(t.maxCartDiscount).reduce((i,r)=>{let o=t.maxCartDiscount[r];return o&&(i[r]=new l(o)),i},{}),this.discountMethod=t.discountMethod,this.percentageValue=t.percentageValue??0,this.percentageValue>100)throw new f("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[C[t]]??this.name.en:{...this.name}}getDescription(t){return t?this.description[t]??this.description[C[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 s=new l({amount:0,currency:r}),c;if(o&&!this.isActive())return s;let u=this.getMinCartValue(i),a=this.getMaxCartDiscount(i);if(!u||u.compareTo(t)>0||!a)return s;let g=this.getCategory(),y=this.getDiscountMethod(),m=g==="SHIPPING"?e:t;if(m.getAmount()<=0)return s;switch(y){case"flat":let mt=a;c=m.min(mt);break;case"percentage":c=m.multiply(this.getPercentageValue()/100).round();break;default:return s}return c.min(a)}};var U=class extends b{id;customerId;customerEmail;anonymousId;lineItems;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 L(i)),this.billingAddress=t.billingAddress?new P(t.billingAddress,e):null,this.shippingAddress=t.shippingAddress?new P(t.shippingAddress,e):null,this.coupons=(t.coupons??[]).map(i=>new N(i)),this.shippingDetails=t.shippingDetails?d.deepClone(t.shippingDetails):null,this.total={subtotal:new l(t.total.subtotal),shipping:new l(t.total.shipping),effectiveShipping:new l(t.total.effectiveShipping),taxTotal:new l(t.total.taxTotal),couponTotal:Object.fromEntries(Object.entries(t.total.couponTotal).map(([i,r])=>[i,new l(r)])),couponDiscountTotal:new l(t.total.couponDiscountTotal),grandTotal:new l(t.total.grandTotal)};}getId(){return this.id}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getAnonymousId(){return this.anonymousId}getLineItems(){return this.lineItems.map(t=>new L(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getShippingDetails(){return this.shippingDetails?{...this.shippingDetails}:null}getShippingAddress(){return this.shippingAddress?new P(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new P(this.billingAddress.getDetails()):null}getCoupons(){return this.coupons}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return this.total}getDetails(){return {...super.getDetails(),id:this.getId(),customerId:this.getCustomerId(),customerEmail:this.getCustomerEmail(),anonymousId:this.getAnonymousId(),lineItems:this.getLineItems().map(t=>t.getDetails()),shippingDetails:this.getShippingDetails(),shippingAddress:this.getShippingAddress()?.getDetails()||null,billingAddress:this.getBillingAddress()?.getDetails()||null,coupons:this.getCoupons().map(t=>t.getDetails()),total:{subtotal:this.getTotal().subtotal.getDetails(),shipping:this.getTotal().shipping.getDetails(),effectiveShipping:this.getTotal().effectiveShipping.getDetails(),taxTotal:this.getTotal().taxTotal.getDetails(),couponTotal:Object.fromEntries(Object.entries(this.getTotal().couponTotal).map(([t,e])=>[t,e.getDetails()])),couponDiscountTotal:this.getTotal().couponDiscountTotal.getDetails(),grandTotal:this.getTotal().grandTotal.getDetails()},country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}calculateTotals(){let t=new l({amount:0,currency:this.currency}),e=this.lineItems.filter(m=>m.getState()!=="CANCELLED"),i=e.reduce((m,A)=>m.add(A.getTotal().subtotal),t),r=new l({amount:this.shippingDetails?.cost||0,currency:this.currency}).round(),o=t,s={},c={};this.coupons.forEach(m=>{let A=m.calculateApplicableCouponDiscount(i,r,this.country,this.currency);o=o.add(A),s[m.getCode()]=A,m.getCategory()!=="SHIPPING"&&(c[m.getCode()]=A);}),this.applyDiscountsInLineItem(c);let u=e.reduce((m,A)=>m.add(A.getTotal().taxTotal),t),a=this.coupons.find(m=>m.getCategory()==="SHIPPING"),g=a?r.subtract(s[a.getCode()]||t):r,y=i.add(r).add(u).subtract(o);this.total={subtotal:i,shipping:r,effectiveShipping:g,couponTotal:s,couponDiscountTotal:o,taxTotal:u,grandTotal:y};}updateShippingDetails(t){this.shippingDetails=t,this.calculateTotals();}applyCoupons(t){let e=t.filter(r=>r.getCategory()==="SHIPPING"),i=t.filter(r=>r.getCategory()!=="SHIPPING");this.coupons=[],this.total.couponDiscountTotal=this.total.subtotal.zero(),this.total.couponTotal={},i.length&&this.applyNonShippingCoupons(i),this.applyDiscountsInLineItem(this.total.couponTotal),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 s=this.coupons.find(a=>a.getCode()===r);if(!s||o.isZero())return;let c=this.lineItems.filter(a=>a.getState()!=="CANCELLED"&&!a.getTotal().subtotal.isZero()).sort((a,g)=>a.getTotal().subtotal.compareTo(g.getTotal().subtotal)),u=new l({amount:0,currency:this.currency});c.forEach((a,g)=>{let y;g===c.length-1?y=o.subtract(u):y=o.multiply(a.getTotal().subtotal).divide(this.total.subtotal).round(),u=u.add(y),i.get(a.getId())?.push({coupon:s,amount:y});});}),this.lineItems.forEach(r=>{r.getState()==="CANCELLED"||this.total.subtotal.isZero()?r.updateDiscounts([]):r.updateDiscounts(i.get(r.getId())||[]);});}updateTax(t){this.lineItems.forEach(e=>{e.updateTax(t[e.getPricing().taxCategory]);}),this.calculateTotals();}applyNonShippingCoupons(t){let e=t.filter(i=>i.getType()==="coupon");if(e.length===1){let i=e[0].calculateApplicableCouponDiscount(this.total.subtotal,this.total.shipping,this.country,this.currency);i.getAmount()>0&&(this.coupons.push(e[0]),this.total.couponTotal[e[0].getCode()]=i,this.total.couponDiscountTotal=i);}}applyShippingCoupons(t){if(this.total.shipping.getAmount()>0&&t.length>0){let e=this.total.subtotal.subtract(this.total.couponDiscountTotal),i=t.reduce((o,s)=>{if(!o)return s;let c=s.calculateApplicableCouponDiscount(e,this.total.shipping,this.country,this.currency).min(this.total.shipping),u=o.calculateApplicableCouponDiscount(e,this.total.shipping,this.country,this.currency).min(this.total.shipping);return c===u?s.getType()==="coupon"?s:o:c>u?s:o}),r=i.calculateApplicableCouponDiscount(e,this.total.shipping,this.country,this.currency).min(this.total.shipping);r.getAmount()>0&&(this.coupons.push(i),this.total.couponTotal[i.getCode()]=r,this.total.couponDiscountTotal=this.total.couponDiscountTotal.add(r),this.total.effectiveShipping=this.total.shipping.subtract(r));}}};var Mt=(r=>(r.ACTIVE="ACTIVE",r.FROZEN="FROZEN",r.MERGED="MERGED",r.ORDERED="ORDERED",r))(Mt||{}),Lt={expiresAtInSeconds:120*24*60*60},st=class extends U{state;expireAt;config;constructor(t,e=new Date,i=Lt){super(t,e),this.state=t.state,this.expireAt=t.expireAt&&typeof t.expireAt=="number"?t.expireAt:Math.floor(e.getTime()/1e3)+i.expiresAtInSeconds,this.config=i;}getState(){return this.state}getExpireAt(){return this.expireAt}isActive(){let t=Math.ceil(Date.now()/1e3);return this.state==="ACTIVE"&&this.expireAt>t}clearCartItems(){this.lineItems=[],this.coupons=[],this.shippingDetails=null,this.total.couponTotal={},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=S.generateSelectionAttributesKey(i),o=this.lineItems.findIndex(s=>s.getProductKey()===e&&S.generateSelectionAttributesKey(s.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(s=>s.getId()===t);if(o<0)throw new w(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 w(t);return this.lineItems.splice(i,1),this.calculateTotals(),i}getDetails(){return {...super.getDetails(),state:this.getState(),expireAt:this.getExpireAt()}}};exports.CartState=Mt;exports.DEFAULT_CART_CONFIG=Lt;exports.default=st;//# sourceMappingURL=Cart.js.map
3
3
  //# sourceMappingURL=Cart.js.map