b23-lib 2.0.17 → 2.0.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Auth/index.js +1 -1
- package/dist/Auth/index.js.map +1 -1
- package/dist/Auth/index.mjs +1 -1
- package/dist/Classes/Address.d.mts +1 -1
- package/dist/Classes/Address.d.ts +1 -1
- package/dist/Classes/Base.d.mts +1 -1
- package/dist/Classes/Base.d.ts +1 -1
- package/dist/Classes/Cart.d.mts +1 -1
- package/dist/Classes/Cart.d.ts +1 -1
- package/dist/Classes/Cart.js +1 -1
- package/dist/Classes/Cart.js.map +1 -1
- package/dist/Classes/Cart.mjs +1 -1
- package/dist/Classes/Common.d.mts +1 -1
- package/dist/Classes/Common.d.ts +1 -1
- package/dist/Classes/Coupon.d.mts +1 -1
- package/dist/Classes/Coupon.d.ts +1 -1
- package/dist/Classes/Coupon.js +1 -1
- package/dist/Classes/Coupon.js.map +1 -1
- package/dist/Classes/Coupon.mjs +1 -1
- package/dist/Classes/Customer.d.mts +1 -1
- package/dist/Classes/Customer.d.ts +1 -1
- package/dist/Classes/CustomerAddress.d.mts +1 -1
- package/dist/Classes/CustomerAddress.d.ts +1 -1
- package/dist/Classes/Inventory.d.mts +1 -1
- package/dist/Classes/Inventory.d.ts +1 -1
- package/dist/Classes/Inventory.js +1 -1
- package/dist/Classes/Inventory.js.map +1 -1
- package/dist/Classes/Inventory.mjs +1 -1
- package/dist/Classes/LineItem.d.mts +1 -1
- package/dist/Classes/LineItem.d.ts +1 -1
- package/dist/Classes/LineItem.js +1 -1
- package/dist/Classes/LineItem.js.map +1 -1
- package/dist/Classes/LineItem.mjs +1 -1
- package/dist/Classes/Order.d.mts +1 -1
- package/dist/Classes/Order.d.ts +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/Payment.d.mts +1 -1
- package/dist/Classes/Payment.d.ts +1 -1
- package/dist/Classes/Price.d.mts +1 -1
- package/dist/Classes/Price.d.ts +1 -1
- package/dist/Classes/Price.js +1 -1
- package/dist/Classes/Price.js.map +1 -1
- package/dist/Classes/Price.mjs +1 -1
- package/dist/Classes/Product.d.mts +1 -1
- package/dist/Classes/Product.d.ts +1 -1
- package/dist/Classes/Product.js +1 -1
- package/dist/Classes/Product.js.map +1 -1
- package/dist/Classes/Product.mjs +1 -1
- package/dist/Classes/ShoppingContainer.d.mts +1 -1
- package/dist/Classes/ShoppingContainer.d.ts +1 -1
- package/dist/Classes/ShoppingContainer.js +1 -1
- package/dist/Classes/ShoppingContainer.js.map +1 -1
- package/dist/Classes/ShoppingContainer.mjs +1 -1
- package/dist/Classes/TaxRule.d.mts +1 -1
- package/dist/Classes/TaxRule.d.ts +1 -1
- package/dist/Classes/TaxRule.js +1 -1
- package/dist/Classes/TaxRule.js.map +1 -1
- package/dist/Classes/TaxRule.mjs +1 -1
- package/dist/Classes/TieredPrice.d.mts +1 -1
- package/dist/Classes/TieredPrice.d.ts +1 -1
- package/dist/Classes/TieredPrice.js +1 -1
- package/dist/Classes/TieredPrice.js.map +1 -1
- package/dist/Classes/TieredPrice.mjs +1 -1
- package/dist/{Common-5lGZCX-j.d.mts → Common-Bd8Xv8x4.d.mts} +3 -0
- package/dist/{Common-C6bnAhuf.d.ts → Common-CXp_zjft.d.ts} +3 -0
- package/dist/{chunk-ZHUEVC3L.mjs → chunk-5PVVYTQ2.mjs} +2 -2
- package/dist/chunk-5PVVYTQ2.mjs.map +1 -0
- package/dist/{chunk-KGCBP35B.mjs → chunk-I3IWW4V2.mjs} +2 -2
- package/dist/{chunk-KGCBP35B.mjs.map → chunk-I3IWW4V2.mjs.map} +1 -1
- package/dist/{chunk-G5ZDSYCU.mjs → chunk-K6Q6YDUX.mjs} +2 -2
- package/dist/{chunk-G5ZDSYCU.mjs.map → chunk-K6Q6YDUX.mjs.map} +1 -1
- package/dist/chunk-R32ZSPV6.mjs +2 -0
- package/dist/chunk-R32ZSPV6.mjs.map +1 -0
- package/dist/{chunk-WEXGU2UL.mjs → chunk-U5CHHGFX.mjs} +2 -2
- package/dist/{chunk-WEXGU2UL.mjs.map → chunk-U5CHHGFX.mjs.map} +1 -1
- package/dist/{chunk-PE55IHCY.mjs → chunk-U6I3CMOB.mjs} +2 -2
- package/dist/chunk-U6I3CMOB.mjs.map +1 -0
- package/dist/{chunk-3ZEYSNQ4.mjs → chunk-ZVLJ5BAG.mjs} +2 -2
- package/dist/{chunk-3ZEYSNQ4.mjs.map → chunk-ZVLJ5BAG.mjs.map} +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.d.ts +1 -1
- 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-5I6SCJMC.mjs +0 -2
- package/dist/chunk-5I6SCJMC.mjs.map +0 -1
- package/dist/chunk-PE55IHCY.mjs.map +0 -1
- package/dist/chunk-ZHUEVC3L.mjs.map +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a as a$3}from'./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {a as a$3}from'./chunk-U5CHHGFX.mjs';import {a}from'./chunk-K6Q6YDUX.mjs';import {a as a$2}from'./chunk-ZVLJ5BAG.mjs';import {a as a$1}from'./chunk-R32ZSPV6.mjs';import {e}from'./chunk-72DR3HF2.mjs';import {b}from'./chunk-7LEGYAOJ.mjs';import {b as b$1,d,e as e$1,g,h,i}from'./chunk-DGFO2MH6.mjs';var p=class{id;productKey;selectionAttributes;name;specifications;primaryImage;subItems;pricing;state;total;constructor(t){this.id=t.id,this.productKey=t.productKey,this.selectionAttributes=a.deepClone(t.selectionAttributes),this.name=a.deepClone(t.name),this.specifications=a.deepClone(t.specifications),this.primaryImage=new b(t.primaryImage),this.subItems=a.deepClone(t.subItems);let i=new Set;this.subItems.forEach(e=>{if(i.has(e.size))throw new b$1(e.size);i.add(e.size);}),this.pricing={unitPrice:new a$1(t.pricing.unitPrice),tierPricing:new a$2(t.pricing.tierPricing),taxCategory:t.pricing.taxCategory,tax:{taxRuleId:t.pricing.tax.taxRuleId,taxSystem:t.pricing.tax.taxSystem,country:t.pricing.tax.country,rate:t.pricing.tax.rate,taxSlabs:t.pricing.tax.taxSlabs.map(e=>({rate:e.rate,minUnitPrice:new a$1(e.minUnitPrice),maxUnitPrice:e.maxUnitPrice?new a$1(e.maxUnitPrice):void 0}))}},this.state=t.state??"INITIAL",this.total={quantity:t.total.quantity,subtotal:new a$1(t.total.subtotal),discounts:Object.fromEntries(Object.entries(t.total.discounts).map(([e,a])=>[e,new a$1(a)])),taxableAmount:new a$1(t.total.taxableAmount),taxTotal:new a$1(t.total.taxTotal),grandTotal:new a$1(t.total.grandTotal)};}getId(){return this.id}getProductKey(){return this.productKey}getSelectionAttributes(){return a.deepClone(this.selectionAttributes)}getName(t){return t?a.deepClone(this.name[t]??this.name[e[t]]??this.name.en):a.deepClone(this.name)}getSpecifications(t){return t?a.deepClone(this.specifications[t]??this.specifications[e[t]]??this.specifications.en):a.deepClone(this.specifications)}getImage(){return this.primaryImage}getSubItems(){return a.deepClone(this.subItems)}getTotalQuantity(){return this.total.quantity}getPricing(){return {unitPrice:this.pricing.unitPrice,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,tax:{taxRuleId:this.pricing.tax.taxRuleId,taxSystem:this.pricing.tax.taxSystem,country:this.pricing.tax.country,rate:this.pricing.tax.rate,taxSlabs:this.pricing.tax.taxSlabs}}}getState(){return this.state}getTotal(){return {quantity:this.total.quantity,subtotal:this.total.subtotal,taxableAmount:this.total.taxableAmount,taxTotal:this.total.taxTotal,discounts:Object.fromEntries(Object.entries(this.total.discounts).map(([t,i])=>[t,i])),grandTotal:this.total.grandTotal}}getDetails(){return {id:this.getId(),productKey:this.getProductKey(),selectionAttributes:this.getSelectionAttributes(),name:this.getName(),specifications:this.getSpecifications(),primaryImage:this.getImage().getDetails(),subItems:this.getSubItems(),pricing:{unitPrice:this.getPricing().unitPrice.getDetails(),tierPricing:this.getPricing().tierPricing.getDetails(),taxCategory:this.getPricing().taxCategory,tax:{taxRuleId:this.getPricing().tax.taxRuleId,taxSystem:this.getPricing().tax.taxSystem,country:this.getPricing().tax.country,rate:this.getPricing().tax.rate,taxSlabs:this.getPricing().tax.taxSlabs.map(t=>({rate:t.rate,minUnitPrice:t.minUnitPrice.getDetails(),maxUnitPrice:t.maxUnitPrice?t.maxUnitPrice.getDetails():void 0}))}},state:this.getState(),total:{quantity:this.getTotal().quantity,subtotal:this.getTotal().subtotal.getDetails(),taxableAmount:this.getTotal().taxableAmount.getDetails(),taxTotal:this.getTotal().taxTotal.getDetails(),discounts:Object.fromEntries(Object.entries(this.getTotal().discounts).map(([t,i])=>[t,i.getDetails()])),grandTotal:this.getTotal().grandTotal.getDetails()}}}addSubItems(t,i){t.forEach(e=>{let a=this.subItems.find(n=>n.size===e.size);a?a.quantity=i?a.quantity+e.quantity:e.quantity:this.subItems.push(e);}),this.subItems=this.subItems.filter(e=>e.quantity>=0),this.calculateTotals();}updateProductData(t,i,e){if(this.productKey!==t.getKey()||!t.validateSelectionAttribute(this.selectionAttributes))throw new d;if(!t.getIsActive())throw new e$1;this.subItems.forEach(c=>{if(!t.validateSize(c.size))throw new g});let a=t.getPriceDetails(i);if(!a||a.getBaseUnitPrice().getCurrency()!==e)throw new h;this.name=t.getName(),this.specifications=t.getSpecifications(),this.primaryImage=t.getImages(this.selectionAttributes).primary;let n=this.subItems.reduce((c,l)=>c+l.quantity,0),{unitPrice:s}=a.getApplicableTier(n);this.pricing={unitPrice:s,tierPricing:a,taxCategory:a.getTaxCategory(),tax:this.pricing.tax},this.calculateTotals();}updateDiscounts(t){let i={};t.forEach(e=>{i[e.coupon.getCode()]=e.amount;}),this.total.discounts=i,this.calculateTotals();}updateTax(t){if(!t.appliesTo(this.pricing.taxCategory,this.pricing.tax.country))throw new i;let i$1=this.total.quantity>0?this.total.taxableAmount.divide(this.total.quantity):this.total.taxableAmount.zero();this.pricing.tax={taxRuleId:t.getTaxRuleId(),taxSystem:t.getTaxSystem(),country:t.getCountry(),rate:t.getApplicableTaxRate(i$1),taxSlabs:t.getSlabs()},this.calculateTotals();}calculateTotals(){let t=this.pricing.unitPrice.zero(),i=this.subItems.reduce((u,g)=>u+g.quantity,0),{unitPrice:e}=this.pricing.tierPricing.getApplicableTier(i),a=e.multiply(i),n=Object.values(this.total.discounts).reduce((u,g)=>u.add(g),t),s=a.subtract(n),c=i>0?s.divide(i):t,l=a$3.getApplicableTaxRate(c,this.pricing.tax.taxSlabs),h=s.multiply(l).round(),C=a.subtract(n).add(h);this.total={quantity:i,subtotal:a,taxableAmount:s,taxTotal:h,discounts:this.total.discounts,grandTotal:C};}clearLineItem(){let t=this.pricing.unitPrice.zero();this.id="",this.productKey="",this.selectionAttributes={color:{name:""}},this.name={en:""},this.primaryImage=new b({sources:{original:""}}),this.subItems=[],this.pricing={unitPrice:t,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,tax:this.pricing.tax},this.total={quantity:0,subtotal:t,taxableAmount:t,taxTotal:t,discounts:{},grandTotal:t};}};export{p as a};//# sourceMappingURL=chunk-U6I3CMOB.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-U6I3CMOB.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/Classes/LineItem.ts"],"names":["LineItemModel","data","Utils_default","ImageInfoModel","uniqueSelectionAttributes","item","DuplicateSizeError","PriceModel","TieredPriceModel","s","couponCode","discount","locale","LocaleLanguageMap","subItems","addQuantity","subItem","existingSubItem","sub","product","cartCountry","cartCurrency","ProductMismatchError","ProductInactiveError","SizeMismatchError","productPricing","PricingNotFoundError","quantity","sum","unitPrice","appliedDiscounts","lineItemDiscounts","taxRule","InvalidTaxRuleError","taxableUnitPrice","zero","totalQuantity","subTotal","discounts","taxableAmount","unitTaxbleAmount","taxRate","TaxRuleModel","taxTotal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AA,CAAK,OAAQ,CAAA,GACpB,EACA,IAAK,CAAA,KAAA,CAAQ,CACX,QAAA,CAAU,CACV,CAAA,QAAA,CAAUA,CACV,CAAA,aAAA,CAAeA,CACf,CAAA,QAAA,CAAUA,CACV,CAAA,SAAA,CAAW,EAAC,CACZ,UAAYA,CAAAA,CACd,EACF,CACF","file":"chunk-U6I3CMOB.mjs","sourcesContent":["import Utils from \"../Utils\";\r\nimport { Color, CountryCode, CurrencyCode, LocaleCode, LocalizedString, LocalizedValue } from \"./Common\";\r\nimport CouponModel from \"./Coupon\";\r\nimport { LineItemState, LocaleLanguageMap, TaxCategory, TaxSystem } from \"./Enum\";\r\nimport ImageInfoModel, { ImageInfoData } from \"./ImageInfo\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport ProductModel, { ProductSelectionAttributes, ProductSpecification, SelectionAttributes } from \"./Product\";\r\nimport { TaxRuleModel, TaxSlabModel, TaxSlabs } from \"./TaxRule\";\r\nimport { TieredPriceData, TieredPriceModel } from \"./TieredPrice\";\r\nimport {\r\n DuplicateSizeError,\r\n ProductMismatchError,\r\n ProductInactiveError,\r\n SizeMismatchError,\r\n PricingNotFoundError,\r\n InvalidTaxRuleError\r\n} from \"./Error\";\r\n\r\nexport type SubItem = {\r\n size: string | 'ONESIZE';\r\n quantity: number;\r\n};\r\n\r\nexport type LineItemPricing = {\r\n unitPrice: PriceData;\r\n tierPricing: TieredPriceData;\r\n taxCategory: TaxCategory;\r\n tax: {\r\n taxRuleId: string;\r\n taxSystem: TaxSystem;\r\n country: CountryCode;\r\n rate: number;\r\n taxSlabs: TaxSlabs;\r\n };\r\n};\r\n\r\nexport type LineItemTotals = {\r\n quantity: number;\r\n subtotal: PriceData;\r\n discounts: Record<string, PriceData>; // couponCode -> discount mapping\r\n taxableAmount: PriceData; // subtotal - discount\r\n taxTotal: PriceData;\r\n grandTotal: PriceData;\r\n};\r\n\r\nexport type LineItemAttributes = {\r\n id: string;\r\n\r\n productKey: string;\r\n selectionAttributes: SelectionAttributes;\r\n\r\n name: LocalizedString;\r\n specifications: LocalizedValue<ProductSpecification>;\r\n primaryImage: ImageInfoData;\r\n\r\n subItems: SubItem[];\r\n\r\n pricing: LineItemPricing;\r\n\r\n state?: LineItemState;\r\n total: LineItemTotals;\r\n}\r\n\r\nexport type LineItemData = Required<LineItemAttributes>;\r\n\r\n/**\r\n * Represents a line item within a shopping cart.\r\n */\r\nexport default class LineItemModel {\r\n protected id: string;\r\n protected productKey: string;\r\n protected selectionAttributes: SelectionAttributes;\r\n\r\n protected name: LocalizedString;\r\n protected specifications: LocalizedValue<ProductSpecification>;\r\n protected primaryImage: ImageInfoModel;\r\n protected subItems: SubItem[];\r\n protected pricing: {\r\n unitPrice: PriceModel;\r\n tierPricing: TieredPriceModel;\r\n taxCategory: TaxCategory;\r\n tax: {\r\n taxRuleId: string;\r\n taxSystem: TaxSystem;\r\n country: CountryCode;\r\n taxSlabs: TaxSlabModel[];\r\n rate: number;\r\n };\r\n };\r\n\r\n protected state: LineItemState;\r\n protected total: {\r\n quantity: number;\r\n subtotal: PriceModel;\r\n discounts: Record<string, PriceModel>;\r\n taxableAmount: PriceModel; // subtotal - discount\r\n\r\n taxTotal: PriceModel;\r\n grandTotal: PriceModel;\r\n };\r\n\r\n /**\r\n * Creates an instance of LineItemModel.\r\n * @param data - The initial line item attributes.\r\n */\r\n constructor(data: LineItemAttributes) {\r\n this.id = data.id;\r\n this.productKey = data.productKey;\r\n this.selectionAttributes = Utils.deepClone(data.selectionAttributes);\r\n\r\n this.name = Utils.deepClone(data.name);\r\n this.specifications = Utils.deepClone(data.specifications);\r\n this.primaryImage = new ImageInfoModel(data.primaryImage);\r\n this.subItems = Utils.deepClone(data.subItems);\r\n\r\n let uniqueSelectionAttributes = new Set();\r\n this.subItems.forEach(item => {\r\n if (uniqueSelectionAttributes.has(item.size)) {\r\n throw new DuplicateSizeError(item.size);\r\n }\r\n uniqueSelectionAttributes.add(item.size);\r\n });\r\n\r\n this.pricing = {\r\n unitPrice: new PriceModel(data.pricing.unitPrice),\r\n tierPricing: new TieredPriceModel(data.pricing.tierPricing),\r\n taxCategory: data.pricing.taxCategory,\r\n tax: {\r\n taxRuleId: data.pricing.tax.taxRuleId,\r\n taxSystem: data.pricing.tax.taxSystem,\r\n country: data.pricing.tax.country,\r\n rate: data.pricing.tax.rate,\r\n taxSlabs: data.pricing.tax.taxSlabs.map(s => ({\r\n rate: s.rate,\r\n minUnitPrice: new PriceModel(s.minUnitPrice),\r\n maxUnitPrice: s.maxUnitPrice ? new PriceModel(s.maxUnitPrice) : undefined,\r\n })),\r\n },\r\n }\r\n\r\n this.state = data.state ?? LineItemState.INITIAL;\r\n\r\n this.total = {\r\n quantity: data.total.quantity,\r\n subtotal: new PriceModel(data.total.subtotal),\r\n discounts: Object.fromEntries(\r\n Object.entries(data.total.discounts).map(([couponCode, discount]) => [\r\n couponCode,\r\n new PriceModel(discount),\r\n ])\r\n ),\r\n taxableAmount: new PriceModel(data.total.taxableAmount),\r\n taxTotal: new PriceModel(data.total.taxTotal),\r\n grandTotal: new PriceModel(data.total.grandTotal),\r\n }\r\n }\r\n\r\n /**\r\n * Gets the unique identifier of the line item.\r\n * @returns The unique ID string.\r\n */\r\n getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the product key associated with this line item.\r\n * @returns The product key string.\r\n */\r\n getProductKey(): string {\r\n return this.productKey;\r\n }\r\n\r\n /**\r\n * Gets the selection attributes (e.g., size, color) for this line item.\r\n * @returns A copy of the selection attributes object.\r\n */\r\n getSelectionAttributes(): SelectionAttributes {\r\n return Utils.deepClone(this.selectionAttributes);\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 Utils.deepClone(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 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 | undefined\r\n getSpecifications(locale?: LocaleCode): LocalizedValue<ProductSpecification> | ProductSpecification | undefined {\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 image information model for this line item.\r\n * @returns The ImageInfoModel instance.\r\n */\r\n getImage(): ImageInfoModel {\r\n return this.primaryImage;\r\n }\r\n\r\n /**\r\n * Gets the sub-items (size/quantity breakdown).\r\n * @returns A copy of the array of SubItems.\r\n */\r\n getSubItems(): SubItem[] {\r\n return Utils.deepClone(this.subItems);\r\n }\r\n\r\n /**\r\n * Gets the total quantity for this line item across all sub-items.\r\n * @returns The total quantity as a number.\r\n */\r\n getTotalQuantity(): number {\r\n return this.total.quantity;\r\n }\r\n\r\n /**\r\n * Gets the pricing information model for this line item.\r\n * @returns An object containing unit price, tiered pricing, tax category, and tax details.\r\n */\r\n getPricing() {\r\n return {\r\n unitPrice: this.pricing.unitPrice,\r\n tierPricing: this.pricing.tierPricing,\r\n taxCategory: this.pricing.taxCategory,\r\n tax: {\r\n taxRuleId: this.pricing.tax.taxRuleId,\r\n taxSystem: this.pricing.tax.taxSystem,\r\n country: this.pricing.tax.country,\r\n rate: this.pricing.tax.rate,\r\n taxSlabs: this.pricing.tax.taxSlabs,\r\n }\r\n };\r\n }\r\n\r\n /**\r\n * Gets the current state of the line item.\r\n * @returns The LineItemState enum value.\r\n */\r\n getState() {\r\n return this.state;\r\n }\r\n\r\n /**\r\n * Gets the total price for this line item (including all sub-items).\r\n * @returns An object containing line item totals including subtotal, tax, discounts, and grand total.\r\n */\r\n getTotal() {\r\n return {\r\n quantity: this.total.quantity,\r\n subtotal: this.total.subtotal,\r\n taxableAmount: this.total.taxableAmount,\r\n taxTotal: this.total.taxTotal,\r\n discounts: Object.fromEntries(\r\n Object.entries(this.total.discounts).map(([couponCode, discount]) => [\r\n couponCode,\r\n discount,\r\n ])\r\n ),\r\n grandTotal: this.total.grandTotal,\r\n };\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the line item's details.\r\n * @returns LineItemData.\r\n */\r\n getDetails(): LineItemData {\r\n return {\r\n id: this.getId(),\r\n productKey: this.getProductKey(),\r\n selectionAttributes: this.getSelectionAttributes(),\r\n name: this.getName(),\r\n specifications: this.getSpecifications(),\r\n primaryImage: this.getImage().getDetails(),\r\n subItems: this.getSubItems(),\r\n pricing: {\r\n unitPrice: this.getPricing().unitPrice.getDetails(),\r\n tierPricing: this.getPricing().tierPricing.getDetails(),\r\n taxCategory: this.getPricing().taxCategory,\r\n tax: {\r\n taxRuleId: this.getPricing().tax.taxRuleId,\r\n taxSystem: this.getPricing().tax.taxSystem,\r\n country: this.getPricing().tax.country,\r\n rate: this.getPricing().tax.rate,\r\n taxSlabs: this.getPricing().tax.taxSlabs.map(s => ({\r\n rate: s.rate,\r\n minUnitPrice: s.minUnitPrice.getDetails(),\r\n maxUnitPrice: s.maxUnitPrice ? s.maxUnitPrice.getDetails() : undefined,\r\n })),\r\n }\r\n },\r\n state: this.getState(),\r\n total: {\r\n quantity: this.getTotal().quantity,\r\n subtotal: this.getTotal().subtotal.getDetails(),\r\n taxableAmount: this.getTotal().taxableAmount.getDetails(),\r\n taxTotal: this.getTotal().taxTotal.getDetails(),\r\n discounts: Object.fromEntries(\r\n Object.entries(this.getTotal().discounts).map(([couponCode, discount]) => [\r\n couponCode,\r\n discount.getDetails(),\r\n ])\r\n ),\r\n grandTotal: this.getTotal().grandTotal.getDetails(),\r\n }\r\n };\r\n }\r\n\r\n /**\r\n * Adds or updates sub-items (e.g., sizes with quantities) to the line item.\r\n * If a sub-item with the same size already exists, its quantity is either\r\n * updated by adding the new quantity or replaced entirely, based on the `addQuantity` flag.\r\n * Sub-items with a resulting quantity of 0 are removed.\r\n * @param subItems - An array of `SubItem` objects to add or update.\r\n * @param addQuantity - If true, adds the quantity from `subItem` to the existing quantity.\r\n * If false, replaces the existing quantity with the one from `subItem`.\r\n */\r\n addSubItems(subItems: SubItem[], addQuantity: boolean): void {\r\n subItems.forEach(subItem => {\r\n const existingSubItem = this.subItems.find(item => item.size === subItem.size);\r\n if (existingSubItem) {\r\n existingSubItem.quantity = addQuantity ? existingSubItem.quantity + subItem.quantity : subItem.quantity;\r\n } else {\r\n this.subItems.push(subItem);\r\n }\r\n })\r\n this.subItems = this.subItems.filter(sub => sub.quantity >= 0);\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Updates the line item with the latest product data (price, image, name, specifications).\r\n * Validates that the product matches the line item's selection and is active.\r\n * @param product - The product model to update from.\r\n * @param cartCountry - The country code for pricing context.\r\n * @param cartCurrency - The currency code for pricing context.\r\n * @throws {Error} If product mismatch, inactive, size mismatch, or pricing missing.\r\n */\r\n public updateProductData(product: ProductModel, cartCountry: CountryCode, cartCurrency: CurrencyCode): void {\r\n if (this.productKey !== product.getKey() || !product.validateSelectionAttribute(this.selectionAttributes)) {\r\n throw new ProductMismatchError();\r\n } else if (!product.getIsActive()) {\r\n throw new ProductInactiveError();\r\n }\r\n\r\n this.subItems.forEach(subItem => {\r\n if (!product.validateSize(subItem.size)) {\r\n throw new SizeMismatchError();\r\n }\r\n });\r\n\r\n const productPricing = product.getPriceDetails(cartCountry);\r\n if (!productPricing || productPricing.getBaseUnitPrice().getCurrency() !== cartCurrency) {\r\n throw new PricingNotFoundError();\r\n }\r\n this.name = product.getName();\r\n this.specifications = product.getSpecifications();\r\n this.primaryImage = product.getImages(this.selectionAttributes).primary;\r\n\r\n const quantity = this.subItems.reduce((sum, s) => sum + s.quantity, 0);\r\n const { unitPrice } = productPricing.getApplicableTier(quantity);\r\n\r\n this.pricing = {\r\n unitPrice: unitPrice,\r\n tierPricing: productPricing,\r\n taxCategory: productPricing.getTaxCategory(),\r\n tax: this.pricing.tax\r\n }\r\n\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Updates the discounts applied to this line item and recalculates totals.\r\n * @param appliedDiscounts - List of coupons and their allocated discount amounts.\r\n */\r\n public updateDiscounts(appliedDiscounts: { coupon: CouponModel, amount: PriceModel }[]): void {\r\n let lineItemDiscounts = {} as Record<string, PriceModel>;\r\n appliedDiscounts.forEach(discount => {\r\n lineItemDiscounts[discount.coupon.getCode()] = discount.amount;\r\n });\r\n\r\n this.total.discounts = lineItemDiscounts;\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Updates the tax rule for this line item and recalculates totals.\r\n * @param taxRule - The new tax rule to apply.\r\n * @throws {Error} If the tax rule category does not match the item's tax category.\r\n */\r\n public updateTax(taxRule: TaxRuleModel): void {\r\n if (!taxRule.appliesTo(this.pricing.taxCategory, this.pricing.tax.country)) {\r\n throw new InvalidTaxRuleError();\r\n }\r\n\r\n const taxableUnitPrice = this.total.quantity > 0 ? \r\n this.total.taxableAmount.divide(this.total.quantity) \r\n : \r\n this.total.taxableAmount.zero();\r\n\r\n this.pricing.tax = {\r\n taxRuleId: taxRule.getTaxRuleId(),\r\n taxSystem: taxRule.getTaxSystem(),\r\n country: taxRule.getCountry(),\r\n rate: taxRule.getApplicableTaxRate(taxableUnitPrice),\r\n taxSlabs: taxRule.getSlabs(),\r\n };\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Recalculates the line item totals based on current quantity, unit price, discounts, and tax rates.\r\n */\r\n public calculateTotals(): void {\r\n const zero = this.pricing.unitPrice.zero();\r\n const totalQuantity = this.subItems.reduce((sum, s) => sum + s.quantity, 0);\r\n const { unitPrice } = this.pricing.tierPricing.getApplicableTier(totalQuantity);\r\n const subTotal = unitPrice.multiply(totalQuantity);\r\n const discounts = Object.values(this.total.discounts).reduce((sum, s) => sum.add(s), zero);\r\n const taxableAmount = subTotal.subtract(discounts);\r\n const unitTaxbleAmount = totalQuantity > 0 ? taxableAmount.divide(totalQuantity) : zero;\r\n const taxRate = TaxRuleModel.getApplicableTaxRate(unitTaxbleAmount, this.pricing.tax.taxSlabs);\r\n const taxTotal = taxableAmount.multiply(taxRate).round();\r\n const grandTotal = subTotal.subtract(discounts).add(taxTotal);\r\n\r\n this.total = {\r\n quantity: totalQuantity,\r\n subtotal: subTotal,\r\n taxableAmount: taxableAmount,\r\n taxTotal: taxTotal,\r\n discounts: this.total.discounts,\r\n grandTotal: grandTotal\r\n }\r\n }\r\n\r\n /**\r\n * Resets the line item's properties to their default empty or initial state.\r\n * Useful for clearing out line item data without creating a new instance.\r\n * Recalculates total quantity and price total afterwards (which will be zero).\r\n */\r\n clearLineItem(): void {\r\n const zero = this.pricing.unitPrice.zero()\r\n this.id = '';\r\n this.productKey = '';\r\n this.selectionAttributes = { color: { name: '' } };\r\n this.name = { en: '' };\r\n this.primaryImage = new ImageInfoModel({ sources: { original: '' } });\r\n this.subItems = [];\r\n this.pricing = {\r\n unitPrice: zero,\r\n tierPricing: this.pricing.tierPricing,\r\n taxCategory: this.pricing.taxCategory,\r\n tax: this.pricing.tax\r\n }\r\n this.total = {\r\n quantity: 0,\r\n subtotal: zero,\r\n taxableAmount: zero,\r\n taxTotal: zero,\r\n discounts: {},\r\n grandTotal: zero\r\n };\r\n }\r\n}"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a}from'./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {a}from'./chunk-R32ZSPV6.mjs';import {j,k,l,m,n}from'./chunk-DGFO2MH6.mjs';var y=class{baseUnitPrice;taxCategory;tiers;constructor(t){let e=new a(t.baseUnitPrice);if(!t.taxCategory)throw new j;let r=(t.tiers??[]).map(i=>({minQuantity:i.minQuantity,unitPrice:new a(i.unitPrice)})).sort((i,n)=>i.minQuantity-n.minQuantity);if(r.some(i=>i.minQuantity<=0))throw new k;let m=r.some(i=>i.unitPrice.getCurrency()!==e.getCurrency()),g=r.some((i,n)=>n>0&&i.unitPrice.compareTo(r[n-1].unitPrice)>0),h=r[0]?.unitPrice.compareTo(e)>0;if(m||g||h)throw new l("Tiers must share the same currency and must not increase in unit price.");this.baseUnitPrice=e,this.taxCategory=t.taxCategory,this.tiers=r;}getBaseUnitPrice(){return this.baseUnitPrice}getTaxCategory(){return this.taxCategory}getTiers(){return this.tiers}getDetails(){return {baseUnitPrice:this.baseUnitPrice.getDetails(),taxCategory:this.taxCategory,tiers:this.tiers.map(t=>({minQuantity:t.minQuantity,unitPrice:t.unitPrice.getDetails()}))}}getApplicableTier(t){if(t<=0)throw new m;for(let e=this.tiers.length-1;e>=0;e--)if(t>=this.tiers[e].minQuantity)return this.tiers[e];throw new n(t)}getMinQuantity(){return this.tiers[0]?.minQuantity??1}getMaxDiscountPercent(){if(!this.tiers.length)return 0;let t=this.tiers[this.tiers.length-1].unitPrice.getAmount(),e=this.baseUnitPrice.getAmount();return (e-t)/e*100}};export{y as a};//# sourceMappingURL=chunk-ZVLJ5BAG.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-ZVLJ5BAG.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/Classes/TieredPrice.ts"],"names":["TieredPriceModel","data","baseUnitPrice","PriceModel","InvalidTaxCategoryError","tiers","tier","a","b","t","InvalidMinQuantityError","hasDifferentCurrency","hasIrregularPricing","index","basePriceExceedsFirstTier","InvalidTieredPriceError","quantity","InvalidQuantityError","i","NoApplicableTierError","lowestTierPrice","basePrice"],"mappings":"kFAkCaA,IAAAA,CAAAA,CAAN,KAAuB,CAClB,aACA,CAAA,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CAAU,SAAU,EAAA,CACxEC,CAAY,CAAA,IAAA,CAAK,aAAc,CAAA,SAAA,EAErC,CAAA,OAAA,CAASA,CAAYD,CAAAA,CAAAA,EAAmBC,CAAa,CAAA,GACvD,CACF","file":"chunk-
|
|
1
|
+
{"version":3,"sources":["../src/Classes/TieredPrice.ts"],"names":["TieredPriceModel","data","baseUnitPrice","PriceModel","InvalidTaxCategoryError","tiers","tier","a","b","t","InvalidMinQuantityError","hasDifferentCurrency","hasIrregularPricing","index","basePriceExceedsFirstTier","InvalidTieredPriceError","quantity","InvalidQuantityError","i","NoApplicableTierError","lowestTierPrice","basePrice"],"mappings":"kFAkCaA,IAAAA,CAAAA,CAAN,KAAuB,CAClB,aACA,CAAA,WAAA,CACA,KAWV,CAAA,WAAA,CAAYC,CAA6B,CAAA,CACvC,IAAMC,CAAAA,CAAgB,IAAIC,CAAAA,CAAWF,CAAK,CAAA,aAAa,CAEvD,CAAA,GAAI,CAACA,CAAAA,CAAK,WACR,CAAA,MAAM,IAAIG,CAAAA,CAGZ,IAAMC,CAAAA,CAAAA,CAASJ,CAAK,CAAA,KAAA,EAAS,EAAC,EAC3B,GAAIK,CAAAA,CAAAA,GAAS,CACZ,WAAA,CAAaA,CAAK,CAAA,WAAA,CAClB,SAAW,CAAA,IAAIH,CAAWG,CAAAA,CAAAA,CAAK,SAAS,CAC1C,CAAE,CAAA,CAAA,CACD,IAAK,CAAA,CAACC,CAAGC,CAAAA,CAAAA,GAAMD,CAAE,CAAA,WAAA,CAAcC,CAAE,CAAA,WAAW,CAG/C,CAAA,GAD8BH,CAAM,CAAA,IAAA,CAAKI,CAAKA,EAAAA,CAAAA,CAAE,WAAe,EAAA,CAAC,CAE9D,CAAA,MAAM,IAAIC,CAGZ,CAAA,IAAMC,CAAuBN,CAAAA,CAAAA,CAAM,IACjCI,CAAAA,CAAAA,EAAKA,CAAE,CAAA,SAAA,CAAU,WAAY,EAAA,GAAMP,CAAc,CAAA,WAAA,EACnD,CAAA,CACMU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,EAAA,IAAA,CAAK,KAAME,CAAAA,CAAC,CAAE,CAAA,WAAA,CAC5B,OAAO,IAAA,CAAK,KAAMA,CAAAA,CAAC,CAIvB,CAAA,MAAM,IAAIC,CAAAA,CAAsBH,CAAQ,CAC1C,CAKA,cAAA,EAAyB,CACvB,OAAO,IAAK,CAAA,KAAA,CAAM,CAAC,CAAA,EAAG,WAAe,EAAA,CACvC,CAKA,qBAAA,EAAgC,CAC9B,GAAI,CAAC,IAAA,CAAK,KAAM,CAAA,MAAA,CAAQ,OAAO,CAAA,CAE/B,IAAMI,CAAAA,CAAkB,IAAK,CAAA,KAAA,CAAM,IAAK,CAAA,KAAA,CAAM,MAAS,CAAA,CAAC,CAAE,CAAA,SAAA,CAAU,SAAU,EAAA,CACxEC,CAAY,CAAA,IAAA,CAAK,aAAc,CAAA,SAAA,EAErC,CAAA,OAAA,CAASA,CAAYD,CAAAA,CAAAA,EAAmBC,CAAa,CAAA,GACvD,CACF","file":"chunk-ZVLJ5BAG.mjs","sourcesContent":["import { TaxCategory } from \"./Enum\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport {\r\n InvalidTaxCategoryError,\r\n InvalidMinQuantityError,\r\n InvalidTieredPriceError,\r\n InvalidQuantityError,\r\n NoApplicableTierError\r\n} from \"./Error\";\r\n\r\n/**\r\n * Represents a pricing tier based on a minimum purchase quantity.\r\n */\r\nexport type PriceTier = {\r\n minQuantity: number;\r\n unitPrice: PriceModel;\r\n};\r\n\r\n/**\r\n * Represents the attributes required for tiered pricing.\r\n */\r\nexport type TieredPriceAttributes = {\r\n baseUnitPrice: PriceData;\r\n taxCategory: TaxCategory;\r\n\r\n /** Quantity-based pricing tiers */\r\n tiers: {\r\n minQuantity: number;\r\n unitPrice: PriceData;\r\n }[];\r\n};\r\n\r\nexport type TieredPriceData = TieredPriceAttributes;\r\n\r\nexport class TieredPriceModel {\r\n protected baseUnitPrice: PriceModel;\r\n protected taxCategory: TaxCategory;\r\n protected tiers: PriceTier[];\r\n\r\n /** Constructor\r\n * Initializes the tiered pricing model with the provided attributes.\r\n * @param data - The tiered pricing attributes.\r\n *\r\n * @throws {Error}\r\n * - If the tax category is not valid\r\n * - If any tier has an invalid minimum quantity or unit price\r\n * - If the base unit price is not valid\r\n */\r\n constructor(data: TieredPriceAttributes) {\r\n const baseUnitPrice = new PriceModel(data.baseUnitPrice);\r\n\r\n if (!data.taxCategory) {\r\n throw new InvalidTaxCategoryError();\r\n }\r\n\r\n const tiers = (data.tiers ?? [])\r\n .map(tier => ({\r\n minQuantity: tier.minQuantity,\r\n unitPrice: new PriceModel(tier.unitPrice),\r\n }))\r\n .sort((a, b) => a.minQuantity - b.minQuantity);\r\n\r\n const hasInvalidMinQuantity = tiers.some(t => t.minQuantity <= 0);\r\n if (hasInvalidMinQuantity) {\r\n throw new InvalidMinQuantityError();\r\n }\r\n\r\n const hasDifferentCurrency = tiers.some(\r\n t => t.unitPrice.getCurrency() !== baseUnitPrice.getCurrency()\r\n );\r\n const hasIrregularPricing = tiers.some(\r\n (tier, index) =>\r\n index > 0 &&\r\n tier.unitPrice.compareTo(tiers[index - 1].unitPrice) > 0\r\n );\r\n const basePriceExceedsFirstTier = tiers[0]?.unitPrice.compareTo(baseUnitPrice) > 0;\r\n\r\n if (hasDifferentCurrency || hasIrregularPricing || basePriceExceedsFirstTier) {\r\n throw new InvalidTieredPriceError(\r\n \"Tiers must share the same currency and must not increase in unit price.\"\r\n );\r\n }\r\n\r\n this.baseUnitPrice = baseUnitPrice;\r\n this.taxCategory = data.taxCategory;\r\n this.tiers = tiers;\r\n }\r\n\r\n /** \r\n * Returns the base unit price \r\n * @returns The base unit price as a PriceModel instance.\r\n */\r\n getBaseUnitPrice(): PriceModel {\r\n return this.baseUnitPrice;\r\n }\r\n\r\n /** \r\n * Returns the tax category \r\n * @returns The tax category as a TaxCategory enum value.\r\n */\r\n getTaxCategory(): TaxCategory {\r\n return this.taxCategory;\r\n }\r\n\r\n /** \r\n * Returns all pricing tiers sorted by minimum quantity \r\n * @returns An array of PriceTier objects.\r\n */\r\n getTiers(): readonly PriceTier[] {\r\n return this.tiers;\r\n }\r\n\r\n getDetails(): TieredPriceData {\r\n return {\r\n baseUnitPrice: this.baseUnitPrice.getDetails(),\r\n taxCategory: this.taxCategory,\r\n tiers: this.tiers.map(tier => ({\r\n minQuantity: tier.minQuantity,\r\n unitPrice: tier.unitPrice.getDetails()\r\n }))\r\n };\r\n }\r\n\r\n /**\r\n * Returns the applicable unit price for a given quantity.\r\n *\r\n * @param quantity - Purchase quantity\r\n * @returns The unit price for the highest applicable tier\r\n *\r\n * @throws {Error}\r\n * - If quantity is less than or equal to zero\r\n * - If quantity does not meet the minimum requirement of any tier\r\n */\r\n getApplicableTier(quantity: number): PriceTier {\r\n if (quantity <= 0) {\r\n throw new InvalidQuantityError();\r\n }\r\n\r\n for (let i = this.tiers.length - 1; i >= 0; i--) {\r\n if (quantity >= this.tiers[i].minQuantity) {\r\n return this.tiers[i];\r\n }\r\n }\r\n\r\n throw new NoApplicableTierError(quantity);\r\n }\r\n\r\n /**\r\n * Returns the minimum quantity required to purchase this product.\r\n */\r\n getMinQuantity(): number {\r\n return this.tiers[0]?.minQuantity ?? 1;\r\n }\r\n\r\n /**\r\n * Returns the maximum discount percentage achievable compared to the base unit price.\r\n */\r\n getMaxDiscountPercent(): number {\r\n if (!this.tiers.length) return 0;\r\n\r\n const lowestTierPrice = this.tiers[this.tiers.length - 1].unitPrice.getAmount();\r\n const basePrice = this.baseUnitPrice.getAmount();\r\n\r\n return ((basePrice - lowestTierPrice) / basePrice) * 100;\r\n }\r\n}\r\n"]}
|
package/dist/index.d.mts
CHANGED
|
@@ -2,7 +2,7 @@ import { TaxCategory, GenderCategory, OperationalCountry, OperationalCountryCurr
|
|
|
2
2
|
import { SelectionAttributes } from './Classes/Product.mjs';
|
|
3
3
|
import './Classes/Base.mjs';
|
|
4
4
|
import './Auth/index.mjs';
|
|
5
|
-
import './Common-
|
|
5
|
+
import './Common-Bd8Xv8x4.mjs';
|
|
6
6
|
import './Classes/ImageInfo.mjs';
|
|
7
7
|
import './Classes/TieredPrice.mjs';
|
|
8
8
|
|
package/dist/index.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { TaxCategory, GenderCategory, OperationalCountry, OperationalCountryCurr
|
|
|
2
2
|
import { SelectionAttributes } from './Classes/Product.js';
|
|
3
3
|
import './Classes/Base.js';
|
|
4
4
|
import './Auth/index.js';
|
|
5
|
-
import './Common-
|
|
5
|
+
import './Common-CXp_zjft.js';
|
|
6
6
|
import './Classes/ImageInfo.js';
|
|
7
7
|
import './Classes/TieredPrice.js';
|
|
8
8
|
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
'use strict';var ie=require('crypto'),he=require('util');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ie__default=/*#__PURE__*/_interopDefault(ie);var he__default=/*#__PURE__*/_interopDefault(he);var V=(e=>(e.IN="IN",e))(V||{}),D=(e=>(e.INR="INR",e))(D||{}),w=(t=>(t["en-IN"]="en-IN",t["kn-IN"]="kn-IN",t))(w||{}),L=(r=>(r.en="en",r.kn="kn",r))(L||{}),A={"en-IN":"en","kn-IN":"kn"};var W={INR:"\u20B9"},J={INR:"en-IN"},k=(l=>(l.MALE="Male",l.FEMALE="Female",l.UNISEX="Unisex",l.KIDS="Kids",l.BOY="Boy",l.GIRL="Girl",l.GENERAL="General",l))(k||{});var G=(r=>(r.APPAREL="apparel",r.EXEMPT="exempt",r))(G||{});var M=new Uint8Array(256),$=M.length;function j(){return $>M.length-16&&(ie__default.default.randomFillSync(M),$=0),M.slice($,$+=16)}var Z=/^(?:[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 ne(t){return typeof t=="string"&&Z.test(t)}var X=ne;var d=[];for(let t=0;t<256;++t)d.push((t+256).toString(16).slice(1));function R(t,e=0){return d[t[e+0]]+d[t[e+1]]+d[t[e+2]]+d[t[e+3]]+"-"+d[t[e+4]]+d[t[e+5]]+"-"+d[t[e+6]]+d[t[e+7]]+"-"+d[t[e+8]]+d[t[e+9]]+"-"+d[t[e+10]]+d[t[e+11]]+d[t[e+12]]+d[t[e+13]]+d[t[e+14]]+d[t[e+15]]}function se(t){if(!X(t))throw TypeError("Invalid UUID");let e,r=new Uint8Array(16);return r[0]=(e=parseInt(t.slice(0,8),16))>>>24,r[1]=e>>>16&255,r[2]=e>>>8&255,r[3]=e&255,r[4]=(e=parseInt(t.slice(9,13),16))>>>8,r[5]=e&255,r[6]=(e=parseInt(t.slice(14,18),16))>>>8,r[7]=e&255,r[8]=(e=parseInt(t.slice(19,23),16))>>>8,r[9]=e&255,r[10]=(e=parseInt(t.slice(24,36),16))/1099511627776&255,r[11]=e/4294967296&255,r[12]=e>>>24&255,r[13]=e>>>16&255,r[14]=e>>>8&255,r[15]=e&255,r}var ee=se;function oe(t){t=unescape(encodeURIComponent(t));let e=[];for(let r=0;r<t.length;++r)e.push(t.charCodeAt(r));return e}var ae="6ba7b810-9dad-11d1-80b4-00c04fd430c8",ce="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Y(t,e,r){function i(n,o,c,l){var s;if(typeof n=="string"&&(n=oe(n)),typeof o=="string"&&(o=ee(o)),((s=o)===null||s===void 0?void 0:s.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=r(u),u[6]=u[6]&15|e,u[8]=u[8]&63|128,c){l=l||0;for(let b=0;b<16;++b)c[l+b]=u[b];return c}return R(u)}try{i.name=t;}catch{}return i.DNS=ae,i.URL=ce,i}var q={randomUUID:ie__default.default.randomUUID};function le(t,e,r){if(q.randomUUID&&!e&&!t)return q.randomUUID();t=t||{};let i=t.random||(t.rng||j)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){r=r||0;for(let n=0;n<16;++n)e[r+n]=i[n];return e}return R(i)}var Q=le;function ge(t){return Array.isArray(t)?t=Buffer.from(t):typeof t=="string"&&(t=Buffer.from(t,"utf8")),ie__default.default.createHash("sha1").update(t).digest()}var te=ge;var pe=Y("v5",80,te),H=pe;var me={isUUID:t=>/^[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(t),isEmail:t=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(t),isURL:t=>/^(http|https):\/\/[^ "]+$/.test(t),generateUUID:(t,e)=>e&&t?H(t,e):Q(),generateSearchId:(t,e)=>`${t}#${h.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:t=>{let[e,r]=t.split("#");return {key:e,selectionAttributes:h.parseSelectionAttributesKey(r)}},deepClone(t){return structuredClone(t)}},g=me;var C=class{customFields;version;createdAt;modifiedAt;modifiedBy;constructor(e,r=new Date){this.customFields={...e.customFields},this.version=e.version??1,this.createdAt=e.createdAt&&!isNaN(Date.parse(e.createdAt))?new Date(e.createdAt).toISOString():r.toISOString(),this.modifiedAt=e.modifiedAt&&!isNaN(Date.parse(e.modifiedAt))?new Date(e.modifiedAt).toISOString():r.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,r,i,n){this.modifiedBy={id:e,authType:r,requestId:i,lambdaName:n};}getCustomField(e){return this.customFields[e]??null}setCustomField(e,r){this.customFields[e]=r;}getAllCustomFields(){return {...this.customFields}}};var O=class extends Error{constructor(e){super(`Duplicate selection attribute found: ${e}`),this.name="DuplicateSelectionAttributeError";}};var m=class extends Error{constructor(e="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${e}`),this.name="SelectionAttributeParseError";}};var v=class extends Error{constructor(e="Tax category is not valid."){super(`InvalidTaxCategory: ${e}`),this.name="InvalidTaxCategoryError";}},U=class extends Error{constructor(e="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${e}`),this.name="InvalidMinQuantityError";}},F=class extends Error{constructor(e){super(`InvalidTieredPrice: ${e}`),this.name="InvalidTieredPriceError";}},_=class extends Error{constructor(e="Quantity must be greater than zero."){super(`InvalidQuantity: ${e}`),this.name="InvalidQuantityError";}},z=class extends Error{constructor(e){super(`NoApplicableTier: Quantity ${e} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}};var E=class extends Error{constructor(e="Amount cannot be negative."){super(`InvalidAmount: ${e}`),this.name="InvalidPriceAmountError";}},x=class extends Error{constructor(e="Currency code is required."){super(`InvalidCurrency: ${e}`),this.name="InvalidCurrencyCodeError";}},y=class extends Error{constructor(e="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${e}`),this.name="CurrencyMismatchError";}},p=class extends Error{constructor(e){super(`InvalidArgument: ${e}`),this.name="InvalidArgumentError";}},P=class extends Error{constructor(e="Invalid image source configuration."){super(`InvalidImageSource: ${e}`),this.name="InvalidImageSourceError";}};var I=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 P("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,r){if(r===void 0){if(e==="original")throw new P("Cannot remove the 'original' image source.");delete this.sources[e];}else this.sources[e]=r;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var T=class t{amount;currency;constructor(e){if(e.amount<0)throw new E("Amount cannot be negative.");if(!e.currency)throw new x("Currency code is required.");this.amount=e.amount,this.currency=e.currency;}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}compareTo(e){if(e instanceof t){if(this.currency!==e.getCurrency())throw new y("Cannot compare prices in different currencies.")}else throw new p("Must be a PriceModel instance.");return this.amount-e.getAmount()}add(e){if(e instanceof t){if(this.currency!==e.getCurrency())throw new y("Cannot add prices in different currencies.")}else throw new p("Must be a PriceModel instance.");return new t({amount:this.amount+e.getAmount(),currency:this.currency})}subtract(e){if(e instanceof t){if(this.currency!==e.getCurrency())throw new y("Cannot subtract prices in different currencies.")}else throw new p("Must be a PriceModel instance.");return new t({amount:this.amount-e.getAmount(),currency:this.currency})}multiply(e){if(e instanceof t){if(this.currency!==e.getCurrency())throw new y("Cannot multiply prices in different currencies.");return new t({amount:this.amount*e.getAmount(),currency:this.currency})}else if(typeof e=="number"&&e>=0)return new t({amount:this.amount*e,currency:this.currency});throw new p("Must be a non-negative number.")}divide(e){if(e instanceof t){if(this.currency!==e.getCurrency())throw new y("Cannot divide prices in different currencies.");return new t({amount:this.amount/e.getAmount(),currency:this.currency})}else if(typeof e=="number"&&e>0)return new t({amount:this.amount/e,currency:this.currency});throw new p("Must be a positive number.")}min(...e){if(e.length===0)throw new p("Must provide at least one PriceModel.");return e.reduce((r,i)=>{if(i instanceof t){if(r.getCurrency()!==i.getCurrency())throw new y("Cannot compare prices in different currencies.")}else throw new p("Must be a PriceModel instance.");return r.compareTo(i)<0?r:i})}max(...e){if(e.length===0)throw new p("Must provide at least one PriceModel.");return e.reduce((r,i)=>{if(i instanceof t){if(r.getCurrency()!==i.getCurrency())throw new y("Cannot compare prices in different currencies.")}else throw new p("Must be a PriceModel instance.");return r.compareTo(i)>0?r:i})}zero(){return new t({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new t({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return t.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return t.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(e,r,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let n=J[r];if(!r||!n)throw new x("Invalid currency code for formatting.");let o=e,c=i.displayAsInteger?0:t.getDecimalPlaces(r),l={style:i.style??"currency",currency:r,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:c,maximumFractionDigits:c};i.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(n,l).format(o)}catch(s){return console.error(`Error formatting price for currency "${r}" and locale "${n}":`,s),`${W[r]??r} ${t.addThousandSeparators(o.toFixed(c))}`}}static getDecimalPlaces(e){switch(e){case"INR":default:return 2}}static addThousandSeparators(e){let r=e.split("."),i=r[0],n=r.length>1?"."+r[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+n}static getRoundedAmount(e,r){if(e<0)throw new E("Amount cannot be negative for rounding.");if(r===void 0)throw new x("Invalid currency code for rounding.");let i=t.getDecimalPlaces(r),n=Math.pow(10,i);return Math.round(e*n)/n}};var K=class{baseUnitPrice;taxCategory;tiers;constructor(e){let r=new T(e.baseUnitPrice);if(!e.taxCategory)throw new v;let i=(e.tiers??[]).map(s=>({minQuantity:s.minQuantity,unitPrice:new T(s.unitPrice)})).sort((s,u)=>s.minQuantity-u.minQuantity);if(i.some(s=>s.minQuantity<=0))throw new U;let o=i.some(s=>s.unitPrice.getCurrency()!==r.getCurrency()),c=i.some((s,u)=>u>0&&s.unitPrice.compareTo(i[u-1].unitPrice)>0),l=i[0]?.unitPrice.compareTo(r)>0;if(o||c||l)throw new F("Tiers must share the same currency and must not increase in unit price.");this.baseUnitPrice=r,this.taxCategory=e.taxCategory,this.tiers=i;}getBaseUnitPrice(){return this.baseUnitPrice}getTaxCategory(){return this.taxCategory}getTiers(){return this.tiers}getDetails(){return {baseUnitPrice:this.baseUnitPrice.getDetails(),taxCategory:this.taxCategory,tiers:this.tiers.map(e=>({minQuantity:e.minQuantity,unitPrice:e.unitPrice.getDetails()}))}}getApplicableTier(e){if(e<=0)throw new _;for(let r=this.tiers.length-1;r>=0;r--)if(e>=this.tiers[r].minQuantity)return this.tiers[r];throw new z(e)}getMinQuantity(){return this.tiers[0]?.minQuantity??1}getMaxDiscountPercent(){if(!this.tiers.length)return 0;let e=this.tiers[this.tiers.length-1].unitPrice.getAmount(),r=this.baseUnitPrice.getAmount();return (r-e)/r*100}};var h=class t extends C{id;key;name;description;slug;brand;pricing;variants;targetGender;attributes;specifications;categories;isActive;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static productSKURegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static generateSelectionAttributesKey(e){if(typeof e!="object")throw new m("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 r={},i=e.split("|");for(let n of i){let[o,c]=n.split(":");c.startsWith("c+")?r[o]={name:c.slice(2)}:r[o]=c;}return r}catch(r){throw new m(r?.message)}}constructor(e,r=new Date){super(e,r),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]=new K(e.pricing[o])),n),{}),this.targetGender=e.targetGender,this.attributes=g.deepClone(e.attributes),this.specifications=g.deepClone(e.specifications),this.categories=g.deepClone(e.categories);let i=new Set;this.variants=(e.variants||[]).map(n=>{if(!n.selectionAttributes||typeof n.selectionAttributes!="object")throw new m("Selection attributes are required");this.checkSelectionAttributes(n.selectionAttributes);let o=t.generateSelectionAttributesKey(n.selectionAttributes);if(i.has(o))throw new O(o);return i.add(o),{sku:n.sku,selectionAttributes:n.selectionAttributes,images:{primary:new I(n.images.primary),gallery:(n.images.gallery||[]).map(c=>new I(c))}}}),this.isActive=e.isActive,this.searchTags=e.searchTags?g.deepClone(e.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e){return e?this.name[e]??this.name[A[e]]??this.name.en:g.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[A[e]]??this.description.en:g.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[A[e]]??this.slug.en:g.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:this.pricing}getAttributes(){return g.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:e.selectionAttributes,images:{primary:e.images.primary,gallery:e.images.gallery}}))}getImagesBySelectionAttributes(e){let r=t.generateSelectionAttributesKey(e),i=this.variants.find(n=>t.generateSelectionAttributesKey(n.selectionAttributes)===r);return i?i.images:null}getImages(e,r){switch(r){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 g.deepClone(this.categories)}getSpecifications(e){return e?g.deepClone(this.specifications[e]??this.specifications[A[e]]??this.specifications.en):g.deepClone(this.specifications)}getSearchTags(e){return e?g.deepClone(this.searchTags[e]??this.searchTags[A[e]]??this.searchTags.en):g.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((r,i)=>(this.pricing[i]&&(r[i]=this.pricing[i]?.getDetails()),r),{}),attributes:this.getAttributes(),variants:this.variants.map(r=>({sku:r.sku,selectionAttributes:g.deepClone(r.selectionAttributes),images:{primary:r.images.primary.getDetails(),gallery:r.images.gallery.map(i=>i.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...e}}checkSelectionAttributes(e){if(!e||typeof e!="object")throw new m("Selection attributes are required");Object.keys(this.attributes).forEach(r=>{if(r.toLowerCase()==="size")return;let i=this.attributes[r],n=e[r];if(n===void 0)throw new m(`Selection attribute '${r}' is missing`);if(typeof i=="string"){if(typeof n!="string"||i!==n)throw new m(`Selection attribute '${r}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof n!="string"||!i.includes(n))throw new m(`Selection attribute '${r}' is invalid`)}else if(typeof n!="object"||!("name"in n)||i.findIndex(o=>o.name===n.name)<0)throw new m(`Selection attribute '${r}' is invalid`)}});}validateSelectionAttribute(e){let r=t.generateSelectionAttributesKey(e);return this.variants.some(i=>t.generateSelectionAttributesKey(i.selectionAttributes)===r)}validateSize(e){return this.attributes.size.includes(e)}};var re={$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:h.productKeyRegex.source},productSku:{type:"string",pattern:h.productSKURegex.source},taxCategory:{type:"string",enum:Object.values(G)},genderCategory:{type:"string",enum:Object.values(k)},price:{type:"object",properties:{amount:{type:"number",minimum:0},currency:{$ref:"#/definitions/currency"}},required:["amount","currency"]},color:{type:"object",properties:{name:{type:"string"},hexCode:{type:"string"}},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}$"},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(V)},currency:{type:"string",enum:Object.values(D)},locale:{type:"string",enum:Object.values(w)},language:{type:"string",enum:Object.values(L)},localeOrLanguage:{type:"string",enum:[...Object.values(w),...Object.values(L)]},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 ye={getStandardSchemaDefinition(){return re}},fe=ye;var N=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 S={logException:(t,e)=>{console.error(`Exception Occurred in Function: ${t}, Error: ${S.inspect(e)}`);},logError:(t,e)=>{console.error(`Error Occurred in Function: ${t}, Error: ${S.inspect(e)}`);},logWarning:(t,e)=>{console.warn(`Warning in Function: ${t} - ${S.inspect(e)}`);},logMessage:(t,e)=>{console.log(`Message in Function: ${t} - ${S.inspect(e)}`);},logInvalidPayload:(t,e)=>{console.error(`Invalid Payload received for Function: ${t}, Error: ${S.inspect(e)}`);},inspect:t=>typeof t=="string"?t:he__default.default.inspect(t)},f=S;var be={handleException:(t,e,r)=>{e.knownError?(e.logError&&f.logError(t,e),r.status(e.status).json({status:e.status,error:e.error})):e.status&&e.error?(f.logException(t,e),r.status(e.status).json({error:e.errorMessage||JSON.stringify(e.error),status:e.status})):(f.logException(t,e),r.status(500).json({status:500,error:N.INTERNAL_SERVER_ERROR}));},generateResponse:(t,e,r)=>({status:t,data:e,error:r}),generateError:(t,e,r=!0,i=!1)=>({status:t,error:e,knownError:r,logError:i})},Ae=be;var xe=async(t,e,r="GET",i={},n)=>{let o={method:r,headers:{"Content-Type":"application/json",...i}};r!=="GET"&&n&&(o.body=JSON.stringify(n));let c=`${t}${e?"/"+e:""}`,l=c.includes("api.xetile.com")||c.includes("localhost");try{let s=await fetch(c,o);if(!s.ok){let b,B=await s.text();try{b=JSON.parse(B);}catch{b={status:s.status,error:B||s.statusText},f.logWarning("Fetch",`Failed to parse error response body as JSON for URL-${c}. Raw text: ${B}`);}throw {status:s.status,statusText:s.statusText,error:b}}let u=await s.json();return f.logMessage("Fetch",`API call successful: URL-${c}, Status- ${s.status}`),{status:s.status,statusText:s.statusText,data:l?u.data:u}}catch(s){throw f.logError("Fetch",`API call failed: URL-${c}, Status- ${s.status||500}, Error- ${f.inspect(s.error||s)}`),{status:s.status||500,statusText:s.statusText||N.INTERNAL_SERVER_ERROR,error:s.error||{status:s.status||500,error:s.statusText||N.SOMETHING_WENT_WRONG}}}},Ie=xe;
|
|
1
|
+
'use strict';var ie=require('crypto'),he=require('util');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ie__default=/*#__PURE__*/_interopDefault(ie);var he__default=/*#__PURE__*/_interopDefault(he);var V=(e=>(e.IN="IN",e))(V||{}),D=(e=>(e.INR="INR",e))(D||{}),w=(t=>(t["en-IN"]="en-IN",t["kn-IN"]="kn-IN",t))(w||{}),L=(r=>(r.en="en",r.kn="kn",r))(L||{}),A={"en-IN":"en","kn-IN":"kn"};var W={INR:"\u20B9"},J={INR:"en-IN"},k=(l=>(l.MALE="Male",l.FEMALE="Female",l.UNISEX="Unisex",l.KIDS="Kids",l.BOY="Boy",l.GIRL="Girl",l.GENERAL="General",l))(k||{});var G=(r=>(r.APPAREL="apparel",r.EXEMPT="exempt",r))(G||{});var $=new Uint8Array(256),M=$.length;function j(){return M>$.length-16&&(ie__default.default.randomFillSync($),M=0),$.slice(M,M+=16)}var Z=/^(?:[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 ne(t){return typeof t=="string"&&Z.test(t)}var X=ne;var d=[];for(let t=0;t<256;++t)d.push((t+256).toString(16).slice(1));function R(t,e=0){return d[t[e+0]]+d[t[e+1]]+d[t[e+2]]+d[t[e+3]]+"-"+d[t[e+4]]+d[t[e+5]]+"-"+d[t[e+6]]+d[t[e+7]]+"-"+d[t[e+8]]+d[t[e+9]]+"-"+d[t[e+10]]+d[t[e+11]]+d[t[e+12]]+d[t[e+13]]+d[t[e+14]]+d[t[e+15]]}function se(t){if(!X(t))throw TypeError("Invalid UUID");let e,r=new Uint8Array(16);return r[0]=(e=parseInt(t.slice(0,8),16))>>>24,r[1]=e>>>16&255,r[2]=e>>>8&255,r[3]=e&255,r[4]=(e=parseInt(t.slice(9,13),16))>>>8,r[5]=e&255,r[6]=(e=parseInt(t.slice(14,18),16))>>>8,r[7]=e&255,r[8]=(e=parseInt(t.slice(19,23),16))>>>8,r[9]=e&255,r[10]=(e=parseInt(t.slice(24,36),16))/1099511627776&255,r[11]=e/4294967296&255,r[12]=e>>>24&255,r[13]=e>>>16&255,r[14]=e>>>8&255,r[15]=e&255,r}var ee=se;function oe(t){t=unescape(encodeURIComponent(t));let e=[];for(let r=0;r<t.length;++r)e.push(t.charCodeAt(r));return e}var ae="6ba7b810-9dad-11d1-80b4-00c04fd430c8",ce="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Y(t,e,r){function i(n,o,c,l){var s;if(typeof n=="string"&&(n=oe(n)),typeof o=="string"&&(o=ee(o)),((s=o)===null||s===void 0?void 0:s.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=r(u),u[6]=u[6]&15|e,u[8]=u[8]&63|128,c){l=l||0;for(let b=0;b<16;++b)c[l+b]=u[b];return c}return R(u)}try{i.name=t;}catch{}return i.DNS=ae,i.URL=ce,i}var q={randomUUID:ie__default.default.randomUUID};function le(t,e,r){if(q.randomUUID&&!e&&!t)return q.randomUUID();t=t||{};let i=t.random||(t.rng||j)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){r=r||0;for(let n=0;n<16;++n)e[r+n]=i[n];return e}return R(i)}var Q=le;function ge(t){return Array.isArray(t)?t=Buffer.from(t):typeof t=="string"&&(t=Buffer.from(t,"utf8")),ie__default.default.createHash("sha1").update(t).digest()}var te=ge;var pe=Y("v5",80,te),H=pe;var me={isUUID:t=>/^[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(t),isEmail:t=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(t),isURL:t=>/^(http|https):\/\/[^ "]+$/.test(t),generateUUID:(t,e)=>e&&t?H(t,e):Q(),generateSearchId:(t,e)=>`${t}#${h.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:t=>{let[e,r]=t.split("#");return {key:e,selectionAttributes:h.parseSelectionAttributesKey(r)}},deepClone(t){return structuredClone(t)}},g=me;var C=class{customFields;version;createdAt;modifiedAt;modifiedBy;constructor(e,r=new Date){this.customFields={...e.customFields},this.version=e.version??1,this.createdAt=e.createdAt&&!isNaN(Date.parse(e.createdAt))?new Date(e.createdAt).toISOString():r.toISOString(),this.modifiedAt=e.modifiedAt&&!isNaN(Date.parse(e.modifiedAt))?new Date(e.modifiedAt).toISOString():r.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,r,i,n){this.modifiedBy={id:e,authType:r,requestId:i,lambdaName:n};}getCustomField(e){return this.customFields[e]??null}setCustomField(e,r){this.customFields[e]=r;}getAllCustomFields(){return {...this.customFields}}};var O=class extends Error{constructor(e){super(`Duplicate selection attribute found: ${e}`),this.name="DuplicateSelectionAttributeError";}};var m=class extends Error{constructor(e="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${e}`),this.name="SelectionAttributeParseError";}};var v=class extends Error{constructor(e="Tax category is not valid."){super(`InvalidTaxCategory: ${e}`),this.name="InvalidTaxCategoryError";}},U=class extends Error{constructor(e="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${e}`),this.name="InvalidMinQuantityError";}},F=class extends Error{constructor(e){super(`InvalidTieredPrice: ${e}`),this.name="InvalidTieredPriceError";}},_=class extends Error{constructor(e="Quantity must be greater than zero."){super(`InvalidQuantity: ${e}`),this.name="InvalidQuantityError";}},z=class extends Error{constructor(e){super(`NoApplicableTier: Quantity ${e} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}};var E=class extends Error{constructor(e="Amount cannot be negative."){super(`InvalidAmount: ${e}`),this.name="InvalidPriceAmountError";}},x=class extends Error{constructor(e="Currency code is required."){super(`InvalidCurrency: ${e}`),this.name="InvalidCurrencyCodeError";}},y=class extends Error{constructor(e="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${e}`),this.name="CurrencyMismatchError";}},p=class extends Error{constructor(e){super(`InvalidArgument: ${e}`),this.name="InvalidArgumentError";}},P=class extends Error{constructor(e="Invalid image source configuration."){super(`InvalidImageSource: ${e}`),this.name="InvalidImageSourceError";}};var I=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 P("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,r){if(r===void 0){if(e==="original")throw new P("Cannot remove the 'original' image source.");delete this.sources[e];}else this.sources[e]=r;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var T=class t{#e;amount;currency;constructor(e){if(this.#e="PriceModel",e.amount<0)throw new E("Amount cannot be negative.");if(!e.currency)throw new x("Currency code is required.");this.amount=e.amount,this.currency=e.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}}compareTo(e){if(t.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new y("Cannot compare prices in different currencies.")}else throw new p("Must be a PriceModel instance.");return this.amount-e.getAmount()}add(e){if(t.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new y("Cannot add prices in different currencies.")}else throw new p("Must be a PriceModel instance.");return new t({amount:this.amount+e.getAmount(),currency:this.currency})}subtract(e){if(t.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new y("Cannot subtract prices in different currencies.")}else throw new p("Must be a PriceModel instance.");return new t({amount:this.amount-e.getAmount(),currency:this.currency})}multiply(e){if(t.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new y("Cannot multiply prices in different currencies.");return new t({amount:this.amount*e.getAmount(),currency:this.currency})}else if(typeof e=="number"&&e>=0)return new t({amount:this.amount*e,currency:this.currency});throw new p("Must be a non-negative number.")}divide(e){if(t.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new y("Cannot divide prices in different currencies.");return new t({amount:this.amount/e.getAmount(),currency:this.currency})}else if(typeof e=="number"&&e>0)return new t({amount:this.amount/e,currency:this.currency});throw new p("Must be a positive number.")}min(...e){if(e.length===0)throw new p("Must provide at least one PriceModel.");return e.reduce((r,i)=>{if(t.isPriceModel(i)){if(r.getCurrency()!==i.getCurrency())throw new y("Cannot compare prices in different currencies.")}else throw new p("Must be a PriceModel instance.");return r.compareTo(i)<0?r:i})}max(...e){if(e.length===0)throw new p("Must provide at least one PriceModel.");return e.reduce((r,i)=>{if(t.isPriceModel(i)){if(r.getCurrency()!==i.getCurrency())throw new y("Cannot compare prices in different currencies.")}else throw new p("Must be a PriceModel instance.");return r.compareTo(i)>0?r:i})}zero(){return new t({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new t({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return t.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return t.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(e,r,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let n=J[r];if(!r||!n)throw new x("Invalid currency code for formatting.");let o=e,c=i.displayAsInteger?0:t.getDecimalPlaces(r),l={style:i.style??"currency",currency:r,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:c,maximumFractionDigits:c};i.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(n,l).format(o)}catch(s){return console.error(`Error formatting price for currency "${r}" and locale "${n}":`,s),`${W[r]??r} ${t.addThousandSeparators(o.toFixed(c))}`}}static getDecimalPlaces(e){switch(e){case"INR":default:return 2}}static addThousandSeparators(e){let r=e.split("."),i=r[0],n=r.length>1?"."+r[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+n}static getRoundedAmount(e,r){if(e<0)throw new E("Amount cannot be negative for rounding.");if(r===void 0)throw new x("Invalid currency code for rounding.");let i=t.getDecimalPlaces(r),n=Math.pow(10,i);return Math.round(e*n)/n}};var K=class{baseUnitPrice;taxCategory;tiers;constructor(e){let r=new T(e.baseUnitPrice);if(!e.taxCategory)throw new v;let i=(e.tiers??[]).map(s=>({minQuantity:s.minQuantity,unitPrice:new T(s.unitPrice)})).sort((s,u)=>s.minQuantity-u.minQuantity);if(i.some(s=>s.minQuantity<=0))throw new U;let o=i.some(s=>s.unitPrice.getCurrency()!==r.getCurrency()),c=i.some((s,u)=>u>0&&s.unitPrice.compareTo(i[u-1].unitPrice)>0),l=i[0]?.unitPrice.compareTo(r)>0;if(o||c||l)throw new F("Tiers must share the same currency and must not increase in unit price.");this.baseUnitPrice=r,this.taxCategory=e.taxCategory,this.tiers=i;}getBaseUnitPrice(){return this.baseUnitPrice}getTaxCategory(){return this.taxCategory}getTiers(){return this.tiers}getDetails(){return {baseUnitPrice:this.baseUnitPrice.getDetails(),taxCategory:this.taxCategory,tiers:this.tiers.map(e=>({minQuantity:e.minQuantity,unitPrice:e.unitPrice.getDetails()}))}}getApplicableTier(e){if(e<=0)throw new _;for(let r=this.tiers.length-1;r>=0;r--)if(e>=this.tiers[r].minQuantity)return this.tiers[r];throw new z(e)}getMinQuantity(){return this.tiers[0]?.minQuantity??1}getMaxDiscountPercent(){if(!this.tiers.length)return 0;let e=this.tiers[this.tiers.length-1].unitPrice.getAmount(),r=this.baseUnitPrice.getAmount();return (r-e)/r*100}};var h=class t extends C{id;key;name;description;slug;brand;pricing;variants;targetGender;attributes;specifications;categories;isActive;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static productSKURegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static generateSelectionAttributesKey(e){if(typeof e!="object")throw new m("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 r={},i=e.split("|");for(let n of i){let[o,c]=n.split(":");c.startsWith("c+")?r[o]={name:c.slice(2)}:r[o]=c;}return r}catch(r){throw new m(r?.message)}}constructor(e,r=new Date){super(e,r),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]=new K(e.pricing[o])),n),{}),this.targetGender=e.targetGender,this.attributes=g.deepClone(e.attributes),this.specifications=g.deepClone(e.specifications),this.categories=g.deepClone(e.categories);let i=new Set;this.variants=(e.variants||[]).map(n=>{if(!n.selectionAttributes||typeof n.selectionAttributes!="object")throw new m("Selection attributes are required");this.checkSelectionAttributes(n.selectionAttributes);let o=t.generateSelectionAttributesKey(n.selectionAttributes);if(i.has(o))throw new O(o);return i.add(o),{sku:n.sku,selectionAttributes:n.selectionAttributes,images:{primary:new I(n.images.primary),gallery:(n.images.gallery||[]).map(c=>new I(c))}}}),this.isActive=e.isActive,this.searchTags=e.searchTags?g.deepClone(e.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e){return e?this.name[e]??this.name[A[e]]??this.name.en:g.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[A[e]]??this.description.en:g.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[A[e]]??this.slug.en:g.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:this.pricing}getAttributes(){return g.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:e.selectionAttributes,images:{primary:e.images.primary,gallery:e.images.gallery}}))}getImagesBySelectionAttributes(e){let r=t.generateSelectionAttributesKey(e),i=this.variants.find(n=>t.generateSelectionAttributesKey(n.selectionAttributes)===r);return i?i.images:null}getImages(e,r){switch(r){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 g.deepClone(this.categories)}getSpecifications(e){return e?g.deepClone(this.specifications[e]??this.specifications[A[e]]??this.specifications.en):g.deepClone(this.specifications)}getSearchTags(e){return e?g.deepClone(this.searchTags[e]??this.searchTags[A[e]]??this.searchTags.en):g.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((r,i)=>(this.pricing[i]&&(r[i]=this.pricing[i]?.getDetails()),r),{}),attributes:this.getAttributes(),variants:this.variants.map(r=>({sku:r.sku,selectionAttributes:g.deepClone(r.selectionAttributes),images:{primary:r.images.primary.getDetails(),gallery:r.images.gallery.map(i=>i.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...e}}checkSelectionAttributes(e){if(!e||typeof e!="object")throw new m("Selection attributes are required");Object.keys(this.attributes).forEach(r=>{if(r.toLowerCase()==="size")return;let i=this.attributes[r],n=e[r];if(n===void 0)throw new m(`Selection attribute '${r}' is missing`);if(typeof i=="string"){if(typeof n!="string"||i!==n)throw new m(`Selection attribute '${r}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof n!="string"||!i.includes(n))throw new m(`Selection attribute '${r}' is invalid`)}else if(typeof n!="object"||!("name"in n)||i.findIndex(o=>o.name===n.name)<0)throw new m(`Selection attribute '${r}' is invalid`)}});}validateSelectionAttribute(e){let r=t.generateSelectionAttributesKey(e);return this.variants.some(i=>t.generateSelectionAttributesKey(i.selectionAttributes)===r)}validateSize(e){return this.attributes.size.includes(e)}};var re={$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:h.productKeyRegex.source},productSku:{type:"string",pattern:h.productSKURegex.source},taxCategory:{type:"string",enum:Object.values(G)},genderCategory:{type:"string",enum:Object.values(k)},price:{type:"object",properties:{amount:{type:"number",minimum:0},currency:{$ref:"#/definitions/currency"}},required:["amount","currency"]},color:{type:"object",properties:{name:{type:"string"},hexCode:{type:"string"}},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}$"},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(V)},currency:{type:"string",enum:Object.values(D)},locale:{type:"string",enum:Object.values(w)},language:{type:"string",enum:Object.values(L)},localeOrLanguage:{type:"string",enum:[...Object.values(w),...Object.values(L)]},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 ye={getStandardSchemaDefinition(){return re}},fe=ye;var N=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 S={logException:(t,e)=>{console.error(`Exception Occurred in Function: ${t}, Error: ${S.inspect(e)}`);},logError:(t,e)=>{console.error(`Error Occurred in Function: ${t}, Error: ${S.inspect(e)}`);},logWarning:(t,e)=>{console.warn(`Warning in Function: ${t} - ${S.inspect(e)}`);},logMessage:(t,e)=>{console.log(`Message in Function: ${t} - ${S.inspect(e)}`);},logInvalidPayload:(t,e)=>{console.error(`Invalid Payload received for Function: ${t}, Error: ${S.inspect(e)}`);},inspect:t=>typeof t=="string"?t:he__default.default.inspect(t)},f=S;var be={handleException:(t,e,r)=>{e.knownError?(e.logError&&f.logError(t,e),r.status(e.status).json({status:e.status,error:e.error})):e.status&&e.error?(f.logException(t,e),r.status(e.status).json({error:e.errorMessage||JSON.stringify(e.error),status:e.status})):(f.logException(t,e),r.status(500).json({status:500,error:N.INTERNAL_SERVER_ERROR}));},generateResponse:(t,e,r)=>({status:t,data:e,error:r}),generateError:(t,e,r=!0,i=!1)=>({status:t,error:e,knownError:r,logError:i})},Ae=be;var xe=async(t,e,r="GET",i={},n)=>{let o={method:r,headers:{"Content-Type":"application/json",...i}};r!=="GET"&&n&&(o.body=JSON.stringify(n));let c=`${t}${e?"/"+e:""}`,l=c.includes("api.xetile.com")||c.includes("localhost");try{let s=await fetch(c,o);if(!s.ok){let b,B=await s.text();try{b=JSON.parse(B);}catch{b={status:s.status,error:B||s.statusText},f.logWarning("Fetch",`Failed to parse error response body as JSON for URL-${c}. Raw text: ${B}`);}throw {status:s.status,statusText:s.statusText,error:b}}let u=await s.json();return f.logMessage("Fetch",`API call successful: URL-${c}, Status- ${s.status}`),{status:s.status,statusText:s.statusText,data:l?u.data:u}}catch(s){throw f.logError("Fetch",`API call failed: URL-${c}, Status- ${s.status||500}, Error- ${f.inspect(s.error||s)}`),{status:s.status||500,statusText:s.statusText||N.INTERNAL_SERVER_ERROR,error:s.error||{status:s.status||500,error:s.statusText||N.SOMETHING_WENT_WRONG}}}},Ie=xe;
|
|
2
2
|
exports.Fetch=Ie;exports.Logger=f;exports.ResponseUtility=Ae;exports.Schema=fe;exports.Utils=g;//# sourceMappingURL=index.js.map
|
|
3
3
|
//# sourceMappingURL=index.js.map
|