b23-lib 2.0.1 → 2.0.2
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/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/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.d.mts +3 -7
- package/dist/Classes/Product.d.ts +3 -7
- 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.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/chunk-ISS46WVH.mjs +2 -0
- package/dist/chunk-ISS46WVH.mjs.map +1 -0
- package/dist/{chunk-2SGUPNWZ.mjs → chunk-LXJGGXF3.mjs} +2 -2
- package/dist/{chunk-2SGUPNWZ.mjs.map → chunk-LXJGGXF3.mjs.map} +1 -1
- package/dist/{chunk-EP7WVZXC.mjs → chunk-M4BZMGTB.mjs} +2 -2
- package/dist/{chunk-EP7WVZXC.mjs.map → chunk-M4BZMGTB.mjs.map} +1 -1
- package/dist/{chunk-RBROVHJ4.mjs → chunk-QLLM365R.mjs} +2 -2
- package/dist/{chunk-RBROVHJ4.mjs.map → chunk-QLLM365R.mjs.map} +1 -1
- package/dist/{chunk-CEGQFFYZ.mjs → chunk-SFTIM3X7.mjs} +2 -2
- package/dist/{chunk-CEGQFFYZ.mjs.map → chunk-SFTIM3X7.mjs.map} +1 -1
- package/dist/index.d.mts +38 -1
- package/dist/index.d.ts +38 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-LNIZAPER.mjs +0 -2
- package/dist/chunk-LNIZAPER.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/Classes/LineItem.ts"],"names":["LineItemModel","data","Utils_default","ImageInfoModel","uniqueSelectionAttributes","item","DuplicateSizeError","PriceModel","TieredPriceModel","couponCode","discount","locale","LocaleLanguageMap","subItems","addQuantity","subItem","existingSubItem","sub","product","cartCountry","cartCurrency","ProductMismatchError","ProductInactiveError","SizeMismatchError","productPricing","PricingNotFoundError","quantity","sum","s","unitPrice","appliedDiscounts","lineItemDiscounts","taxRule","InvalidTaxRuleError","taxableUnitPrice","zero","totalQuantity","subTotal","discounts","taxableAmount","unitTaxbleAmount","taxRate","TaxRuleModel","taxTotal","grandTotal"],"mappings":"ySAoEqBA,IAAAA,CAAAA,CAArB,KAAmC,CACvB,EACA,CAAA,UAAA,CACA,kBAEA,CAAA,IAAA,CACA,cACA,CAAA,YAAA,CACA,QACA,CAAA,OAAA,CAaA,KACA,CAAA,KAAA,CAcV,YAAYC,CAA0B,CAAA,CACpC,IAAK,CAAA,EAAA,CAAKA,CAAK,CAAA,EAAA,CACf,IAAK,CAAA,UAAA,CAAaA,CAAK,CAAA,UAAA,CACvB,IAAK,CAAA,kBAAA,CAAqBC,CAAM,CAAA,SAAA,CAAUD,EAAK,kBAAkB,CAAA,CAEjE,IAAK,CAAA,IAAA,C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,QAAU,CAAA,CAAA,CACV,QAAUA,CAAAA,CAAAA,CACV,aAAeA,CAAAA,CAAAA,CACf,QAAUA,CAAAA,CAAAA,CACV,SAAW,CAAA,EACX,CAAA,UAAA,CAAYA,CACd,EACF,CACF","file":"chunk-CEGQFFYZ.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, 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 selectionAttribute: 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 selectionAttribute: 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: TaxSlabs;\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.selectionAttribute = Utils.deepClone(data.selectionAttribute);\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: Utils.deepClone(data.pricing.tax.taxSlabs),\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 getSelectionAttribute(): SelectionAttributes {\r\n return Utils.deepClone(this.selectionAttribute);\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: Utils.deepClone(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 selectionAttribute: this.getSelectionAttribute(),\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: this.getPricing().tax\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.selectionAttribute)) {\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.selectionAttribute).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.taxableAmount.divide(this.total.quantity);\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 = taxableAmount.divide(totalQuantity);\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.selectionAttribute = { 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
|
+
{"version":3,"sources":["../src/Classes/LineItem.ts"],"names":["LineItemModel","data","Utils_default","ImageInfoModel","uniqueSelectionAttributes","item","DuplicateSizeError","PriceModel","TieredPriceModel","couponCode","discount","locale","LocaleLanguageMap","subItems","addQuantity","subItem","existingSubItem","sub","product","cartCountry","cartCurrency","ProductMismatchError","ProductInactiveError","SizeMismatchError","productPricing","PricingNotFoundError","quantity","sum","s","unitPrice","appliedDiscounts","lineItemDiscounts","taxRule","InvalidTaxRuleError","taxableUnitPrice","zero","totalQuantity","subTotal","discounts","taxableAmount","unitTaxbleAmount","taxRate","TaxRuleModel","taxTotal","grandTotal"],"mappings":"ySAoEqBA,IAAAA,CAAAA,CAArB,KAAmC,CACvB,EACA,CAAA,UAAA,CACA,kBAEA,CAAA,IAAA,CACA,cACA,CAAA,YAAA,CACA,QACA,CAAA,OAAA,CAaA,KACA,CAAA,KAAA,CAcV,YAAYC,CAA0B,CAAA,CACpC,IAAK,CAAA,EAAA,CAAKA,CAAK,CAAA,EAAA,CACf,IAAK,CAAA,UAAA,CAAaA,CAAK,CAAA,UAAA,C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,CAAA,WAAA,CAC1B,GAAK,CAAA,IAAA,CAAK,OAAQ,CAAA,GACpB,CACA,CAAA,IAAA,CAAK,KAAQ,CAAA,CACX,QAAU,CAAA,CAAA,CACV,QAAUA,CAAAA,CAAAA,CACV,aAAeA,CAAAA,CAAAA,CACf,QAAUA,CAAAA,CAAAA,CACV,SAAW,CAAA,EACX,CAAA,UAAA,CAAYA,CACd,EACF,CACF","file":"chunk-SFTIM3X7.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, 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 selectionAttribute: 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 selectionAttribute: 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: TaxSlabs;\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.selectionAttribute = Utils.deepClone(data.selectionAttribute);\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: Utils.deepClone(data.pricing.tax.taxSlabs),\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 getSelectionAttribute(): SelectionAttributes {\r\n return Utils.deepClone(this.selectionAttribute);\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: Utils.deepClone(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 selectionAttribute: this.getSelectionAttribute(),\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: this.getPricing().tax\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.selectionAttribute)) {\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.selectionAttribute).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.taxableAmount.divide(this.total.quantity);\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 = taxableAmount.divide(totalQuantity);\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.selectionAttribute = { 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}"]}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { OperationalCountry, OperationalCountryCurrency, OperationalLocale, OperationalLanguage } from './Classes/Enum.mjs';
|
|
1
|
+
import { TaxCategory, GenderCategory, OperationalCountry, OperationalCountryCurrency, OperationalLocale, OperationalLanguage } from './Classes/Enum.mjs';
|
|
2
2
|
import { SelectionAttributes } from './Classes/Product.mjs';
|
|
3
3
|
import './Classes/Base.mjs';
|
|
4
4
|
import './Auth/index.mjs';
|
|
@@ -96,6 +96,43 @@ declare const Schema: {
|
|
|
96
96
|
type: string;
|
|
97
97
|
pattern: string;
|
|
98
98
|
};
|
|
99
|
+
productSku: {
|
|
100
|
+
type: string;
|
|
101
|
+
pattern: string;
|
|
102
|
+
};
|
|
103
|
+
taxCategory: {
|
|
104
|
+
type: string;
|
|
105
|
+
enum: TaxCategory[];
|
|
106
|
+
};
|
|
107
|
+
genderCategory: {
|
|
108
|
+
type: string;
|
|
109
|
+
enum: GenderCategory[];
|
|
110
|
+
};
|
|
111
|
+
price: {
|
|
112
|
+
type: string;
|
|
113
|
+
properties: {
|
|
114
|
+
amount: {
|
|
115
|
+
type: string;
|
|
116
|
+
minimum: number;
|
|
117
|
+
};
|
|
118
|
+
currency: {
|
|
119
|
+
$ref: string;
|
|
120
|
+
};
|
|
121
|
+
};
|
|
122
|
+
required: string[];
|
|
123
|
+
};
|
|
124
|
+
color: {
|
|
125
|
+
type: string;
|
|
126
|
+
properties: {
|
|
127
|
+
name: {
|
|
128
|
+
type: string;
|
|
129
|
+
};
|
|
130
|
+
hexCode: {
|
|
131
|
+
type: string;
|
|
132
|
+
};
|
|
133
|
+
};
|
|
134
|
+
required: string[];
|
|
135
|
+
};
|
|
99
136
|
firstName: {
|
|
100
137
|
$ref: string;
|
|
101
138
|
};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { OperationalCountry, OperationalCountryCurrency, OperationalLocale, OperationalLanguage } from './Classes/Enum.js';
|
|
1
|
+
import { TaxCategory, GenderCategory, OperationalCountry, OperationalCountryCurrency, OperationalLocale, OperationalLanguage } from './Classes/Enum.js';
|
|
2
2
|
import { SelectionAttributes } from './Classes/Product.js';
|
|
3
3
|
import './Classes/Base.js';
|
|
4
4
|
import './Auth/index.js';
|
|
@@ -96,6 +96,43 @@ declare const Schema: {
|
|
|
96
96
|
type: string;
|
|
97
97
|
pattern: string;
|
|
98
98
|
};
|
|
99
|
+
productSku: {
|
|
100
|
+
type: string;
|
|
101
|
+
pattern: string;
|
|
102
|
+
};
|
|
103
|
+
taxCategory: {
|
|
104
|
+
type: string;
|
|
105
|
+
enum: TaxCategory[];
|
|
106
|
+
};
|
|
107
|
+
genderCategory: {
|
|
108
|
+
type: string;
|
|
109
|
+
enum: GenderCategory[];
|
|
110
|
+
};
|
|
111
|
+
price: {
|
|
112
|
+
type: string;
|
|
113
|
+
properties: {
|
|
114
|
+
amount: {
|
|
115
|
+
type: string;
|
|
116
|
+
minimum: number;
|
|
117
|
+
};
|
|
118
|
+
currency: {
|
|
119
|
+
$ref: string;
|
|
120
|
+
};
|
|
121
|
+
};
|
|
122
|
+
required: string[];
|
|
123
|
+
};
|
|
124
|
+
color: {
|
|
125
|
+
type: string;
|
|
126
|
+
properties: {
|
|
127
|
+
name: {
|
|
128
|
+
type: string;
|
|
129
|
+
};
|
|
130
|
+
hexCode: {
|
|
131
|
+
type: string;
|
|
132
|
+
};
|
|
133
|
+
};
|
|
134
|
+
required: string[];
|
|
135
|
+
};
|
|
99
136
|
firstName: {
|
|
100
137
|
$ref: string;
|
|
101
138
|
};
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
'use strict';var ee=require('crypto'),me=require('util');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ee__default=/*#__PURE__*/_interopDefault(ee);var me__default=/*#__PURE__*/_interopDefault(me);var K=(e=>(e.IN="IN",e))(K||{}),N=(e=>(e.INR="INR",e))(N||{}),D=(t=>(t["en-IN"]="en-IN",t["kn-IN"]="kn-IN",t))(D||{}),L=(r=>(r.en="en",r.kn="kn",r))(L||{}),I={"en-IN":"en","kn-IN":"kn"};var H={INR:"\u20B9"},j={INR:"en-IN"};var $=new Uint8Array(256),w=$.length;function k(){return w>$.length-16&&(ee__default.default.randomFillSync($),w=0),$.slice(w,w+=16)}var q=/^(?:[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 te(t){return typeof t=="string"&&q.test(t)}var W=te;var l=[];for(let t=0;t<256;++t)l.push((t+256).toString(16).slice(1));function M(t,e=0){return l[t[e+0]]+l[t[e+1]]+l[t[e+2]]+l[t[e+3]]+"-"+l[t[e+4]]+l[t[e+5]]+"-"+l[t[e+6]]+l[t[e+7]]+"-"+l[t[e+8]]+l[t[e+9]]+"-"+l[t[e+10]]+l[t[e+11]]+l[t[e+12]]+l[t[e+13]]+l[t[e+14]]+l[t[e+15]]}function re(t){if(!W(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 J=re;function ie(t){t=unescape(encodeURIComponent(t));let e=[];for(let r=0;r<t.length;++r)e.push(t.charCodeAt(r));return e}var ne="6ba7b810-9dad-11d1-80b4-00c04fd430c8",se="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function V(t,e,r){function i(n,a,c,y){var s;if(typeof n=="string"&&(n=ie(n)),typeof a=="string"&&(a=J(a)),((s=a)===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(a),u.set(n,a.length),u=r(u),u[6]=u[6]&15|e,u[8]=u[8]&63|128,c){y=y||0;for(let f=0;f<16;++f)c[y+f]=u[f];return c}return M(u)}try{i.name=t;}catch{}return i.DNS=ne,i.URL=se,i}var G={randomUUID:ee__default.default.randomUUID};function ae(t,e,r){if(G.randomUUID&&!e&&!t)return G.randomUUID();t=t||{};let i=t.random||(t.rng||k)();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 M(i)}var Y=ae;function ue(t){return Array.isArray(t)?t=Buffer.from(t):typeof t=="string"&&(t=Buffer.from(t,"utf8")),ee__default.default.createHash("sha1").update(t).digest()}var Z=ue;var le=V("v5",80,Z),Q=le;var de={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?Q(t,e):Y(),generateSearchId:(t,e)=>`${t}#${h.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:t=>{let[e,r]=t.split("#");return {key:e,selectionAttribute:r}},deepClone(t){return structuredClone(t)}},d=de;var E=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 R=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";}},O=class extends Error{constructor(e="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${e}`),this.name="InvalidMinQuantityError";}},U=class extends Error{constructor(e){super(`InvalidTieredPrice: ${e}`),this.name="InvalidTieredPriceError";}},F=class extends Error{constructor(e="Quantity must be greater than zero."){super(`InvalidQuantity: ${e}`),this.name="InvalidQuantityError";}},_=class extends Error{constructor(e){super(`NoApplicableTier: Quantity ${e} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}};var C=class extends Error{constructor(e="Amount cannot be negative."){super(`InvalidAmount: ${e}`),this.name="InvalidPriceAmountError";}},b=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";}},g=class extends Error{constructor(e){super(`InvalidArgument: ${e}`),this.name="InvalidArgumentError";}},S=class extends Error{constructor(e="Invalid image source configuration."){super(`InvalidImageSource: ${e}`),this.name="InvalidImageSourceError";}};var A=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 S("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 S("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 x=class t{amount;currency;constructor(e){if(e.amount<0)throw new C("Amount cannot be negative.");if(!e.currency)throw new b("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 p("Cannot compare prices in different currencies.")}else throw new g("Must be a PriceModel instance.");return this.amount-e.getAmount()}add(e){if(e instanceof t){if(this.currency!==e.getCurrency())throw new p("Cannot add prices in different currencies.")}else throw new g("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 p("Cannot subtract prices in different currencies.")}else throw new g("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 p("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 g("Must be a non-negative number.")}divide(e){if(e instanceof t){if(this.currency!==e.getCurrency())throw new p("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 g("Must be a positive number.")}min(...e){if(e.length===0)throw new g("Must provide at least one PriceModel.");return e.reduce((r,i)=>{if(i instanceof t){if(r.getCurrency()!==i.getCurrency())throw new p("Cannot compare prices in different currencies.")}else throw new g("Must be a PriceModel instance.");return r.compareTo(i)<0?r:i})}max(...e){if(e.length===0)throw new g("Must provide at least one PriceModel.");return e.reduce((r,i)=>{if(i instanceof t){if(r.getCurrency()!==i.getCurrency())throw new p("Cannot compare prices in different currencies.")}else throw new g("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)}static getFormattedString(e,r,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let n=j[r];if(!r||!n)throw new b("Invalid currency code for formatting.");let a=e,c=i.displayAsInteger?0:t.getDecimalPlaces(r),y={style:i.style??"currency",currency:r,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:c,maximumFractionDigits:c};i.displayAsInteger&&(a=Math.ceil(a));try{return new Intl.NumberFormat(n,y).format(a)}catch(s){return console.error(`Error formatting price for currency "${r}" and locale "${n}":`,s),`${H[r]??r} ${t.addThousandSeparators(a.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 C("Amount cannot be negative for rounding.");if(r===void 0)throw new b("Invalid currency code for rounding.");let i=t.getDecimalPlaces(r),n=Math.pow(10,i);return Math.round(e*n)/n}};var z=class{baseUnitPrice;taxCategory;tiers;constructor(e){let r=new x(e.baseUnitPrice);if(!e.taxCategory)throw new v;let i=(e.tiers??[]).map(s=>({minQuantity:s.minQuantity,unitPrice:new x(s.unitPrice)})).sort((s,u)=>s.minQuantity-u.minQuantity);if(i.some(s=>s.minQuantity<=0))throw new O;let a=i.some(s=>s.unitPrice.getCurrency()!==r.getCurrency()),c=i.some((s,u)=>u>0&&s.unitPrice.compareTo(i[u-1].unitPrice)>0),y=i[0]?.unitPrice.compareTo(r)>0;if(a||c||y)throw new U("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 F;for(let r=this.tiers.length-1;r>=0;r--)if(e>=this.tiers[r].minQuantity)return this.tiers[r];throw new _(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 E{id;key;sku;name;description;slug;brand;pricing;variants;targetGender;attributes;specifications;categories;isActive;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static generateSelectionAttributesKey(e){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("|")}static parseSelectionAttributesKey(e){try{let r={},i=e.split("|");for(let n of i){let[a,c]=n.split(":");c.startsWith("c+")?r[a]={name:c.slice(2)}:r[a]=c;}return r}catch(r){throw new R(r?.message)}}constructor(e,r=new Date){super(e,r),this.id=e.id,this.key=e.key,this.sku=e.sku,this.name={...e.name},this.description={...e.description},this.slug={...e.slug},this.brand=e.brand,this.pricing=Object.keys(e.pricing).reduce((i,n)=>(e.pricing[n]&&(i[n]=new z(e.pricing[n])),i),{}),this.targetGender=e.targetGender,this.attributes=d.deepClone(e.attributes),this.specifications=d.deepClone(e.specifications),this.categories=d.deepClone(e.categories),this.variants=(e.variants||[]).map(i=>({selectionAttributes:i.selectionAttributes,images:{primary:new A(i.images.primary),gallery:(i.images.gallery||[]).map(n=>new A(n))}})),this.isActive=e.isActive,this.searchTags=e.searchTags?d.deepClone(e.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getSku(){return this.sku}getName(e){return e?this.name[e]??this.name[I[e]]??this.name.en:d.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[I[e]]??this.description.en:d.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[I[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)}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 d.deepClone(this.categories)}getSpecifications(e){return e?d.deepClone(this.specifications[e]??this.specifications[I[e]]??this.specifications.en):d.deepClone(this.specifications)}getSearchTags(e){return e?d.deepClone(this.searchTags[e]??this.searchTags[I[e]]??this.searchTags.en):d.deepClone(this.searchTags)}getDetails(){let e=super.getDetails();return {id:this.getId(),key:this.getKey(),sku:this.getSku(),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=>({selectionAttributes:d.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}}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 X={$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},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(K)},currency:{type:"string",enum:Object.values(N)},locale:{type:"string",enum:Object.values(D)},language:{type:"string",enum:Object.values(L)},localeOrLanguage:{type:"string",enum:[...Object.values(D),...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 ge={getStandardSchemaDefinition(){return X}},pe=ge;var P=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 T={logException:(t,e)=>{console.error(`Exception Occurred in Function: ${t}, Error: ${T.inspect(e)}`);},logError:(t,e)=>{console.error(`Error Occurred in Function: ${t}, Error: ${T.inspect(e)}`);},logWarning:(t,e)=>{console.warn(`Warning in Function: ${t} - ${T.inspect(e)}`);},logMessage:(t,e)=>{console.log(`Message in Function: ${t} - ${T.inspect(e)}`);},logInvalidPayload:(t,e)=>{console.error(`Invalid Payload received for Function: ${t}, Error: ${T.inspect(e)}`);},inspect:t=>typeof t=="string"?t:me__default.default.inspect(t)},m=T;var ye={handleException:(t,e,r)=>{e.knownError?(e.logError&&m.logError(t,e),r.status(e.status).json({status:e.status,error:e.error})):e.status&&e.error?(m.logException(t,e),r.status(e.status).json({error:e.errorMessage||JSON.stringify(e.error),status:e.status})):(m.logException(t,e),r.status(500).json({status:500,error:P.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})},fe=ye;var he=async(t,e,r="GET",i={},n)=>{let a={method:r,headers:{"Content-Type":"application/json",...i}};r!=="GET"&&n&&(a.body=JSON.stringify(n));let c=`${t}${e?"/"+e:""}`,y=c.includes("api.xetile.com")||c.includes("localhost");try{let s=await fetch(c,a);if(!s.ok){let f,B=await s.text();try{f=JSON.parse(B);}catch{f={status:s.status,error:B||s.statusText},m.logWarning("Fetch",`Failed to parse error response body as JSON for URL-${c}. Raw text: ${B}`);}throw {status:s.status,statusText:s.statusText,error:f}}let u=await s.json();return m.logMessage("Fetch",`API call successful: URL-${c}, Status- ${s.status}`),{status:s.status,statusText:s.statusText,data:y?u.data:u}}catch(s){throw m.logError("Fetch",`API call failed: URL-${c}, Status- ${s.status||500}, Error- ${m.inspect(s.error||s)}`),{status:s.status||500,statusText:s.statusText||P.INTERNAL_SERVER_ERROR,error:s.error||{status:s.status||500,error:s.statusText||P.SOMETHING_WENT_WRONG}}}},Ie=he;
|
|
2
|
-
exports.Fetch=
|
|
1
|
+
'use strict';var re=require('crypto'),fe=require('util');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var re__default=/*#__PURE__*/_interopDefault(re);var fe__default=/*#__PURE__*/_interopDefault(fe);var K=(e=>(e.IN="IN",e))(K||{}),N=(e=>(e.INR="INR",e))(N||{}),D=(t=>(t["en-IN"]="en-IN",t["kn-IN"]="kn-IN",t))(D||{}),L=(r=>(r.en="en",r.kn="kn",r))(L||{}),b={"en-IN":"en","kn-IN":"kn"};var H={INR:"\u20B9"},W={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 V=(r=>(r.APPAREL="apparel",r.EXEMPT="exempt",r))(V||{});var w=new Uint8Array(256),$=w.length;function G(){return $>w.length-16&&(re__default.default.randomFillSync(w),$=0),w.slice($,$+=16)}var J=/^(?:[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 ie(t){return typeof t=="string"&&J.test(t)}var Z=ie;var d=[];for(let t=0;t<256;++t)d.push((t+256).toString(16).slice(1));function M(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 ne(t){if(!Z(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 X=ne;function se(t){t=unescape(encodeURIComponent(t));let e=[];for(let r=0;r<t.length;++r)e.push(t.charCodeAt(r));return e}var oe="6ba7b810-9dad-11d1-80b4-00c04fd430c8",ae="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Y(t,e,r){function i(n,a,c,l){var s;if(typeof n=="string"&&(n=se(n)),typeof a=="string"&&(a=X(a)),((s=a)===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(a),u.set(n,a.length),u=r(u),u[6]=u[6]&15|e,u[8]=u[8]&63|128,c){l=l||0;for(let f=0;f<16;++f)c[l+f]=u[f];return c}return M(u)}try{i.name=t;}catch{}return i.DNS=oe,i.URL=ae,i}var Q={randomUUID:re__default.default.randomUUID};function ue(t,e,r){if(Q.randomUUID&&!e&&!t)return Q.randomUUID();t=t||{};let i=t.random||(t.rng||G)();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 M(i)}var j=ue;function de(t){return Array.isArray(t)?t=Buffer.from(t):typeof t=="string"&&(t=Buffer.from(t,"utf8")),re__default.default.createHash("sha1").update(t).digest()}var ee=de;var ge=Y("v5",80,ee),q=ge;var pe={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?q(t,e):j(),generateSearchId:(t,e)=>`${t}#${h.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:t=>{let[e,r]=t.split("#");return {key:e,selectionAttribute:r}},deepClone(t){return structuredClone(t)}},g=pe;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 R=class extends Error{constructor(e="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${e}`),this.name="SelectionAttributeParseError";}};var O=class extends Error{constructor(e="Tax category is not valid."){super(`InvalidTaxCategory: ${e}`),this.name="InvalidTaxCategoryError";}},v=class extends Error{constructor(e="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${e}`),this.name="InvalidMinQuantityError";}},U=class extends Error{constructor(e){super(`InvalidTieredPrice: ${e}`),this.name="InvalidTieredPriceError";}},F=class extends Error{constructor(e="Quantity must be greater than zero."){super(`InvalidQuantity: ${e}`),this.name="InvalidQuantityError";}},_=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";}},I=class extends Error{constructor(e="Currency code is required."){super(`InvalidCurrency: ${e}`),this.name="InvalidCurrencyCodeError";}},m=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";}},S=class extends Error{constructor(e="Invalid image source configuration."){super(`InvalidImageSource: ${e}`),this.name="InvalidImageSourceError";}};var x=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 S("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 S("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 A=class t{amount;currency;constructor(e){if(e.amount<0)throw new E("Amount cannot be negative.");if(!e.currency)throw new I("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 m("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 m("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 m("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 m("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 m("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 m("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 m("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)}static getFormattedString(e,r,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let n=W[r];if(!r||!n)throw new I("Invalid currency code for formatting.");let a=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&&(a=Math.ceil(a));try{return new Intl.NumberFormat(n,l).format(a)}catch(s){return console.error(`Error formatting price for currency "${r}" and locale "${n}":`,s),`${H[r]??r} ${t.addThousandSeparators(a.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 I("Invalid currency code for rounding.");let i=t.getDecimalPlaces(r),n=Math.pow(10,i);return Math.round(e*n)/n}};var z=class{baseUnitPrice;taxCategory;tiers;constructor(e){let r=new A(e.baseUnitPrice);if(!e.taxCategory)throw new O;let i=(e.tiers??[]).map(s=>({minQuantity:s.minQuantity,unitPrice:new A(s.unitPrice)})).sort((s,u)=>s.minQuantity-u.minQuantity);if(i.some(s=>s.minQuantity<=0))throw new v;let a=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(a||c||l)throw new U("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 F;for(let r=this.tiers.length-1;r>=0;r--)if(e>=this.tiers[r].minQuantity)return this.tiers[r];throw new _(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){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("|")}static parseSelectionAttributesKey(e){try{let r={},i=e.split("|");for(let n of i){let[a,c]=n.split(":");c.startsWith("c+")?r[a]={name:c.slice(2)}:r[a]=c;}return r}catch(r){throw new R(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((i,n)=>(e.pricing[n]&&(i[n]=new z(e.pricing[n])),i),{}),this.targetGender=e.targetGender,this.attributes=g.deepClone(e.attributes),this.specifications=g.deepClone(e.specifications),this.categories=g.deepClone(e.categories),this.variants=(e.variants||[]).map(i=>({sku:i.sku,selectionAttributes:i.selectionAttributes,images:{primary:new x(i.images.primary),gallery:(i.images.gallery||[]).map(n=>new x(n))}})),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[b[e]]??this.name.en:g.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[b[e]]??this.description.en:g.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[b[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)}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[b[e]]??this.specifications.en):g.deepClone(this.specifications)}getSearchTags(e){return e?g.deepClone(this.searchTags[e]??this.searchTags[b[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}}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 te={$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(V)},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"]},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(K)},currency:{type:"string",enum:Object.values(N)},locale:{type:"string",enum:Object.values(D)},language:{type:"string",enum:Object.values(L)},localeOrLanguage:{type:"string",enum:[...Object.values(D),...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 me={getStandardSchemaDefinition(){return te}},ye=me;var P=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 T={logException:(t,e)=>{console.error(`Exception Occurred in Function: ${t}, Error: ${T.inspect(e)}`);},logError:(t,e)=>{console.error(`Error Occurred in Function: ${t}, Error: ${T.inspect(e)}`);},logWarning:(t,e)=>{console.warn(`Warning in Function: ${t} - ${T.inspect(e)}`);},logMessage:(t,e)=>{console.log(`Message in Function: ${t} - ${T.inspect(e)}`);},logInvalidPayload:(t,e)=>{console.error(`Invalid Payload received for Function: ${t}, Error: ${T.inspect(e)}`);},inspect:t=>typeof t=="string"?t:fe__default.default.inspect(t)},y=T;var he={handleException:(t,e,r)=>{e.knownError?(e.logError&&y.logError(t,e),r.status(e.status).json({status:e.status,error:e.error})):e.status&&e.error?(y.logException(t,e),r.status(e.status).json({error:e.errorMessage||JSON.stringify(e.error),status:e.status})):(y.logException(t,e),r.status(500).json({status:500,error:P.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})},be=he;var Ie=async(t,e,r="GET",i={},n)=>{let a={method:r,headers:{"Content-Type":"application/json",...i}};r!=="GET"&&n&&(a.body=JSON.stringify(n));let c=`${t}${e?"/"+e:""}`,l=c.includes("api.xetile.com")||c.includes("localhost");try{let s=await fetch(c,a);if(!s.ok){let f,B=await s.text();try{f=JSON.parse(B);}catch{f={status:s.status,error:B||s.statusText},y.logWarning("Fetch",`Failed to parse error response body as JSON for URL-${c}. Raw text: ${B}`);}throw {status:s.status,statusText:s.statusText,error:f}}let u=await s.json();return y.logMessage("Fetch",`API call successful: URL-${c}, Status- ${s.status}`),{status:s.status,statusText:s.statusText,data:l?u.data:u}}catch(s){throw y.logError("Fetch",`API call failed: URL-${c}, Status- ${s.status||500}, Error- ${y.inspect(s.error||s)}`),{status:s.status||500,statusText:s.statusText||P.INTERNAL_SERVER_ERROR,error:s.error||{status:s.status||500,error:s.statusText||P.SOMETHING_WENT_WRONG}}}},xe=Ie;
|
|
2
|
+
exports.Fetch=xe;exports.Logger=y;exports.ResponseUtility=be;exports.Schema=ye;exports.Utils=g;//# sourceMappingURL=index.js.map
|
|
3
3
|
//# sourceMappingURL=index.js.map
|