b23-lib 3.0.6 → 3.0.8

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.
Files changed (126) hide show
  1. package/dist/Auth/index.js +1 -1
  2. package/dist/Auth/index.js.map +1 -1
  3. package/dist/Auth/index.mjs +1 -1
  4. package/dist/Classes/Address.d.mts +1 -1
  5. package/dist/Classes/Address.d.ts +1 -1
  6. package/dist/Classes/Address.js +1 -1
  7. package/dist/Classes/Address.js.map +1 -1
  8. package/dist/Classes/Address.mjs +1 -1
  9. package/dist/Classes/Base.d.mts +1 -1
  10. package/dist/Classes/Base.d.ts +1 -1
  11. package/dist/Classes/Base.js +1 -1
  12. package/dist/Classes/Base.js.map +1 -1
  13. package/dist/Classes/Base.mjs +1 -1
  14. package/dist/Classes/Cart.d.mts +1 -1
  15. package/dist/Classes/Cart.d.ts +1 -1
  16. package/dist/Classes/Cart.js +1 -1
  17. package/dist/Classes/Cart.js.map +1 -1
  18. package/dist/Classes/Cart.mjs +1 -1
  19. package/dist/Classes/Charge.d.mts +46 -1
  20. package/dist/Classes/Charge.d.ts +46 -1
  21. package/dist/Classes/Charge.js +1 -1
  22. package/dist/Classes/Charge.js.map +1 -1
  23. package/dist/Classes/Charge.mjs +1 -1
  24. package/dist/Classes/Common.d.mts +1 -1
  25. package/dist/Classes/Common.d.ts +1 -1
  26. package/dist/Classes/Coupon.d.mts +1 -1
  27. package/dist/Classes/Coupon.d.ts +1 -1
  28. package/dist/Classes/Coupon.js +1 -1
  29. package/dist/Classes/Coupon.js.map +1 -1
  30. package/dist/Classes/Coupon.mjs +1 -1
  31. package/dist/Classes/Customer.d.mts +1 -1
  32. package/dist/Classes/Customer.d.ts +1 -1
  33. package/dist/Classes/Customer.js +1 -1
  34. package/dist/Classes/Customer.js.map +1 -1
  35. package/dist/Classes/Customer.mjs +1 -1
  36. package/dist/Classes/CustomerAddress.d.mts +1 -1
  37. package/dist/Classes/CustomerAddress.d.ts +1 -1
  38. package/dist/Classes/CustomerAddress.js +1 -1
  39. package/dist/Classes/CustomerAddress.js.map +1 -1
  40. package/dist/Classes/CustomerAddress.mjs +1 -1
  41. package/dist/Classes/CustomerAddress.mjs.map +1 -1
  42. package/dist/Classes/Inventory.d.mts +1 -1
  43. package/dist/Classes/Inventory.d.ts +1 -1
  44. package/dist/Classes/Inventory.js +1 -1
  45. package/dist/Classes/Inventory.js.map +1 -1
  46. package/dist/Classes/Inventory.mjs +1 -1
  47. package/dist/Classes/Inventory.mjs.map +1 -1
  48. package/dist/Classes/LineItem.d.mts +1 -1
  49. package/dist/Classes/LineItem.d.ts +1 -1
  50. package/dist/Classes/LineItem.js +1 -1
  51. package/dist/Classes/LineItem.js.map +1 -1
  52. package/dist/Classes/LineItem.mjs +1 -1
  53. package/dist/Classes/Order.d.mts +5 -5
  54. package/dist/Classes/Order.d.ts +5 -5
  55. package/dist/Classes/Order.js +1 -1
  56. package/dist/Classes/Order.js.map +1 -1
  57. package/dist/Classes/Order.mjs +1 -1
  58. package/dist/Classes/Order.mjs.map +1 -1
  59. package/dist/Classes/Payment.d.mts +1 -1
  60. package/dist/Classes/Payment.d.ts +1 -1
  61. package/dist/Classes/Payment.js +1 -1
  62. package/dist/Classes/Payment.js.map +1 -1
  63. package/dist/Classes/Payment.mjs +1 -1
  64. package/dist/Classes/Price.d.mts +1 -1
  65. package/dist/Classes/Price.d.ts +1 -1
  66. package/dist/Classes/Product.d.mts +1 -1
  67. package/dist/Classes/Product.d.ts +1 -1
  68. package/dist/Classes/Product.js +1 -1
  69. package/dist/Classes/Product.js.map +1 -1
  70. package/dist/Classes/Product.mjs +1 -1
  71. package/dist/Classes/ShoppingContainer.d.mts +43 -2
  72. package/dist/Classes/ShoppingContainer.d.ts +43 -2
  73. package/dist/Classes/ShoppingContainer.js +1 -1
  74. package/dist/Classes/ShoppingContainer.js.map +1 -1
  75. package/dist/Classes/ShoppingContainer.mjs +1 -1
  76. package/dist/Classes/TaxRule.d.mts +1 -1
  77. package/dist/Classes/TaxRule.d.ts +1 -1
  78. package/dist/Classes/TaxRule.js +1 -1
  79. package/dist/Classes/TaxRule.js.map +1 -1
  80. package/dist/Classes/TaxRule.mjs +1 -1
  81. package/dist/Classes/TieredPrice.d.mts +1 -1
  82. package/dist/Classes/TieredPrice.d.ts +1 -1
  83. package/dist/Classes/TieredPrice.js +1 -1
  84. package/dist/Classes/TieredPrice.js.map +1 -1
  85. package/dist/Classes/TieredPrice.mjs +1 -1
  86. package/dist/{Common-Bd8Xv8x4.d.mts → Common-XM4zQpWC.d.mts} +1 -1
  87. package/dist/{Common-CXp_zjft.d.ts → Common-uAn7Sunn.d.ts} +1 -1
  88. package/dist/chunk-3RTEHBPX.mjs +2 -0
  89. package/dist/chunk-3RTEHBPX.mjs.map +1 -0
  90. package/dist/chunk-EB5IQLSA.mjs +2 -0
  91. package/dist/chunk-EB5IQLSA.mjs.map +1 -0
  92. package/dist/chunk-FSAVZRS6.mjs +2 -0
  93. package/dist/chunk-FSAVZRS6.mjs.map +1 -0
  94. package/dist/{chunk-YSUBOEFT.mjs → chunk-HX32EJ3F.mjs} +2 -2
  95. package/dist/{chunk-YSUBOEFT.mjs.map → chunk-HX32EJ3F.mjs.map} +1 -1
  96. package/dist/{chunk-6VRUVGN3.mjs → chunk-L3CNGDFJ.mjs} +2 -2
  97. package/dist/chunk-L3CNGDFJ.mjs.map +1 -0
  98. package/dist/chunk-NNMLXCUS.mjs +2 -0
  99. package/dist/chunk-NNMLXCUS.mjs.map +1 -0
  100. package/dist/chunk-UMVN5K5M.mjs +2 -0
  101. package/dist/chunk-UMVN5K5M.mjs.map +1 -0
  102. package/dist/chunk-UXZBULDS.mjs +2 -0
  103. package/dist/chunk-UXZBULDS.mjs.map +1 -0
  104. package/dist/chunk-XBFSNBKL.mjs +2 -0
  105. package/dist/chunk-XBFSNBKL.mjs.map +1 -0
  106. package/dist/index.d.mts +1 -1
  107. package/dist/index.d.ts +1 -1
  108. package/dist/index.js +2 -2
  109. package/dist/index.js.map +1 -1
  110. package/dist/index.mjs +1 -1
  111. package/package.json +1 -1
  112. package/dist/chunk-2ZQIRKRB.mjs +0 -2
  113. package/dist/chunk-2ZQIRKRB.mjs.map +0 -1
  114. package/dist/chunk-52Y5EI7O.mjs +0 -2
  115. package/dist/chunk-52Y5EI7O.mjs.map +0 -1
  116. package/dist/chunk-6KCJVEZD.mjs +0 -2
  117. package/dist/chunk-6KCJVEZD.mjs.map +0 -1
  118. package/dist/chunk-6VRUVGN3.mjs.map +0 -1
  119. package/dist/chunk-DLLGHKS5.mjs +0 -2
  120. package/dist/chunk-DLLGHKS5.mjs.map +0 -1
  121. package/dist/chunk-HR5HHV6O.mjs +0 -2
  122. package/dist/chunk-HR5HHV6O.mjs.map +0 -1
  123. package/dist/chunk-Y5D6RHTJ.mjs +0 -2
  124. package/dist/chunk-Y5D6RHTJ.mjs.map +0 -1
  125. package/dist/chunk-YKRWZ24N.mjs +0 -2
  126. package/dist/chunk-YKRWZ24N.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/Classes/Charge.ts"],"names":["ChargeModel","CustomFieldModel","data","PriceModel","r","FixedTaxRuleModel","discountId","discount","taxRuleId","taxBreakdown","locale","Utils_default","LocaleLanguageMap","key","value","taxRules","taxRule","InvalidTaxRuleError","appliedDiscounts","chargeDiscounts","zero","price","totalDiscount","sum","s","grossAmount","totalRate","taxableBase","totalTaxAmount","distributedTax","maxRateRule","prev","current","maxRateRuleId","rate","taxAmount","maxRateTaxAmount","netPrice","grandTotal","k","v"],"mappings":"4OAqEA,IAAqBA,EAArB,cAAyCC,CAAiB,CAC5C,EACA,CAAA,IAAA,CACA,SACA,UACA,CAAA,UAAA,CACA,OAKA,CAAA,KAAA,CAEV,YAAYC,CAAwB,CAAA,CAChC,MAAMA,CAAI,CAAA,CACV,KAAK,EAAKA,CAAAA,CAAAA,CAAK,EACf,CAAA,IAAA,CAAK,KAAOA,CAAK,CAAA,IAAA,CACjB,KAAK,QAAWA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AAC,CAAA,GAAM,CAACD,CAAAA,CAAG,CACzF,IAAMC,CAAAA,CAAAA,CAAE,KACR,YAAcA,CAAAA,CAAAA,CAAE,aAAa,UAAW,EAAA,CACxC,OAAQA,CAAE,CAAA,MAAA,CAAO,YACjB,CAAA,MAAA,CAAQA,EAAE,MACV,CAAA,SAAA,CAAWA,EAAE,SACjB,CAAC,CAAC,CAAC,EACH,QAAU,CAAA,IAAA,CAAK,MAAM,QAAS,CAAA,UAAA,GAC9B,UAAY,CAAA,IAAA,CAAK,MAAM,UAAW,CAAA,UAAA,EACtC,CACA,CAAA,YAAA,CAAc,KAAK,kBAAmB,EAC1C,CAEJ,CACJ","file":"chunk-UMVN5K5M.mjs","sourcesContent":["import BaseModel, { BaseAttributes, BaseData, CustomFieldAttributes, CustomFieldModel } from \"./Base\";\r\nimport Utils from \"../Utils\";\r\nimport { LocaleCode, LocalizedString } from \"./Common\";\r\nimport { ChargeType, LocaleLanguageMap, TaxSystem } from \"./Enum\";\r\nimport { InvalidTaxRuleError } from \"./Error\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport { FixedTaxRuleData, FixedTaxRuleModel, TaxRuleData, TaxRuleModel } from \"./TaxRule\";\r\nimport CouponModel from \"./Coupon\";\r\n\r\nexport type ChargePricing = {\r\n price: PriceData;\r\n taxCategory: string;\r\n applicableTaxRule: FixedTaxRuleData[];\r\n};\r\n\r\nexport type ChargeTaxBreakdown = {\r\n rate: number;\r\n taxablePrice: PriceData;\r\n amount: PriceData;\r\n system: TaxSystem;\r\n subSystem: string;\r\n};\r\n\r\nexport type ChargeTaxBreakdownModel = {\r\n rate: number;\r\n taxablePrice: PriceModel;\r\n amount: PriceModel;\r\n system: TaxSystem;\r\n subSystem: string;\r\n};\r\n\r\nexport type ChargeTotals = {\r\n price: PriceData;\r\n discounts: Record<string, PriceData>;\r\n totalDiscount: PriceData;\r\n netPrice: PriceData;\r\n taxBreakdown: Record<string, ChargeTaxBreakdown>;\r\n taxTotal: PriceData;\r\n grandTotal: PriceData;\r\n};\r\n\r\nexport type ChargeTotalsModel = {\r\n price: PriceModel;\r\n discounts: Record<string, PriceModel>;\r\n totalDiscount: PriceModel;\r\n netPrice: PriceModel;\r\n taxBreakdown: Record<string, ChargeTaxBreakdownModel>;\r\n taxTotal: PriceModel;\r\n grandTotal: PriceModel;\r\n};\r\n\r\nexport type ChargeAttributes = CustomFieldAttributes & {\r\n id: string;\r\n name: LocalizedString;\r\n category: string;\r\n lineItemId?: string;\r\n chargeType: ChargeType;\r\n pricing: ChargePricing;\r\n total: ChargeTotals;\r\n};\r\n\r\nexport type ChargeData = Omit<Required<ChargeAttributes>, 'lineItemId'> & {\r\n lineItemId?: string;\r\n};\r\n\r\n/**\r\n * Represents an additional charge (or discount if amount is negative) in a shopping container.\r\n * Supports its own tax rules.\r\n */\r\nexport default class ChargeModel extends CustomFieldModel {\r\n protected id: string;\r\n protected name: LocalizedString;\r\n protected category: string;\r\n protected lineItemId?: string;\r\n protected chargeType: ChargeType;\r\n protected pricing: {\r\n price: PriceModel;\r\n taxCategory: string;\r\n applicableTaxRule: FixedTaxRuleModel[];\r\n };\r\n protected total: ChargeTotalsModel;\r\n\r\n constructor(data: ChargeAttributes) {\r\n super(data);\r\n this.id = data.id;\r\n this.name = data.name;\r\n this.category = data.category;\r\n this.lineItemId = data.lineItemId;\r\n this.chargeType = data.chargeType;\r\n this.pricing = {\r\n price: new PriceModel(data.pricing.price),\r\n taxCategory: data.pricing.taxCategory,\r\n applicableTaxRule: data.pricing.applicableTaxRule.map(r => new FixedTaxRuleModel(r))\r\n };\r\n\r\n this.total = {\r\n price: new PriceModel(data.total.price),\r\n discounts: Object.fromEntries(\r\n Object.entries(data.total.discounts).map(([discountId, discount]) => [\r\n discountId,\r\n new PriceModel(discount)\r\n ])\r\n ),\r\n totalDiscount: new PriceModel(data.total.totalDiscount),\r\n netPrice: new PriceModel(data.total.netPrice),\r\n taxBreakdown: Object.fromEntries(\r\n Object.entries(data.total.taxBreakdown).map(([taxRuleId, taxBreakdown]) => [\r\n taxRuleId,\r\n {\r\n rate: taxBreakdown.rate,\r\n taxablePrice: new PriceModel(taxBreakdown.taxablePrice),\r\n amount: new PriceModel(taxBreakdown.amount),\r\n system: taxBreakdown.system,\r\n subSystem: taxBreakdown.subSystem\r\n }\r\n ])\r\n ),\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 charge.\r\n * @returns \r\n */\r\n public getId(): string { return this.id; }\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 charge category.\r\n * @returns The category string.\r\n */\r\n public getCategory(): string { return this.category; }\r\n\r\n /**\r\n * Gets the charge type.\r\n * @returns The charge type enum value.\r\n */\r\n public getChargeType(): ChargeType { return this.chargeType; }\r\n\r\n /**\r\n * Gets the related line item id, if any.\r\n * @returns The line item id or undefined.\r\n */\r\n public getLineItemId(): string | undefined { return this.lineItemId; }\r\n\r\n /**\r\n * Gets the pricing details (models) for this charge.\r\n * @returns Pricing details including price, tax category, and tax rules.\r\n */\r\n public getPricing() {\r\n return {\r\n price: this.pricing.price,\r\n taxCategory: this.pricing.taxCategory,\r\n applicableTaxRule: [...this.pricing.applicableTaxRule]\r\n };\r\n }\r\n \r\n /**\r\n * Gets the computed totals for this charge.\r\n * @returns Totals including discounts, taxes, and grand total.\r\n */\r\n public getTotal(): ChargeTotalsModel {\r\n return {\r\n price: this.total.price,\r\n discounts: { ...this.total.discounts },\r\n netPrice: this.total.netPrice,\r\n totalDiscount: this.total.totalDiscount,\r\n taxBreakdown: Object.fromEntries(\r\n Object.entries(this.total.taxBreakdown).map(([key, value]) => [\r\n key,\r\n {\r\n rate: value.rate,\r\n taxablePrice: value.taxablePrice,\r\n amount: value.amount,\r\n system: value.system,\r\n subSystem: value.subSystem\r\n }\r\n ])\r\n ),\r\n taxTotal: this.total.taxTotal,\r\n grandTotal: this.total.grandTotal,\r\n };\r\n }\r\n\r\n /**\r\n * Gets the applicable tax rules for this charge.\r\n * @returns A list of tax rules.\r\n */\r\n public getApplicableTaxRules(): FixedTaxRuleModel[] {\r\n return [...this.pricing.applicableTaxRule];\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(taxRules: FixedTaxRuleModel[]): void {\r\n taxRules.forEach(taxRule => {\r\n if (!taxRule.appliesTo(this.pricing.taxCategory, taxRule.getTaxCountry())) {\r\n throw new InvalidTaxRuleError();\r\n }\r\n });\r\n\r\n // Remove the old taxableUnitPrice calculation - no longer needed\r\n this.pricing.applicableTaxRule = taxRules;\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 chargeDiscounts = {} as Record<string, PriceModel>;\r\n appliedDiscounts.forEach(discount => {\r\n chargeDiscounts[discount.coupon.getCode()] = discount.amount;\r\n });\r\n\r\n this.total.discounts = chargeDiscounts;\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Recalculates totals for this charge based on pricing and discounts.\r\n */\r\n public calculateTotals(): void {\r\n const zero = this.pricing.price.zero();\r\n const price = this.pricing.price;\r\n\r\n const totalDiscount = Object.values(this.total.discounts).reduce((sum, s) => sum.add(s), zero);\r\n const grossAmount = price.subtract(totalDiscount);\r\n\r\n const taxBreakdown: Record<string, ChargeTaxBreakdownModel> = {};\r\n\r\n // 1. Calculate total rate for inclusive back-calculation\r\n const totalRate = this.pricing.applicableTaxRule.reduce((sum, r) => sum + r.getApplicableTaxRate(), 0);\r\n\r\n // 2. Calculate BASE and TOTAL TAX using balancing logic\r\n // We round the base first, then define tax as the residual (Gross - Base)\r\n // This guarantees Base + Tax === GrandTotal (inclusive price)\r\n const taxableBase = grossAmount.divide(1 + totalRate).round();\r\n const totalTaxAmount = totalRate > 0 ? grossAmount.subtract(taxableBase) : zero;\r\n\r\n // 3. Distribute total tax among rules\r\n // We find the rule with the largest rate to absorb the rounding residual\r\n let distributedTax = zero;\r\n const maxRateRule = this.pricing.applicableTaxRule.reduce((prev, current) =>\r\n (current.getApplicableTaxRate() > prev.getApplicableTaxRate()) ? current : prev\r\n );\r\n const maxRateRuleId = maxRateRule.getTaxRuleId();\r\n\r\n // Calculate all other rules first\r\n this.pricing.applicableTaxRule.forEach((taxRule) => {\r\n if (taxRule.getTaxRuleId() === maxRateRuleId) return;\r\n\r\n const rate = taxRule.getApplicableTaxRate();\r\n const taxAmount = totalRate > 0 ? totalTaxAmount.multiply(rate).divide(totalRate).round() : zero;\r\n\r\n taxBreakdown[taxRule.getTaxRuleId()] = {\r\n rate: rate,\r\n taxablePrice: taxableBase,\r\n amount: taxAmount,\r\n system: taxRule.getTaxSystem(),\r\n subSystem: taxRule.getTaxSubSystem()\r\n };\r\n distributedTax = distributedTax.add(taxAmount);\r\n });\r\n\r\n // Assign residual to the largest rate rule\r\n const maxRateTaxAmount = totalTaxAmount.subtract(distributedTax);\r\n taxBreakdown[maxRateRuleId] = {\r\n rate: maxRateRule.getApplicableTaxRate(),\r\n taxablePrice: taxableBase,\r\n amount: maxRateTaxAmount,\r\n system: maxRateRule.getTaxSystem(),\r\n subSystem: maxRateRule.getTaxSubSystem()\r\n };\r\n\r\n const netPrice = taxableBase;\r\n const grandTotal = grossAmount;\r\n\r\n this.total = {\r\n price: price,\r\n discounts: this.total.discounts,\r\n netPrice: netPrice,\r\n totalDiscount: totalDiscount,\r\n taxBreakdown: taxBreakdown,\r\n taxTotal: totalTaxAmount,\r\n grandTotal: grandTotal\r\n };\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing this charge.\r\n * @returns ChargeData for serialization.\r\n */\r\n public getDetails(): ChargeData {\r\n const details: ChargeData = {\r\n id: this.id,\r\n name: Utils.deepClone(this.name),\r\n category: this.category,\r\n lineItemId: this.lineItemId,\r\n chargeType: this.chargeType,\r\n pricing: {\r\n price: this.pricing.price.getDetails(),\r\n taxCategory: this.pricing.taxCategory,\r\n applicableTaxRule: this.pricing.applicableTaxRule.map(r => r.getDetails())\r\n },\r\n total: {\r\n price: this.total.price.getDetails(),\r\n discounts: Object.fromEntries(Object.entries(this.total.discounts).map(([k, v]) => [k, v.getDetails()])),\r\n totalDiscount: this.total.totalDiscount.getDetails(),\r\n netPrice: this.total.netPrice.getDetails(),\r\n taxBreakdown: Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([k, v]) => [k, {\r\n rate: v.rate,\r\n taxablePrice: v.taxablePrice.getDetails(),\r\n amount: v.amount.getDetails(),\r\n system: v.system,\r\n subSystem: v.subSystem\r\n }])),\r\n taxTotal: this.total.taxTotal.getDetails(),\r\n grandTotal: this.total.grandTotal.getDetails()\r\n },\r\n customFields: this.getAllCustomFields()\r\n };\r\n return details;\r\n }\r\n}\r\n"]}
