b23-lib 3.10.1 → 4.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Auth/index.js +1 -1
- package/dist/Auth/index.js.map +1 -1
- package/dist/Auth/index.mjs +1 -1
- package/dist/Classes/Cart.js +1 -1
- package/dist/Classes/Cart.js.map +1 -1
- package/dist/Classes/Cart.mjs +1 -1
- package/dist/Classes/Charge.d.mts +23 -7
- package/dist/Classes/Charge.d.ts +23 -7
- package/dist/Classes/Charge.js +1 -1
- package/dist/Classes/Charge.js.map +1 -1
- package/dist/Classes/Charge.mjs +1 -1
- package/dist/Classes/Coupon.js +1 -1
- package/dist/Classes/Coupon.js.map +1 -1
- package/dist/Classes/Coupon.mjs +1 -1
- package/dist/Classes/Inventory.js +1 -1
- package/dist/Classes/Inventory.js.map +1 -1
- package/dist/Classes/Inventory.mjs +1 -1
- package/dist/Classes/Invoice.d.mts +44 -10
- package/dist/Classes/Invoice.d.ts +44 -10
- package/dist/Classes/Invoice.js +1 -1
- package/dist/Classes/Invoice.js.map +1 -1
- package/dist/Classes/Invoice.mjs +1 -1
- package/dist/Classes/Invoice.mjs.map +1 -1
- package/dist/Classes/LineItem.d.mts +28 -8
- package/dist/Classes/LineItem.d.ts +28 -8
- package/dist/Classes/LineItem.js +1 -1
- package/dist/Classes/LineItem.js.map +1 -1
- package/dist/Classes/LineItem.mjs +1 -1
- package/dist/Classes/Order.js +1 -1
- package/dist/Classes/Order.js.map +1 -1
- package/dist/Classes/Order.mjs +1 -1
- package/dist/Classes/Product.js +1 -1
- package/dist/Classes/Product.js.map +1 -1
- package/dist/Classes/Product.mjs +1 -1
- package/dist/Classes/ShoppingContainer.d.mts +55 -26
- package/dist/Classes/ShoppingContainer.d.ts +55 -26
- package/dist/Classes/ShoppingContainer.js +1 -1
- package/dist/Classes/ShoppingContainer.js.map +1 -1
- package/dist/Classes/ShoppingContainer.mjs +1 -1
- package/dist/Classes/TaxRule.js +1 -1
- package/dist/Classes/TaxRule.js.map +1 -1
- package/dist/Classes/TaxRule.mjs +1 -1
- package/dist/Classes/TieredPrice.js +1 -1
- package/dist/Classes/TieredPrice.js.map +1 -1
- package/dist/Classes/TieredPrice.mjs +1 -1
- package/dist/{chunk-MBR2GRKU.mjs → chunk-3SUQYXIJ.mjs} +2 -2
- package/dist/{chunk-MBR2GRKU.mjs.map → chunk-3SUQYXIJ.mjs.map} +1 -1
- package/dist/chunk-MAUKFI5A.mjs +2 -0
- package/dist/chunk-MAUKFI5A.mjs.map +1 -0
- package/dist/chunk-MWDQACOC.mjs +2 -0
- package/dist/chunk-MWDQACOC.mjs.map +1 -0
- package/dist/chunk-QW2TQXMP.mjs +2 -0
- package/dist/chunk-QW2TQXMP.mjs.map +1 -0
- package/dist/chunk-XMNNRBPH.mjs +2 -0
- package/dist/chunk-XMNNRBPH.mjs.map +1 -0
- package/dist/{chunk-4PTWJI6J.mjs → chunk-XXKEHCV5.mjs} +2 -2
- package/dist/chunk-XXKEHCV5.mjs.map +1 -0
- package/dist/{chunk-EZ35IKUA.mjs → chunk-YT3U73BS.mjs} +2 -2
- package/dist/chunk-YT3U73BS.mjs.map +1 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-4PTWJI6J.mjs.map +0 -1
- package/dist/chunk-5N2HRXWJ.mjs +0 -2
- package/dist/chunk-5N2HRXWJ.mjs.map +0 -1
- package/dist/chunk-6QSZECNF.mjs +0 -2
- package/dist/chunk-6QSZECNF.mjs.map +0 -1
- package/dist/chunk-EZ35IKUA.mjs.map +0 -1
- package/dist/chunk-MPKIC2MS.mjs +0 -2
- package/dist/chunk-MPKIC2MS.mjs.map +0 -1
- package/dist/chunk-NXDEYUDI.mjs +0 -2
- package/dist/chunk-NXDEYUDI.mjs.map +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {b as b$1}from'./chunk-7RAIVZKB.mjs';import {a}from'./chunk-UIQH5QIR.mjs';import {e as e$1}from'./chunk-PL5HGCWN.mjs';import {h,e,l as l$1,n,m as m$1,o,p,y}from'./chunk-O6BLQQO7.mjs';import {b}from'./chunk-UXZBULDS.mjs';import G from'crypto';var C=new Uint8Array(256),T=C.length;function v(){return T>C.length-16&&(G.randomFillSync(C),T=0),C.slice(T,T+=16)}var R=/^(?:[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 q(r){return typeof r=="string"&&R.test(r)}var $=q;var u=[];for(let r=0;r<256;++r)u.push((r+256).toString(16).slice(1));function x(r,e=0){return u[r[e+0]]+u[r[e+1]]+u[r[e+2]]+u[r[e+3]]+"-"+u[r[e+4]]+u[r[e+5]]+"-"+u[r[e+6]]+u[r[e+7]]+"-"+u[r[e+8]]+u[r[e+9]]+"-"+u[r[e+10]]+u[r[e+11]]+u[r[e+12]]+u[r[e+13]]+u[r[e+14]]+u[r[e+15]]}function j(r){if(!$(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 B=j;function Z(r){r=unescape(encodeURIComponent(r));let e=[];for(let t=0;t<r.length;++t)e.push(r.charCodeAt(t));return e}var Y="6ba7b810-9dad-11d1-80b4-00c04fd430c8",F="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function U(r,e,t){function i(n,s,a,c){var p;if(typeof n=="string"&&(n=Z(n)),typeof s=="string"&&(s=B(s)),((p=s)===null||p===void 0?void 0:p.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let o=new Uint8Array(16+n.length);if(o.set(s),o.set(n,s.length),o=t(o),o[6]=o[6]&15|e,o[8]=o[8]&63|128,a){c=c||0;for(let y=0;y<16;++y)a[c+y]=o[y];return a}return x(o)}try{i.name=r;}catch{}return i.DNS=Y,i.URL=F,i}var L={randomUUID:G.randomUUID};function W(r,e,t){if(L.randomUUID&&!e&&!r)return L.randomUUID();r=r||{};let i=r.random||(r.rng||v)();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 x(i)}var E=W;function J(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),G.createHash("sha1").update(r).digest()}var N=J;var _=U("v5",80,N),Q=_;var ee={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?Q(r,e):E(),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)}},l=ee;var m=class r extends b{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,a]=n.split(":");a.startsWith("c+")?t[s]={name:a.slice(2)}:t[s]=a;}return t}catch(t){throw new h(t?.message)}}constructor(e$1,t=new Date){super(e$1,t),this.id=e$1.id,this.key=e$1.key,this.name={...e$1.name},this.description={...e$1.description},this.slug={...e$1.slug},this.brand=e$1.brand,this.pricing=Object.keys(e$1.pricing).reduce((n,s)=>(e$1.pricing[s]&&(n[s]=S.create(e$1.pricing[s])),n),{}),this.targetGender=e$1.targetGender,this.attributes=l.deepClone(e$1.attributes),this.specifications=l.deepClone(e$1.specifications),this.categories=l.deepClone(e$1.categories),this.productType=e$1.productType??"GOODS";let i=new Set;this.variants=(e$1.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 e(s);return i.add(s),{sku:n.sku,selectionAttributes:n.selectionAttributes,images:{primary:new b$1(n.images.primary),gallery:(n.images.gallery||[]).map(a=>new b$1(a))}}}),this.isActive=e$1.isActive,this.searchTags=e$1.searchTags?l.deepClone(e$1.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e){return e?this.name[e]??this.name[e$1[e]]??this.name.en:l.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[e$1[e]]??this.description.en:l.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[e$1[e]]??this.slug.en:l.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:{...this.pricing}}getAttributes(){return l.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:l.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 l.deepClone(this.categories)}getProductType(){return this.productType}getSpecifications(e){return e?l.deepClone(this.specifications[e]??this.specifications[e$1[e]]??this.specifications.en):l.deepClone(this.specifications)}getSearchTags(e){return e?l.deepClone(this.searchTags[e]??this.searchTags[e$1[e]]??this.searchTags.en):l.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:l.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 te=(t=>(t.VOLUME="volume",t.SELECTION="selection",t))(te||{}),S=class{type;taxCategory;isTaxInclusive;static create(e){return e.type==="selection"?new V(e):new z(e)}constructor(e){if(!e.taxCategory)throw new l$1;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 S{baseUnitPrice;tiers;currency;constructor(e){if(super(e),this.type="volume",!e.baseUnitPrice)throw new n("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(c=>({enabled:c.enabled??!0,minQuantity:c.minQuantity,unitPrice:new a(c.unitPrice)})).sort((c,p)=>c.minQuantity-p.minQuantity);if(t.some(c=>c.minQuantity<=0))throw new m$1;let n$1=this.baseUnitPrice.getCurrency()!==this.currency||t.some(c=>c.unitPrice.getCurrency()!==this.currency),s=t.some((c,p)=>p>0&&c.unitPrice.compareTo(t[p-1].unitPrice)>0),a$1=t[0]?.unitPrice.compareTo(this.baseUnitPrice)>0;if(n$1||s||a$1)throw new n("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 o;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 p(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()}))}}},V=class extends S{currency;selections;constructor(e){super(e),this.type="selection",this.currency=e.currency,this.selections=(e.selections??[]).map(t=>{if(!t.baseUnitPrice)throw new n("Base unit price is required for each selection.");let i=new a(t.baseUnitPrice),n$1=(t.tiers??[]).map(o=>({enabled:o.enabled??!0,minQuantity:o.minQuantity??1,unitPrice:new a(o.unitPrice)})).sort((o,y)=>o.minQuantity-y.minQuantity);if(n$1.some(o=>o.minQuantity<=0))throw new m$1;let a$1=i.getCurrency()!==this.currency||n$1.some(o=>o.unitPrice.getCurrency()!==this.currency),c=n$1.some((o,y)=>y>0&&o.unitPrice.compareTo(n$1[y-1].unitPrice)>0),p=n$1[0]?.unitPrice.compareTo(i)>0;if(a$1||c||p)throw new n("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$1}});}findMatch(e,t=!1){let i=m.generateSelectionAttributesKey(e),n$1=this.selections.find(s=>m.generateSelectionAttributesKey(s.selectionAttributes)===i);if(!n$1&&t)throw new n("No pricing configuration found for selection variant.");return n$1??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 y("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 o;if(!t)throw new y("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 a=n[s];if(e>=a.minQuantity)return a.unitPrice}throw new p(e)}getMinQuantity(e){if(!e)throw new y("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 y("Selection attributes are required to get max discount for selection pricing.");let t=this.findMatch(e,!0),i=t.tiers.filter(c=>c.enabled);if(!i.length)return 0;let n=Math.min(...i.map(c=>c.unitPrice.getAmount())),s=t.baseUnitPrice.getAmount(),a=(s-n)/s*100;return a>0?a:0}getTiers(e){if(!e)throw new y("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 y("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 y("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()}))}:{}}))}}};export{l as a,te as b,S as c,z as d,V as e,m as f};//# sourceMappingURL=chunk-4PTWJI6J.mjs.map
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {b as b$1}from'./chunk-7RAIVZKB.mjs';import {a}from'./chunk-UIQH5QIR.mjs';import {e as e$1}from'./chunk-PL5HGCWN.mjs';import {h,e,l as l$1,n,m as m$1,o,p,y}from'./chunk-O6BLQQO7.mjs';import {b}from'./chunk-UXZBULDS.mjs';import G from'crypto';var C=new Uint8Array(256),T=C.length;function v(){return T>C.length-16&&(G.randomFillSync(C),T=0),C.slice(T,T+=16)}var R=/^(?:[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 q(r){return typeof r=="string"&&R.test(r)}var B=q;var u=[];for(let r=0;r<256;++r)u.push((r+256).toString(16).slice(1));function x(r,e=0){return u[r[e+0]]+u[r[e+1]]+u[r[e+2]]+u[r[e+3]]+"-"+u[r[e+4]]+u[r[e+5]]+"-"+u[r[e+6]]+u[r[e+7]]+"-"+u[r[e+8]]+u[r[e+9]]+"-"+u[r[e+10]]+u[r[e+11]]+u[r[e+12]]+u[r[e+13]]+u[r[e+14]]+u[r[e+15]]}function j(r){if(!B(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 $=j;function Z(r){r=unescape(encodeURIComponent(r));let e=[];for(let t=0;t<r.length;++t)e.push(r.charCodeAt(t));return e}var Y="6ba7b810-9dad-11d1-80b4-00c04fd430c8",F="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function U(r,e,t){function i(n,s,a,c){var p;if(typeof n=="string"&&(n=Z(n)),typeof s=="string"&&(s=$(s)),((p=s)===null||p===void 0?void 0:p.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let o=new Uint8Array(16+n.length);if(o.set(s),o.set(n,s.length),o=t(o),o[6]=o[6]&15|e,o[8]=o[8]&63|128,a){c=c||0;for(let y=0;y<16;++y)a[c+y]=o[y];return a}return x(o)}try{i.name=r;}catch{}return i.DNS=Y,i.URL=F,i}var L={randomUUID:G.randomUUID};function W(r,e,t){if(L.randomUUID&&!e&&!r)return L.randomUUID();r=r||{};let i=r.random||(r.rng||v)();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 x(i)}var E=W;function J(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),G.createHash("sha1").update(r).digest()}var N=J;var _=U("v5",80,N),z=_;var ee={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?z(r,e):E(),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)}},l=ee;var m=class r extends b{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,a]=n.split(":");a.startsWith("c+")?t[s]={name:a.slice(2)}:t[s]=a;}return t}catch(t){throw new h(t?.message)}}constructor(e$1,t=new Date){super(e$1,t),this.id=e$1.id,this.key=e$1.key,this.name={...e$1.name},this.description={...e$1.description},this.slug={...e$1.slug},this.brand=e$1.brand,this.pricing=Object.keys(e$1.pricing).reduce((n,s)=>(e$1.pricing[s]&&(n[s]=S.create(e$1.pricing[s])),n),{}),this.targetGender=e$1.targetGender,this.attributes=l.deepClone(e$1.attributes),this.specifications=l.deepClone(e$1.specifications),this.categories=l.deepClone(e$1.categories),this.productType=e$1.productType??"GOODS";let i=new Set;this.variants=(e$1.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 e(s);return i.add(s),{sku:n.sku,selectionAttributes:n.selectionAttributes,images:{primary:new b$1(n.images.primary),gallery:(n.images.gallery||[]).map(a=>new b$1(a))}}}),this.isActive=e$1.isActive,this.searchTags=e$1.searchTags?l.deepClone(e$1.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e){return e?this.name[e]??this.name[e$1[e]]??this.name.en:l.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[e$1[e]]??this.description.en:l.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[e$1[e]]??this.slug.en:l.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:{...this.pricing}}getAttributes(){return l.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:l.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 l.deepClone(this.categories)}getProductType(){return this.productType}getSpecifications(e){return e?l.deepClone(this.specifications[e]??this.specifications[e$1[e]]??this.specifications.en):l.deepClone(this.specifications)}getSearchTags(e){return e?l.deepClone(this.searchTags[e]??this.searchTags[e$1[e]]??this.searchTags.en):l.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:l.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 te=(t=>(t.VOLUME="volume",t.SELECTION="selection",t))(te||{}),S=class{type;taxCategory;isTaxInclusive;static create(e){return e.type==="selection"?new V(e):new Q(e)}constructor(e){if(!e.taxCategory)throw new l$1;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}},Q=class extends S{baseUnitPrice;tiers;currency;constructor(e){if(super(e),this.type="volume",!e.baseUnitPrice)throw new n("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(c=>({enabled:c.enabled??!0,minQuantity:c.minQuantity,unitPrice:new a(c.unitPrice)})).sort((c,p)=>c.minQuantity-p.minQuantity);if(t.some(c=>c.minQuantity<=0))throw new m$1;if(this.baseUnitPrice.isZero()||t[0]?.unitPrice.isZero())throw new n("Base unit price and tier unit price must not be zero.");let n$1=this.baseUnitPrice.getCurrency()!==this.currency||t.some(c=>c.unitPrice.getCurrency()!==this.currency),s=t.some((c,p)=>p>0&&c.unitPrice.compareTo(t[p-1].unitPrice)>0),a$1=t[0]?.unitPrice.compareTo(this.baseUnitPrice)>0;if(n$1||s||a$1)throw new n("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 o;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 p(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()}))}}},V=class extends S{currency;selections;constructor(e){super(e),this.type="selection",this.currency=e.currency,this.selections=(e.selections??[]).map(t=>{if(!t.baseUnitPrice)throw new n("Base unit price is required for each selection.");let i=new a(t.baseUnitPrice),n$1=(t.tiers??[]).map(o=>({enabled:o.enabled??!0,minQuantity:o.minQuantity??1,unitPrice:new a(o.unitPrice)})).sort((o,y)=>o.minQuantity-y.minQuantity);if(n$1.some(o=>o.minQuantity<=0))throw new m$1;if(i.isZero()||n$1[0]?.unitPrice.isZero())throw new n("Base unit price and tier unit price must not be zero.");let a$1=i.getCurrency()!==this.currency||n$1.some(o=>o.unitPrice.getCurrency()!==this.currency),c=n$1.some((o,y)=>y>0&&o.unitPrice.compareTo(n$1[y-1].unitPrice)>0),p=n$1[0]?.unitPrice.compareTo(i)>0;if(a$1||c||p)throw new n("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$1}});}findMatch(e,t=!1){let i=m.generateSelectionAttributesKey(e),n$1=this.selections.find(s=>m.generateSelectionAttributesKey(s.selectionAttributes)===i);if(!n$1&&t)throw new n("No pricing configuration found for selection variant.");return n$1??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 y("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 o;if(!t)throw new y("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 a=n[s];if(e>=a.minQuantity)return a.unitPrice}throw new p(e)}getMinQuantity(e){if(!e)throw new y("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 y("Selection attributes are required to get max discount for selection pricing.");let t=this.findMatch(e,!0),i=t.tiers.filter(c=>c.enabled);if(!i.length)return 0;let n=Math.min(...i.map(c=>c.unitPrice.getAmount())),s=t.baseUnitPrice.getAmount(),a=(s-n)/s*100;return a>0?a:0}getTiers(e){if(!e)throw new y("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 y("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 y("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()}))}:{}}))}}};export{l as a,te as b,S as c,Q as d,V as e,m as f};//# sourceMappingURL=chunk-XXKEHCV5.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-XXKEHCV5.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../node_modules/uuid/dist/esm-node/rng.js","../node_modules/uuid/dist/esm-node/regex.js","../node_modules/uuid/dist/esm-node/validate.js","../node_modules/uuid/dist/esm-node/stringify.js","../node_modules/uuid/dist/esm-node/parse.js","../node_modules/uuid/dist/esm-node/v35.js","../node_modules/uuid/dist/esm-node/native.js","../node_modules/uuid/dist/esm-node/v4.js","../node_modules/uuid/dist/esm-node/sha1.js","../node_modules/uuid/dist/esm-node/v5.js","../src/Utils/index.ts","../src/Classes/Product.ts","../src/Classes/TieredPrice.ts"],"names":["rnds8Pool","poolPtr","rng","crypto","regex_default","validate","uuid","validate_default","byteToHex","i","unsafeStringify","arr","offset","parse","v","parse_default","stringToBytes","str","bytes","DNS","URL","v35","name","version","hashfunc","generateUUID","value","namespace","buf","_namespace","native_default","v4","options","rnds","v4_default","sha1","sha1_default","v5","v5_default","Utils","key","selectionAttributes","ProductModel","searchId","selectionAttributesKey","obj","Utils_default","_ProductModel","BaseModel","SelectionAttributeParseError","attributes","parts","part","error","data","date","acc","country","TieredPriceModel","uniqueSelectionAttributes","variant","DuplicateSelectionAttributeError","ImageInfoModel","image","locale","LocaleLanguageMap","searchKey","match","category","baseDetails","img","allowedAttributeValues","providedValue","c","size","PricingType","SelectionTieredPriceModel","VolumeTieredPriceModel","InvalidTaxCategoryError","InvalidTieredPriceError","PriceModel","tiers","tier","a","b","t","InvalidMinQuantityError","hasDifferentCurrency","hasIrregularPricing","index","basePriceExceedsFirstTier","quantity","InvalidQuantityError","enabledTiers","NoApplicableTierError","minTierPrice","basePrice","discount","selection","baseUnitPrice","throwOnNotFound","InvalidPricingTypeError"],"mappings":"yPACA,IAAMA,CAAY,CAAA,IAAI,WAAW,GAAG,CAAA,CAEhCC,CAAUD,CAAAA,CAAAA,CAAU,OACT,SAARE,CAAAA,EAAuB,CAC5B,OAAID,CAAAA,CAAUD,EAAU,MAAS,CAAA,EAAA,GAC/BG,CAAO,CAAA,cAAA,CAAeH,CAAS,CAC/BC,CAAAA,CAAAA,CAAU,GAGLD,CAAU,CAAA,KAAA,CAAMC,EAASA,CAAW,EAAA,EAAE,CAC/C,CCXA,IAAOG,CAAQ,CAAA,qHAAA,CCEf,SAASC,CAASC,CAAAA,CAAAA,CAAM,CACtB,OAAO,OAAOA,CAAS,EAAA,QAAA,EAAYF,EAAM,IAAKE,CAAAA,CAAI,CACpD,CAEA,IAAOC,CAAQF,CAAAA,CAAAA,CCAf,IAAMG,CAAAA,CAAY,EAElB,CAAA,IAAA,IAASC,EAAI,CAAGA,CAAAA,CAAAA,CAAI,IAAK,EAAEA,CAAAA,CACzBD,CAAU,CAAA,IAAA,CAAA,CAAMC,EAAI,GAAO,EAAA,QAAA,CAAS,EAAE,CAAE,CAAA,KAAA,CAAM,CAAC,CAAC,CAAA,CAG3C,SAASC,CAAAA,CAAgBC,EAAKC,CAAS,CAAA,CAAA,CAAG,CAG/C,OAAOJ,CAAAA,CAAUG,EAAIC,CAAS,CAAA,CAAC,CAAC,CAAA,CAAIJ,EAAUG,CAAIC,CAAAA,CAAAA,CAAS,CAAC,CAAC,EAAIJ,CAAUG,CAAAA,CA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AA,SAAA,CAAWA,EAAK,SAAU,CAAA,UAAA,EAC5B,CAAA,CAAE,CACJ,CAAI,CAAA,EACN,CAAE,CAAA,CACJ,CACF,CACF","file":"chunk-XXKEHCV5.mjs","sourcesContent":["import crypto from 'crypto';\nconst rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate\n\nlet poolPtr = rnds8Pool.length;\nexport default function rng() {\n if (poolPtr > rnds8Pool.length - 16) {\n crypto.randomFillSync(rnds8Pool);\n poolPtr = 0;\n }\n\n return rnds8Pool.slice(poolPtr, poolPtr += 16);\n}","export default /^(?:[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;","import REGEX from './regex.js';\n\nfunction validate(uuid) {\n return typeof uuid === 'string' && REGEX.test(uuid);\n}\n\nexport default validate;","import validate from './validate.js';\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\n\nconst byteToHex = [];\n\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\n\nexport function unsafeStringify(arr, offset = 0) {\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];\n}\n\nfunction stringify(arr, offset = 0) {\n const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\nexport default stringify;","import validate from './validate.js';\n\nfunction parse(uuid) {\n if (!validate(uuid)) {\n throw TypeError('Invalid UUID');\n }\n\n let v;\n const arr = new Uint8Array(16); // Parse ########-....-....-....-............\n\n arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;\n arr[1] = v >>> 16 & 0xff;\n arr[2] = v >>> 8 & 0xff;\n arr[3] = v & 0xff; // Parse ........-####-....-....-............\n\n arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;\n arr[5] = v & 0xff; // Parse ........-....-####-....-............\n\n arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;\n arr[7] = v & 0xff; // Parse ........-....-....-####-............\n\n arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;\n arr[9] = v & 0xff; // Parse ........-....-....-....-############\n // (Use \"/\" to avoid 32-bit truncation when bit-shifting high-order bytes)\n\n arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;\n arr[11] = v / 0x100000000 & 0xff;\n arr[12] = v >>> 24 & 0xff;\n arr[13] = v >>> 16 & 0xff;\n arr[14] = v >>> 8 & 0xff;\n arr[15] = v & 0xff;\n return arr;\n}\n\nexport default parse;","import { unsafeStringify } from './stringify.js';\nimport parse from './parse.js';\n\nfunction stringToBytes(str) {\n str = unescape(encodeURIComponent(str)); // UTF8 escape\n\n const bytes = [];\n\n for (let i = 0; i < str.length; ++i) {\n bytes.push(str.charCodeAt(i));\n }\n\n return bytes;\n}\n\nexport const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';\nexport const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';\nexport default function v35(name, version, hashfunc) {\n function generateUUID(value, namespace, buf, offset) {\n var _namespace;\n\n if (typeof value === 'string') {\n value = stringToBytes(value);\n }\n\n if (typeof namespace === 'string') {\n namespace = parse(namespace);\n }\n\n if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) {\n throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');\n } // Compute hash of namespace and value, Per 4.3\n // Future: Use spread syntax when supported on all platforms, e.g. `bytes =\n // hashfunc([...namespace, ... value])`\n\n\n let bytes = new Uint8Array(16 + value.length);\n bytes.set(namespace);\n bytes.set(value, namespace.length);\n bytes = hashfunc(bytes);\n bytes[6] = bytes[6] & 0x0f | version;\n bytes[8] = bytes[8] & 0x3f | 0x80;\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = bytes[i];\n }\n\n return buf;\n }\n\n return unsafeStringify(bytes);\n } // Function#name is not settable on some platforms (#270)\n\n\n try {\n generateUUID.name = name; // eslint-disable-next-line no-empty\n } catch (err) {} // For CommonJS default export support\n\n\n generateUUID.DNS = DNS;\n generateUUID.URL = URL;\n return generateUUID;\n}","import crypto from 'crypto';\nexport default {\n randomUUID: crypto.randomUUID\n};","import native from './native.js';\nimport rng from './rng.js';\nimport { unsafeStringify } from './stringify.js';\n\nfunction v4(options, buf, offset) {\n if (native.randomUUID && !buf && !options) {\n return native.randomUUID();\n }\n\n options = options || {};\n const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return unsafeStringify(rnds);\n}\n\nexport default v4;","import crypto from 'crypto';\n\nfunction sha1(bytes) {\n if (Array.isArray(bytes)) {\n bytes = Buffer.from(bytes);\n } else if (typeof bytes === 'string') {\n bytes = Buffer.from(bytes, 'utf8');\n }\n\n return crypto.createHash('sha1').update(bytes).digest();\n}\n\nexport default sha1;","import v35 from './v35.js';\nimport sha1 from './sha1.js';\nconst v5 = v35('v5', 0x50, sha1);\nexport default v5;","import { v4 as uuidv4, v5 as uuidv5 } from 'uuid';\r\nimport ProductModel, { SelectionAttributes } from '../Classes/Product';\r\n\r\nconst Utils = {\r\n isUUID: (value: string): boolean => {\r\n const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\r\n return uuidRegex.test(value);\r\n },\r\n\r\n isEmail: (value: string): boolean => {\r\n const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/;\r\n return emailRegex.test(value);\r\n },\r\n\r\n isURL: (value: string): boolean => {\r\n const urlRegex = /^(http|https):\\/\\/[^ \"]+$/;\r\n return urlRegex.test(value);\r\n },\r\n \r\n generateUUID: (value?: string, namespace?: string) => {\r\n if(namespace && value){\r\n return uuidv5(value, namespace);\r\n }\r\n return uuidv4();\r\n },\r\n\r\n generateSearchId: (key: string, selectionAttributes: SelectionAttributes) => {\r\n return `${key}#${ProductModel.generateSelectionAttributesKey(selectionAttributes)}`;\r\n },\r\n\r\n getKeyfromSearchId: (searchId: string) => {\r\n const [key, selectionAttributesKey] = searchId.split('#');\r\n return {\r\n key,\r\n selectionAttributes: ProductModel.parseSelectionAttributesKey(selectionAttributesKey)\r\n }\r\n },\r\n\r\n /**\r\n * Deep clones an object using `structuredClone`. Don't use this on a class instance.\r\n * @param obj - The object to clone.\r\n * @returns A deep clone of the object.\r\n */\r\n deepClone<T>(obj: T): T {\r\n return structuredClone(obj);\r\n }\r\n}\r\n\r\nexport default Utils;\r\n","import Utils from \"../Utils\";\r\nimport BaseModel, { BaseAttributes } from \"./Base\";\r\nimport { Color, LocalizedString, CountryCode, LocaleCode, LocalizedValue, Prettify } from './Common';\r\nimport { GenderCategory, ImageCategory, LocaleLanguageMap, ProductType } from \"./Enum\";\r\nimport { DuplicateSelectionAttributeError, DuplicateSizeError, SelectionAttributeParseError } from \"./Error\";\r\nimport ImageInfoModel, { ImageInfoData } from \"./ImageInfo\";\r\nimport { TieredPriceModel, TieredPriceAttributes, TieredPriceData } from \"./TieredPrice\";\r\n\r\nexport type ProductSelectionAttributes = Prettify<{\r\n color: Color[];\r\n size: string[];\r\n} & {\r\n [key: string]: string | string[] | Color[];\r\n}>;\r\n\r\nexport type SelectionAttributes = {\r\n color: Color;\r\n [key: string]: string | Color;\r\n};\r\n\r\nexport type VariantData = {\r\n sku: string;\r\n selectionAttributes: SelectionAttributes;\r\n images: {\r\n primary: ImageInfoData;\r\n gallery: ImageInfoData[];\r\n };\r\n};\r\n\r\nexport type VariantModel = {\r\n sku: string;\r\n selectionAttributes: SelectionAttributes;\r\n images: {\r\n primary: ImageInfoModel;\r\n gallery: ImageInfoModel[];\r\n };\r\n};\r\n\r\n\r\nexport type ProductSpecification = { [key: string]: string | string[] };\r\n\r\nexport type ProductAttributes = BaseAttributes & {\r\n id: string;\r\n key: string;\r\n\r\n name: LocalizedString;\r\n description: LocalizedString;\r\n slug: LocalizedString;\r\n brand: string;\r\n\r\n pricing: {\r\n [country in CountryCode]?: TieredPriceAttributes;\r\n };\r\n\r\n targetGender: GenderCategory;\r\n attributes: ProductSelectionAttributes;\r\n specifications: LocalizedValue<ProductSpecification>;\r\n categories: string[];\r\n productType?: ProductType;\r\n\r\n variants: VariantData[];\r\n\r\n // Metadata\r\n isActive: boolean;\r\n searchTags?: LocalizedValue<string[]>;\r\n};\r\n\r\nexport type ProductData = Required<ProductAttributes>\r\n\r\nexport default class ProductModel extends BaseModel {\r\n protected id: string;\r\n protected key: string;\r\n\r\n protected name: LocalizedString;\r\n protected description: LocalizedString;\r\n protected slug: LocalizedString;\r\n protected brand: string;\r\n\r\n protected pricing: {\r\n [country in CountryCode]?: TieredPriceModel;\r\n };\r\n\r\n protected variants: VariantModel[];\r\n\r\n protected targetGender: GenderCategory;\r\n protected attributes: ProductSelectionAttributes;\r\n protected specifications: LocalizedValue<ProductSpecification>;\r\n protected categories: string[];\r\n protected productType: ProductType;\r\n\r\n // Metadata\r\n protected isActive: boolean;\r\n\r\n protected searchTags: LocalizedValue<string[]>;\r\n\r\n static productKeyRegex = /^(?!\\s)(?!.*\\s$)[A-Z0-9-]{4,16}$/;\r\n static productSKURegex = /^(?!\\s)(?!.*\\s$)[A-Z0-9-]{4,16}$/;\r\n\r\n /**\r\n * Generates a unique key for checking uniqueness for a given selection attributes.\r\n * Excludes 'size' from the key generation.\r\n * @param selectionAttributes - The selection attributes.\r\n * @returns A string key representing the unique attribute combination.\r\n */\r\n static generateSelectionAttributesKey(selectionAttributes: SelectionAttributes): string {\r\n if (typeof selectionAttributes !== 'object') {\r\n throw new SelectionAttributeParseError('Selection attributes must be an object');\r\n }\r\n\r\n const sortedKeys = Object.keys(selectionAttributes)\r\n .filter(key => selectionAttributes[key] !== undefined && key.toLowerCase() !== 'size')\r\n .sort()\r\n\r\n return sortedKeys.map(key => {\r\n if ((selectionAttributes[key] as Color).name) {\r\n return `${key}:c+${(selectionAttributes[key] as Color).name}`;\r\n }\r\n return `${key}:${selectionAttributes[key]}`;\r\n }).join('|').toLowerCase();\r\n }\r\n\r\n /**\r\n * Parses a selection attributes key into an object.\r\n * @param key - The selection attributes key to parse.\r\n * @returns An object containing the parsed selection attributes.\r\n */\r\n static parseSelectionAttributesKey(key: string): SelectionAttributes {\r\n try {\r\n const attributes: SelectionAttributes = {} as unknown as SelectionAttributes;\r\n const parts = key.split('|');\r\n for (const part of parts) {\r\n const [key, value] = part.split(':');\r\n if (value.startsWith('c+')) {\r\n attributes[key] = { name: value.slice(2) } as Color;\r\n } else {\r\n attributes[key] = value;\r\n }\r\n }\r\n return attributes;\r\n } catch (error: any) {\r\n throw new SelectionAttributeParseError(error?.message);\r\n }\r\n }\r\n\r\n /**\r\n * Creates an instance of ProductModel.\r\n * Initializes properties based on the provided data, creating copies where necessary.\r\n * @param data - The initial product attributes.\r\n * @param date - Optional date for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: ProductAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n\r\n this.id = data.id;\r\n this.key = data.key;\r\n\r\n this.name = { ...data.name };\r\n this.description = { ...data.description };\r\n this.slug = { ...data.slug };\r\n this.brand = data.brand;\r\n\r\n this.pricing = (Object.keys(data.pricing) as CountryCode[]).reduce((acc, country) => {\r\n if (data.pricing[country]) {\r\n acc[country] = TieredPriceModel.create(data.pricing[country] as TieredPriceAttributes);\r\n }\r\n return acc;\r\n }, {} as { [country in CountryCode]?: TieredPriceModel });\r\n\r\n this.targetGender = data.targetGender;\r\n this.attributes = Utils.deepClone(data.attributes);\r\n this.specifications = Utils.deepClone(data.specifications);\r\n this.categories = Utils.deepClone(data.categories);\r\n this.productType = data.productType ?? ProductType.GOODS;\r\n\r\n const uniqueSelectionAttributes = new Set<string>();\r\n this.variants = (data.variants || []).map(variant => {\r\n if (!variant.selectionAttributes || typeof variant.selectionAttributes !== 'object') {\r\n throw new SelectionAttributeParseError('Selection attributes are required');\r\n }\r\n\r\n this.checkSelectionAttributes(variant.selectionAttributes);\r\n const key = ProductModel.generateSelectionAttributesKey(variant.selectionAttributes);\r\n if (uniqueSelectionAttributes.has(key)) {\r\n throw new DuplicateSelectionAttributeError(key);\r\n }\r\n uniqueSelectionAttributes.add(key);\r\n return {\r\n sku: variant.sku,\r\n selectionAttributes: variant.selectionAttributes,\r\n images: {\r\n primary: new ImageInfoModel(variant.images.primary),\r\n gallery: (variant.images.gallery || []).map(image => new ImageInfoModel(image))\r\n }\r\n };\r\n });\r\n\r\n this.isActive = data.isActive;\r\n this.searchTags = data.searchTags ? Utils.deepClone(data.searchTags) : { en: [] };\r\n }\r\n\r\n /**\r\n * Gets the base Product ID.\r\n * @returns Product ID.\r\n */\r\n getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the user-friendly product key.\r\n * @returns Product Key.\r\n */\r\n getKey(): string {\r\n return this.key;\r\n }\r\n\r\n /**\r\n * Gets the full localized product name object.\r\n * @returns A copy of the LocalizedString object for the name.\r\n */\r\n getName(): LocalizedString\r\n /**\r\n * Gets the product name for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The name string for the specified locale.\r\n */\r\n getName(locale: LocaleCode): string\r\n getName(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.name[locale] ?? this.name[LocaleLanguageMap[locale]] ?? this.name.en;\r\n } else {\r\n return Utils.deepClone(this.name);\r\n }\r\n }\r\n\r\n /**\r\n * Gets the full localized product description object.\r\n * @returns A copy of the LocalizedString object for the description.\r\n */\r\n getDescription(): LocalizedString\r\n /**\r\n * Gets the product description for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The description string for the specified locale.\r\n */\r\n getDescription(locale: LocaleCode): string\r\n getDescription(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.description[locale] ?? this.description[LocaleLanguageMap[locale]] ?? this.description.en;\r\n } else {\r\n return Utils.deepClone(this.description);\r\n }\r\n }\r\n\r\n /**\r\n * Gets the full localized product slug object.\r\n * @returns A copy of the LocalizedString object for the slug.\r\n */\r\n getSlug(): LocalizedString\r\n /**\r\n * Gets the product slug for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The slug string for the specified locale.\r\n */\r\n getSlug(locale: LocaleCode): string\r\n getSlug(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.slug[locale] ?? this.slug[LocaleLanguageMap[locale]] ?? this.slug.en;\r\n } else {\r\n return Utils.deepClone(this.slug);\r\n }\r\n }\r\n\r\n /**\r\n * Gets the brand associated with the product.\r\n * @returns The brand name string.\r\n */\r\n getBrand(): string {\r\n return this.brand;\r\n }\r\n\r\n /**\r\n * Gets the tiered price details for the product.\r\n * @returns Pricing details mapped by country.\r\n */\r\n getPriceDetails(): { [country in CountryCode]?: TieredPriceModel }\r\n /**\r\n * Gets the tiered price details for a specific country.\r\n * @param country - The country code.\r\n * @returns The tiered price model for the country, or null if not found.\r\n */\r\n getPriceDetails(country: CountryCode): TieredPriceModel | null\r\n getPriceDetails(country?: CountryCode): { [country in CountryCode]?: TieredPriceModel } | TieredPriceModel | null {\r\n if (country) {\r\n return this.pricing[country] ?? null;\r\n }\r\n return { ...this.pricing };\r\n }\r\n\r\n /**\r\n * Gets the variant-specific attributes (color, sizes). Returns copies.\r\n * @returns Product Attributes.\r\n */\r\n getAttributes(): ProductSelectionAttributes {\r\n return Utils.deepClone(this.attributes);\r\n }\r\n\r\n\r\n /**\r\n * Gets the variant-specific attributes (color, sizes). Returns copies.\r\n * @returns Product Attributes.\r\n */\r\n getVariants(): VariantModel[] {\r\n return this.variants.map(variant => ({\r\n sku: variant.sku,\r\n selectionAttributes: Utils.deepClone(variant.selectionAttributes),\r\n images: {\r\n primary: variant.images.primary,\r\n gallery: [...variant.images.gallery]\r\n }\r\n }));\r\n }\r\n\r\n /**\r\n * Gets the images for a specific selection attribute combination.\r\n * @param selectionAttributes - The selection attributes to search for.\r\n * @returns The matching image set or null if not found.\r\n */\r\n private getImagesBySelectionAttributes(selectionAttributes: SelectionAttributes): { primary: ImageInfoModel; gallery: ImageInfoModel[] } | null {\r\n const searchKey = ProductModel.generateSelectionAttributesKey(selectionAttributes);\r\n\r\n const match = this.variants.find(variant =>\r\n ProductModel.generateSelectionAttributesKey(variant.selectionAttributes) === searchKey\r\n );\r\n\r\n return match ? {\r\n primary: match.images.primary,\r\n gallery: [...match.images.gallery]\r\n } : null;\r\n }\r\n\r\n /**\r\n * Gets the images for a specific selection attribute combination.\r\n * @param selectionAttributes - The selection attributes to search for.\r\n * @returns The matching image set or null if not found.\r\n */\r\n getImages(selectionAttributes: SelectionAttributes): { primary: ImageInfoModel; gallery: ImageInfoModel[] }\r\n getImages(selectionAttributes: SelectionAttributes, category: ImageCategory.PRIMARY): ImageInfoModel\r\n getImages(selectionAttributes: SelectionAttributes, category: ImageCategory.GALLERY): ImageInfoModel[]\r\n getImages(selectionAttributes: SelectionAttributes, category?: ImageCategory): { primary: ImageInfoModel; gallery: ImageInfoModel[] } | ImageInfoModel | ImageInfoModel[] {\r\n switch (category) {\r\n case ImageCategory.PRIMARY:\r\n return this.getImagesBySelectionAttributes(selectionAttributes)?.primary ?? this.variants[0]?.images?.primary;\r\n case ImageCategory.GALLERY:\r\n return this.getImagesBySelectionAttributes(selectionAttributes)?.gallery ?? [];\r\n default:\r\n return this.getImagesBySelectionAttributes(selectionAttributes) ?? { primary: this.variants[0]?.images?.primary, gallery: [] };\r\n }\r\n }\r\n\r\n\r\n /**\r\n * Checks if the product is active.\r\n * @returns True if the product is active, false otherwise.\r\n */\r\n getIsActive(): boolean {\r\n return this.isActive;\r\n }\r\n\r\n /**\r\n * Gets the target gender category for the product.\r\n * @returns The GenderCategory enum value.\r\n */\r\n getTargetGender(): GenderCategory {\r\n return this.targetGender;\r\n }\r\n\r\n /**\r\n * Gets the list of categories the product belongs to. Returns a copy.\r\n * @returns An array of category.\r\n */\r\n getCategories(): string[] {\r\n return Utils.deepClone(this.categories);\r\n }\r\n\r\n /**\r\n * Gets the product type.\r\n * @returns ProductType.\r\n */\r\n getProductType(): ProductType {\r\n return this.productType;\r\n }\r\n\r\n /**\r\n * Gets the full localized product specifications object.\r\n * @returns Product Specifications\r\n */\r\n getSpecifications(): LocalizedValue<ProductSpecification>\r\n /**\r\n * Gets the product specifications for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The ProductSpecification object for the specified locale, or undefined if not found.\r\n */\r\n getSpecifications(locale: LocaleCode): ProductSpecification\r\n getSpecifications(locale?: LocaleCode): LocalizedValue<ProductSpecification> | ProductSpecification {\r\n if (locale) {\r\n return Utils.deepClone(this.specifications[locale] ?? this.specifications[LocaleLanguageMap[locale]] ?? this.specifications.en);\r\n } else {\r\n return Utils.deepClone(this.specifications);\r\n }\r\n }\r\n\r\n /**\r\n * Gets the localized list of search tags. Returns a copy.\r\n * @returns Localized array of search tags.\r\n */\r\n getSearchTags(): LocalizedValue<string[]>\r\n /**\r\n * Gets the search tags for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The array of search tags for the specified locale, or undefined if not found.\r\n */\r\n getSearchTags(locale: LocaleCode): string[]\r\n getSearchTags(locale?: LocaleCode): LocalizedValue<string[]> | string[] {\r\n if (locale) {\r\n return Utils.deepClone(this.searchTags[locale] ?? this.searchTags[LocaleLanguageMap[locale]] ?? this.searchTags.en);\r\n } else {\r\n return Utils.deepClone(this.searchTags);\r\n }\r\n }\r\n\r\n /**\r\n *\r\n * @returns ProductData\r\n */\r\n getDetails(): ProductData {\r\n const baseDetails = super.getDetails();\r\n return {\r\n id: this.getId(),\r\n key: this.getKey(),\r\n name: this.getName(),\r\n description: this.getDescription(),\r\n slug: this.getSlug(),\r\n brand: this.getBrand(),\r\n pricing: (Object.keys(this.pricing) as CountryCode[]).reduce((acc, country) => {\r\n if (this.pricing[country]) {\r\n acc[country] = this.pricing[country]?.getDetails();\r\n }\r\n return acc;\r\n }, {} as { [country in CountryCode]: TieredPriceData }),\r\n attributes: this.getAttributes(),\r\n variants: this.variants.map(v => ({\r\n sku: v.sku,\r\n selectionAttributes: Utils.deepClone(v.selectionAttributes),\r\n images: {\r\n primary: v.images.primary.getDetails(),\r\n gallery: v.images.gallery.map(img => img.getDetails())\r\n }\r\n })),\r\n isActive: this.getIsActive(),\r\n targetGender: this.getTargetGender(),\r\n categories: this.getCategories(),\r\n productType: this.getProductType(),\r\n specifications: this.getSpecifications(),\r\n searchTags: this.getSearchTags(),\r\n ...baseDetails\r\n };\r\n }\r\n\r\n /**\r\n * Checks if the provided selection attributes are valid for the product.\r\n * @param selectionAttributes The selection attributes to validate.\r\n * @throws {SelectionAttributeParseError} If the selection attributes are invalid.\r\n */\r\n checkSelectionAttributes(selectionAttributes: SelectionAttributes): void {\r\n if (!selectionAttributes || typeof selectionAttributes !== 'object') {\r\n throw new SelectionAttributeParseError('Selection attributes are required');\r\n }\r\n\r\n Object.keys(this.attributes).forEach(key => {\r\n if(key.toLowerCase() === 'size') return;\r\n \r\n const allowedAttributeValues = this.attributes[key];\r\n const providedValue = selectionAttributes[key];\r\n\r\n if (providedValue === undefined) {\r\n throw new SelectionAttributeParseError(`Selection attribute '${key}' is missing`);\r\n }\r\n\r\n if (typeof allowedAttributeValues === 'string') {\r\n if (typeof providedValue !== 'string' || allowedAttributeValues !== providedValue) {\r\n throw new SelectionAttributeParseError(`Selection attribute '${key}' is invalid`);\r\n }\r\n } else if (Array.isArray(allowedAttributeValues)) {\r\n if (allowedAttributeValues.length > 0 && typeof allowedAttributeValues[0] === 'string') {\r\n if (typeof providedValue !== 'string' || !(allowedAttributeValues as string[]).includes(providedValue)) {\r\n throw new SelectionAttributeParseError(`Selection attribute '${key}' is invalid`);\r\n }\r\n } else {\r\n // Color validation\r\n if (\r\n typeof providedValue !== 'object' ||\r\n !('name' in providedValue) ||\r\n (allowedAttributeValues as Color[]).findIndex(c => c.name === (providedValue as Color).name) < 0\r\n ) {\r\n throw new SelectionAttributeParseError(`Selection attribute '${key}' is invalid`);\r\n }\r\n }\r\n }\r\n });\r\n }\r\n\r\n /**\r\n * Gets the SKU of the variant matching the selection attributes.\r\n * @param selectionAttributes - The selection attributes to search for.\r\n * @returns The SKU string, or undefined if no matching variant is found.\r\n */\r\n public getSku(selectionAttributes: SelectionAttributes): string | undefined {\r\n const searchKey = ProductModel.generateSelectionAttributesKey(selectionAttributes);\r\n const match = this.variants.find(variant =>\r\n ProductModel.generateSelectionAttributesKey(variant.selectionAttributes) === searchKey\r\n );\r\n return match?.sku;\r\n }\r\n\r\n /**\r\n * Validates if the provided selection attributes exist for this product.\r\n * @param selectionAttributes - The attributes to validate.\r\n * @returns True if a valid selection attribute exists, false otherwise.\r\n */\r\n validateSelectionAttribute(selectionAttributes: SelectionAttributes): boolean {\r\n const searchKey = ProductModel.generateSelectionAttributesKey(selectionAttributes);\r\n\r\n return this.variants.some(variant => ProductModel.generateSelectionAttributesKey(variant.selectionAttributes) === searchKey);\r\n }\r\n\r\n /**\r\n * Validates if a specific size is available for this product.\r\n * @param size - The size to check.\r\n * @returns True if the size exists in the product's attributes, false otherwise.\r\n */\r\n validateSize(size: string): boolean {\r\n return this.attributes.size.includes(size);\r\n }\r\n}\r\n","import PriceModel, { PriceData } from \"./Price\";\nimport type { SelectionAttributes } from \"./Product\";\nimport ProductModel from \"./Product\";\nimport {\n InvalidTaxCategoryError,\n InvalidMinQuantityError,\n InvalidTieredPriceError,\n InvalidQuantityError,\n InvalidPricingTypeError,\n NoApplicableTierError\n} from \"./Error\";\nimport { CountryCode, CurrencyCode, Prettify } from \"./Common\";\n\nexport enum PricingType {\n VOLUME = 'volume',\n SELECTION = 'selection',\n}\n\n/**\n * Represents a pricing tier based on a minimum purchase quantity.\n */\nexport type PriceTier = {\n enabled: boolean;\n minQuantity: number;\n unitPrice: PriceModel;\n};\n\nexport type PriceTierData = {\n enabled: boolean;\n minQuantity: number;\n unitPrice: PriceData;\n};\n\n/**\n * Represents the configuration for a specific selection variant.\n */\nexport type SelectionPricingData = {\n selectionAttributes: SelectionAttributes;\n baseUnitPrice: PriceData;\n tiers?: PriceTierData[];\n};\n\nexport type SelectionPricing = {\n selectionAttributes: SelectionAttributes;\n baseUnitPrice: PriceModel;\n tiers: PriceTier[];\n};\n\nexport type PriceTierAttributes = Prettify<Omit<PriceTierData, 'enabled'> & { enabled?: boolean }>;\n\n/**\n * Represents the attributes required for tiered pricing.\n */\nexport type VolumenTieredPriceAttributes = {\n type?: PricingType.VOLUME;\n taxCategory: string;\n isTaxInclusive?: boolean;\n currency?: CurrencyCode;\n baseUnitPrice: PriceData;\n tiers: PriceTierAttributes[];\n}\n\nexport type SelectionTieredPriceAttributes = {\n type: PricingType.SELECTION;\n taxCategory: string;\n isTaxInclusive?: boolean;\n currency: CurrencyCode;\n selections: (Omit<SelectionPricingData, 'tiers'> & { tiers?: PriceTierAttributes[] })[];\n}\n\nexport type TieredPriceAttributes = VolumenTieredPriceAttributes | SelectionTieredPriceAttributes;\n\nexport type VolumenTieredPriceData = {\n type: PricingType.VOLUME;\n taxCategory: string;\n isTaxInclusive: boolean;\n currency: CurrencyCode;\n baseUnitPrice: PriceData;\n tiers: PriceTierData[];\n};\n\nexport type SelectionTieredPriceData = {\n type: PricingType.SELECTION;\n taxCategory: string;\n isTaxInclusive: boolean;\n currency: CurrencyCode;\n selections: SelectionPricingData[];\n}\n\nexport type TieredPriceData = VolumenTieredPriceData | SelectionTieredPriceData;\n\nexport abstract class TieredPriceModel {\n protected type: PricingType;\n protected taxCategory: string;\n protected isTaxInclusive: boolean;\n\n /** \n * Factory method to instantiate the correct concrete TieredPriceModel implementation.\n */\n static create(data: TieredPriceAttributes): TieredPriceModel {\n if (data.type === PricingType.SELECTION) {\n return new SelectionTieredPriceModel(data);\n }\n return new VolumeTieredPriceModel(data);\n }\n\n constructor(data: TieredPriceAttributes) {\n if (!data.taxCategory) {\n throw new InvalidTaxCategoryError();\n }\n this.taxCategory = data.taxCategory;\n this.isTaxInclusive = data.isTaxInclusive ?? false;\n this.type = data.type ?? PricingType.VOLUME;\n }\n\n getType(): PricingType {\n return this.type;\n }\n\n getTaxCategory(): string {\n return this.taxCategory;\n }\n\n getIsTaxInclusive(): boolean {\n return this.isTaxInclusive;\n }\n\n abstract isPriceAvailable(selectionAttributes?: SelectionAttributes): boolean;\n abstract getBaseUnitPrice(selectionAttributes?: SelectionAttributes): PriceModel;\n abstract getDetails(): TieredPriceData;\n abstract getCurrency(): CurrencyCode;\n abstract getApplicableUnitPrice(quantity: number, selectionAttributes?: SelectionAttributes): PriceModel;\n abstract getMinQuantity(selectionAttributes?: SelectionAttributes): number;\n abstract getMaxDiscountPercent(selectionAttributes?: SelectionAttributes): number;\n abstract getTiers(selectionAttributes?: SelectionAttributes): PriceTier[];\n abstract getMinPrice(selectionAttributes?: SelectionAttributes): PriceModel | null;\n abstract getMaxPrice(selectionAttributes?: SelectionAttributes): PriceModel | null;\n}\n\nexport class VolumeTieredPriceModel extends TieredPriceModel {\n protected baseUnitPrice: PriceModel;\n protected tiers: PriceTier[];\n protected currency: CurrencyCode;\n\n constructor(data: Extract<TieredPriceAttributes, { type?: PricingType.VOLUME }>) {\n super(data);\n this.type = PricingType.VOLUME;\n \n if (!data.baseUnitPrice) {\n throw new InvalidTieredPriceError(\"Base unit price is required for volume pricing.\");\n }\n this.baseUnitPrice = new PriceModel(data.baseUnitPrice);\n this.currency = data.currency ?? this.baseUnitPrice.getCurrency();\n\n const tiers = (data.tiers ?? [])\n .map(tier => ({\n enabled: tier.enabled ?? true,\n minQuantity: tier.minQuantity,\n unitPrice: new PriceModel(tier.unitPrice),\n }))\n .sort((a, b) => a.minQuantity - b.minQuantity);\n\n const hasInvalidMinQuantity = tiers.some(t => t.minQuantity <= 0);\n if (hasInvalidMinQuantity) {\n throw new InvalidMinQuantityError();\n }\n\n if(this.baseUnitPrice.isZero() || tiers[0]?.unitPrice.isZero()) {\n throw new InvalidTieredPriceError(\"Base unit price and tier unit price must not be zero.\");\n }\n\n const hasDifferentCurrency = this.baseUnitPrice.getCurrency() !== this.currency || tiers.some(\n t => t.unitPrice.getCurrency() !== this.currency\n );\n const hasIrregularPricing = tiers.some(\n (tier, index) =>\n index > 0 &&\n tier.unitPrice.compareTo(tiers[index - 1].unitPrice) > 0\n );\n const basePriceExceedsFirstTier = tiers[0]?.unitPrice.compareTo(this.baseUnitPrice) > 0;\n\n if (hasDifferentCurrency || hasIrregularPricing || basePriceExceedsFirstTier) {\n throw new InvalidTieredPriceError(\n \"Tiers must share the same currency and must not increase in unit price.\"\n );\n }\n\n this.tiers = tiers;\n }\n\n isPriceAvailable(): boolean {\n return this.tiers.filter(t => t.enabled).length > 0;\n }\n\n getBaseUnitPrice(): PriceModel {\n return this.baseUnitPrice;\n }\n\n getCurrency(): CurrencyCode {\n return this.baseUnitPrice.getCurrency();\n }\n\n getApplicableUnitPrice(quantity: number): PriceModel {\n if (quantity <= 0) {\n throw new InvalidQuantityError();\n }\n\n const enabledTiers = this.tiers.filter(t => t.enabled);\n for (let i = enabledTiers.length - 1; i >= 0; i--) {\n const tier = enabledTiers[i];\n if (quantity >= tier.minQuantity) {\n return tier.unitPrice;\n }\n }\n\n throw new NoApplicableTierError(quantity);\n }\n\n getMinQuantity(): number {\n const enabledTiers = this.tiers.filter(tier => tier.enabled);\n return enabledTiers[0]?.minQuantity ?? 1;\n }\n\n getMaxDiscountPercent(): number {\n const enabledTiers = this.tiers.filter(tier => tier.enabled);\n if (!enabledTiers.length) return 0;\n \n const minTierPrice = Math.min(...enabledTiers.map(t => t.unitPrice.getAmount()));\n const basePrice = this.baseUnitPrice.getAmount();\n \n const discount = ((basePrice - minTierPrice) / basePrice) * 100;\n return discount > 0 ? discount : 0;\n }\n\n getMinPrice(): PriceModel | null {\n const enabledTiers = this.tiers.filter(tier => tier.enabled);\n return enabledTiers.length ? enabledTiers[enabledTiers.length - 1].unitPrice : null;\n }\n\n getMaxPrice(): PriceModel | null {\n const enabledTiers = this.tiers.filter(tier => tier.enabled);\n return enabledTiers.length ? enabledTiers[0].unitPrice : null;\n }\n\n getTiers(): PriceTier[] {\n return this.tiers.map(tier => ({\n enabled: tier.enabled,\n minQuantity: tier.minQuantity,\n unitPrice: tier.unitPrice\n }));\n }\n\n getDetails(): VolumenTieredPriceData {\n return {\n type: this.type as PricingType.VOLUME,\n taxCategory: this.taxCategory,\n isTaxInclusive: this.isTaxInclusive,\n currency: this.currency,\n baseUnitPrice: this.baseUnitPrice.getDetails(),\n tiers: this.tiers.map(tier => ({\n enabled: tier.enabled,\n minQuantity: tier.minQuantity,\n unitPrice: tier.unitPrice.getDetails()\n }))\n };\n }\n}\n\nexport class SelectionTieredPriceModel extends TieredPriceModel {\n protected currency: CurrencyCode;\n protected selections: SelectionPricing[];\n\n constructor(data: Extract<TieredPriceAttributes, { type: PricingType.SELECTION }>) {\n super(data);\n this.type = PricingType.SELECTION;\n this.currency = data.currency;\n\n this.selections = (data.selections ?? []).map(selection => {\n if (!selection.baseUnitPrice) {\n throw new InvalidTieredPriceError(\"Base unit price is required for each selection.\");\n }\n const baseUnitPrice = new PriceModel(selection.baseUnitPrice);\n\n const tiers = (selection.tiers ?? [])\n .map(tier => ({\n enabled: tier.enabled ?? true,\n minQuantity: tier.minQuantity ?? 1,\n unitPrice: new PriceModel(tier.unitPrice),\n }))\n .sort((a, b) => a.minQuantity - b.minQuantity);\n\n const hasInvalidMinQuantity = tiers.some(t => t.minQuantity <= 0);\n if (hasInvalidMinQuantity) {\n throw new InvalidMinQuantityError();\n }\n\n if(baseUnitPrice.isZero() || tiers[0]?.unitPrice.isZero()) {\n throw new InvalidTieredPriceError(\"Base unit price and tier unit price must not be zero.\");\n }\n\n const hasDifferentCurrency = baseUnitPrice.getCurrency() !== this.currency || tiers.some(\n t => t.unitPrice.getCurrency() !== this.currency\n );\n const hasIrregularPricing = tiers.some(\n (tier, index) =>\n index > 0 &&\n tier.unitPrice.compareTo(tiers[index - 1].unitPrice) > 0\n );\n const basePriceExceedsFirstTier = tiers[0]?.unitPrice.compareTo(baseUnitPrice) > 0;\n\n if (hasDifferentCurrency || hasIrregularPricing || basePriceExceedsFirstTier) {\n throw new InvalidTieredPriceError(\n \"Tiers must share the same currency and must not increase in unit price within the same selection.\"\n );\n }\n\n return {\n selectionAttributes: { ...selection.selectionAttributes },\n baseUnitPrice,\n tiers\n };\n });\n }\n\n protected findMatch(selectionAttributes: SelectionAttributes, throwOnNotFound = false): SelectionPricing | null {\n const key = ProductModel.generateSelectionAttributesKey(selectionAttributes);\n const match = this.selections.find(\n s => ProductModel.generateSelectionAttributesKey(s.selectionAttributes) === key\n );\n if (!match && throwOnNotFound) {\n throw new InvalidTieredPriceError(\"No pricing configuration found for selection variant.\");\n }\n return match ?? null;\n }\n\n isPriceAvailable(selectionAttributes?: SelectionAttributes): boolean {\n if(!selectionAttributes) {\n console.warn('Selection attributes are required to check price availability for selection pricing.');\n return false;\n }\n const match = this.findMatch(selectionAttributes);\n return match ? match.tiers.filter(t => t.enabled).length > 0 : false;\n }\n\n getBaseUnitPrice(selectionAttributes?: SelectionAttributes): PriceModel {\n if (!selectionAttributes) {\n throw new InvalidPricingTypeError(\"Selection attributes are required to get base unit price for selection pricing.\");\n }\n const match = this.findMatch(selectionAttributes, true)!;\n return match.baseUnitPrice;\n }\n\n getCurrency(): CurrencyCode {\n return this.currency;\n }\n\n getApplicableUnitPrice(quantity: number, selectionAttributes?: SelectionAttributes): PriceModel {\n if (quantity <= 0) {\n throw new InvalidQuantityError();\n }\n if (!selectionAttributes) {\n throw new InvalidPricingTypeError(\"Selection attributes are required to get applicable unit price for selection pricing.\");\n }\n \n const match = this.findMatch(selectionAttributes, true)!;\n\n const enabledTiers = match.tiers.filter(t => t.enabled);\n for (let i = enabledTiers.length - 1; i >= 0; i--) {\n const tier = enabledTiers[i];\n if (quantity >= tier.minQuantity) {\n return tier.unitPrice;\n }\n }\n throw new NoApplicableTierError(quantity);\n }\n\n getMinQuantity(selectionAttributes?: SelectionAttributes): number {\n if (!selectionAttributes) {\n throw new InvalidPricingTypeError(\"Selection attributes are required to get min quantity for selection pricing.\");\n }\n const match = this.findMatch(selectionAttributes, true)!;\n const enabledTiers = match.tiers.filter(t => t.enabled);\n return enabledTiers[0]?.minQuantity ?? 1;\n }\n\n getMaxDiscountPercent(selectionAttributes?: SelectionAttributes): number {\n if (!selectionAttributes) {\n throw new InvalidPricingTypeError(\"Selection attributes are required to get max discount for selection pricing.\");\n }\n const match = this.findMatch(selectionAttributes, true)!;\n\n const enabledTiers = match.tiers.filter(t => t.enabled);\n if (!enabledTiers.length) return 0;\n\n const minTierPrice = Math.min(...enabledTiers.map(t => t.unitPrice.getAmount()));\n const basePrice = match.baseUnitPrice.getAmount();\n \n const discount = ((basePrice - minTierPrice) / basePrice) * 100;\n return discount > 0 ? discount : 0;\n }\n\n getTiers(selectionAttributes?: SelectionAttributes): PriceTier[] {\n if (!selectionAttributes) {\n throw new InvalidPricingTypeError(\"Selection attributes are required to get tiers for selection pricing.\");\n }\n const match = this.findMatch(selectionAttributes, true)!;\n return match.tiers.map(tier => ({\n enabled: tier.enabled,\n minQuantity: tier.minQuantity,\n unitPrice: tier.unitPrice\n }));\n }\n\n getMinPrice(selectionAttributes?: SelectionAttributes): PriceModel | null {\n if (!selectionAttributes) {\n throw new InvalidPricingTypeError(\"Selection attributes are required to get min price for selection pricing.\");\n }\n const match = this.findMatch(selectionAttributes);\n if (!match) return null;\n const enabledTiers = match.tiers.filter(t => t.enabled);\n return enabledTiers.length ? enabledTiers[enabledTiers.length - 1].unitPrice : null;\n }\n\n getMaxPrice(selectionAttributes?: SelectionAttributes): PriceModel | null {\n if (!selectionAttributes) {\n throw new InvalidPricingTypeError(\"Selection attributes are required to get max price for selection pricing.\");\n }\n const match = this.findMatch(selectionAttributes);\n if (!match) return null;\n const enabledTiers = match.tiers.filter(t => t.enabled);\n return enabledTiers.length ? enabledTiers[0].unitPrice : null;\n }\n\n getDetails(): SelectionTieredPriceData {\n return {\n type: this.type as PricingType.SELECTION,\n taxCategory: this.taxCategory,\n isTaxInclusive: this.isTaxInclusive,\n currency: this.currency,\n selections: this.selections.map(selection => ({\n selectionAttributes: selection.selectionAttributes,\n baseUnitPrice: selection.baseUnitPrice.getDetails(),\n ...(selection.tiers.length > 0 ? {\n tiers: selection.tiers.map(tier => ({\n enabled: tier.enabled,\n minQuantity: tier.minQuantity,\n unitPrice: tier.unitPrice.getDetails()\n }))\n } : {})\n }))\n };\n }\n}\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a as a$1}from'./chunk-UIQH5QIR.mjs';import {a}from'./chunk-UXZBULDS.mjs';var n=class extends a{taxRuleId;taxCategory;taxSystem;taxSubSystem;country;rate;minPrice;maxPrice;excludeMin;excludeMax;effectiveFrom;effectiveTo;constructor(e){super(e),this.taxRuleId=e.taxRuleId,this.taxSystem=e.taxSystem,this.taxSubSystem=e.taxSubSystem,this.taxCategory=e.taxCategory,this.country=e.country,this.rate=e.rate,this.minPrice=new a$1(e.minPrice),this.maxPrice=e.maxPrice?new a$1(e.maxPrice):void 0,this.excludeMin=e.excludeMin??!1,this.excludeMax=e.excludeMax??!1,this.effectiveFrom=new Date(e.effectiveFrom).toISOString(),this.effectiveTo=e.effectiveTo?new Date(e.effectiveTo).toISOString():void 0;}getTaxRuleId(){return this.taxRuleId}getTaxSystem(){return this.taxSystem}getTaxSubSystem(){return this.taxSubSystem}getTaxCategory(){return this.taxCategory}getCountry(){return this.country}getRate(){return this.rate}getMinPrice(){return this.minPrice}getMaxPrice(){return this.maxPrice}getExcludeMin(){return this.excludeMin}getExcludeMax(){return this.excludeMax}getEffectiveFrom(){return this.effectiveFrom}getEffectiveTo(){return this.effectiveTo}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxSubSystem:this.getTaxSubSystem(),taxCategory:this.getTaxCategory(),country:this.getCountry(),rate:this.getRate(),minPrice:this.getMinPrice().getDetails(),maxPrice:this.getMaxPrice()?.getDetails(),excludeMin:this.getExcludeMin(),excludeMax:this.getExcludeMax(),effectiveFrom:this.effectiveFrom,effectiveTo:this.effectiveTo?this.effectiveTo:void 0,customFields:this.getAllCustomFields()}}appliesTo(e,o,t,i=new Date){let r=!t||(this.excludeMin?this.minPrice.compareTo(t)<0:this.minPrice.compareTo(t)<=0)&&(this.maxPrice?this.excludeMax?this.maxPrice.compareTo(t)>0:this.maxPrice.compareTo(t)>=0:!0);return this.taxCategory===e&&this.country===o&&r&&Date.parse(this.effectiveFrom)<=i.getTime()&&(this.effectiveTo?Date.parse(this.effectiveTo)>=i.getTime():!0)}getApplicableTaxRate(e){return this.appliesTo(this.taxCategory,this.country,e)?this.rate:0}calculateTax(e){return this.appliesTo(this.taxCategory,this.country,e)?e.multiply(this.rate):e.zero()}static getTaxRateDisplayString(e,o,t){let i=o*100,r=i%1===0?i.toString():i.toFixed(2).replace(/\.?0+$/,"");return t?.percentageOnly?`${r}%`:e.getTaxSystem()==="GST"?`${e.getTaxSubSystem()} ${r}%`:`${e.getTaxSystem()} ${r}%`}};export{n as a};//# sourceMappingURL=chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {a as a$1}from'./chunk-UIQH5QIR.mjs';import {a}from'./chunk-UXZBULDS.mjs';var n=class extends a{taxRuleId;taxCategory;taxSystem;taxSubSystem;country;rate;minPrice;maxPrice;excludeMin;excludeMax;effectiveFrom;effectiveTo;constructor(e){super(e),this.taxRuleId=e.taxRuleId,this.taxSystem=e.taxSystem,this.taxSubSystem=e.taxSubSystem,this.taxCategory=e.taxCategory,this.country=e.country,this.rate=e.rate,this.minPrice=new a$1(e.minPrice),this.maxPrice=e.maxPrice?new a$1(e.maxPrice):void 0,this.excludeMin=e.excludeMin??!1,this.excludeMax=e.excludeMax??!1,this.effectiveFrom=new Date(e.effectiveFrom).toISOString(),this.effectiveTo=e.effectiveTo?new Date(e.effectiveTo).toISOString():void 0;}getTaxRuleId(){return this.taxRuleId}getTaxSystem(){return this.taxSystem}getTaxSubSystem(){return this.taxSubSystem}getTaxCategory(){return this.taxCategory}getCountry(){return this.country}getRate(){return this.rate}getMinPrice(){return this.minPrice}getMaxPrice(){return this.maxPrice}getExcludeMin(){return this.excludeMin}getExcludeMax(){return this.excludeMax}getEffectiveFrom(){return this.effectiveFrom}getEffectiveTo(){return this.effectiveTo}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxSubSystem:this.getTaxSubSystem(),taxCategory:this.getTaxCategory(),country:this.getCountry(),rate:this.getRate(),minPrice:this.getMinPrice().getDetails(),maxPrice:this.getMaxPrice()?.getDetails(),excludeMin:this.getExcludeMin(),excludeMax:this.getExcludeMax(),effectiveFrom:this.effectiveFrom,effectiveTo:this.effectiveTo?this.effectiveTo:void 0,customFields:this.getAllCustomFields()}}appliesTo(e,o,t,i=new Date){let r=!t||(this.excludeMin?this.minPrice.compareTo(t)<0:this.minPrice.compareTo(t)<=0)&&(this.maxPrice?this.excludeMax?this.maxPrice.compareTo(t)>0:this.maxPrice.compareTo(t)>=0:!0);return this.taxCategory===e&&this.country===o&&r&&Date.parse(this.effectiveFrom)<=i.getTime()&&(this.effectiveTo?Date.parse(this.effectiveTo)>=i.getTime():!0)}getApplicableTaxRate(e){return this.appliesTo(this.taxCategory,this.country,e)?this.rate:0}calculateTax(e){return this.appliesTo(this.taxCategory,this.country,e)?e.multiply(this.rate).round():e.zero()}static getTaxRateDisplayString(e,o,t){let i=o*100,r=i%1===0?i.toString():i.toFixed(2).replace(/\.?0+$/,"");return t?.percentageOnly?`${r}%`:e.getTaxSystem()==="GST"?`${e.getTaxSubSystem()} ${r}%`:`${e.getTaxSystem()} ${r}%`}};export{n as a};//# sourceMappingURL=chunk-YT3U73BS.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-YT3U73BS.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/Classes/TaxRule.ts"],"names":["TaxRuleModel","CustomFieldModel","data","PriceModel","taxCategory","country","price","at","isPriceInRange","taxRule","rate","formateOption","percentage","rateStr"],"mappings":"iFAsBaA,IAAAA,CAAAA,CAAN,cAA2BC,CAAiB,CACvC,UACA,WACA,CAAA,SAAA,CACA,aACA,OACA,CAAA,IAAA,CACA,SACA,QACA,CAAA,UAAA,CACA,WACA,aACA,CAAA,WAAA,CAEV,YAAYC,CAAyB,CAAA,CACnC,MAAMA,CAAI,CAAA,CACV,KAAK,SAAYA,CAAAA,CAAAA,CAAK,UACtB,IAAK,CAAA,SAAA,CAAYA,EAAK,SACtB,CAAA,IAAA,CAAK,aAAeA,CAAK,CAAA,YAAA,CACzB,KAAK,WAAcA,CAAAA,CAAAA,CAAK,YACxB,IAAK,CAAA,OAAA,CAAUA,EAAK,OACpB,CAAA,IAAA,CAAK,IAAOA,CAAAA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IAEP,CAAA,CACT,CAOA,YAAaA,CAAAA,CAAAA,CAA+B,CAC1C,OAAI,IAAA,CAAK,UAAU,IAAK,CAAA,WAAA,CAAa,KAAK,OAASA,CAAAA,CAAK,EAIjDA,CAAM,CAAA,QAAA,CAAS,KAAK,IAAI,CAAA,CAAE,OAHxBA,CAAAA,CAAAA,CAAM,IAAK,EAItB,CAGA,OAAO,wBAAwBG,CAAuBC,CAAAA,CAAAA,CAAcC,EAEzD,CACT,IAAMC,EAAaF,CAAO,CAAA,GAAA,CAEpBG,EAAUD,CAAa,CAAA,CAAA,GAAM,EAAIA,CAAW,CAAA,QAAA,GAAaA,CAAW,CAAA,OAAA,CAAQ,CAAC,CAAE,CAAA,OAAA,CAAQ,QAAU,CAAA,EAAE,CAEzG,CAAA,OAAID,GAAe,cACV,CAAA,CAAA,EAAGE,CAAO,CAGfJ,CAAAA,CAAAA,CAAAA,CAAAA,CAAQ,cAAmB,GAAA,KAAA,CACtB,GAAGA,CAAQ,CAAA,eAAA,EAAiB,CAAII,CAAAA,EAAAA,CAAO,IAEzC,CAAGJ,EAAAA,CAAAA,CAAQ,cAAc,CAAA,CAAA,EAAII,CAAO,CAAA,CAAA,CAC7C,CACF","file":"chunk-YT3U73BS.mjs","sourcesContent":["import { CustomFieldAttributes, CustomFieldModel } from \"./Base\";\r\nimport { CountryCode, ISODateTimeUTC, Prettify } from \"./Common\";\r\nimport { TaxSystem } from \"./Enum\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\n\r\nexport type TaxRuleAttributes = Prettify<CustomFieldAttributes & {\r\n taxRuleId: string;\r\n taxCategory: string;\r\n taxSystem: TaxSystem;\r\n taxSubSystem: string;\r\n country: CountryCode;\r\n rate: number;\r\n minPrice: PriceData;\r\n maxPrice?: PriceData;\r\n excludeMin?: boolean;\r\n excludeMax?: boolean;\r\n effectiveFrom: ISODateTimeUTC;\r\n effectiveTo?: ISODateTimeUTC;\r\n}>;\r\n\r\nexport type TaxRuleData = TaxRuleAttributes;\r\n\r\nexport class TaxRuleModel extends CustomFieldModel {\r\n protected taxRuleId: string;\r\n protected taxCategory: string;\r\n protected taxSystem: TaxSystem;\r\n protected taxSubSystem: string;\r\n protected country: CountryCode;\r\n protected rate: number;\r\n protected minPrice: PriceModel;\r\n protected maxPrice?: PriceModel;\r\n protected excludeMin: boolean;\r\n protected excludeMax: boolean;\r\n protected effectiveFrom: ISODateTimeUTC;\r\n protected effectiveTo?: ISODateTimeUTC;\r\n\r\n constructor(data: TaxRuleAttributes) {\r\n super(data);\r\n this.taxRuleId = data.taxRuleId;\r\n this.taxSystem = data.taxSystem;\r\n this.taxSubSystem = data.taxSubSystem;\r\n this.taxCategory = data.taxCategory;\r\n this.country = data.country;\r\n this.rate = data.rate;\r\n this.minPrice = new PriceModel(data.minPrice);\r\n this.maxPrice = data.maxPrice ? new PriceModel(data.maxPrice) : undefined;\r\n this.excludeMin = data.excludeMin ?? false;\r\n this.excludeMax = data.excludeMax ?? false;\r\n this.effectiveFrom = new Date(data.effectiveFrom).toISOString();\r\n this.effectiveTo = data.effectiveTo ? new Date(data.effectiveTo).toISOString() : undefined;\r\n }\r\n\r\n getTaxRuleId(): string {\r\n return this.taxRuleId;\r\n }\r\n\r\n getTaxSystem(): TaxSystem {\r\n return this.taxSystem;\r\n }\r\n\r\n getTaxSubSystem(): string {\r\n return this.taxSubSystem;\r\n }\r\n\r\n getTaxCategory(): string {\r\n return this.taxCategory;\r\n }\r\n\r\n getCountry(): CountryCode {\r\n return this.country;\r\n }\r\n\r\n getRate(): number {\r\n return this.rate;\r\n }\r\n\r\n getMinPrice(): PriceModel {\r\n return this.minPrice;\r\n }\r\n\r\n getMaxPrice(): PriceModel | undefined {\r\n return this.maxPrice;\r\n }\r\n\r\n getExcludeMin(): boolean {\r\n return this.excludeMin;\r\n }\r\n\r\n getExcludeMax(): boolean {\r\n return this.excludeMax;\r\n }\r\n\r\n getEffectiveFrom(): string {\r\n return this.effectiveFrom;\r\n }\r\n\r\n getEffectiveTo(): string | undefined {\r\n return this.effectiveTo;\r\n }\r\n\r\n getDetails(): TaxRuleData {\r\n return {\r\n taxRuleId: this.getTaxRuleId(),\r\n taxSystem: this.getTaxSystem(),\r\n taxSubSystem: this.getTaxSubSystem(),\r\n taxCategory: this.getTaxCategory(),\r\n country: this.getCountry(),\r\n rate: this.getRate(),\r\n minPrice: this.getMinPrice().getDetails(),\r\n maxPrice: this.getMaxPrice()?.getDetails(),\r\n excludeMin: this.getExcludeMin(),\r\n excludeMax: this.getExcludeMax(),\r\n effectiveFrom: this.effectiveFrom,\r\n effectiveTo: this.effectiveTo ? this.effectiveTo : undefined,\r\n customFields: this.getAllCustomFields(),\r\n };\r\n }\r\n\r\n /**\r\n * Checks whether this tax rule is applicable for the given category and country at a specific time.\r\n * @param taxCategory - The tax category to check.\r\n * @param country - The country code to check.\r\n * @param price - The price to check against the rule's price range (optional).\r\n * @param at - The date to check effectiveness against (defaults to now).\r\n * @returns True if the rule is applicable, false otherwise.\r\n */\r\n appliesTo(taxCategory: string, country: CountryCode, price?: PriceModel, at: Date = new Date()): boolean {\r\n const isPriceInRange = !price || (\r\n (this.excludeMin ? this.minPrice.compareTo(price) < 0 : this.minPrice.compareTo(price) <= 0) &&\r\n (this.maxPrice\r\n ? (this.excludeMax ? this.maxPrice.compareTo(price) > 0 : this.maxPrice.compareTo(price) >= 0)\r\n : true\r\n )\r\n );\r\n\r\n return (\r\n this.taxCategory === taxCategory &&\r\n this.country === country &&\r\n isPriceInRange &&\r\n Date.parse(this.effectiveFrom) <= at.getTime() &&\r\n (this.effectiveTo ? Date.parse(this.effectiveTo) >= at.getTime() : true)\r\n );\r\n }\r\n\r\n /**\r\n * Gets the applicable tax rate for a given price. Returns the tax rate if the rule applies, otherwise returns 0.\r\n * @param price - The price to check against the tax rule.\r\n * @returns The applicable tax rate as a decimal (e.g., 0.18 for 18%).\r\n */\r\n getApplicableTaxRate(price: PriceModel): number {\r\n if(this.appliesTo(this.taxCategory, this.country, price)) {\r\n return this.rate;\r\n }\r\n return 0;\r\n }\r\n\r\n /**\r\n * Calculates the tax amount for a given taxable amount.\r\n * @param price - The price used to determine the tax amount.\r\n * @returns The calculated tax amount as a PriceModel. Returns zero if the tax rule does not apply.\r\n */\r\n calculateTax(price: PriceModel): PriceModel {\r\n if(!this.appliesTo(this.taxCategory, this.country, price)) {\r\n return price.zero(); // Return zero tax if the rule does not apply\r\n }\r\n\r\n return price.multiply(this.rate).round();\r\n }\r\n\r\n\r\n static getTaxRateDisplayString(taxRule: TaxRuleModel, rate: number, formateOption?: {\r\n percentageOnly?: boolean;\r\n }): string {\r\n const percentage = rate * 100;\r\n // Format to remove trailing zeros if it's an integer, otherwise keep up to 2 decimal places\r\n const rateStr = percentage % 1 === 0 ? percentage.toString() : percentage.toFixed(2).replace(/\\.?0+$/, '');\r\n\r\n if (formateOption?.percentageOnly) {\r\n return `${rateStr}%`;\r\n }\r\n\r\n if (taxRule.getTaxSystem() === TaxSystem.GST) {\r\n return `${taxRule.getTaxSubSystem()} ${rateStr}%`;\r\n }\r\n return `${taxRule.getTaxSystem()} ${rateStr}%`;\r\n }\r\n}\r\n\r\n"]}
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
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;
|
|
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 B=new Uint8Array(256),V=B.length;function k(){return V>B.length-16&&(le__default.default.randomFillSync(B),V=0),B.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 z(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 z(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 z(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 K=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";}},b=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";}},P=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 T=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 P("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 P("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 P("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 P("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 P("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 P("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 P("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 J(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 b("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;if(this.baseUnitPrice.isZero()||t[0]?.unitPrice.isZero())throw new b("Base unit price and tier unit price must not be zero.");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 b("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()}))}}},J=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 b("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;if(i.isZero()||n[0]?.unitPrice.isZero())throw new b("Base unit price and tier unit price must not be zero.");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 b("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 b("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 T("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 T("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 T("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 T("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 T("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 T("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 T("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 K(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
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
|