b23-lib 3.9.9 → 3.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Auth/index.js +1 -1
- package/dist/Auth/index.js.map +1 -1
- package/dist/Auth/index.mjs +1 -1
- package/dist/chunk-XZFALA7N.mjs +2 -0
- package/dist/chunk-XZFALA7N.mjs.map +1 -0
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-AMIRIUMH.mjs +0 -2
- package/dist/chunk-AMIRIUMH.mjs.map +0 -1
package/dist/Auth/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a as a$1,b,d,c as c$1}from'../chunk-
|
|
1
|
+
import {a as a$1,b,d,c as c$1}from'../chunk-XZFALA7N.mjs';import {a as a$2}from'../chunk-4PTWJI6J.mjs';import'../chunk-7RAIVZKB.mjs';import'../chunk-UIQH5QIR.mjs';import'../chunk-PL5HGCWN.mjs';import'../chunk-O6BLQQO7.mjs';import'../chunk-UXZBULDS.mjs';import {importPKCS8,SignJWT,importSPKI,jwtVerify,decodeJwt}from'jose';import a from'assert';var c=class l{static instance=null;id;type;token;initializedAt;lambdaName;requestId;constructor(e,t,i,r){this.id=e,this.type=t,this.token=i,this.lambdaName=process.env.AWS_LAMBDA_FUNCTION_NAME,this.initializedAt=new Date;}static getInstance(){return a(l.instance,a$1.AUTH_CONTEXT_NOT_INITIALIZED),l.instance}static init(e,t,i,r){return l.instance=new l(e,t,i,r),l.instance}static uninit(){l.instance=null;}getId(){return this.id}getType(){return this.type}getToken(){return this.token}getLambdaName(){return this.lambdaName}getRequestId(){return this.requestId}getInitializedAt(){return this.initializedAt}getSystemID(e){let t=this.lambdaName||e;return this.requestId?`${t} - ${this.requestId}`:t}};var K={userTokenAge:"30 days",userPrivateKeys:"[]",userPublicKeys:"[]",anonymousTokenAge:"30 days",anonymousPrivateKeys:"[]",anonymousPublicKeys:"[]",systemTokenAge:"5 min",systemPrivateKeys:"[]",systemPublicKeys:"[]",adminTokenAge:"30 days",adminPrivateKeys:"[]",adminPublicKeys:"[]",cdnKeys:"[]"},U=(n=>(n.ANON="Anon",n.USER="User",n.SYSTEM="System",n.ADMIN="Admin",n.CDN="CDN",n))(U||{}),v={allowAnonymous:!1,allowSystem:!0,allowUser:!0,allowCDN:!1},N=class{userTokenAge;userPrivateKeys;userPublicKeys;anonymousTokenAge;anonymousPrivateKeys;anonymousPublicKeys;systemTokenAge;systemPrivateKeys;systemPublicKeys;adminTokenAge;adminPrivateKeys;adminPublicKeys;cdnKeys;constructor(e=K){let{userTokenAge:t,userPrivateKeys:i,userPublicKeys:r,anonymousTokenAge:n,anonymousPrivateKeys:g,anonymousPublicKeys:h,systemTokenAge:m,systemPrivateKeys:T,systemPublicKeys:A,adminTokenAge:u,adminPrivateKeys:d,adminPublicKeys:S,cdnKeys:f}={...K,...e};this.userTokenAge=t,this.userPrivateKeys=this.parseKeyArray(i,"user private"),this.userPublicKeys=this.parseKeyArray(r,"user public"),this.anonymousTokenAge=n,this.anonymousPrivateKeys=this.parseKeyArray(g,"anonymous private"),this.anonymousPublicKeys=this.parseKeyArray(h,"anonymous public"),this.systemTokenAge=m,this.systemPrivateKeys=this.parseKeyArray(T,"system private"),this.systemPublicKeys=this.parseKeyArray(A,"system public"),this.adminTokenAge=u,this.adminPrivateKeys=this.parseKeyArray(d,"admin private"),this.adminPublicKeys=this.parseKeyArray(S,"admin public"),this.cdnKeys=this.parseKeyArray(f,"cdn"),this.logWarnings();}parseKeyArray(e,t){try{let i=JSON.parse(e);return !Array.isArray(i)||!i.every(r=>typeof r=="string")?(b.logError("AuthUtility",`Invalid format for ${t} keys in config: Expected stringified array of strings.`),[]):i}catch(i){return b.logError("AuthUtility",`Failed to parse ${t} keys from config: ${i}`),[]}}logWarnings(){let e=(t,i,r)=>i.length>r&&b.logWarning("AuthUtility",`More than ${r} ${t} keys provided. This is not recommended.`);e("user private",this.userPrivateKeys,3),e("user public",this.userPublicKeys,3),e("anonymous private",this.anonymousPrivateKeys,1),e("anonymous public",this.anonymousPublicKeys,3),e("system private",this.systemPrivateKeys,1),e("system public",this.systemPublicKeys,3),e("admin private",this.adminPrivateKeys,1),e("admin public",this.adminPublicKeys,3);}async createSignedJWT(e,t,i){let r=await importPKCS8(t,"RS256");return await new SignJWT(e).setProtectedHeader({alg:"RS256"}).setExpirationTime(i).setIssuedAt().sign(r)}async verifySignedJWT(e,t,i){for(let r=t.length-1;r>=0;r--)try{let n=await importSPKI(t[r],"RS256");return (await jwtVerify(e,n,{clockTolerance:30,maxTokenAge:i})).payload}catch(n){if(r===0)throw n;continue}throw new Error(a$1.INVALID_TOKEN)}async createAnonymousToken(e,t){a(this.anonymousPrivateKeys.length,a$1.ANONYMOUS_PRIVATE_KEY_NOT_FOUND),a(a$2.isUUID(e),a$1.INVALID_UUID);let i={id:e,type:"Anon",...t};return await this.createSignedJWT(i,this.anonymousPrivateKeys[this.anonymousPrivateKeys.length-1],this.anonymousTokenAge)}async verifyAnonymousToken(e){a(this.anonymousPublicKeys.length,a$1.ANONYMOUS_PUBLIC_KEY_NOT_FOUND);let t=await this.verifySignedJWT(e,this.anonymousPublicKeys,this.anonymousTokenAge);return a(t.type==="Anon",a$1.INVALID_AUTH_TYPE),t}async createUserToken(e,t){a(this.userPrivateKeys.length,a$1.USER_PRIVATE_KEY_NOT_FOUND),a(a$2.isUUID(e),a$1.INVALID_UUID);let i={id:e,type:"User",...t};return await this.createSignedJWT(i,this.userPrivateKeys[this.userPrivateKeys.length-1],this.userTokenAge)}async verifyUserToken(e){a(this.userPublicKeys.length,a$1.USER_PUBLIC_KEY_NOT_FOUND);let t=await this.verifySignedJWT(e,this.userPublicKeys,this.userTokenAge);return a(t.type==="User",a$1.INVALID_AUTH_TYPE),t}async createSystemToken(e,t){a(this.systemPrivateKeys.length,a$1.SYSTEM_PRIVATE_KEY_NOT_FOUND);let i={id:e,type:"System",...t};return await this.createSignedJWT(i,this.systemPrivateKeys[this.systemPrivateKeys.length-1],this.systemTokenAge)}async verifySystemToken(e){a(this.systemPublicKeys.length,a$1.USER_PUBLIC_KEY_NOT_FOUND);let t=await this.verifySignedJWT(e,this.systemPublicKeys,this.systemTokenAge);return a(t.type==="System",a$1.INVALID_AUTH_TYPE),t}async createAdminToken(e,t,i){a(this.adminPrivateKeys.length,a$1.ADMIN_PRIVATE_KEY_NOT_FOUND),a(a$2.isEmail(e),a$1.INVALID_EMAIL),a(a$2.isURL(t),a$1.INVALID_VERIFIER);let r={id:e,type:"Admin",verifier:t,...i};return await this.createSignedJWT(r,this.adminPrivateKeys[this.adminPrivateKeys.length-1],this.adminTokenAge)}async verifyAdminToken(e,t,i){a(this.adminPublicKeys.length,a$1.ADMIN_PUBLIC_KEY_NOT_FOUND);let r=await this.verifySignedJWT(e,this.adminPublicKeys,this.adminTokenAge);if(a(r.type==="Admin",a$1.INVALID_AUTH_TYPE),i){let n=await d(r.verifier,"","POST",{},{token:e,permissions:t});if(a(n.data.isTokenValid===!0,a$1.INVALID_TOKEN),n.data.hasPermissions!==!0)throw c$1.generateError(403,a$1.INVALID_PERMISSIONS)}return r}async verifyCDNToken(e){return a(this.cdnKeys.includes(e),a$1.INVALID_TOKEN),{id:e,type:"CDN"}}AuthMiddleware(e=v,t=[]){let{allowAnonymous:i,allowSystem:r,allowUser:n,allowCDN:g}={...v,...e};return async(h,m,T)=>{try{let[A,u]=h.get("Authorization")?.split(" ")||[];if(!u)throw new Error(a$1.INVALID_TOKEN);let d;switch(A){case"Anon":if(!i)throw c$1.generateError(403,a$1.ANONYMOUS_SESSION_NOT_ALLOWED);d=await this.verifyAnonymousToken(u);break;case"User":if(!n)throw c$1.generateError(403,a$1.USER_SESSION_NOT_ALLOWED);d=await this.verifyUserToken(u);break;case"System":if(!r)throw c$1.generateError(403,a$1.SYSTEM_SESSION_NOT_ALLOWED);d=await this.verifySystemToken(u);break;case"Admin":d=await this.verifyAdminToken(u,t,!0);break;case"CDN":if(!g)throw c$1.generateError(403,a$1.CDN_SESSION_NOT_ALLOWED);d=await this.verifyCDNToken(u);break;default:throw c$1.generateError(403,a$1.INVALID_AUTH_TYPE)}T();}catch(A){b.logError("AuthMiddleware",A),c$1.handleException("AuthMiddleware",c$1.generateError(401,A.error||a$1.TOKEN_EXPIRED,!0),m);}}}decodeJWTPayloadWithJose(e){if(!e||typeof e!="string")return b.logError("AuthContextMiddleware","Invalid token provided for decoding."),null;try{return decodeJwt(e)}catch(t){return b.logError("AuthContextMiddleware",`Failed to decode JWT payload: ${t}`),null}}AuthContextMiddleware(){return async(e,t,i)=>{try{let[r,n]=e.get("Authorization")?.split(" ")||[],g=r==="CDN"?{id:n,type:"CDN"}:r?this.decodeJWTPayloadWithJose(n):{},h=c.init(g?.id||n,g?.type||r,n,e.get("x-request-id"));b.logMessage("AuthContextMiddleware",`AuthContext initialized: ${h.getType()||"No-Type"} - ${h.getId()||"No-Id"}`),t.on("finish",()=>{b.logMessage("AuthContextMiddleware","Uninitializing AuthContext"),c.uninit();}),i();}catch(r){b.logError("AuthContextMiddleware",r),c$1.handleException("AuthContextMiddleware",c$1.generateError(500,r.error||a$1.INTERNAL_SERVER_ERROR,!0),t);}}}},j=N;export{c as AuthContext,U as AuthType,v as DefaultAuthMiddlewareConfig,K as DefaultAuthUtilityConfig,j as default};//# sourceMappingURL=index.mjs.map
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import I from'util';var a=Object.freeze({INVALID_UUID:"Invalid UUID",INVALID_EMAIL:"Invalid Email",INVALID_TOKEN:"Invalid Token",TOKEN_EXPIRED:"Token Expired",INVALID_VERIFIER:"Invalid Verifier",INVALID_PERMISSIONS:"Invalid Permissions",INVALID_AUTH_TYPE:"Invalid Authorization Type",USER_PRIVATE_KEY_NOT_FOUND:"User Private Key Not Found",USER_PUBLIC_KEY_NOT_FOUND:"User Public Key Not Found",ANONYMOUS_PRIVATE_KEY_NOT_FOUND:"Anonymous Private Key Not Found",ANONYMOUS_PUBLIC_KEY_NOT_FOUND:"Anonymous Public Key Not Found",SYSTEM_PRIVATE_KEY_NOT_FOUND:"System Private Key Not Found",SYSTEM_PUBLIC_KEY_NOT_FOUND:"System Public Key Not Found",ADMIN_PRIVATE_KEY_NOT_FOUND:"Admin Private Key Not Found",ADMIN_PUBLIC_KEY_NOT_FOUND:"Admin Public Key Not Found",SECRET_TOKEN_NOT_FOUND:"Secret Token Not Found",ANONYMOUS_SESSION_NOT_ALLOWED:"Anonymous Session Not Allowed",USER_SESSION_NOT_ALLOWED:"User Session Not Allowed",SYSTEM_SESSION_NOT_ALLOWED:"System Session Not Allowed",CDN_SESSION_NOT_ALLOWED:"CDN Session Not Allowed",INTERNAL_SERVER_ERROR:"Internal Server Error",SOMETHING_WENT_WRONG:"Something went wrong",AUTH_CONTEXT_NOT_INITIALIZED:"Auth Context not Initialized"});var n={logException:(s,t)=>{console.error(`Exception Occurred in Function: ${s}, Error: ${n.inspect(t)}`);},logError:(s,t)=>{console.error(`Error Occurred in Function: ${s}, Error: ${n.inspect(t)}`);},logWarning:(s,t)=>{console.warn(`Warning in Function: ${s} - ${n.inspect(t)}`);},logMessage:(s,t)=>{console.log(`Message in Function: ${s} - ${n.inspect(t)}`);},logInvalidPayload:(s,t)=>{console.error(`Invalid Payload received for Function: ${s}, Error: ${n.inspect(t)}`);},inspect:s=>typeof s=="string"?s:I.inspect(s)},o=n;var S={handleException:(s,t,r)=>{t.knownError?(t.logError&&o.logError(s,t),r.status(t.status).json({status:t.status,error:t.error})):t.status&&t.error?(o.logException(s,t),r.status(t.status).json({error:t.errorMessage||JSON.stringify(t.error),status:t.status})):(o.logException(s,t),r.status(500).json({status:500,error:a.INTERNAL_SERVER_ERROR}));},generateResponse:(s,t,r)=>({status:s,data:t,error:r}),generateError:(s,t,r=!0,E=!1)=>({status:s,error:t,knownError:r,logError:E})},D=S;var y=async(s,t,r="GET",E={},l)=>{let c={method:r,headers:{"Content-Type":"application/json",...E}};r!=="GET"&&l&&(c.body=JSON.stringify(l));let i=`${s}${t?"/"+t:""}`;try{let e=await fetch(i,c);if(!e.ok){let u,N=await e.text();try{u=JSON.parse(N);}catch{u={status:e.status,error:N||e.statusText},o.logWarning("Fetch",`Failed to parse error response body as JSON for URL-${i}. Raw text: ${N}`);}throw {status:e.status,statusText:e.statusText,error:u}}let O=await e.json();return o.logMessage("Fetch",`API call successful: URL-${i}, Status- ${e.status}`),{status:e.status,statusText:e.statusText,data:O}}catch(e){throw o.logError("Fetch",`API call failed: URL-${i}, Status- ${e.status||500}, Error- ${o.inspect(e.error||e)}`),{status:e.status||500,statusText:e.statusText||a.INTERNAL_SERVER_ERROR,error:e.error||{status:e.status||500,error:e.statusText||a.SOMETHING_WENT_WRONG}}}},K=y;export{a,o as b,D as c,K as d};//# sourceMappingURL=chunk-XZFALA7N.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-XZFALA7N.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/enums/ErrorTypes.ts","../src/Logger/index.ts","../src/Utils/response.ts","../src/Utils/fetch.ts"],"names":["ErrorTypes_default","Logger","functionName","error","message","errorMessage","context","util","Logger_default","ResponseUtility","res","status","data","knownError","logError","response_default","Fetch","baseURL","endpoint","method","headers","payload","options","completeURL","response","errorBody","errorText","body","err","fetch_default"],"mappings":"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","file":"chunk-XZFALA7N.mjs","sourcesContent":["export default Object.freeze({\r\n INVALID_UUID: \"Invalid UUID\",\r\n INVALID_EMAIL: \"Invalid Email\",\r\n INVALID_TOKEN: \"Invalid Token\",\r\n TOKEN_EXPIRED: \"Token Expired\",\r\n INVALID_VERIFIER: \"Invalid Verifier\",\r\n INVALID_PERMISSIONS: \"Invalid Permissions\",\r\n INVALID_AUTH_TYPE: \"Invalid Authorization Type\",\r\n USER_PRIVATE_KEY_NOT_FOUND: \"User Private Key Not Found\",\r\n USER_PUBLIC_KEY_NOT_FOUND: \"User Public Key Not Found\",\r\n ANONYMOUS_PRIVATE_KEY_NOT_FOUND: \"Anonymous Private Key Not Found\",\r\n ANONYMOUS_PUBLIC_KEY_NOT_FOUND: \"Anonymous Public Key Not Found\",\r\n SYSTEM_PRIVATE_KEY_NOT_FOUND: \"System Private Key Not Found\",\r\n SYSTEM_PUBLIC_KEY_NOT_FOUND: \"System Public Key Not Found\",\r\n ADMIN_PRIVATE_KEY_NOT_FOUND: \"Admin Private Key Not Found\",\r\n ADMIN_PUBLIC_KEY_NOT_FOUND: \"Admin Public Key Not Found\",\r\n SECRET_TOKEN_NOT_FOUND: \"Secret Token Not Found\",\r\n ANONYMOUS_SESSION_NOT_ALLOWED: \"Anonymous Session Not Allowed\",\r\n USER_SESSION_NOT_ALLOWED: \"User Session Not Allowed\",\r\n SYSTEM_SESSION_NOT_ALLOWED: \"System Session Not Allowed\",\r\n CDN_SESSION_NOT_ALLOWED: \"CDN Session Not Allowed\",\r\n INTERNAL_SERVER_ERROR: \"Internal Server Error\",\r\n SOMETHING_WENT_WRONG: 'Something went wrong',\r\n AUTH_CONTEXT_NOT_INITIALIZED: 'Auth Context not Initialized'\r\n})","import util from 'util';\r\nconst Logger = {\r\n logException: (functionName: string, error: any) => {\r\n console.error(`Exception Occurred in Function: ${functionName}, Error: ${Logger.inspect(error)}`);\r\n },\r\n\r\n logError: (functionName: string, error: any) => {\r\n console.error(`Error Occurred in Function: ${functionName}, Error: ${Logger.inspect(error)}`);\r\n },\r\n\r\n logWarning: (functionName: string, message: any) => {\r\n console.warn(`Warning in Function: ${functionName} - ${Logger.inspect(message)}`);\r\n },\r\n\r\n logMessage: (functionName: string, message: any) => {\r\n console.log(`Message in Function: ${functionName} - ${Logger.inspect(message)}`);\r\n },\r\n\r\n logInvalidPayload: (functionName: string, errorMessage: string) => {\r\n console.error(`Invalid Payload received for Function: ${functionName}, Error: ${Logger.inspect(errorMessage)}`);\r\n },\r\n\r\n inspect: (context: any) => {\r\n return (typeof context === \"string\" ? context : util.inspect(context));\r\n }\r\n}\r\n\r\nexport default Logger;","import ErrorTypes from \"../enums/ErrorTypes\";\r\nimport Logger from \"../Logger\";\r\n\r\nexport const ResponseUtility = {\r\n handleException: (functionName: string, error: any, res: any) => {\r\n if (error.knownError) {\r\n error.logError && Logger.logError(functionName, error);\r\n res.status(error.status).json({\r\n status: error.status,\r\n error: error.error\r\n });\r\n } else if(error.status && error.error) {\r\n Logger.logException(functionName, error);\r\n res.status(error.status).json({\r\n error: error.errorMessage || JSON.stringify(error.error),\r\n status: error.status,\r\n });\r\n } else {\r\n Logger.logException(functionName, error);\r\n res.status(500).json({\r\n status: 500,\r\n error: ErrorTypes.INTERNAL_SERVER_ERROR\r\n })\r\n }\r\n },\r\n\r\n generateResponse: (status: number, data?: any, error?: string) => {\r\n return {\r\n status,\r\n data,\r\n error\r\n }\r\n },\r\n\r\n generateError: (status: number, error: string, knownError: Boolean = true, logError: boolean = false) => {\r\n return {\r\n status,\r\n error,\r\n knownError,\r\n logError\r\n }\r\n }\r\n}\r\n\r\nexport default ResponseUtility;","\"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 \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: 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"]}
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
'use strict';var de=require('crypto'),Ce=require('util');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var de__default=/*#__PURE__*/_interopDefault(de);var Ce__default=/*#__PURE__*/_interopDefault(Ce);var Q=(e=>(e.IN="IN",e))(Q||{}),O=(e=>(e.INR="INR",e))(O||{}),U=(r=>(r["en-IN"]="en-IN",r["kn-IN"]="kn-IN",r))(U||{}),R=(t=>(t.en="en",t.kn="kn",t))(R||{}),x={"en-IN":"en","kn-IN":"kn"};var re={INR:"\u20B9"},ie={INR:"en-IN"},k=(o=>(o.MALE="Male",o.FEMALE="Female",o.UNISEX="Unisex",o.KIDS="Kids",o.BOY="Boy",o.GIRL="Girl",o.GENERAL="General",o))(k||{});var F=(t=>(t.GOODS="GOODS",t.SERVICE="SERVICE",t))(F||{});var K=new Uint8Array(256),V=K.length;function G(){return V>K.length-16&&(de__default.default.randomFillSync(K),V=0),K.slice(V,V+=16)}var ne=/^(?:[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 pe(r){return typeof r=="string"&&ne.test(r)}var se=pe;var d=[];for(let r=0;r<256;++r)d.push((r+256).toString(16).slice(1));function B(r,e=0){return d[r[e+0]]+d[r[e+1]]+d[r[e+2]]+d[r[e+3]]+"-"+d[r[e+4]]+d[r[e+5]]+"-"+d[r[e+6]]+d[r[e+7]]+"-"+d[r[e+8]]+d[r[e+9]]+"-"+d[r[e+10]]+d[r[e+11]]+d[r[e+12]]+d[r[e+13]]+d[r[e+14]]+d[r[e+15]]}function ge(r){if(!se(r))throw TypeError("Invalid UUID");let e,t=new Uint8Array(16);return t[0]=(e=parseInt(r.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(r.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(r.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(r.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(r.slice(24,36),16))/1099511627776&255,t[11]=e/4294967296&255,t[12]=e>>>24&255,t[13]=e>>>16&255,t[14]=e>>>8&255,t[15]=e&255,t}var oe=ge;function me(r){r=unescape(encodeURIComponent(r));let e=[];for(let t=0;t<r.length;++t)e.push(r.charCodeAt(t));return e}var ye="6ba7b810-9dad-11d1-80b4-00c04fd430c8",fe="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function j(r,e,t){function i(n,s,c,o){var a;if(typeof n=="string"&&(n=me(n)),typeof s=="string"&&(s=oe(s)),((a=s)===null||a===void 0?void 0:a.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let l=new Uint8Array(16+n.length);if(l.set(s),l.set(n,s.length),l=t(l),l[6]=l[6]&15|e,l[8]=l[8]&63|128,c){o=o||0;for(let g=0;g<16;++g)c[o+g]=l[g];return c}return B(l)}try{i.name=r;}catch{}return i.DNS=ye,i.URL=fe,i}var Y={randomUUID:de__default.default.randomUUID};function be(r,e,t){if(Y.randomUUID&&!e&&!r)return Y.randomUUID();r=r||{};let i=r.random||(r.rng||G)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){t=t||0;for(let n=0;n<16;++n)e[t+n]=i[n];return e}return B(i)}var H=be;function Te(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),de__default.default.createHash("sha1").update(r).digest()}var ae=Te;var Ae=j("v5",80,ae),W=Ae;var xe={isUUID:r=>/^[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(r),isEmail:r=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(r),isURL:r=>/^(http|https):\/\/[^ "]+$/.test(r),generateUUID:(r,e)=>e&&r?W(r,e):H(),generateSearchId:(r,e)=>`${r}#${m.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:r=>{let[e,t]=r.split("#");return {key:e,selectionAttributes:m.parseSelectionAttributesKey(t)}},deepClone(r){return structuredClone(r)}},p=xe;var ce=r=>structuredClone(r),J=class{customFields;constructor(e,t=new Date){this.customFields={...e.customFields};}getCustomField(e){let t=this.customFields[e];return t==null?t:ce(t)}setCustomField(e,t){this.customFields[e]=t;}getAllCustomFields(){return ce(this.customFields)}},D=class extends J{version;createdAt;modifiedAt;modifiedBy;constructor(e,t=new Date){super(e),this.version=e.version??1,this.createdAt=e.createdAt&&!isNaN(Date.parse(e.createdAt))?new Date(e.createdAt).toISOString():t.toISOString(),this.modifiedAt=e.modifiedAt&&!isNaN(Date.parse(e.modifiedAt))?new Date(e.modifiedAt).toISOString():t.toISOString(),this.modifiedBy={...e.modifiedBy};}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return {...this.modifiedBy}}setModifiedBy(e,t,i,n){this.modifiedBy={id:e,authType:t,requestId:i,lambdaName:n};}};var z=class extends Error{constructor(e){super(`Duplicate selection attribute found: ${e}`),this.name="DuplicateSelectionAttributeError";}};var h=class extends Error{constructor(e="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${e}`),this.name="SelectionAttributeParseError";}};var _=class extends Error{constructor(e="Tax category is not valid."){super(`InvalidTaxCategory: ${e}`),this.name="InvalidTaxCategoryError";}},w=class extends Error{constructor(e="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${e}`),this.name="InvalidMinQuantityError";}},T=class extends Error{constructor(e){super(`InvalidTieredPrice: ${e}`),this.name="InvalidTieredPriceError";}},M=class extends Error{constructor(e="Quantity must be greater than zero."){super(`InvalidQuantity: ${e}`),this.name="InvalidQuantityError";}},N=class extends Error{constructor(e){super(`NoApplicableTier: Quantity ${e} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}};var v=class extends Error{constructor(e="Amount cannot be negative."){super(`InvalidAmount: ${e}`),this.name="InvalidPriceAmountError";}},I=class extends Error{constructor(e="Currency code is required."){super(`InvalidCurrency: ${e}`),this.name="InvalidCurrencyCodeError";}},b=class extends Error{constructor(e="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${e}`),this.name="CurrencyMismatchError";}},y=class extends Error{constructor(e){super(`InvalidArgument: ${e}`),this.name="InvalidArgumentError";}},$=class extends Error{constructor(e="Invalid image source configuration."){super(`InvalidImageSource: ${e}`),this.name="InvalidImageSourceError";}};var P=class extends Error{constructor(e="Invalid pricing type."){super(`InvalidPricingType: ${e}`),this.name="InvalidPricingTypeError";}};var S=class{sources;alt;order;label;constructor(e){if(this.sources={...e.sources},this.alt=e.alt,this.order=e.order,this.label=e.label,!this.sources.original)throw new $("ImageInfoModel cannot be created without an 'original' source URL.")}getSources(){return {...this.sources}}getSource(e){return this.sources[e]||this.sources.original}getAlt(){return this.alt}getOrder(){return this.order}getLabel(){return this.label}setAlt(e){this.alt=e;}setOrder(e){this.order=e;}setLabel(e){this.label=e;}setSource(e,t){if(t===void 0){if(e==="original")throw new $("Cannot remove the 'original' image source.");delete this.sources[e];}else this.sources[e]=t;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var A=class r{#e;amount;currency;constructor(e){if(this.#e="PriceModel",e.amount<0)throw new v("Amount cannot be negative.");if(!e.currency)throw new I("Currency code is required.");this.currency=e.currency,this.amount=parseFloat(e.amount.toFixed(r.getPrecisionPlaces(this.currency)));}get kind(){return this.#e}static isPriceModel(e){return typeof e=="object"&&e!==null&&e.kind==="PriceModel"}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}getPreciseAmount(e){return parseFloat(e.toFixed(r.getPrecisionPlaces(this.currency)))}compareTo(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new b("Cannot compare prices in different currencies.")}else throw new y("Must be a PriceModel instance.");return this.getPreciseAmount(this.amount-e.getAmount())}add(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new b("Cannot add prices in different currencies.")}else throw new y("Must be a PriceModel instance.");return new r({amount:this.getPreciseAmount(this.amount+e.getAmount()),currency:this.currency})}subtract(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new b("Cannot subtract prices in different currencies.")}else throw new y("Must be a PriceModel instance.");return new r({amount:this.getPreciseAmount(this.amount-e.getAmount()),currency:this.currency})}multiply(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new b("Cannot multiply prices in different currencies.");return new r({amount:this.getPreciseAmount(this.amount*e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>=0)return new r({amount:this.getPreciseAmount(this.amount*e),currency:this.currency});throw new y("Must be a non-negative number.")}divide(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new b("Cannot divide prices in different currencies.");return new r({amount:this.getPreciseAmount(this.amount/e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>0)return new r({amount:this.getPreciseAmount(this.amount/e),currency:this.currency});throw new y("Must be a positive number.")}min(...e){if(e.length===0)throw new y("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(r.isPriceModel(i)){if(t.getCurrency()!==i.getCurrency())throw new b("Cannot compare prices in different currencies.")}else throw new y("Must be a PriceModel instance.");return t.compareTo(i)<0?t:i},this)}max(...e){if(e.length===0)throw new y("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(r.isPriceModel(i)){if(t.getCurrency()!==i.getCurrency())throw new b("Cannot compare prices in different currencies.")}else throw new y("Must be a PriceModel instance.");return t.compareTo(i)>0?t:i},this)}zero(){return new r({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new r({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return r.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return r.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(e,t,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let n=ie[t];if(!t||!n)throw new I("Invalid currency code for formatting.");let s=e,c=i.displayAsInteger?0:r.getDecimalPlaces(t),o={style:i.style??"currency",currency:t,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:c,maximumFractionDigits:c};i.displayAsInteger&&(s=Math.ceil(s));try{return new Intl.NumberFormat(n,o).format(s)}catch(a){return console.error(`Error formatting price for currency "${t}" and locale "${n}":`,a),`${re[t]??t} ${r.addThousandSeparators(s.toFixed(c))}`}}static getDecimalPlaces(e){switch(e){case"INR":default:return 2}}static getPrecisionPlaces(e){switch(e){case"INR":default:return 6}}static addThousandSeparators(e){let t=e.split("."),i=t[0],n=t.length>1?"."+t[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+n}static getRoundedAmount(e,t){if(e<0)throw new v("Amount cannot be negative for rounding.");if(t===void 0)throw new I("Invalid currency code for rounding.");let i=r.getDecimalPlaces(t),n=Math.pow(10,i);return Math.round(e*n)/n}static getSmallestUnit(e){let t=r.getDecimalPlaces(e);return 1/Math.pow(10,t)}};var ee=(t=>(t.VOLUME="volume",t.SELECTION="selection",t))(ee||{}),C=class{type;taxCategory;isTaxInclusive;static create(e){return e.type==="selection"?new X(e):new Z(e)}constructor(e){if(!e.taxCategory)throw new _;this.taxCategory=e.taxCategory,this.isTaxInclusive=e.isTaxInclusive??!1,this.type=e.type??"volume";}getType(){return this.type}getTaxCategory(){return this.taxCategory}getIsTaxInclusive(){return this.isTaxInclusive}},Z=class extends C{baseUnitPrice;tiers;currency;constructor(e){if(super(e),this.type="volume",!e.baseUnitPrice)throw new T("Base unit price is required for volume pricing.");this.baseUnitPrice=new A(e.baseUnitPrice),this.currency=e.currency??this.baseUnitPrice.getCurrency();let t=(e.tiers??[]).map(o=>({enabled:o.enabled??!0,minQuantity:o.minQuantity,unitPrice:new A(o.unitPrice)})).sort((o,a)=>o.minQuantity-a.minQuantity);if(t.some(o=>o.minQuantity<=0))throw new w;let n=this.baseUnitPrice.getCurrency()!==this.currency||t.some(o=>o.unitPrice.getCurrency()!==this.currency),s=t.some((o,a)=>a>0&&o.unitPrice.compareTo(t[a-1].unitPrice)>0),c=t[0]?.unitPrice.compareTo(this.baseUnitPrice)>0;if(n||s||c)throw new T("Tiers must share the same currency and must not increase in unit price.");this.tiers=t;}isPriceAvailable(){return this.tiers.filter(e=>e.enabled).length>0}getBaseUnitPrice(){return this.baseUnitPrice}getCurrency(){return this.baseUnitPrice.getCurrency()}getApplicableUnitPrice(e){if(e<=0)throw new M;let t=this.tiers.filter(i=>i.enabled);for(let i=t.length-1;i>=0;i--){let n=t[i];if(e>=n.minQuantity)return n.unitPrice}throw new N(e)}getMinQuantity(){return this.tiers.filter(t=>t.enabled)[0]?.minQuantity??1}getMaxDiscountPercent(){let e=this.tiers.filter(s=>s.enabled);if(!e.length)return 0;let t=Math.min(...e.map(s=>s.unitPrice.getAmount())),i=this.baseUnitPrice.getAmount(),n=(i-t)/i*100;return n>0?n:0}getMinPrice(){let e=this.tiers.filter(t=>t.enabled);return e.length?e[e.length-1].unitPrice:null}getMaxPrice(){let e=this.tiers.filter(t=>t.enabled);return e.length?e[0].unitPrice:null}getTiers(){return this.tiers.map(e=>({enabled:e.enabled,minQuantity:e.minQuantity,unitPrice:e.unitPrice}))}getDetails(){return {type:this.type,taxCategory:this.taxCategory,isTaxInclusive:this.isTaxInclusive,currency:this.currency,baseUnitPrice:this.baseUnitPrice.getDetails(),tiers:this.tiers.map(e=>({enabled:e.enabled,minQuantity:e.minQuantity,unitPrice:e.unitPrice.getDetails()}))}}},X=class extends C{currency;selections;constructor(e){super(e),this.type="selection",this.currency=e.currency,this.selections=(e.selections??[]).map(t=>{if(!t.baseUnitPrice)throw new T("Base unit price is required for each selection.");let i=new A(t.baseUnitPrice),n=(t.tiers??[]).map(l=>({enabled:l.enabled??!0,minQuantity:l.minQuantity??1,unitPrice:new A(l.unitPrice)})).sort((l,g)=>l.minQuantity-g.minQuantity);if(n.some(l=>l.minQuantity<=0))throw new w;let c=i.getCurrency()!==this.currency||n.some(l=>l.unitPrice.getCurrency()!==this.currency),o=n.some((l,g)=>g>0&&l.unitPrice.compareTo(n[g-1].unitPrice)>0),a=n[0]?.unitPrice.compareTo(i)>0;if(c||o||a)throw new T("Tiers must share the same currency and must not increase in unit price within the same selection.");return {selectionAttributes:{...t.selectionAttributes},baseUnitPrice:i,tiers:n}});}findMatch(e,t=!1){let i=m.generateSelectionAttributesKey(e),n=this.selections.find(s=>m.generateSelectionAttributesKey(s.selectionAttributes)===i);if(!n&&t)throw new T("No pricing configuration found for selection variant.");return n??null}isPriceAvailable(e){if(!e)return console.warn("Selection attributes are required to check price availability for selection pricing."),!1;let t=this.findMatch(e);return t?t.tiers.filter(i=>i.enabled).length>0:!1}getBaseUnitPrice(e){if(!e)throw new P("Selection attributes are required to get base unit price for selection pricing.");return this.findMatch(e,!0).baseUnitPrice}getCurrency(){return this.currency}getApplicableUnitPrice(e,t){if(e<=0)throw new M;if(!t)throw new P("Selection attributes are required to get applicable unit price for selection pricing.");let n=this.findMatch(t,!0).tiers.filter(s=>s.enabled);for(let s=n.length-1;s>=0;s--){let c=n[s];if(e>=c.minQuantity)return c.unitPrice}throw new N(e)}getMinQuantity(e){if(!e)throw new P("Selection attributes are required to get min quantity for selection pricing.");return this.findMatch(e,!0).tiers.filter(n=>n.enabled)[0]?.minQuantity??1}getMaxDiscountPercent(e){if(!e)throw new P("Selection attributes are required to get max discount for selection pricing.");let t=this.findMatch(e,!0),i=t.tiers.filter(o=>o.enabled);if(!i.length)return 0;let n=Math.min(...i.map(o=>o.unitPrice.getAmount())),s=t.baseUnitPrice.getAmount(),c=(s-n)/s*100;return c>0?c:0}getTiers(e){if(!e)throw new P("Selection attributes are required to get tiers for selection pricing.");return this.findMatch(e,!0).tiers.map(i=>({enabled:i.enabled,minQuantity:i.minQuantity,unitPrice:i.unitPrice}))}getMinPrice(e){if(!e)throw new P("Selection attributes are required to get min price for selection pricing.");let t=this.findMatch(e);if(!t)return null;let i=t.tiers.filter(n=>n.enabled);return i.length?i[i.length-1].unitPrice:null}getMaxPrice(e){if(!e)throw new P("Selection attributes are required to get max price for selection pricing.");let t=this.findMatch(e);if(!t)return null;let i=t.tiers.filter(n=>n.enabled);return i.length?i[0].unitPrice:null}getDetails(){return {type:this.type,taxCategory:this.taxCategory,isTaxInclusive:this.isTaxInclusive,currency:this.currency,selections:this.selections.map(e=>({selectionAttributes:e.selectionAttributes,baseUnitPrice:e.baseUnitPrice.getDetails(),...e.tiers.length>0?{tiers:e.tiers.map(t=>({enabled:t.enabled,minQuantity:t.minQuantity,unitPrice:t.unitPrice.getDetails()}))}:{}}))}}};var m=class r extends D{id;key;name;description;slug;brand;pricing;variants;targetGender;attributes;specifications;categories;productType;isActive;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static productSKURegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static generateSelectionAttributesKey(e){if(typeof e!="object")throw new h("Selection attributes must be an object");return Object.keys(e).filter(i=>e[i]!==void 0&&i.toLowerCase()!=="size").sort().map(i=>e[i].name?`${i}:c+${e[i].name}`:`${i}:${e[i]}`).join("|").toLowerCase()}static parseSelectionAttributesKey(e){try{let t={},i=e.split("|");for(let n of i){let[s,c]=n.split(":");c.startsWith("c+")?t[s]={name:c.slice(2)}:t[s]=c;}return t}catch(t){throw new h(t?.message)}}constructor(e,t=new Date){super(e,t),this.id=e.id,this.key=e.key,this.name={...e.name},this.description={...e.description},this.slug={...e.slug},this.brand=e.brand,this.pricing=Object.keys(e.pricing).reduce((n,s)=>(e.pricing[s]&&(n[s]=C.create(e.pricing[s])),n),{}),this.targetGender=e.targetGender,this.attributes=p.deepClone(e.attributes),this.specifications=p.deepClone(e.specifications),this.categories=p.deepClone(e.categories),this.productType=e.productType??"GOODS";let i=new Set;this.variants=(e.variants||[]).map(n=>{if(!n.selectionAttributes||typeof n.selectionAttributes!="object")throw new h("Selection attributes are required");this.checkSelectionAttributes(n.selectionAttributes);let s=r.generateSelectionAttributesKey(n.selectionAttributes);if(i.has(s))throw new z(s);return i.add(s),{sku:n.sku,selectionAttributes:n.selectionAttributes,images:{primary:new S(n.images.primary),gallery:(n.images.gallery||[]).map(c=>new S(c))}}}),this.isActive=e.isActive,this.searchTags=e.searchTags?p.deepClone(e.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e){return e?this.name[e]??this.name[x[e]]??this.name.en:p.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[x[e]]??this.description.en:p.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[x[e]]??this.slug.en:p.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:{...this.pricing}}getAttributes(){return p.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:p.deepClone(e.selectionAttributes),images:{primary:e.images.primary,gallery:[...e.images.gallery]}}))}getImagesBySelectionAttributes(e){let t=r.generateSelectionAttributesKey(e),i=this.variants.find(n=>r.generateSelectionAttributesKey(n.selectionAttributes)===t);return i?{primary:i.images.primary,gallery:[...i.images.gallery]}:null}getImages(e,t){switch(t){case"PRIMARY":return this.getImagesBySelectionAttributes(e)?.primary??this.variants[0]?.images?.primary;case"GALLERY":return this.getImagesBySelectionAttributes(e)?.gallery??[];default:return this.getImagesBySelectionAttributes(e)??{primary:this.variants[0]?.images?.primary,gallery:[]}}}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return p.deepClone(this.categories)}getProductType(){return this.productType}getSpecifications(e){return e?p.deepClone(this.specifications[e]??this.specifications[x[e]]??this.specifications.en):p.deepClone(this.specifications)}getSearchTags(e){return e?p.deepClone(this.searchTags[e]??this.searchTags[x[e]]??this.searchTags.en):p.deepClone(this.searchTags)}getDetails(){let e=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((t,i)=>(this.pricing[i]&&(t[i]=this.pricing[i]?.getDetails()),t),{}),attributes:this.getAttributes(),variants:this.variants.map(t=>({sku:t.sku,selectionAttributes:p.deepClone(t.selectionAttributes),images:{primary:t.images.primary.getDetails(),gallery:t.images.gallery.map(i=>i.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),productType:this.getProductType(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...e}}checkSelectionAttributes(e){if(!e||typeof e!="object")throw new h("Selection attributes are required");Object.keys(this.attributes).forEach(t=>{if(t.toLowerCase()==="size")return;let i=this.attributes[t],n=e[t];if(n===void 0)throw new h(`Selection attribute '${t}' is missing`);if(typeof i=="string"){if(typeof n!="string"||i!==n)throw new h(`Selection attribute '${t}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof n!="string"||!i.includes(n))throw new h(`Selection attribute '${t}' is invalid`)}else if(typeof n!="object"||!("name"in n)||i.findIndex(s=>s.name===n.name)<0)throw new h(`Selection attribute '${t}' is invalid`)}});}getSku(e){let t=r.generateSelectionAttributesKey(e);return this.variants.find(n=>r.generateSelectionAttributesKey(n.selectionAttributes)===t)?.sku}validateSelectionAttribute(e){let t=r.generateSelectionAttributesKey(e);return this.variants.some(i=>r.generateSelectionAttributesKey(i.selectionAttributes)===t)}validateSize(e){return this.attributes.size.includes(e)}};var ue={$id:"standards",definitions:{lowercaseText:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]*$"},lowercaseText10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,10}$"},lowercaseText16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,16}$"},lowercaseText30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,30}$"},lowercaseText50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,50}$"},lowercaseText256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,256}$"},text:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).*$"},text10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,10}$"},text16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,16}$"},text30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,30}$"},text50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,50}$"},text256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,256}$"},requiredText:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).+$"},requiredText10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,10}$"},requiredText16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,16}$"},requiredText30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,30}$"},requiredText50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,50}$"},requiredText256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,256}$"},url:{type:"string",pattern:"^https://[^\\s/$.?#].[^\\s]*$",maxLength:2048},uuid:{type:"string",minLength:1,pattern:"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"},productKey:{type:"string",pattern:m.productKeyRegex.source},productSku:{type:"string",pattern:m.productSKURegex.source},productType:{type:"string",enum:Object.values(F)},genderCategory:{type:"string",enum:Object.values(k)},price:{type:"object",properties:{amount:{type:"number",minimum:0},currency:{$ref:"#/definitions/currency"}},additionalProperties:!1,required:["amount","currency"]},color:{type:"object",properties:{name:{type:"string"},hex:{type:"string"}},additionalProperties:!1,required:["name"]},attributeValue:{oneOf:[{type:"string"},{$ref:"#/definitions/color"}]},selectionAttributes:{type:"object",properties:{color:{$ref:"#/definitions/color"}},required:["color"],additionalProperties:{$ref:"#/definitions/attributeValue"}},firstName:{$ref:"#/definitions/requiredText30"},lastName:{$ref:"#/definitions/text30"},company:{$ref:"#/definitions/text50"},phone:{type:"string",pattern:"^[0-9]{10}$"},e164Phone:{type:"string",pattern:"^\\+[1-9]\\d{1,14}$"},email:{type:"string",pattern:"^[^\\s]+@[^\\s]+\\.[^\\s]+$"},addressLine1:{$ref:"#/definitions/requiredText50"},addressLine2:{$ref:"#/definitions/text50"},city:{$ref:"#/definitions/requiredText30"},postalCode:{$ref:"#/definitions/requiredText16"},state:{type:"string",enum:["AP","AR","AS","BR","CT","GA","GJ","HR","HP","JH","KA","KL","MP","MH","MN","ML","MZ","NL","OR","PB","RJ","SK","TN","TG","TR","UP","UT","WB","AN","CH","DH","LD","DL","PY","LA","JK"]},country:{type:"string",enum:Object.values(Q)},currency:{type:"string",enum:Object.values(O)},locale:{type:"string",enum:Object.values(U)},language:{type:"string",enum:Object.values(R)},localeOrLanguage:{type:"string",enum:[...Object.values(U),...Object.values(R)]},addressType:{type:"string",enum:["shipping","billing","billing&shipping"]},address:{type:"object",properties:{firstName:{$ref:"standards#/definitions/firstName"},lastName:{$ref:"standards#/definitions/lastName"},company:{$ref:"standards#/definitions/company"},phone:{$ref:"standards#/definitions/phone"},email:{$ref:"standards#/definitions/email"},addressLine1:{$ref:"standards#/definitions/addressLine1"},addressLine2:{$ref:"standards#/definitions/addressLine2"},city:{$ref:"standards#/definitions/city"},postalCode:{$ref:"standards#/definitions/postalCode"},state:{$ref:"standards#/definitions/state"},country:{$ref:"standards#/definitions/country"}},required:["firstName","lastName","phone","email","addressLine1","postalCode","state","country"]}}};var le={$id:"TieredPrices",definitions:{pricingType:{enum:Object.values(ee)},tier:{type:"object",properties:{enabled:{type:"boolean"},minQuantity:{type:"integer",minimum:1},unitPrice:{$ref:"standards#/definitions/price"}},required:["minQuantity","unitPrice"]},volumeTieredPrice:{type:"object",properties:{type:{const:"volume"},currency:{$ref:"standards#/definitions/currency"},baseUnitPrice:{$ref:"standards#/definitions/price"},taxCategory:{$ref:"standards#/definitions/requiredText"},isTaxInclusive:{type:"boolean"},tiers:{type:"array",items:{$ref:"TieredPrices#/definitions/tier"}}},required:["taxCategory","baseUnitPrice"]},selectionTieredPrice:{type:"object",properties:{type:{const:"selection"},currency:{$ref:"standards#/definitions/currency"},taxCategory:{$ref:"standards#/definitions/requiredText"},isTaxInclusive:{type:"boolean"},selections:{type:"array",items:{type:"object",properties:{selectionAttributes:{$ref:"standards#/definitions/selectionAttributes"},baseUnitPrice:{$ref:"standards#/definitions/price"},tiers:{type:"array",items:{$ref:"TieredPrices#/definitions/tier"}}},required:["selectionAttributes","baseUnitPrice"]}}},required:["type","taxCategory","currency"]},tieredPrice:{anyOf:[{$ref:"TieredPrices#/definitions/volumeTieredPrice"},{$ref:"TieredPrices#/definitions/selectionTieredPrice"}]}}};var Ie={getStandardSchemaDefinition(){return ue},getTieredPriceSchemaDefinition(){return le}},Se=Ie;var L=Object.freeze({INVALID_UUID:"Invalid UUID",INVALID_EMAIL:"Invalid Email",INVALID_TOKEN:"Invalid Token",TOKEN_EXPIRED:"Token Expired",INVALID_VERIFIER:"Invalid Verifier",INVALID_PERMISSIONS:"Invalid Permissions",INVALID_AUTH_TYPE:"Invalid Authorization Type",USER_PRIVATE_KEY_NOT_FOUND:"User Private Key Not Found",USER_PUBLIC_KEY_NOT_FOUND:"User Public Key Not Found",ANONYMOUS_PRIVATE_KEY_NOT_FOUND:"Anonymous Private Key Not Found",ANONYMOUS_PUBLIC_KEY_NOT_FOUND:"Anonymous Public Key Not Found",SYSTEM_PRIVATE_KEY_NOT_FOUND:"System Private Key Not Found",SYSTEM_PUBLIC_KEY_NOT_FOUND:"System Public Key Not Found",ADMIN_PRIVATE_KEY_NOT_FOUND:"Admin Private Key Not Found",ADMIN_PUBLIC_KEY_NOT_FOUND:"Admin Public Key Not Found",SECRET_TOKEN_NOT_FOUND:"Secret Token Not Found",ANONYMOUS_SESSION_NOT_ALLOWED:"Anonymous Session Not Allowed",USER_SESSION_NOT_ALLOWED:"User Session Not Allowed",SYSTEM_SESSION_NOT_ALLOWED:"System Session Not Allowed",CDN_SESSION_NOT_ALLOWED:"CDN Session Not Allowed",INTERNAL_SERVER_ERROR:"Internal Server Error",SOMETHING_WENT_WRONG:"Something went wrong",AUTH_CONTEXT_NOT_INITIALIZED:"Auth Context not Initialized"});var E={logException:(r,e)=>{console.error(`Exception Occurred in Function: ${r}, Error: ${E.inspect(e)}`);},logError:(r,e)=>{console.error(`Error Occurred in Function: ${r}, Error: ${E.inspect(e)}`);},logWarning:(r,e)=>{console.warn(`Warning in Function: ${r} - ${E.inspect(e)}`);},logMessage:(r,e)=>{console.log(`Message in Function: ${r} - ${E.inspect(e)}`);},logInvalidPayload:(r,e)=>{console.error(`Invalid Payload received for Function: ${r}, Error: ${E.inspect(e)}`);},inspect:r=>typeof r=="string"?r:Ce__default.default.inspect(r)},f=E;var Ee={handleException:(r,e,t)=>{e.knownError?(e.logError&&f.logError(r,e),t.status(e.status).json({status:e.status,error:e.error})):e.status&&e.error?(f.logException(r,e),t.status(e.status).json({error:e.errorMessage||JSON.stringify(e.error),status:e.status})):(f.logException(r,e),t.status(500).json({status:500,error:L.INTERNAL_SERVER_ERROR}));},generateResponse:(r,e,t)=>({status:r,data:e,error:t}),generateError:(r,e,t=!0,i=!1)=>({status:r,error:e,knownError:t,logError:i})},De=Ee;var we=async(r,e,t="GET",i={},n)=>{let s={method:t,headers:{"Content-Type":"application/json",...i}};t!=="GET"&&n&&(s.body=JSON.stringify(n));let c=`${r}${e?"/"+e:""}`,o=c.includes("api.xetile.com")||c.includes("localhost");try{let a=await fetch(c,s);if(!a.ok){let g,q=await a.text();try{g=JSON.parse(q);}catch{g={status:a.status,error:q||a.statusText},f.logWarning("Fetch",`Failed to parse error response body as JSON for URL-${c}. Raw text: ${q}`);}throw {status:a.status,statusText:a.statusText,error:g}}let l=await a.json();return f.logMessage("Fetch",`API call successful: URL-${c}, Status- ${a.status}`),{status:a.status,statusText:a.statusText,data:o?l.data:l}}catch(a){throw f.logError("Fetch",`API call failed: URL-${c}, Status- ${a.status||500}, Error- ${f.inspect(a.error||a)}`),{status:a.status||500,statusText:a.statusText||L.INTERNAL_SERVER_ERROR,error:a.error||{status:a.status||500,error:a.statusText||L.SOMETHING_WENT_WRONG}}}},Me=we;var te=class{cache=new Map;maxSize;ttl;cleanupInterval;constructor(e=1e3,t=5*60*1e3){if(!Number.isFinite(e)||e<1)throw new RangeError("maxSize must be a finite number greater than or equal to 1.");if(!Number.isFinite(t)||t<1)throw new RangeError("ttl must be a finite number greater than or equal to 1.");this.maxSize=e,this.ttl=t,this.cleanupInterval=setInterval(()=>this.cleanup(),60*1e3),this.cleanupInterval.unref&&this.cleanupInterval.unref();}cleanup(){let e=Date.now();for(let[t,i]of this.cache.entries())e>=i.expiry&&this.cache.delete(t);}set(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxSize){let i=this.cache.keys().next().value;i!==void 0&&this.cache.delete(i);}this.cache.set(e,{value:t,expiry:Date.now()+this.ttl});}get(e){let t=this.cache.get(e);if(t){if(Date.now()>=t.expiry){this.cache.delete(e);return}return this.cache.delete(e),f.logMessage("MemoryCache.get",`Successfully read cache data for key: ${e}`),this.cache.set(e,t),t.value}}dispose(){clearInterval(this.cleanupInterval);}},Ne=te;
|
|
2
|
-
exports.Fetch=
|
|
1
|
+
'use strict';var le=require('crypto'),Se=require('util');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var le__default=/*#__PURE__*/_interopDefault(le);var Se__default=/*#__PURE__*/_interopDefault(Se);var q=(e=>(e.IN="IN",e))(q||{}),O=(e=>(e.INR="INR",e))(O||{}),U=(r=>(r["en-IN"]="en-IN",r["kn-IN"]="kn-IN",r))(U||{}),R=(t=>(t.en="en",t.kn="kn",t))(R||{}),x={"en-IN":"en","kn-IN":"kn"};var te={INR:"\u20B9"},re={INR:"en-IN"},Q=(s=>(s.MALE="Male",s.FEMALE="Female",s.UNISEX="Unisex",s.KIDS="Kids",s.BOY="Boy",s.GIRL="Girl",s.GENERAL="General",s))(Q||{});var F=(t=>(t.GOODS="GOODS",t.SERVICE="SERVICE",t))(F||{});var K=new Uint8Array(256),V=K.length;function k(){return V>K.length-16&&(le__default.default.randomFillSync(K),V=0),K.slice(V,V+=16)}var ie=/^(?:[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 de(r){return typeof r=="string"&&ie.test(r)}var ne=de;var l=[];for(let r=0;r<256;++r)l.push((r+256).toString(16).slice(1));function B(r,e=0){return l[r[e+0]]+l[r[e+1]]+l[r[e+2]]+l[r[e+3]]+"-"+l[r[e+4]]+l[r[e+5]]+"-"+l[r[e+6]]+l[r[e+7]]+"-"+l[r[e+8]]+l[r[e+9]]+"-"+l[r[e+10]]+l[r[e+11]]+l[r[e+12]]+l[r[e+13]]+l[r[e+14]]+l[r[e+15]]}function pe(r){if(!ne(r))throw TypeError("Invalid UUID");let e,t=new Uint8Array(16);return t[0]=(e=parseInt(r.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(r.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(r.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(r.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(r.slice(24,36),16))/1099511627776&255,t[11]=e/4294967296&255,t[12]=e>>>24&255,t[13]=e>>>16&255,t[14]=e>>>8&255,t[15]=e&255,t}var se=pe;function ge(r){r=unescape(encodeURIComponent(r));let e=[];for(let t=0;t<r.length;++t)e.push(r.charCodeAt(t));return e}var me="6ba7b810-9dad-11d1-80b4-00c04fd430c8",ye="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function G(r,e,t){function i(n,o,a,s){var p;if(typeof n=="string"&&(n=ge(n)),typeof o=="string"&&(o=se(o)),((p=o)===null||p===void 0?void 0:p.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let u=new Uint8Array(16+n.length);if(u.set(o),u.set(n,o.length),u=t(u),u[6]=u[6]&15|e,u[8]=u[8]&63|128,a){s=s||0;for(let g=0;g<16;++g)a[s+g]=u[g];return a}return B(u)}try{i.name=r;}catch{}return i.DNS=me,i.URL=ye,i}var j={randomUUID:le__default.default.randomUUID};function he(r,e,t){if(j.randomUUID&&!e&&!r)return j.randomUUID();r=r||{};let i=r.random||(r.rng||k)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){t=t||0;for(let n=0;n<16;++n)e[t+n]=i[n];return e}return B(i)}var Y=he;function Pe(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),le__default.default.createHash("sha1").update(r).digest()}var oe=Pe;var Te=G("v5",80,oe),H=Te;var Ae={isUUID:r=>/^[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(r),isEmail:r=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(r),isURL:r=>/^(http|https):\/\/[^ "]+$/.test(r),generateUUID:(r,e)=>e&&r?H(r,e):Y(),generateSearchId:(r,e)=>`${r}#${m.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:r=>{let[e,t]=r.split("#");return {key:e,selectionAttributes:m.parseSelectionAttributesKey(t)}},deepClone(r){return structuredClone(r)}},d=Ae;var ae=r=>structuredClone(r),W=class{customFields;constructor(e,t=new Date){this.customFields={...e.customFields};}getCustomField(e){let t=this.customFields[e];return t==null?t:ae(t)}setCustomField(e,t){this.customFields[e]=t;}getAllCustomFields(){return ae(this.customFields)}},D=class extends W{version;createdAt;modifiedAt;modifiedBy;constructor(e,t=new Date){super(e),this.version=e.version??1,this.createdAt=e.createdAt&&!isNaN(Date.parse(e.createdAt))?new Date(e.createdAt).toISOString():t.toISOString(),this.modifiedAt=e.modifiedAt&&!isNaN(Date.parse(e.modifiedAt))?new Date(e.modifiedAt).toISOString():t.toISOString(),this.modifiedBy={...e.modifiedBy};}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return {...this.modifiedBy}}setModifiedBy(e,t,i,n){this.modifiedBy={id:e,authType:t,requestId:i,lambdaName:n};}};var z=class extends Error{constructor(e){super(`Duplicate selection attribute found: ${e}`),this.name="DuplicateSelectionAttributeError";}};var h=class extends Error{constructor(e="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${e}`),this.name="SelectionAttributeParseError";}};var _=class extends Error{constructor(e="Tax category is not valid."){super(`InvalidTaxCategory: ${e}`),this.name="InvalidTaxCategoryError";}},w=class extends Error{constructor(e="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${e}`),this.name="InvalidMinQuantityError";}},T=class extends Error{constructor(e){super(`InvalidTieredPrice: ${e}`),this.name="InvalidTieredPriceError";}},M=class extends Error{constructor(e="Quantity must be greater than zero."){super(`InvalidQuantity: ${e}`),this.name="InvalidQuantityError";}},N=class extends Error{constructor(e){super(`NoApplicableTier: Quantity ${e} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}};var v=class extends Error{constructor(e="Amount cannot be negative."){super(`InvalidAmount: ${e}`),this.name="InvalidPriceAmountError";}},I=class extends Error{constructor(e="Currency code is required."){super(`InvalidCurrency: ${e}`),this.name="InvalidCurrencyCodeError";}},b=class extends Error{constructor(e="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${e}`),this.name="CurrencyMismatchError";}},y=class extends Error{constructor(e){super(`InvalidArgument: ${e}`),this.name="InvalidArgumentError";}},$=class extends Error{constructor(e="Invalid image source configuration."){super(`InvalidImageSource: ${e}`),this.name="InvalidImageSourceError";}};var P=class extends Error{constructor(e="Invalid pricing type."){super(`InvalidPricingType: ${e}`),this.name="InvalidPricingTypeError";}};var S=class{sources;alt;order;label;constructor(e){if(this.sources={...e.sources},this.alt=e.alt,this.order=e.order,this.label=e.label,!this.sources.original)throw new $("ImageInfoModel cannot be created without an 'original' source URL.")}getSources(){return {...this.sources}}getSource(e){return this.sources[e]||this.sources.original}getAlt(){return this.alt}getOrder(){return this.order}getLabel(){return this.label}setAlt(e){this.alt=e;}setOrder(e){this.order=e;}setLabel(e){this.label=e;}setSource(e,t){if(t===void 0){if(e==="original")throw new $("Cannot remove the 'original' image source.");delete this.sources[e];}else this.sources[e]=t;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var A=class r{#e;amount;currency;constructor(e){if(this.#e="PriceModel",e.amount<0)throw new v("Amount cannot be negative.");if(!e.currency)throw new I("Currency code is required.");this.currency=e.currency,this.amount=parseFloat(e.amount.toFixed(r.getPrecisionPlaces(this.currency)));}get kind(){return this.#e}static isPriceModel(e){return typeof e=="object"&&e!==null&&e.kind==="PriceModel"}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}getPreciseAmount(e){return parseFloat(e.toFixed(r.getPrecisionPlaces(this.currency)))}compareTo(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new b("Cannot compare prices in different currencies.")}else throw new y("Must be a PriceModel instance.");return this.getPreciseAmount(this.amount-e.getAmount())}add(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new b("Cannot add prices in different currencies.")}else throw new y("Must be a PriceModel instance.");return new r({amount:this.getPreciseAmount(this.amount+e.getAmount()),currency:this.currency})}subtract(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new b("Cannot subtract prices in different currencies.")}else throw new y("Must be a PriceModel instance.");return new r({amount:this.getPreciseAmount(this.amount-e.getAmount()),currency:this.currency})}multiply(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new b("Cannot multiply prices in different currencies.");return new r({amount:this.getPreciseAmount(this.amount*e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>=0)return new r({amount:this.getPreciseAmount(this.amount*e),currency:this.currency});throw new y("Must be a non-negative number.")}divide(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new b("Cannot divide prices in different currencies.");return new r({amount:this.getPreciseAmount(this.amount/e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>0)return new r({amount:this.getPreciseAmount(this.amount/e),currency:this.currency});throw new y("Must be a positive number.")}min(...e){if(e.length===0)throw new y("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(r.isPriceModel(i)){if(t.getCurrency()!==i.getCurrency())throw new b("Cannot compare prices in different currencies.")}else throw new y("Must be a PriceModel instance.");return t.compareTo(i)<0?t:i},this)}max(...e){if(e.length===0)throw new y("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(r.isPriceModel(i)){if(t.getCurrency()!==i.getCurrency())throw new b("Cannot compare prices in different currencies.")}else throw new y("Must be a PriceModel instance.");return t.compareTo(i)>0?t:i},this)}zero(){return new r({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new r({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return r.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return r.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(e,t,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let n=re[t];if(!t||!n)throw new I("Invalid currency code for formatting.");let o=e,a=i.displayAsInteger?0:r.getDecimalPlaces(t),s={style:i.style??"currency",currency:t,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:a,maximumFractionDigits:a};i.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(n,s).format(o)}catch(p){return console.error(`Error formatting price for currency "${t}" and locale "${n}":`,p),`${te[t]??t} ${r.addThousandSeparators(o.toFixed(a))}`}}static getDecimalPlaces(e){switch(e){case"INR":default:return 2}}static getPrecisionPlaces(e){switch(e){case"INR":default:return 6}}static addThousandSeparators(e){let t=e.split("."),i=t[0],n=t.length>1?"."+t[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+n}static getRoundedAmount(e,t){if(e<0)throw new v("Amount cannot be negative for rounding.");if(t===void 0)throw new I("Invalid currency code for rounding.");let i=r.getDecimalPlaces(t),n=Math.pow(10,i);return Math.round(e*n)/n}static getSmallestUnit(e){let t=r.getDecimalPlaces(e);return 1/Math.pow(10,t)}};var X=(t=>(t.VOLUME="volume",t.SELECTION="selection",t))(X||{}),C=class{type;taxCategory;isTaxInclusive;static create(e){return e.type==="selection"?new Z(e):new J(e)}constructor(e){if(!e.taxCategory)throw new _;this.taxCategory=e.taxCategory,this.isTaxInclusive=e.isTaxInclusive??!1,this.type=e.type??"volume";}getType(){return this.type}getTaxCategory(){return this.taxCategory}getIsTaxInclusive(){return this.isTaxInclusive}},J=class extends C{baseUnitPrice;tiers;currency;constructor(e){if(super(e),this.type="volume",!e.baseUnitPrice)throw new T("Base unit price is required for volume pricing.");this.baseUnitPrice=new A(e.baseUnitPrice),this.currency=e.currency??this.baseUnitPrice.getCurrency();let t=(e.tiers??[]).map(s=>({enabled:s.enabled??!0,minQuantity:s.minQuantity,unitPrice:new A(s.unitPrice)})).sort((s,p)=>s.minQuantity-p.minQuantity);if(t.some(s=>s.minQuantity<=0))throw new w;let n=this.baseUnitPrice.getCurrency()!==this.currency||t.some(s=>s.unitPrice.getCurrency()!==this.currency),o=t.some((s,p)=>p>0&&s.unitPrice.compareTo(t[p-1].unitPrice)>0),a=t[0]?.unitPrice.compareTo(this.baseUnitPrice)>0;if(n||o||a)throw new T("Tiers must share the same currency and must not increase in unit price.");this.tiers=t;}isPriceAvailable(){return this.tiers.filter(e=>e.enabled).length>0}getBaseUnitPrice(){return this.baseUnitPrice}getCurrency(){return this.baseUnitPrice.getCurrency()}getApplicableUnitPrice(e){if(e<=0)throw new M;let t=this.tiers.filter(i=>i.enabled);for(let i=t.length-1;i>=0;i--){let n=t[i];if(e>=n.minQuantity)return n.unitPrice}throw new N(e)}getMinQuantity(){return this.tiers.filter(t=>t.enabled)[0]?.minQuantity??1}getMaxDiscountPercent(){let e=this.tiers.filter(o=>o.enabled);if(!e.length)return 0;let t=Math.min(...e.map(o=>o.unitPrice.getAmount())),i=this.baseUnitPrice.getAmount(),n=(i-t)/i*100;return n>0?n:0}getMinPrice(){let e=this.tiers.filter(t=>t.enabled);return e.length?e[e.length-1].unitPrice:null}getMaxPrice(){let e=this.tiers.filter(t=>t.enabled);return e.length?e[0].unitPrice:null}getTiers(){return this.tiers.map(e=>({enabled:e.enabled,minQuantity:e.minQuantity,unitPrice:e.unitPrice}))}getDetails(){return {type:this.type,taxCategory:this.taxCategory,isTaxInclusive:this.isTaxInclusive,currency:this.currency,baseUnitPrice:this.baseUnitPrice.getDetails(),tiers:this.tiers.map(e=>({enabled:e.enabled,minQuantity:e.minQuantity,unitPrice:e.unitPrice.getDetails()}))}}},Z=class extends C{currency;selections;constructor(e){super(e),this.type="selection",this.currency=e.currency,this.selections=(e.selections??[]).map(t=>{if(!t.baseUnitPrice)throw new T("Base unit price is required for each selection.");let i=new A(t.baseUnitPrice),n=(t.tiers??[]).map(u=>({enabled:u.enabled??!0,minQuantity:u.minQuantity??1,unitPrice:new A(u.unitPrice)})).sort((u,g)=>u.minQuantity-g.minQuantity);if(n.some(u=>u.minQuantity<=0))throw new w;let a=i.getCurrency()!==this.currency||n.some(u=>u.unitPrice.getCurrency()!==this.currency),s=n.some((u,g)=>g>0&&u.unitPrice.compareTo(n[g-1].unitPrice)>0),p=n[0]?.unitPrice.compareTo(i)>0;if(a||s||p)throw new T("Tiers must share the same currency and must not increase in unit price within the same selection.");return {selectionAttributes:{...t.selectionAttributes},baseUnitPrice:i,tiers:n}});}findMatch(e,t=!1){let i=m.generateSelectionAttributesKey(e),n=this.selections.find(o=>m.generateSelectionAttributesKey(o.selectionAttributes)===i);if(!n&&t)throw new T("No pricing configuration found for selection variant.");return n??null}isPriceAvailable(e){if(!e)return console.warn("Selection attributes are required to check price availability for selection pricing."),!1;let t=this.findMatch(e);return t?t.tiers.filter(i=>i.enabled).length>0:!1}getBaseUnitPrice(e){if(!e)throw new P("Selection attributes are required to get base unit price for selection pricing.");return this.findMatch(e,!0).baseUnitPrice}getCurrency(){return this.currency}getApplicableUnitPrice(e,t){if(e<=0)throw new M;if(!t)throw new P("Selection attributes are required to get applicable unit price for selection pricing.");let n=this.findMatch(t,!0).tiers.filter(o=>o.enabled);for(let o=n.length-1;o>=0;o--){let a=n[o];if(e>=a.minQuantity)return a.unitPrice}throw new N(e)}getMinQuantity(e){if(!e)throw new P("Selection attributes are required to get min quantity for selection pricing.");return this.findMatch(e,!0).tiers.filter(n=>n.enabled)[0]?.minQuantity??1}getMaxDiscountPercent(e){if(!e)throw new P("Selection attributes are required to get max discount for selection pricing.");let t=this.findMatch(e,!0),i=t.tiers.filter(s=>s.enabled);if(!i.length)return 0;let n=Math.min(...i.map(s=>s.unitPrice.getAmount())),o=t.baseUnitPrice.getAmount(),a=(o-n)/o*100;return a>0?a:0}getTiers(e){if(!e)throw new P("Selection attributes are required to get tiers for selection pricing.");return this.findMatch(e,!0).tiers.map(i=>({enabled:i.enabled,minQuantity:i.minQuantity,unitPrice:i.unitPrice}))}getMinPrice(e){if(!e)throw new P("Selection attributes are required to get min price for selection pricing.");let t=this.findMatch(e);if(!t)return null;let i=t.tiers.filter(n=>n.enabled);return i.length?i[i.length-1].unitPrice:null}getMaxPrice(e){if(!e)throw new P("Selection attributes are required to get max price for selection pricing.");let t=this.findMatch(e);if(!t)return null;let i=t.tiers.filter(n=>n.enabled);return i.length?i[0].unitPrice:null}getDetails(){return {type:this.type,taxCategory:this.taxCategory,isTaxInclusive:this.isTaxInclusive,currency:this.currency,selections:this.selections.map(e=>({selectionAttributes:e.selectionAttributes,baseUnitPrice:e.baseUnitPrice.getDetails(),...e.tiers.length>0?{tiers:e.tiers.map(t=>({enabled:t.enabled,minQuantity:t.minQuantity,unitPrice:t.unitPrice.getDetails()}))}:{}}))}}};var m=class r extends D{id;key;name;description;slug;brand;pricing;variants;targetGender;attributes;specifications;categories;productType;isActive;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static productSKURegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static generateSelectionAttributesKey(e){if(typeof e!="object")throw new h("Selection attributes must be an object");return Object.keys(e).filter(i=>e[i]!==void 0&&i.toLowerCase()!=="size").sort().map(i=>e[i].name?`${i}:c+${e[i].name}`:`${i}:${e[i]}`).join("|").toLowerCase()}static parseSelectionAttributesKey(e){try{let t={},i=e.split("|");for(let n of i){let[o,a]=n.split(":");a.startsWith("c+")?t[o]={name:a.slice(2)}:t[o]=a;}return t}catch(t){throw new h(t?.message)}}constructor(e,t=new Date){super(e,t),this.id=e.id,this.key=e.key,this.name={...e.name},this.description={...e.description},this.slug={...e.slug},this.brand=e.brand,this.pricing=Object.keys(e.pricing).reduce((n,o)=>(e.pricing[o]&&(n[o]=C.create(e.pricing[o])),n),{}),this.targetGender=e.targetGender,this.attributes=d.deepClone(e.attributes),this.specifications=d.deepClone(e.specifications),this.categories=d.deepClone(e.categories),this.productType=e.productType??"GOODS";let i=new Set;this.variants=(e.variants||[]).map(n=>{if(!n.selectionAttributes||typeof n.selectionAttributes!="object")throw new h("Selection attributes are required");this.checkSelectionAttributes(n.selectionAttributes);let o=r.generateSelectionAttributesKey(n.selectionAttributes);if(i.has(o))throw new z(o);return i.add(o),{sku:n.sku,selectionAttributes:n.selectionAttributes,images:{primary:new S(n.images.primary),gallery:(n.images.gallery||[]).map(a=>new S(a))}}}),this.isActive=e.isActive,this.searchTags=e.searchTags?d.deepClone(e.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e){return e?this.name[e]??this.name[x[e]]??this.name.en:d.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[x[e]]??this.description.en:d.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[x[e]]??this.slug.en:d.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:{...this.pricing}}getAttributes(){return d.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:d.deepClone(e.selectionAttributes),images:{primary:e.images.primary,gallery:[...e.images.gallery]}}))}getImagesBySelectionAttributes(e){let t=r.generateSelectionAttributesKey(e),i=this.variants.find(n=>r.generateSelectionAttributesKey(n.selectionAttributes)===t);return i?{primary:i.images.primary,gallery:[...i.images.gallery]}:null}getImages(e,t){switch(t){case"PRIMARY":return this.getImagesBySelectionAttributes(e)?.primary??this.variants[0]?.images?.primary;case"GALLERY":return this.getImagesBySelectionAttributes(e)?.gallery??[];default:return this.getImagesBySelectionAttributes(e)??{primary:this.variants[0]?.images?.primary,gallery:[]}}}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return d.deepClone(this.categories)}getProductType(){return this.productType}getSpecifications(e){return e?d.deepClone(this.specifications[e]??this.specifications[x[e]]??this.specifications.en):d.deepClone(this.specifications)}getSearchTags(e){return e?d.deepClone(this.searchTags[e]??this.searchTags[x[e]]??this.searchTags.en):d.deepClone(this.searchTags)}getDetails(){let e=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((t,i)=>(this.pricing[i]&&(t[i]=this.pricing[i]?.getDetails()),t),{}),attributes:this.getAttributes(),variants:this.variants.map(t=>({sku:t.sku,selectionAttributes:d.deepClone(t.selectionAttributes),images:{primary:t.images.primary.getDetails(),gallery:t.images.gallery.map(i=>i.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),productType:this.getProductType(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...e}}checkSelectionAttributes(e){if(!e||typeof e!="object")throw new h("Selection attributes are required");Object.keys(this.attributes).forEach(t=>{if(t.toLowerCase()==="size")return;let i=this.attributes[t],n=e[t];if(n===void 0)throw new h(`Selection attribute '${t}' is missing`);if(typeof i=="string"){if(typeof n!="string"||i!==n)throw new h(`Selection attribute '${t}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof n!="string"||!i.includes(n))throw new h(`Selection attribute '${t}' is invalid`)}else if(typeof n!="object"||!("name"in n)||i.findIndex(o=>o.name===n.name)<0)throw new h(`Selection attribute '${t}' is invalid`)}});}getSku(e){let t=r.generateSelectionAttributesKey(e);return this.variants.find(n=>r.generateSelectionAttributesKey(n.selectionAttributes)===t)?.sku}validateSelectionAttribute(e){let t=r.generateSelectionAttributesKey(e);return this.variants.some(i=>r.generateSelectionAttributesKey(i.selectionAttributes)===t)}validateSize(e){return this.attributes.size.includes(e)}};var ce={$id:"standards",definitions:{lowercaseText:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]*$"},lowercaseText10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,10}$"},lowercaseText16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,16}$"},lowercaseText30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,30}$"},lowercaseText50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,50}$"},lowercaseText256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,256}$"},text:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).*$"},text10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,10}$"},text16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,16}$"},text30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,30}$"},text50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,50}$"},text256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,256}$"},requiredText:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).+$"},requiredText10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,10}$"},requiredText16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,16}$"},requiredText30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,30}$"},requiredText50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,50}$"},requiredText256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,256}$"},url:{type:"string",pattern:"^https://[^\\s/$.?#].[^\\s]*$",maxLength:2048},uuid:{type:"string",minLength:1,pattern:"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"},productKey:{type:"string",pattern:m.productKeyRegex.source},productSku:{type:"string",pattern:m.productSKURegex.source},productType:{type:"string",enum:Object.values(F)},genderCategory:{type:"string",enum:Object.values(Q)},price:{type:"object",properties:{amount:{type:"number",minimum:0},currency:{$ref:"#/definitions/currency"}},additionalProperties:!1,required:["amount","currency"]},color:{type:"object",properties:{name:{type:"string"},hex:{type:"string"}},additionalProperties:!1,required:["name"]},attributeValue:{oneOf:[{type:"string"},{$ref:"#/definitions/color"}]},selectionAttributes:{type:"object",properties:{color:{$ref:"#/definitions/color"}},required:["color"],additionalProperties:{$ref:"#/definitions/attributeValue"}},firstName:{$ref:"#/definitions/requiredText30"},lastName:{$ref:"#/definitions/text30"},company:{$ref:"#/definitions/text50"},phone:{type:"string",pattern:"^[0-9]{10}$"},e164Phone:{type:"string",pattern:"^\\+[1-9]\\d{1,14}$"},email:{type:"string",pattern:"^[^\\s]+@[^\\s]+\\.[^\\s]+$"},addressLine1:{$ref:"#/definitions/requiredText50"},addressLine2:{$ref:"#/definitions/text50"},city:{$ref:"#/definitions/requiredText30"},postalCode:{$ref:"#/definitions/requiredText16"},state:{type:"string",enum:["AP","AR","AS","BR","CT","GA","GJ","HR","HP","JH","KA","KL","MP","MH","MN","ML","MZ","NL","OR","PB","RJ","SK","TN","TG","TR","UP","UT","WB","AN","CH","DH","LD","DL","PY","LA","JK"]},country:{type:"string",enum:Object.values(q)},currency:{type:"string",enum:Object.values(O)},locale:{type:"string",enum:Object.values(U)},language:{type:"string",enum:Object.values(R)},localeOrLanguage:{type:"string",enum:[...Object.values(U),...Object.values(R)]},addressType:{type:"string",enum:["shipping","billing","billing&shipping"]},address:{type:"object",properties:{firstName:{$ref:"standards#/definitions/firstName"},lastName:{$ref:"standards#/definitions/lastName"},company:{$ref:"standards#/definitions/company"},phone:{$ref:"standards#/definitions/phone"},email:{$ref:"standards#/definitions/email"},addressLine1:{$ref:"standards#/definitions/addressLine1"},addressLine2:{$ref:"standards#/definitions/addressLine2"},city:{$ref:"standards#/definitions/city"},postalCode:{$ref:"standards#/definitions/postalCode"},state:{$ref:"standards#/definitions/state"},country:{$ref:"standards#/definitions/country"}},required:["firstName","lastName","phone","email","addressLine1","postalCode","state","country"]}}};var ue={$id:"TieredPrices",definitions:{pricingType:{enum:Object.values(X)},tier:{type:"object",properties:{enabled:{type:"boolean"},minQuantity:{type:"integer",minimum:1},unitPrice:{$ref:"standards#/definitions/price"}},required:["minQuantity","unitPrice"]},volumeTieredPrice:{type:"object",properties:{type:{const:"volume"},currency:{$ref:"standards#/definitions/currency"},baseUnitPrice:{$ref:"standards#/definitions/price"},taxCategory:{$ref:"standards#/definitions/requiredText"},isTaxInclusive:{type:"boolean"},tiers:{type:"array",items:{$ref:"TieredPrices#/definitions/tier"}}},required:["taxCategory","baseUnitPrice"]},selectionTieredPrice:{type:"object",properties:{type:{const:"selection"},currency:{$ref:"standards#/definitions/currency"},taxCategory:{$ref:"standards#/definitions/requiredText"},isTaxInclusive:{type:"boolean"},selections:{type:"array",items:{type:"object",properties:{selectionAttributes:{$ref:"standards#/definitions/selectionAttributes"},baseUnitPrice:{$ref:"standards#/definitions/price"},tiers:{type:"array",items:{$ref:"TieredPrices#/definitions/tier"}}},required:["selectionAttributes","baseUnitPrice"]}}},required:["type","taxCategory","currency"]},tieredPrice:{anyOf:[{$ref:"TieredPrices#/definitions/volumeTieredPrice"},{$ref:"TieredPrices#/definitions/selectionTieredPrice"}]}}};var xe={getStandardSchemaDefinition(){return ce},getTieredPriceSchemaDefinition(){return ue}},Ie=xe;var L=Object.freeze({INVALID_UUID:"Invalid UUID",INVALID_EMAIL:"Invalid Email",INVALID_TOKEN:"Invalid Token",TOKEN_EXPIRED:"Token Expired",INVALID_VERIFIER:"Invalid Verifier",INVALID_PERMISSIONS:"Invalid Permissions",INVALID_AUTH_TYPE:"Invalid Authorization Type",USER_PRIVATE_KEY_NOT_FOUND:"User Private Key Not Found",USER_PUBLIC_KEY_NOT_FOUND:"User Public Key Not Found",ANONYMOUS_PRIVATE_KEY_NOT_FOUND:"Anonymous Private Key Not Found",ANONYMOUS_PUBLIC_KEY_NOT_FOUND:"Anonymous Public Key Not Found",SYSTEM_PRIVATE_KEY_NOT_FOUND:"System Private Key Not Found",SYSTEM_PUBLIC_KEY_NOT_FOUND:"System Public Key Not Found",ADMIN_PRIVATE_KEY_NOT_FOUND:"Admin Private Key Not Found",ADMIN_PUBLIC_KEY_NOT_FOUND:"Admin Public Key Not Found",SECRET_TOKEN_NOT_FOUND:"Secret Token Not Found",ANONYMOUS_SESSION_NOT_ALLOWED:"Anonymous Session Not Allowed",USER_SESSION_NOT_ALLOWED:"User Session Not Allowed",SYSTEM_SESSION_NOT_ALLOWED:"System Session Not Allowed",CDN_SESSION_NOT_ALLOWED:"CDN Session Not Allowed",INTERNAL_SERVER_ERROR:"Internal Server Error",SOMETHING_WENT_WRONG:"Something went wrong",AUTH_CONTEXT_NOT_INITIALIZED:"Auth Context not Initialized"});var E={logException:(r,e)=>{console.error(`Exception Occurred in Function: ${r}, Error: ${E.inspect(e)}`);},logError:(r,e)=>{console.error(`Error Occurred in Function: ${r}, Error: ${E.inspect(e)}`);},logWarning:(r,e)=>{console.warn(`Warning in Function: ${r} - ${E.inspect(e)}`);},logMessage:(r,e)=>{console.log(`Message in Function: ${r} - ${E.inspect(e)}`);},logInvalidPayload:(r,e)=>{console.error(`Invalid Payload received for Function: ${r}, Error: ${E.inspect(e)}`);},inspect:r=>typeof r=="string"?r:Se__default.default.inspect(r)},f=E;var Ce={handleException:(r,e,t)=>{e.knownError?(e.logError&&f.logError(r,e),t.status(e.status).json({status:e.status,error:e.error})):e.status&&e.error?(f.logException(r,e),t.status(e.status).json({error:e.errorMessage||JSON.stringify(e.error),status:e.status})):(f.logException(r,e),t.status(500).json({status:500,error:L.INTERNAL_SERVER_ERROR}));},generateResponse:(r,e,t)=>({status:r,data:e,error:t}),generateError:(r,e,t=!0,i=!1)=>({status:r,error:e,knownError:t,logError:i})},Ee=Ce;var De=async(r,e,t="GET",i={},n)=>{let o={method:t,headers:{"Content-Type":"application/json",...i}};t!=="GET"&&n&&(o.body=JSON.stringify(n));let a=`${r}${e?"/"+e:""}`;try{let s=await fetch(a,o);if(!s.ok){let u,g=await s.text();try{u=JSON.parse(g);}catch{u={status:s.status,error:g||s.statusText},f.logWarning("Fetch",`Failed to parse error response body as JSON for URL-${a}. Raw text: ${g}`);}throw {status:s.status,statusText:s.statusText,error:u}}let p=await s.json();return f.logMessage("Fetch",`API call successful: URL-${a}, Status- ${s.status}`),{status:s.status,statusText:s.statusText,data:p}}catch(s){throw f.logError("Fetch",`API call failed: URL-${a}, Status- ${s.status||500}, Error- ${f.inspect(s.error||s)}`),{status:s.status||500,statusText:s.statusText||L.INTERNAL_SERVER_ERROR,error:s.error||{status:s.status||500,error:s.statusText||L.SOMETHING_WENT_WRONG}}}},we=De;var ee=class{cache=new Map;maxSize;ttl;cleanupInterval;constructor(e=1e3,t=5*60*1e3){if(!Number.isFinite(e)||e<1)throw new RangeError("maxSize must be a finite number greater than or equal to 1.");if(!Number.isFinite(t)||t<1)throw new RangeError("ttl must be a finite number greater than or equal to 1.");this.maxSize=e,this.ttl=t,this.cleanupInterval=setInterval(()=>this.cleanup(),60*1e3),this.cleanupInterval.unref&&this.cleanupInterval.unref();}cleanup(){let e=Date.now();for(let[t,i]of this.cache.entries())e>=i.expiry&&this.cache.delete(t);}set(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxSize){let i=this.cache.keys().next().value;i!==void 0&&this.cache.delete(i);}this.cache.set(e,{value:t,expiry:Date.now()+this.ttl});}get(e){let t=this.cache.get(e);if(t){if(Date.now()>=t.expiry){this.cache.delete(e);return}return this.cache.delete(e),f.logMessage("MemoryCache.get",`Successfully read cache data for key: ${e}`),this.cache.set(e,t),t.value}}dispose(){clearInterval(this.cleanupInterval);}},Me=ee;
|
|
2
|
+
exports.Fetch=we;exports.Logger=f;exports.MemoryCache=Me;exports.ResponseUtility=Ee;exports.Schema=Ie;exports.Utils=d;//# sourceMappingURL=index.js.map
|
|
3
3
|
//# sourceMappingURL=index.js.map
|