b23-lib 3.2.3 → 3.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Classes/Cart.js +1 -1
- package/dist/Classes/Cart.js.map +1 -1
- package/dist/Classes/Cart.mjs +1 -1
- package/dist/Classes/Charge.d.mts +2 -2
- package/dist/Classes/Charge.d.ts +2 -2
- package/dist/Classes/Charge.js +1 -1
- package/dist/Classes/Charge.js.map +1 -1
- package/dist/Classes/Charge.mjs +1 -1
- package/dist/Classes/Order.js +1 -1
- package/dist/Classes/Order.js.map +1 -1
- package/dist/Classes/Order.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/{chunk-B5JKMVLT.mjs → chunk-3TUSUSXQ.mjs} +2 -2
- package/dist/{chunk-B5JKMVLT.mjs.map → chunk-3TUSUSXQ.mjs.map} +1 -1
- package/dist/{chunk-BSDPFVRK.mjs → chunk-G6LH7V5B.mjs} +2 -2
- package/dist/{chunk-BSDPFVRK.mjs.map → chunk-G6LH7V5B.mjs.map} +1 -1
- package/dist/index.d.mts +48 -1
- package/dist/index.d.ts +48 -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/index.d.ts
CHANGED
|
@@ -317,4 +317,51 @@ declare const Logger: {
|
|
|
317
317
|
inspect: (context: any) => string;
|
|
318
318
|
};
|
|
319
319
|
|
|
320
|
-
|
|
320
|
+
/**
|
|
321
|
+
* In-memory cache with per-entry TTL expiration and LRU-style eviction.
|
|
322
|
+
*
|
|
323
|
+
* Keys are `string` and values are generic (`T`).
|
|
324
|
+
* Expired entries are removed lazily on `get` and periodically by a cleanup timer.
|
|
325
|
+
*/
|
|
326
|
+
declare class MemoryCache<T> {
|
|
327
|
+
private cache;
|
|
328
|
+
private maxSize;
|
|
329
|
+
private ttl;
|
|
330
|
+
private cleanupInterval;
|
|
331
|
+
/**
|
|
332
|
+
* Creates a cache instance.
|
|
333
|
+
*
|
|
334
|
+
* @param maxSize Maximum number of live entries allowed in cache. Must be >= 1.
|
|
335
|
+
* @param ttl Time-to-live in milliseconds for each entry from write time. Must be >= 1.
|
|
336
|
+
*/
|
|
337
|
+
constructor(maxSize?: number, ttl?: number);
|
|
338
|
+
/**
|
|
339
|
+
* Removes expired entries from the cache.
|
|
340
|
+
*/
|
|
341
|
+
private cleanup;
|
|
342
|
+
/**
|
|
343
|
+
* Stores or updates a value in cache.
|
|
344
|
+
* If the key already exists, the value and expiry are replaced.
|
|
345
|
+
* If capacity is reached and key is new, least-recently-used entry is evicted.
|
|
346
|
+
*
|
|
347
|
+
* @param key Cache key.
|
|
348
|
+
* @param value Value to store.
|
|
349
|
+
*/
|
|
350
|
+
set(key: string, value: T): void;
|
|
351
|
+
/**
|
|
352
|
+
* Reads a value by key.
|
|
353
|
+
* Returns `undefined` if the key does not exist or if the entry has expired.
|
|
354
|
+
* Access refreshes recency for eviction order (LRU behavior).
|
|
355
|
+
*
|
|
356
|
+
* @param key Cache key.
|
|
357
|
+
* @returns Cached value or `undefined`.
|
|
358
|
+
*/
|
|
359
|
+
get(key: string): T | undefined;
|
|
360
|
+
/**
|
|
361
|
+
* Stops the background cleanup timer.
|
|
362
|
+
* Call when the cache instance is no longer needed.
|
|
363
|
+
*/
|
|
364
|
+
dispose(): void;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
export { type ErrorType, Fetch, Logger, MemoryCache, ResponseUtility, Schema, type SuccessType, Utils };
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
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)}},P=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 C=class extends Error{constructor(e="Amount cannot be negative."){super(`InvalidAmount: ${e}`),this.name="InvalidPriceAmountError";}},x=class extends Error{constructor(e="Currency code is required."){super(`InvalidCurrency: ${e}`),this.name="InvalidCurrencyCodeError";}},y=class extends Error{constructor(e="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${e}`),this.name="CurrencyMismatchError";}},p=class extends Error{constructor(e){super(`InvalidArgument: ${e}`),this.name="InvalidArgumentError";}},E=class extends Error{constructor(e="Invalid image source configuration."){super(`InvalidImageSource: ${e}`),this.name="InvalidImageSourceError";}};var I=class{sources;alt;order;label;constructor(e){if(this.sources={...e.sources},this.alt=e.alt,this.order=e.order,this.label=e.label,!this.sources.original)throw new E("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 E("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 C("Amount cannot be negative.");if(!e.currency)throw new x("Currency code is required.");this.currency=e.currency,this.amount=parseFloat(e.amount.toFixed(t.getPrecisionPlaces(this.currency)));}get kind(){return this.#e}static isPriceModel(e){return typeof e=="object"&&e!==null&&e.kind==="PriceModel"}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}getPreciseAmount(e){return parseFloat(e.toFixed(t.getPrecisionPlaces(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.getPreciseAmount(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.getPreciseAmount(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.getPreciseAmount(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.getPreciseAmount(this.amount*e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>=0)return new t({amount:this.getPreciseAmount(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.getPreciseAmount(this.amount/e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>0)return new t({amount:this.getPreciseAmount(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 x("Invalid currency code for formatting.");let o=e,c=i.displayAsInteger?0:t.getDecimalPlaces(r),l={style:i.style??"currency",currency:r,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:c,maximumFractionDigits:c};i.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(n,l).format(o)}catch(s){return console.error(`Error formatting price for currency "${r}" and locale "${n}":`,s),`${W[r]??r} ${t.addThousandSeparators(o.toFixed(c))}`}}static getDecimalPlaces(e){switch(e){case"INR":default:return 2}}static getPrecisionPlaces(e){switch(e){case"INR":default:return 6}}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 x("Invalid currency code for rounding.");let i=t.getDecimalPlaces(r),n=Math.pow(10,i);return Math.round(e*n)/n}};var B=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 P{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 B(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 I(n.images.primary),gallery:(n.images.gallery||[]).map(c=>new I(c))}}}),this.isActive=e.isActive,this.searchTags=e.searchTags?g.deepClone(e.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e){return e?this.name[e]??this.name[A[e]]??this.name.en:g.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[A[e]]??this.description.en:g.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[A[e]]??this.slug.en:g.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:{...this.pricing}}getAttributes(){return g.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes: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})},xe=Ae;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,K=await s.text();try{b=JSON.parse(K);}catch{b={status:s.status,error:K||s.statusText},f.logWarning("Fetch",`Failed to parse error response body as JSON for URL-${c}. Raw text: ${K}`);}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=Ie;
|
|
2
|
-
exports.Fetch=
|
|
1
|
+
'use strict';var se=require('crypto'),Ae=require('util');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var se__default=/*#__PURE__*/_interopDefault(se);var Ae__default=/*#__PURE__*/_interopDefault(Ae);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||{}),v=(r=>(r.en="en",r.kn="kn",r))(v||{}),A={"en-IN":"en","kn-IN":"kn"};var J={INR:"\u20B9"},Z={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),$=M.length;function G(){return $>M.length-16&&(se__default.default.randomFillSync(M),$=0),M.slice($,$+=16)}var X=/^(?:[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 oe(t){return typeof t=="string"&&X.test(t)}var ee=oe;var d=[];for(let t=0;t<256;++t)d.push((t+256).toString(16).slice(1));function L(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 ae(t){if(!ee(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 te=ae;function ce(t){t=unescape(encodeURIComponent(t));let e=[];for(let r=0;r<t.length;++r)e.push(t.charCodeAt(r));return e}var ue="6ba7b810-9dad-11d1-80b4-00c04fd430c8",le="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function j(t,e,r){function i(n,o,c,l){var s;if(typeof n=="string"&&(n=ce(n)),typeof o=="string"&&(o=te(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 L(u)}try{i.name=t;}catch{}return i.DNS=ue,i.URL=le,i}var Q={randomUUID:se__default.default.randomUUID};function pe(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 L(i)}var q=pe;function me(t){return Array.isArray(t)?t=Buffer.from(t):typeof t=="string"&&(t=Buffer.from(t,"utf8")),se__default.default.createHash("sha1").update(t).digest()}var re=me;var fe=j("v5",80,re),Y=fe;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?Y(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)}},p=ye;var ie=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:ie(r)}setCustomField(e,r){this.customFields[e]=r;}getAllCustomFields(){return ie(this.customFields)}},P=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 R=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";}},z=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";}},x=class extends Error{constructor(e="Currency code is required."){super(`InvalidCurrency: ${e}`),this.name="InvalidCurrencyCodeError";}},f=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";}},E=class extends Error{constructor(e="Invalid image source configuration."){super(`InvalidImageSource: ${e}`),this.name="InvalidImageSourceError";}};var I=class{sources;alt;order;label;constructor(e){if(this.sources={...e.sources},this.alt=e.alt,this.order=e.order,this.label=e.label,!this.sources.original)throw new E("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 E("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 C("Amount cannot be negative.");if(!e.currency)throw new x("Currency code is required.");this.currency=e.currency,this.amount=parseFloat(e.amount.toFixed(t.getPrecisionPlaces(this.currency)));}get kind(){return this.#e}static isPriceModel(e){return typeof e=="object"&&e!==null&&e.kind==="PriceModel"}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}getPreciseAmount(e){return parseFloat(e.toFixed(t.getPrecisionPlaces(this.currency)))}compareTo(e){if(t.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new f("Cannot compare prices in different currencies.")}else throw new g("Must be a PriceModel instance.");return this.getPreciseAmount(this.amount-e.getAmount())}add(e){if(t.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new f("Cannot add prices in different currencies.")}else throw new g("Must be a PriceModel instance.");return new t({amount:this.getPreciseAmount(this.amount+e.getAmount()),currency:this.currency})}subtract(e){if(t.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new f("Cannot subtract prices in different currencies.")}else throw new g("Must be a PriceModel instance.");return new t({amount:this.getPreciseAmount(this.amount-e.getAmount()),currency:this.currency})}multiply(e){if(t.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new f("Cannot multiply prices in different currencies.");return new t({amount:this.getPreciseAmount(this.amount*e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>=0)return new t({amount:this.getPreciseAmount(this.amount*e),currency:this.currency});throw new g("Must be a non-negative number.")}divide(e){if(t.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new f("Cannot divide prices in different currencies.");return new t({amount:this.getPreciseAmount(this.amount/e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>0)return new t({amount:this.getPreciseAmount(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(t.isPriceModel(i)){if(r.getCurrency()!==i.getCurrency())throw new f("Cannot compare prices in different currencies.")}else throw new g("Must be a PriceModel instance.");return r.compareTo(i)<0?r:i},this)}max(...e){if(e.length===0)throw new g("Must provide at least one PriceModel.");return e.reduce((r,i)=>{if(t.isPriceModel(i)){if(r.getCurrency()!==i.getCurrency())throw new f("Cannot compare prices in different currencies.")}else throw new g("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=Z[r];if(!r||!n)throw new x("Invalid currency code for formatting.");let o=e,c=i.displayAsInteger?0:t.getDecimalPlaces(r),l={style:i.style??"currency",currency:r,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:c,maximumFractionDigits:c};i.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(n,l).format(o)}catch(s){return console.error(`Error formatting price for currency "${r}" and locale "${n}":`,s),`${J[r]??r} ${t.addThousandSeparators(o.toFixed(c))}`}}static getDecimalPlaces(e){switch(e){case"INR":default:return 2}}static getPrecisionPlaces(e){switch(e){case"INR":default:return 6}}static addThousandSeparators(e){let 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 x("Invalid currency code for rounding.");let i=t.getDecimalPlaces(r),n=Math.pow(10,i);return Math.round(e*n)/n}};var B=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 z;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 _(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 P{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 B(e.pricing[o])),n),{}),this.targetGender=e.targetGender,this.attributes=p.deepClone(e.attributes),this.specifications=p.deepClone(e.specifications),this.categories=p.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 R(o);return i.add(o),{sku:n.sku,selectionAttributes:n.selectionAttributes,images:{primary:new I(n.images.primary),gallery:(n.images.gallery||[]).map(c=>new I(c))}}}),this.isActive=e.isActive,this.searchTags=e.searchTags?p.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:p.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[A[e]]??this.description.en:p.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[A[e]]??this.slug.en:p.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:{...this.pricing}}getAttributes(){return p.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:p.deepClone(e.selectionAttributes),images:{primary:e.images.primary,gallery:[...e.images.gallery]}}))}getImagesBySelectionAttributes(e){let 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 p.deepClone(this.categories)}getSpecifications(e){return e?p.deepClone(this.specifications[e]??this.specifications[A[e]]??this.specifications.en):p.deepClone(this.specifications)}getSearchTags(e){return e?p.deepClone(this.searchTags[e]??this.searchTags[A[e]]??this.searchTags.en):p.deepClone(this.searchTags)}getDetails(){let e=super.getDetails();return {id:this.getId(),key:this.getKey(),name:this.getName(),description:this.getDescription(),slug:this.getSlug(),brand:this.getBrand(),pricing:Object.keys(this.pricing).reduce((r,i)=>(this.pricing[i]&&(r[i]=this.pricing[i]?.getDetails()),r),{}),attributes:this.getAttributes(),variants:this.variants.map(r=>({sku:r.sku,selectionAttributes:p.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 ne={$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(v)},localeOrLanguage:{type:"string",enum:[...Object.values(w),...Object.values(v)]},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 he={getStandardSchemaDefinition(){return ne}},be=he;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:Ae__default.default.inspect(t)},y=S;var xe={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: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=xe;var Te=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,K=await s.text();try{b=JSON.parse(K);}catch{b={status:s.status,error:K||s.statusText},y.logWarning("Fetch",`Failed to parse error response body as JSON for URL-${c}. Raw text: ${K}`);}throw {status:s.status,statusText:s.statusText,error:b}}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||N.INTERNAL_SERVER_ERROR,error:s.error||{status:s.status||500,error:s.statusText||N.SOMETHING_WENT_WRONG}}}},Se=Te;var W=class{cache=new Map;maxSize;ttl;cleanupInterval;constructor(e=1e3,r=5*60*1e3){if(!Number.isFinite(e)||e<1)throw new RangeError("maxSize must be a finite number greater than or equal to 1.");if(!Number.isFinite(r)||r<1)throw new RangeError("ttl must be a finite number greater than or equal to 1.");this.maxSize=e,this.ttl=r,this.cleanupInterval=setInterval(()=>this.cleanup(),60*1e3),this.cleanupInterval.unref&&this.cleanupInterval.unref();}cleanup(){let e=Date.now();for(let[r,i]of this.cache.entries())e>=i.expiry&&this.cache.delete(r);}set(e,r){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxSize){let i=this.cache.keys().next().value;i!==void 0&&this.cache.delete(i);}this.cache.set(e,{value:r,expiry:Date.now()+this.ttl});}get(e){let r=this.cache.get(e);if(r){if(Date.now()>=r.expiry){this.cache.delete(e);return}return this.cache.delete(e),this.cache.set(e,r),r.value}}dispose(){clearInterval(this.cleanupInterval);}},Pe=W;
|
|
2
|
+
exports.Fetch=Se;exports.Logger=y;exports.MemoryCache=Pe;exports.ResponseUtility=Ie;exports.Schema=be;exports.Utils=p;//# sourceMappingURL=index.js.map
|
|
3
3
|
//# sourceMappingURL=index.js.map
|