@@ -0,0 +1,2 @@
1
+ var d=i=>structuredClone(i),s=class{customFields;constructor(e,t=new Date){this.customFields={...e.customFields};}getCustomField(e){let t=this.customFields[e];return t==null?t:d(t)}setCustomField(e,t){this.customFields[e]=t;}getAllCustomFields(){return d(this.customFields)}},r=class extends s{version;createdAt;modifiedAt;modifiedBy;constructor(e,t=new Date){super(e),this.version=e.version??1,this.createdAt=e.createdAt&&!isNaN(Date.parse(e.createdAt))?new Date(e.createdAt).toISOString():t.toISOString(),this.modifiedAt=e.modifiedAt&&!isNaN(Date.parse(e.modifiedAt))?new Date(e.modifiedAt).toISOString():t.toISOString(),this.modifiedBy={...e.modifiedBy};}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return {...this.modifiedBy}}setModifiedBy(e,t,o,n){this.modifiedBy={id:e,authType:t,requestId:o,lambdaName:n};}};export{s as a,r as b};//# sourceMappingURL=chunk-UXZBULDS.mjs.map
2
+ //# sourceMappingURL=chunk-UXZBULDS.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/Classes/Base.ts"],"names":["deepClone","obj","CustomFieldModel","data","date","fieldName","value","BaseModel","id","authType","requestId","lambdaName"],"mappings":"AAGMA,IAAAA,CAAAA,CAAgBC,CAAc,EAAA,eAAA,CAAgBA,CAAG,CAAA,CAU1CC,EAAN,KAAuB,CAClB,YACV,CAAA,WAAA,CAAYC,CAA6BC,CAAAA,CAAAA,CAAa,IAAI,IAAQ,CAAA,CAChE,IAAK,CAAA,YAAA,CAAe,CAAE,GAAGD,EAAK,YAAa,EAC7C,CAOA,cAAA,CAAeE,CAAwB,CAAA,CACrC,IAAMC,CAAQ,CAAA,IAAA,CAAK,YAAaD,CAAAA,CAAS,CACzC,CAAA,OAA2BC,GAAU,IAAaA,CAAAA,CAAAA,CAC3CN,CAAUM,CAAAA,CAAK,CACxB,CAQA,eAAeD,CAAmBC,CAAAA,CAAAA,CAAkB,CAClD,IAAA,CAAK,YAAaD,CAAAA,CAAS,CAAIC,CAAAA,EACjC,CAMA,kBAAA,EAAmC,CACjC,OAAON,CAAU,CAAA,IAAA,C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AAO,IAAK,CAAA,UACd,CAMA,iBAAA,EAA4B,CAC1B,OAAO,IAAI,IAAA,CAAK,IAAK,CAAA,UAAU,CAAE,CAAA,OAAA,EACnC,CAMA,eAA4B,CAC1B,OAAO,CAAE,GAAG,IAAK,CAAA,UAAW,CAC9B,CAMA,aAAA,CAAcK,CAAaC,CAAAA,CAAAA,CAAqBC,CAAoBC,CAAAA,CAAAA,CAA2B,CAC7F,IAAK,CAAA,UAAA,CAAa,CAChB,EAAA,CAAAH,CACA,CAAA,QAAA,CAAAC,CACA,CAAA,SAAA,CAAAC,CACA,CAAA,UAAA,CAAAC,CACF,EACF,CACF","file":"chunk-UXZBULDS.mjs","sourcesContent":["import { AuthType } from \"../Auth\";\nimport { ISODateTimeUTC, Prettify } from \"./Common\";\n\nconst deepClone = <T>(obj: T): T => structuredClone(obj);\n\r\nexport interface CustomFields {\r\n [key: string]: any;\r\n}\r\n\r\nexport type CustomFieldAttributes = {\r\n customFields?: CustomFields;\r\n}\r\n\r\nexport class CustomFieldModel {\r\n protected customFields: CustomFields;\r\n constructor(data: CustomFieldAttributes, date: Date = new Date()) {\r\n this.customFields = { ...data.customFields };\r\n }\r\n\r\n /**\r\n * Retrieves the value of a specific custom field.\r\n * @param fieldName - The name (key) of the custom field to retrieve.\r\n * @returns The value of the custom field, or null if the field does not exist.\r\n */\r\n getCustomField(fieldName: string): any {\n const value = this.customFields[fieldName];\n if (value === undefined || value === null) return value;\n return deepClone(value);\n }\n\r\n /**\r\n * Sets the value of a specific custom field.\r\n * Also updates the modification timestamp and increments the version.\r\n * @param fieldName - The name (key) of the custom field to set.\r\n * @param value - The value to assign to the custom field.\r\n */\r\n setCustomField(fieldName: string, value: any): void {\r\n this.customFields[fieldName] = value;\r\n }\r\n\r\n /**\r\n * Retrieves a shallow copy of all custom fields associated with the instance.\r\n * @returns An object containing all custom fields.\r\n */\r\n getAllCustomFields(): CustomFields {\n return deepClone(this.customFields);\n }\n}\r\n\r\nexport type ModifiedBy = {\r\n id?: string;\r\n authType?: string;\r\n requestId?: string;\r\n lambdaName?: string;\r\n}\r\n\r\nexport type BaseAttributes = Prettify<CustomFieldAttributes & {\r\n version?: number;\r\n createdAt?: ISODateTimeUTC;\r\n modifiedAt?: ISODateTimeUTC;\r\n modifiedBy?: ModifiedBy;\r\n}>;\r\n\r\nexport type BaseData = Required<BaseAttributes>;\r\n\r\n/**\r\n * Provides common foundational properties and methods for other data models.\r\n * Handles tracking of custom fields, versioning, and timestamps.\r\n */\r\nexport default class BaseModel extends CustomFieldModel {\r\n protected version: number;\r\n protected createdAt: ISODateTimeUTC;\r\n protected modifiedAt: ISODateTimeUTC;\r\n protected modifiedBy: ModifiedBy;\r\n\r\n /**\r\n * Creates an instance of BaseModel.\r\n * Initializes common properties like timestamps, version, and custom fields.\r\n * @param data - Optional initial attributes for the base model.\r\n * @param date - Optional date object to use for default timestamps (defaults to current time).\r\n */\r\n constructor(data: BaseAttributes, date: Date = new Date()) {\r\n super(data);\r\n this.version = data.version ?? 1;\r\n this.createdAt = data.createdAt && !isNaN(Date.parse(data.createdAt))\r\n ?\r\n new Date(data.createdAt).toISOString()\r\n :\r\n date.toISOString();\r\n this.modifiedAt = data.modifiedAt && !isNaN(Date.parse(data.modifiedAt))\r\n ? new Date(data.modifiedAt).toISOString()\r\n : date.toISOString();\r\n\r\n this.modifiedBy = { ...data.modifiedBy };\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the base model's current state.\r\n * @returns BaseData object containing common properties.\r\n */\r\n getDetails(): BaseData {\r\n return {\r\n customFields: this.getAllCustomFields(), // Use getter to return a copy\r\n version: this.getVersion(),\r\n createdAt: this.getCreatedAt(),\r\n modifiedAt: this.getModifiedAt(),\r\n modifiedBy: this.getModifiedBy(),\r\n }\r\n }\r\n\r\n /**\r\n * Gets the current version number of the model instance.\r\n * @returns The version number.\r\n */\r\n getVersion(): number {\r\n return this.version;\r\n }\r\n\r\n /**\r\n * Gets the creation timestamp as an ISO 8601 string.\r\n * @returns The creation timestamp string.\r\n */\r\n getCreatedAt(): string {\r\n return this.createdAt;\r\n }\r\n\r\n /**\r\n * Gets the creation timestamp as a Unix epoch time (milliseconds).\r\n * @returns The creation time in milliseconds since the epoch.\r\n */\r\n getCreatedAtTime(): number {\r\n return new Date(this.createdAt).getTime();\r\n }\r\n\r\n\r\n /**\r\n * Gets the last modification timestamp as an ISO 8601 string.\r\n * @returns The last modification timestamp string.\r\n */\r\n getModifiedAt(): string {\r\n return this.modifiedAt;\r\n }\r\n\r\n /**\r\n * Gets the last modification timestamp as a Unix epoch time (milliseconds).\r\n * @returns The last modification time in milliseconds since the epoch.\r\n */\r\n getModifiedAtTime(): number {\r\n return new Date(this.modifiedAt).getTime();\r\n }\r\n\r\n /**\r\n * Gets the identifier of the user or process that last modified the instance.\r\n * @returns\r\n */\r\n getModifiedBy(): ModifiedBy {\r\n return { ...this.modifiedBy };\r\n }\r\n\r\n /**\r\n * Sets the identifier of the user or process that last modified the instance.\r\n * @param modifiedBy - The identifier string.\r\n */\r\n setModifiedBy(id?: string, authType?: AuthType, requestId?: string, lambdaName?: string): void {\r\n this.modifiedBy = {\r\n id,\r\n authType,\r\n requestId,\r\n lambdaName,\r\n };\r\n }\r\n}\r\n"]}
@@ -0,0 +1,2 @@
1
+ import {a}from'./chunk-XHGUVYQO.mjs';import {k,l,m as m$1,n,o}from'./chunk-XPKK6DFA.mjs';var m=class{baseUnitPrice;taxCategory;tiers;constructor(t){let i=new a(t.baseUnitPrice);if(!t.taxCategory)throw new k;let r=(t.tiers??[]).map(e=>({minQuantity:e.minQuantity,unitPrice:new a(e.unitPrice)})).sort((e,n)=>e.minQuantity-n.minQuantity);if(r.some(e=>e.minQuantity<=0))throw new l;let y=r.some(e=>e.unitPrice.getCurrency()!==i.getCurrency()),g=r.some((e,n)=>n>0&&e.unitPrice.compareTo(r[n-1].unitPrice)>0),h=r[0]?.unitPrice.compareTo(i)>0;if(y||g||h)throw new m$1("Tiers must share the same currency and must not increase in unit price.");this.baseUnitPrice=i,this.taxCategory=t.taxCategory,this.tiers=r;}getBaseUnitPrice(){return this.baseUnitPrice}getTaxCategory(){return this.taxCategory}getTiers(){return this.tiers.map(t=>({minQuantity:t.minQuantity,unitPrice:t.unitPrice}))}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 n;for(let i=this.tiers.length-1;i>=0;i--)if(t>=this.tiers[i].minQuantity){let r=this.tiers[i];return {minQuantity:r.minQuantity,unitPrice:r.unitPrice}}throw new o(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(),i=this.baseUnitPrice.getAmount();return (i-t)/i*100}};export{m as a};//# sourceMappingURL=chunk-XBFSNBKL.mjs.map
2
+ //# sourceMappingURL=chunk-XBFSNBKL.mjs.map
@@ -0,0 +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","NoApplicableTierError","lowestTierPrice","basePrice"],"mappings":"yFAiCO,IAAMA,CAAN,CAAA,KAAuB,CAClB,aAAA,CACA,WACA,CAAA,KAAA,CAWV,WAAYC,CAAAA,CAAAA,CAA6B,CACvC,IAAMC,CAAgB,CAAA,IAAIC,EAAWF,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,IAAIK,CAAS,GAAA,CACZ,WAAaA,CAAAA,CAAAA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import 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: string;\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: string;\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(): string {\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[] {\n return this.tiers.map(tier => ({\n minQuantity: tier.minQuantity,\n unitPrice: tier.unitPrice\n }));\n }\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 {\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 const tier = this.tiers[i];\n return { minQuantity: tier.minQuantity, unitPrice: tier.unitPrice };\n }\n }\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 { GenderCategory, OperationalCountry, OperationalCountryCurrency, Operati
2
2
  import { SelectionAttributes } from './Classes/Product.mjs';
3
3
  import './Classes/Base.mjs';
4
4
  import './Auth/index.mjs';
5
- import './Common-Bd8Xv8x4.mjs';
5
+ import './Common-XM4zQpWC.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 { GenderCategory, OperationalCountry, OperationalCountryCurrency, Operati
2
2
  import { SelectionAttributes } from './Classes/Product.js';
3
3
  import './Classes/Base.js';
4
4
  import './Auth/index.js';
5
- import './Common-CXp_zjft.js';
5
+ import './Common-uAn7Sunn.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||{}),$=(r=>(r.en="en",r.kn="kn",r))($||{}),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 M=new Uint8Array(256),L=M.length;function G(){return L>M.length-16&&(ie__default.default.randomFillSync(M),L=0),M.slice(L,L+=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 j(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 Y={randomUUID:ie__default.default.randomUUID};function le(t,e,r){if(Y.randomUUID&&!e&&!t)return Y.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 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=j("v5",80,te),Q=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?Q(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 H=class{customFields;constructor(e,r=new Date){this.customFields={...e.customFields};}getCustomField(e){return this.customFields[e]??null}setCustomField(e,r){this.customFields[e]=r;}getAllCustomFields(){return {...this.customFields}}},E=class extends H{version;createdAt;modifiedAt;modifiedBy;constructor(e,r=new Date){super(e),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};}};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 C=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";}},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 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 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 S=class t{#e;amount;currency;constructor(e){if(this.#e="PriceModel",e.amount<0)throw new C("Amount cannot be negative.");if(!e.currency)throw new I("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},this)}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},this)}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 I("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 C("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 K=class{baseUnitPrice;taxCategory;tiers;constructor(e){let r=new S(e.baseUnitPrice);if(!e.taxCategory)throw new v;let i=(e.tiers??[]).map(s=>({minQuantity:s.minQuantity,unitPrice:new S(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 E{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 x(n.images.primary),gallery:(n.images.gallery||[]).map(c=>new x(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},genderCategory:{type:"string",enum:Object.values(k)},price:{type:"object",properties:{amount:{type:"number",minimum:0},currency:{$ref:"#/definitions/currency"}},additionalProperties:!1,required:["amount","currency"]},color:{type:"object",properties:{name:{type:"string"},hex:{type:"string"}},additionalProperties:!1,required:["name"]},attributeValue:{oneOf:[{type:"string"},{$ref:"#/definitions/color"}]},selectionAttributes:{type:"object",properties:{color:{$ref:"#/definitions/color"}},required:["color"],additionalProperties:{$ref:"#/definitions/attributeValue"}},firstName:{$ref:"#/definitions/requiredText30"},lastName:{$ref:"#/definitions/text30"},company:{$ref:"#/definitions/text50"},phone:{type:"string",pattern:"^[0-9]{10}$"},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($)},localeOrLanguage:{type:"string",enum:[...Object.values(w),...Object.values($)]},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 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:he__default.default.inspect(t)},f=T;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 Ie=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}}}},xe=Ie;
2
- exports.Fetch=xe;exports.Logger=f;exports.ResponseUtility=Ae;exports.Schema=fe;exports.Utils=g;//# sourceMappingURL=index.js.map
1
+ 'use strict';var ne=require('crypto'),be=require('util');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ne__default=/*#__PURE__*/_interopDefault(ne);var be__default=/*#__PURE__*/_interopDefault(be);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||{}),$=(r=>(r.en="en",r.kn="kn",r))($||{}),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 M=new Uint8Array(256),L=M.length;function G(){return L>M.length-16&&(ne__default.default.randomFillSync(M),L=0),M.slice(L,L+=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 se(t){return typeof t=="string"&&Z.test(t)}var X=se;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 oe(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=oe;function ae(t){t=unescape(encodeURIComponent(t));let e=[];for(let r=0;r<t.length;++r)e.push(t.charCodeAt(r));return e}var ce="6ba7b810-9dad-11d1-80b4-00c04fd430c8",ue="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function j(t,e,r){function i(n,o,c,l){var s;if(typeof n=="string"&&(n=ae(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=ce,i.URL=ue,i}var Q={randomUUID:ne__default.default.randomUUID};function de(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 R(i)}var Y=de;function pe(t){return Array.isArray(t)?t=Buffer.from(t):typeof t=="string"&&(t=Buffer.from(t,"utf8")),ne__default.default.createHash("sha1").update(t).digest()}var te=pe;var me=j("v5",80,te),q=me;var ye={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,selectionAttributes:h.parseSelectionAttributesKey(r)}},deepClone(t){return structuredClone(t)}},g=ye;var re=t=>structuredClone(t),H=class{customFields;constructor(e,r=new Date){this.customFields={...e.customFields};}getCustomField(e){let r=this.customFields[e];return r==null?r:re(r)}setCustomField(e,r){this.customFields[e]=r;}getAllCustomFields(){return re(this.customFields)}},C=class extends H{version;createdAt;modifiedAt;modifiedBy;constructor(e,r=new Date){super(e),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};}};var v=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 O=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";}},I=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 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 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 I("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},this)}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},this)}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 I("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 I("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 O;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.map(e=>({minQuantity:e.minQuantity,unitPrice:e.unitPrice}))}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){let i=this.tiers[r];return {minQuantity:i.minQuantity,unitPrice:i.unitPrice}}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 v(o);return i.add(o),{sku:n.sku,selectionAttributes:n.selectionAttributes,images:{primary:new x(n.images.primary),gallery:(n.images.gallery||[]).map(c=>new x(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:g.deepClone(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?{primary:i.images.primary,gallery:[...i.images.gallery]}: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 ie={$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},genderCategory:{type:"string",enum:Object.values(k)},price:{type:"object",properties:{amount:{type:"number",minimum:0},currency:{$ref:"#/definitions/currency"}},additionalProperties:!1,required:["amount","currency"]},color:{type:"object",properties:{name:{type:"string"},hex:{type:"string"}},additionalProperties:!1,required:["name"]},attributeValue:{oneOf:[{type:"string"},{$ref:"#/definitions/color"}]},selectionAttributes:{type:"object",properties:{color:{$ref:"#/definitions/color"}},required:["color"],additionalProperties:{$ref:"#/definitions/attributeValue"}},firstName:{$ref:"#/definitions/requiredText30"},lastName:{$ref:"#/definitions/text30"},company:{$ref:"#/definitions/text50"},phone:{type:"string",pattern:"^[0-9]{10}$"},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($)},localeOrLanguage:{type:"string",enum:[...Object.values(w),...Object.values($)]},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 fe={getStandardSchemaDefinition(){return ie}},he=fe;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:be__default.default.inspect(t)},f=S;var Ae={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})},Ie=Ae;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}}}},Te=xe;
2
+ exports.Fetch=Te;exports.Logger=f;exports.ResponseUtility=Ie;exports.Schema=he;exports.Utils=g;//# sourceMappingURL=index.js.map
3
3
  //# sourceMappingURL=index.js.map