@sazito/client-sdk 1.2.1 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -1 +1 @@
1
- const t={timeout:3e4,retry:{enabled:!0,retries:3,retryDelay:1e3},cache:{products:{enabled:!0,ttl:6e5},categories:{enabled:!0,ttl:6e5},cart:{enabled:!1},orders:{enabled:!1},search:{enabled:!0,ttl:3e5},cms:{enabled:!0,ttl:6e5},tags:{enabled:!0,ttl:6e5},entityRoutes:{enabled:!0,ttl:6e5}},debug:!1};function e(e){return{...t,...e,retry:{...t.retry,...e.retry},cache:{...t.cache,...e.cache},customFetchApi:e.customFetchApi||("undefined"!=typeof fetch?fetch:void 0)}}class a{constructor(){this.tokenKey="user_id_token"}get(){if("undefined"==typeof window||"undefined"==typeof document)return null;const t=this.getFromLocalStorage();if(t)return t;return this.parseCookies()[this.tokenKey]||null}set(t,e){if("undefined"==typeof window||"undefined"==typeof document)return void console.warn("[Sazito SDK] Cannot set token in SSR environment");this.setInLocalStorage(t);const a={secure:!0,sameSite:"Lax",maxAge:2592e3,path:"/",...e};this.setCookie(this.tokenKey,t,a)}remove(){"undefined"!=typeof window&&"undefined"!=typeof document&&(this.removeFromLocalStorage(),this.setCookie(this.tokenKey,"",{maxAge:-1,path:"/"}))}getFromLocalStorage(){try{return window.localStorage.getItem(this.tokenKey)}catch{return null}}setInLocalStorage(t){try{window.localStorage.setItem(this.tokenKey,t)}catch{}}removeFromLocalStorage(){try{window.localStorage.removeItem(this.tokenKey)}catch{}}parseCookies(){return"undefined"==typeof document?{}:document.cookie.split(";").reduce((t,e)=>{const[a,i]=e.trim().split("=");return a&&i&&(t[a]=decodeURIComponent(i)),t},{})}setCookie(t,e,a){let i=`${t}=${encodeURIComponent(e)}`;void 0!==a.maxAge&&(i+=`; Max-Age=${a.maxAge}`),a.path&&(i+=`; Path=${a.path}`),a.domain&&(i+=`; Domain=${a.domain}`),a.secure&&(i+="; Secure"),a.httpOnly&&(i+="; HttpOnly"),a.sameSite&&(i+=`; SameSite=${a.sameSite}`),document.cookie=i}}class i{constructor(){this.cache=new Map}get(t,e){const a=this.cache.get(t);return a?e&&Date.now()-a.timestamp>e?(this.cache.delete(t),null):a.data:null}set(t,e){this.cache.set(t,{data:e,timestamp:Date.now()})}delete(t){this.cache.delete(t)}deletePattern(t){const e=new RegExp(t),a=[];this.cache.forEach((t,i)=>{e.test(i)&&a.push(i)}),a.forEach(t=>this.cache.delete(t))}clear(){this.cache.clear()}static generateKey(t,e,a){return`${t}:${e}:${a?JSON.stringify(a):""}`}}const r={no_of_items:"quantity",single_item_price:"unitPrice",total_items_price:"lineTotal",items_total_raw_price:"totalOriginalPrice",items_discount:"totalDiscount",customer_profit:"savings",customer_profit_percentage:"savingsPercentage",total_amount:"totalAmount",net_total:"subtotal",gross_total:"total",final_total:"finalTotal",discount_total:"discountTotal",shipping_total:"shippingTotal",tax_total:"taxTotal",unique_identifier:"identifier",invoice_identifier:"identifier",payment_identifier:"identifier",shipping_address_identifier:"identifier",first_name:"firstName",last_name:"lastName",mobile_phone:"mobilePhone",phone_number:"phoneNumber",postal_code:"postalCode",user_comment:"comment",product_id:"productId",variant_id:"variantId",product_name:"name",product_image:"image",product_variant:"variant",product_variants:"variants",product_categories:"categories",product_attributes:"attributes",product_type:"productType",title:"name",short_description:"shortDescription",stock_quantity:"stockQuantity",stock_number:"stockQuantity",sale_price:"salePrice",raw_price:"originalPrice",has_max_order:"hasMaxOrder",max_no_of_order:"maxOrderQuantity",min_order_count:"minOrderQuantity",sold_count:"soldCount",static_url:"staticUrl",dynamic_form_id:"dynamicFormId",event_entity_id:"eventEntityId",theme_config:"themeConfig",image_id:"imageId",is_stock_managed:"isStockManaged",commercial_files:"commercialFiles",sort_index:"sortIndex",attribute_type:"attributeType",cart_products:"items",cart_product_id:"cartProductId",invoice_items:"items",products:"items",total_count:"total",shipping_method_needed:"needsShipping",shipping_method:"shippingMethod",shipping_address:"shippingAddress",shipping_items:"shippingItems",delivery_time:"deliveryTime",min_delivery_days:"minDays",max_delivery_days:"maxDays",payment_type:"paymentType",payment_types:"methods",reference_code:"code",is_default:"isDefault",is_available:"isAvailable",delete_coupon:"deleteCoupon",form_attributes:"formAttributes",booking_attributes:"bookingAttributes",readable_form_attr:"formFields",created_at:"createdAt",updated_at:"updatedAt",page_number:"page",page_size:"pageSize",total_count_raw:"totalCountRaw",max_price:"maxPrice",min_price:"minPrice",stock_alert_limit:"stockAlertLimit",sub_categories:"subCategories",order_number:"orderNumber",sort_order:"sortOrder",pinned_ids:"pinnedIds",region_id:"regionId",city_id:"cityId",parent_id:"parentId",discount_code:"discountCode",entity_name:"entityType",entity_id:"entityId",other_props:"entity",shipping_methods:"shippingMethods",shipping_rates:"shippingRates",grouped_shipping_rates:"groupedShippingRates",items_shipping_rate:"itemsShippingRate",shipping_rate:"shippingRate",rate_id:"rateId",invoice_item_id:"invoiceItemId",invoice_item_ids:"invoiceItemIds",scheduler_booking_attributes:"schedulerBookingAttributes",inventory_count:"inventoryCount",order_identifier:"orderIdentifier",self_only:"selfOnly",coupon:"coupon",user_set_coordinates_before:"userSetCoordinatesBefore",alt:"alt",url:"url",activate_add_to_cart_alert:"addToCardAlert",activate_advanced_card_to_card:"advancedCardToCard",activate_ayria_payment_customization:"ayriaPaymentGateway",activate_azki_payment_customization:"azkiPaymentGateway",activate_bazar_payment_customization:"bazarPaymentGateway",activate_blog:"shopBlog",activate_card_to_card_payment:"cardToCardPayment",activate_checkout_dynamic_form:"checkoutDynamicForm",activate_different_register_customization:"multiTypeRegister",activate_digipay_payment:"digipayPaymentGateway",activate_digipay_payment_customization:"digipayPaymentGateway",activate_filter_products:"productFilters",activate_ghesta_payment_customization:"ghestaPaymentGateway",activate_mega_footer:"megaFooter",activate_mellat_payment_customization:"mellatPaymentGateway",activate_min_basket:"checkoutMinimumAmount",activate_novapay_payment_customization:"novapayPaymentGateway",activate_ozon_payment_customization:"ozonPaymentGateway",activate_payment_in_place:"paymentInPlace",activate_payping_payment:"paypingPaymentGateway",activate_pec_payment_customization:"pecPaymentGateway",activate_sabin_payment_customization:"sabinPaymentGateway",activate_sadad_payment_customization:"sadadPaymentGateway",activate_search:"shopSearch",activate_sep_payment_customization:"sepPaymentGateway",activate_shop_vat:"shopVat",activate_snapppay_payment_customization:"snapppayPaymentGateway",activate_tajrobe:"tajrobe",activate_tara_payment_customization:"taraPaymentGateway",activate_theme_config_settings:"themeConfigSettings",activate_toman_payment_customization:"tomanPaymentGateway",activate_torobpay_payment_customization:"torobpayPaymentGateway",activate_up_payment_customization:"asanpardakhtPaymentGateway",activate_vandar_payment_customization:"vandarPaymentGateway",activate_wallet:"wallet",activate_yourgate_payment_customization:"yourgatePaymentGateway",activate_zarinpal_payment:"zarinpalPaymentGateway",activate_zarinplus_payment_customization:"zarinplusPaymentGateway",activate_zibal_payment_customization:"zibalPaymentGateway",activate_zify_payment_customization:"zifyPaymentGateway",disable_ordering:"disableOrdering",pwa:"progressiveWebApp",remove_front_basket:"hideCheckout",remove_front_taint:"sazitoBrandingRemoval"},n=Object.entries(r).reduce((t,[e,a])=>(t[a]||(t[a]=e),t),{});function s(t){return t.replace(/_([a-z])/g,(t,e)=>e.toUpperCase())}function o(t){return t.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function c(t){return!(null===t||"object"!=typeof t||Array.isArray(t)||t instanceof Date)}function d(t,e){const a={...t};for(const t of e)delete a[t];return a}function p(t){if(!c(t))return Array.isArray(t)?t.map(t=>p(t)):t;const e={};for(const[a,i]of Object.entries(t)){let t=r[a];t||(t=s(a)),c(i)?e[t]=p(i):Array.isArray(i)?e[t]=i.map(t=>p(t)):e[t]=i}return e}function u(t){if(!c(t))return Array.isArray(t)?t.map(t=>u(t)):t;const e={};for(const[a,i]of Object.entries(t)){let t=n[a];t||(t=o(a)),c(i)?e[t]=u(i):Array.isArray(i)?e[t]=i.map(t=>u(t)):e[t]=i}return e}function l(t){if(t?.data?.result){const e=t.data.result,a=Object.keys(e);return 1===a.length&&c(e[a[0]])?p(e[a[0]]):p(e)}return p(t)}function h(t){if(!t)return t;const{general:e,shop:a,checkout:i,features:r,wallet:n,tajrobe:s,domain:o,enamad:d,google:p,logo:u,social:l,...h}=t,_={...e,...a},{registerType:f,showProductStockNumber:v,...C}=_||{};let S=i;if(c(i)){const t={...i};void 0===t.preventRedirect&&void 0!==t.manual&&(t.preventRedirect=t.manual),delete t.manual,S=t}return{...h,scripts:{enamad:d,google:p},shop:y({...C,domain:o,logo:u,social:l}),settings:{checkout:S,features:b(r),wallet:w(n),tajrobe:P(s),registerType:m(f),showProductStockNumber:g(v)}}}function m(t){return"string"==typeof t?t:""}function g(t){return"boolean"==typeof t?t:c(t)&&Object.prototype.hasOwnProperty.call(t,"enabled")?g(t.enabled):1===t||"1"===t||"true"===t}function y(t){if(!c(t))return t;const e={...t};if(c(e.city)){const t=d(e.city,["createdAt","updatedAt"]);let a=t.region;c(a)&&(a=d(a,["createdAt","updatedAt","cities"])),t.region=a,e.city=t}return e}const _={addToCardAlert:"addToCartAlertEnabled",addToCartAlert:"addToCartAlertEnabled",advancedCardToCard:"advancedCardToCardEnabled",cardToCardPayment:"cardToCardPaymentEnabled",checkoutDynamicForm:"checkoutDynamicFormEnabled",multiTypeRegister:"multiTypeRegisterEnabled",productFilters:"productFiltersEnabled",megaFooter:"megaFooterEnabled",checkoutMinimumAmount:"checkoutMinimumAmountEnabled",paymentInPlace:"paymentInPlaceEnabled",shopBlog:"blogEnabled",shopSearch:"searchEnabled",shopVat:"shopVatEnabled",tajrobe:"tajrobeEnabled",themeConfigSettings:"themeConfigSettingsEnabled",wallet:"walletEnabled",progressiveWebApp:"progressiveWebAppEnabled",disableOrdering:"orderingDisabled",hideCheckout:"checkoutHidden",sazitoBrandingRemoval:"sazitoBrandingRemoved",ayriaPaymentGateway:"ayriaPaymentGatewayEnabled",azkiPaymentGateway:"azkiPaymentGatewayEnabled",bazarPaymentGateway:"bazarPaymentGatewayEnabled",digipayPaymentGateway:"digipayPaymentGatewayEnabled",ghestaPaymentGateway:"ghestaPaymentGatewayEnabled",mellatPaymentGateway:"mellatPaymentGatewayEnabled",novapayPaymentGateway:"novapayPaymentGatewayEnabled",ozonPaymentGateway:"ozonPaymentGatewayEnabled",paypingPaymentGateway:"paypingPaymentGatewayEnabled",pecPaymentGateway:"pecPaymentGatewayEnabled",sabinPaymentGateway:"sabinPaymentGatewayEnabled",sadadPaymentGateway:"sadadPaymentGatewayEnabled",sepPaymentGateway:"sepPaymentGatewayEnabled",snapppayPaymentGateway:"snapppayPaymentGatewayEnabled",taraPaymentGateway:"taraPaymentGatewayEnabled",tomanPaymentGateway:"tomanPaymentGatewayEnabled",torobpayPaymentGateway:"torobpayPaymentGatewayEnabled",asanpardakhtPaymentGateway:"asanpardakhtPaymentGatewayEnabled",vandarPaymentGateway:"vandarPaymentGatewayEnabled",yourgatePaymentGateway:"yourgatePaymentGatewayEnabled",zarinpalPaymentGateway:"zarinpalPaymentGatewayEnabled",zarinplusPaymentGateway:"zarinplusPaymentGatewayEnabled",zibalPaymentGateway:"zibalPaymentGatewayEnabled",zifyPaymentGateway:"zifyPaymentGatewayEnabled",activateEditOrderCustomization:"editOrderEnabled",activateEditOrderCustomizationEnabled:"editOrderEnabled"},f=new Set(["activateAlopeykAdvanced","activate_alopeyk_advanced"]),v=new Set(["auditLogEnabled","editOrderEnabled","rahkaranAccountingCustomizationEnabled","advancedThemeDesignerEnabled","checkoutHidden","eventPublisherEnabled","exportOrdersEnabled","exportProductsEnabled","exportUsersEnabled","fontCustomizationEnabled","forwardShippingEnabled","podroShippingEnabled","postexShippingEnabled","quotaNotificationsEnabled","recaptchaEnabled","rolePoliciesEnabled","sepidarAccountingCustomizationEnabled","shortUrlEnabled","skuSearchEnabled","snappShopCustomizationEnabled","snappboxShippingEnabled","stockAlertNotificationsEnabled","tapsipackShippingEnabled","themeConfigSettingsEnabled","advancedTextEditorEnabled","advancedShippingEnabled","bulkActionEnabled","discountBulkEnabled","discountCodeEnabled","orderBulkActionEnabled","importProductsEnabled","mahakAccountingCustomizationEnabled","millipayPaymentCustomizationEnabled","orderSmsNotificationsEnabled"]);function b(t){if(!c(t))return{};const e={},a=(t,a)=>{if(f.has(t))return;const i=(t=>{if("boolean"==typeof t)return t;if("number"==typeof t)return 1===t||0!==t&&void 0;if("string"==typeof t){const e=t.trim().toLowerCase();return"true"===e||"1"===e||"false"!==e&&"0"!==e&&void 0}})(a);void 0!==i&&(e[t]=i)};c(t.flags)&&Object.entries(t.flags).forEach(([t,e])=>{a(t,e)}),c(t.configurations)&&Object.entries(t.configurations).forEach(([t,e])=>{a(t,e)}),Object.entries(t).forEach(([t,e])=>{"flags"!==t&&"premium"!==t&&"configurations"!==t&&(c(e)&&Object.prototype.hasOwnProperty.call(e,"enabled")?a(t,e.enabled):a(t,e))});const i={};Object.entries(e).forEach(([t,e])=>{const a=function(t){const e=t.includes("_")?s(t):t,a=_[e];if(a)return a;const i=e.startsWith("activate")&&e.length>8?`${e.charAt(8).toLowerCase()}${e.slice(9)}`:e;return i.endsWith("Enabled")||i.endsWith("Disabled")||i.endsWith("Hidden")||i.endsWith("Removed")?i:`${i}Enabled`}(t);v.has(a)||(i[a]=e)});const r={...i};return c(t.premium)&&(r.premium=t.premium),r}function w(t){if(!c(t))return t;const e=c(t.configurations)?{...t,...t.configurations}:{...t},a=t=>"boolean"==typeof t?t:1===t||"1"===t||"true"===t||0!==t&&"0"!==t&&"false"!==t&&void 0;return{enabled:a(e.enabled)??!1,useWithDiscount:a(e.useWithDiscount)??!1,minAmount:(t=>{if("number"==typeof t&&Number.isFinite(t))return t;const e=Number(t);return Number.isFinite(e)?e:void 0})(e.minAmount??e.walletMinAmount)??0,minAmountRequired:a(e.minAmountRequired??e.walletMinStatus)??!1}}function P(t){if(!c(t))return t;const e=c(t.configurations)?{...t,...t.configurations}:{...t};let a=!1;return"boolean"==typeof e.enabled?a=e.enabled:1!==e.enabled&&"1"!==e.enabled&&"true"!==e.enabled||(a=!0),{enabled:a}}function C(t){const e=l(t);return e.items&&Array.isArray(e.items)&&(e.items=e.items.map(t=>({...t,product:{variantId:t.variant?.id||t.product?.variantId,productId:t.variant?.product?.id||t.product?.productId,name:t.name||t.product?.name,image:t.image||t.product?.image,attributes:t.attributes||t.product?.attributes||[],hasMaxOrder:t.product?.hasMaxOrder||!1,maxOrderQuantity:t.product?.maxOrderQuantity,minOrderQuantity:t.product?.minOrderQuantity}}))),e}function S(t){const e=l(t);return e.items&&Array.isArray(e.items)&&(e.items=e.items.map(t=>({...t,discount:t.discount||(t.originalPrice?t.originalPrice-t.unitPrice:0)}))),e}function E(t){if(!t)return t;const e=d(t,["staticUrl","summary","tags","slug"]);return e.variants&&Array.isArray(e.variants)&&(e.variants=e.variants.map(t=>d(t,["name","title","product","status","soldCount"]))),e.categories&&Array.isArray(e.categories)&&(e.categories=e.categories.map(t=>({id:t.id,name:t.name,url:t.url}))),e.images&&Array.isArray(e.images)&&(e.images=e.images.map(t=>d(t,["widthRatio","heightRatio","thumb"]))),e}function A(t){const e=E(t);return e?d(e,["themeConfig"]):e}function I(t){const e=l(t);return e.items&&Array.isArray(e.items)?{items:e.items.map(t=>A(t)),total:e.total||e.items.length,page:e.page||1,pageSize:e.pageSize||e.items.length,totalPages:e.totalPages||Math.ceil((e.total||e.items.length)/(e.pageSize||e.items.length))}:e}function z(t){if(!t)return t;const e={products:{items:[],total:0,page:1,pageSize:20},blogPages:{items:[],total:0,page:1,pageSize:20},cmsPages:{items:[],total:0,page:1,pageSize:20},productCategories:{items:[],total:0,page:1,pageSize:20}};return t.items&&Array.isArray(t.items)&&(e.products.items=t.items.map(t=>A(t)),e.products.total=t.productsCount||0,e.products.page=t.productsPageNumber||1,e.products.pageSize=t.productsPageSize||20),t.blogPages&&Array.isArray(t.blogPages)&&(e.blogPages.items=t.blogPages.map(t=>D(t)),e.blogPages.total=t.blogPagesCount||0,e.blogPages.page=t.blogPagesPageNumber||1,e.blogPages.pageSize=t.blogPagesPageSize||20),t.cmsPages&&Array.isArray(t.cmsPages)&&(e.cmsPages.items=t.cmsPages.map(t=>D(t)),e.cmsPages.total=t.cmsPagesCount||0,e.cmsPages.page=t.cmsPagesPageNumber||1,e.cmsPages.pageSize=t.cmsPagesPageSize||20),t.categories&&Array.isArray(t.categories)&&(e.productCategories.items=t.categories.map(t=>N(t)),e.productCategories.total=t.productCategoriesCount||0,e.productCategories.page=t.productCategoriesPageNumber||1,e.productCategories.pageSize=t.productCategoriesPageSize||20),e}function T(t){return{shipping_address:u(t)}}function k(t,e,a){const i={product_variants:[{id:t,count:e}]};return a&&(i.form_attributes=u(a)),i}function G(t){const e={product_variants:t.productVariants?.map(t=>({id:t.id||t.variantId,count:t.count||t.quantity,form_attributes:t.formAttributes?u(t.formAttributes):void 0}))||[]};return t.coupon&&(e.coupon=t.coupon),e}function $(t){return t?d(t,["staticUrl","products","items"]):t}function N(t){const e=$(t);return e?d(e,["themeConfig"]):e}function O(t){return t?d(t,["staticUrl","urlKey"]):t}function D(t){const e=O(t);return e?d(e,["themeConfig"]):e}function R(t){const e=l(t);if(!e||!e.route)return e;const a=e.route;if(a.entity){switch(a.entityType){case"product":a.entity=E(a.entity);break;case"product_category":a.entity=$(a.entity);break;case"cms_page":case"blog_page":a.entity=O(a.entity)}a.entity=d(a.entity,["id"]),!a.url&&a.entity.url&&(a.url=a.entity.url)}return a}function x(t){if(!t)return t;const e={...t};return e.entity&&(e.entity=N(e.entity),e.entity&&"object"==typeof e.entity&&(e.entity=d(e.entity,["id"]))),e.children&&Array.isArray(e.children)&&(e.children=e.children.map(x)),e}function K(t){const e=l(t);return e?e.cmsPages&&Array.isArray(e.cmsPages)?{items:e.cmsPages.map(D),total:e.total||e.cmsPages.length,page:e.page||e.pageNumber||1,pageSize:e.pageSize||e.cmsPages.length}:e.items&&Array.isArray(e.items)?{items:e.items.map(t=>D(t)),total:e.total||e.items.length,page:e.page||1,pageSize:e.pageSize||e.items.length}:e:e}function M(t){if(!t)return{};const e={};if(void 0!==t.page&&(e.page_number=t.page),void 0!==t.pageSize&&(e.page_size=t.pageSize),t.cmsPageTypes){const a=Array.isArray(t.cmsPageTypes)?t.cmsPageTypes[0]:t.cmsPageTypes;e["filters[]"]=JSON.stringify({name:"cms_page_types",value:a})}return e}function j(t){if(!t)return t;const e={};if(t.entityType&&(e.entityType=t.entityType),void 0!==t.entityId&&(e.entityId=t.entityId),t.entity){const a=d(t.entity,["staticUrl","id"]);Object.keys(a).length>0&&(e.entity=a)}return t.details&&(e.details=t.details),t.children&&Array.isArray(t.children)&&(e.children=t.children.map(t=>j(t))),e}function F(t){const e=l(t);if(!e||!e.tree)return e;const a=e.tree;return a.treeStructure&&a.treeStructure.nodes&&(a.treeStructure.nodes=a.treeStructure.nodes.map(t=>j(t))),e}class U{constructor(t){this.config=t,this.baseUrl="http://api.sazito.com:8080",this.domain=t.domain,this.tokenStorage=new a,this.cache=new i,this.fetchApi=t.customFetchApi.bind(globalThis)}async get(t,e){const a=this.buildUrl(t,e?.params),r=i.generateKey("GET",a,e?.params);if(!1!==e?.cache){const e=this.getApiName(t),a=this.config.cache[e];if(a?.enabled&&a.ttl){const e=this.cache.get(r,a.ttl);if(e)return this.config.debug&&console.log("[Sazito SDK] Cache hit:",t),{data:e}}}const n=await this.request("GET",a,e);return n.data&&!1!==e?.cache&&this.cache.set(r,n.data),n}async post(t,e,a){const i=this.buildUrl(t),r=e?u(e):void 0,n=this.getApiName(t);return this.cache.deletePattern(`GET:.*${n}`),this.request("POST",i,{...a,body:r})}async put(t,e,a){const i=this.buildUrl(t),r=e?u(e):void 0,n=this.getApiName(t);return this.cache.deletePattern(`GET:.*${n}`),this.request("PUT",i,{...a,body:r})}async delete(t,e){const a=this.buildUrl(t),i=this.getApiName(t);return this.cache.deletePattern(`GET:.*${i}`),this.request("DELETE",a,e)}async request(t,e,a,i=0){const r=new AbortController,n=a?.signal||r.signal,s=a?.timeout||this.config.timeout,o=setTimeout(()=>r.abort(),s);try{const r=await this.fetchApi(e,{method:t,headers:this.getHeaders(a?.headers),body:a?.body?JSON.stringify(a.body):void 0,signal:n});clearTimeout(o);const s=void 0!==a?.retries?a.retries:this.config.retry.retries;if(!r.ok&&this.shouldRetry(r.status)&&i<s)return this.config.debug&&console.log(`[Sazito SDK] Retrying request (${i+1}/${s}):`,e),await this.delay(this.config.retry.retryDelay*(i+1)),this.request(t,e,a,i+1);const c=r.headers.get("content-type");let d;d=c?.includes("application/json")?await r.json():await r.text();const u=void 0!==d?.result?d.result:d;this.config.debug&&console.log(`[Sazito SDK] ${t} ${e}:`,{status:r.status,data:u});let l=u?p(u):u;const h=["cart","product","user","order","invoice","payment","shipping"];if(l&&"object"==typeof l&&!Array.isArray(l)){const t=Object.keys(l);1===t.length&&h.includes(t[0])&&"object"==typeof l[t[0]]&&null!==l[t[0]]&&(l=l[t[0]])}return r.ok?{data:l}:{error:{status:r.status,message:l?.message||u?.message||r.statusText||"Request failed",type:"api",details:l}}}catch(t){return clearTimeout(o),this.config.debug&&console.error("[Sazito SDK] Request failed:",t),{error:{message:"AbortError"===t.name?"Request timeout":t.message||"Network error",type:"network",details:t}}}}buildUrl(t,e){const a=`${this.baseUrl}${t}`;if(!e||0===Object.keys(e).length)return a;const i=new URLSearchParams;return Object.entries(e).forEach(([t,e])=>{null!=e&&i.append(t,String(e))}),`${a}?${i.toString()}`}getHeaders(t){const e={"Content-Type":"application/json","x-forwarded-host":this.domain,...t},a=this.tokenStorage.get();return a&&(e.Authorization=a),e}shouldRetry(t){return t>=500&&t<600}delay(t){return new Promise(e=>setTimeout(e,t))}getApiName(t){return t.includes("/products")?"products":t.includes("/product_categories")?"categories":t.includes("/cart")?"cart":t.includes("/orders")?"orders":t.includes("/search")?"search":t.includes("/tags")?"tags":t.includes("/entity_route")?"entityRoutes":"cms"}getTokenStorage(){return this.tokenStorage}clearCache(){this.cache.clear()}}class q{constructor(){this.CART_KEY="CART_CREDENTIALS",this.INVOICE_KEY="INVOICE_CREDENTIALS",this.SHIPPING_KEY="SHIPPING_ADDRESS_CREDENTIALS",this.PAYMENT_KEY="PAYMENT_CREDENTIALS",this.DISCOUNT_KEY="DISCOUNT_CODE_INFO"}getCartCredentials(){return this.getItem(this.CART_KEY)}setCartCredentials(t){this.setItem(this.CART_KEY,t)}clearCartCredentials(){this.removeItem(this.CART_KEY)}getInvoiceCredentials(){return this.getItem(this.INVOICE_KEY)}setInvoiceCredentials(t){this.setItem(this.INVOICE_KEY,t)}clearInvoiceCredentials(){this.removeItem(this.INVOICE_KEY)}getShippingCredentials(){return this.getItem(this.SHIPPING_KEY)}setShippingCredentials(t){this.setItem(this.SHIPPING_KEY,t)}clearShippingCredentials(){this.removeItem(this.SHIPPING_KEY)}getPaymentCredentials(){return this.getItem(this.PAYMENT_KEY)}setPaymentCredentials(t){this.setItem(this.PAYMENT_KEY,t)}clearPaymentCredentials(){this.removeItem(this.PAYMENT_KEY)}getDiscountCode(){return this.getItem(this.DISCOUNT_KEY)}setDiscountCode(t){this.setItem(this.DISCOUNT_KEY,t)}clearDiscountCode(){this.removeItem(this.DISCOUNT_KEY)}clearAll(){this.clearCartCredentials(),this.clearInvoiceCredentials(),this.clearShippingCredentials(),this.clearPaymentCredentials(),this.clearDiscountCode()}getItem(t){if("undefined"==typeof localStorage)return null;try{const e=localStorage.getItem(t);return e?JSON.parse(e):null}catch(e){return console.error(`[Sazito SDK] Error reading ${t} from localStorage:`,e),null}}setItem(t,e){if("undefined"!=typeof localStorage)try{localStorage.setItem(t,JSON.stringify(e))}catch(e){console.error(`[Sazito SDK] Error writing ${t} to localStorage:`,e)}else console.warn("[Sazito SDK] localStorage not available")}removeItem(t){if("undefined"!=typeof localStorage)try{localStorage.removeItem(t)}catch(e){console.error(`[Sazito SDK] Error removing ${t} from localStorage:`,e)}}}const Y="/api/v1/product_categories",L="/api/v1/search",B="/api/v2/carts",H="/api/v2/invoices",W="/api/v2/shipping_addresses",Q="/api/v2/payments",V="/api/v1/orders",J="/api/v1/users",Z="/api/v1/sessions",X="/api/v1/feedbacks",tt="/api/v1/cms_pages",et="/api/v1/images",at="/api/v1/scheduler/events",it="/api/v1/scheduler/bookings",rt="/api/v1/entity_route/route";class nt{constructor(t){this.http=t}mapSortToApi(t){if(!t)return null;return{newest:{sort:"date"},"best-selling":{sort:"sold"},availability:{sort:"stock_status"},discount:{sort:"raw_price"},"!price":{sort:"price",sortOrder:"asc"},price:{sort:"price"}}[t]||null}transformFilters(t){if(!t)return{};const e={},a=[];if(t.categories){const e=Array.isArray(t.categories)?t.categories:[t.categories];e.length>0&&a.push({name:"product_categories",value:e.join(",")})}if(!1===t.availableOnly&&a.push({name:"in_stock"}),t.discountedOnly&&a.push({name:"has_raw_price",value:!0}),t.similarTo&&a.push({name:"similar_to",value:{entity_name:"product",entity_id:t.similarTo}}),a.length>0&&(e["filters[]"]=JSON.stringify(a)),t.pinnedIds&&t.pinnedIds.length>0&&(e.pinned_ids=JSON.stringify(t.pinnedIds)),t.sort){const a=this.mapSortToApi(t.sort);a&&(e.sort=a.sort,a.sortOrder&&(e.sort_order=a.sortOrder))}return void 0!==t.priceMin&&(e.min_price=t.priceMin),void 0!==t.priceMax&&(e.max_price=t.priceMax),t.page&&(e.page=t.page),t.pageSize&&(e.page_size=t.pageSize),e}async get(t,e){const a=t.startsWith("/product/")?t:`/product/${t}`,i=await this.http.get(rt,{...e,params:{url_part:a}});if(i.data){const t=R(i.data);return"product"===t.entityType&&t.entity?{data:t.entity}:"unknown"===t.entityType?{error:{message:"Product not found",type:"api",status:404}}:{error:{message:`Invalid entity type: expected 'product', got '${t.entityType}'`,type:"api",status:400}}}return i}async list(t,e){const a=this.transformFilters(t),i=await this.http.get("/api/v1/products",{...e,params:a});if(i.data){return{data:I(i.data)}}return i}async search(t,e,a){const i={query:t,search_direction:"center",page_size:e?.pageSize||20,page_number:e?.page||1},r=await this.http.get(L,{...a,params:i});if(r.data){return{data:z(r.data)}}return r}}class st{constructor(t){this.http=t}async get(t,e){const a=await this.http.get(`${Y}/${t}`,e);if(a.data){const t=function(t){const e=l(t);return e?$(e.productCategory||e):e}(a.data);return{data:t}}return a}async list(t,e){const a={};void 0!==t?.page&&(a.page_number=t.page),void 0!==t?.pageSize&&(a.page_size=t.pageSize);const i=await this.http.get(Y,{...e,params:a});if(i.data){const t=function(t){const e=l(t);return e?(e.categories&&Array.isArray(e.categories)&&(e.categories=e.categories.map(N)),e.tree&&e.tree.treeStructure&&e.tree.treeStructure.nodes&&(e.tree.treeStructure.nodes=e.tree.treeStructure.nodes.map(x)),e):e}(i.data);return{data:t}}return i}}class ot{constructor(t,e){this.http=t,this.credentials=e}async get(t){const e=this.credentials.getCartCredentials();return e?this.http.get(`${B}/${e.id}`,{...t,params:{identifier:e.identifier}}):{error:{message:"No cart found. Please create a cart first.",type:"validation"}}}async create(t,e){const a=await this.http.post(B,t,e);return a.data&&this.credentials.setCartCredentials({id:a.data.id,identifier:a.data.identifier}),a}async addItem(t,e,a,i){const r=this.credentials.getCartCredentials();if(!r)return this.create({variants:[{id:t,count:e,formAttributes:a}]},i);return await this.http.post(`${B}/${r.id}/add_products_to_cart`,{identifier:r.identifier,variants:[{id:t,count:e}],formAttributes:a},i)}async updateItem(t,e,a){const i=this.credentials.getCartCredentials();return i?this.http.post(`${B}/${i.id}/update_products_in_cart`,{identifier:i.identifier,cartProductId:t,variants:[{id:t,count:e}]},a):{error:{message:"No cart found",type:"validation"}}}async removeItem(t,e,a){const i=this.credentials.getCartCredentials();return i?this.http.post(`${B}/${i.id}/remove_products_from_cart`,{identifier:i.identifier,cartProductId:t,variants:[{id:e}]},a):{error:{message:"No cart found",type:"validation"}}}clearCart(){this.credentials.clearCartCredentials()}}class ct{constructor(t){this.http=t}async list(t,e){return this.http.get(V,{...e,params:t})}async get(t,e){return this.http.get(`${V}/${t}`,e)}}class dt{constructor(t,e){this.http=t,this.credentials=e}async get(t){const e=this.credentials.getInvoiceCredentials();return e?this.http.get(`${H}/${e.id}`,{...t,params:{identifier:e.identifier}}):{error:{message:"No invoice found. Please create an invoice first.",type:"validation"}}}async create(t){const e=this.credentials.getCartCredentials();if(!e)return{error:{message:"No cart found. Please create a cart first.",type:"validation"}};const a=await this.http.post(H,{cart_id:e.id,cart_identifier:e.identifier},t);return a.data&&this.credentials.setInvoiceCredentials({id:a.data.id,identifier:a.data.identifier}),a}async refresh(t){const e=this.credentials.getCartCredentials(),a=this.credentials.getInvoiceCredentials();return e&&a?this.http.post(`/api/v1/invoices/${a.id}/refresh`,{cart_id:e.id,cart_identifier:e.identifier,identifier:a.identifier},t):{error:{message:"No cart or invoice found",type:"validation"}}}async addShippingAddress(t,e,a){const i=this.credentials.getCartCredentials(),r=this.credentials.getInvoiceCredentials();return i&&r?this.http.post(`/api/v1/invoices/${r.id}/add_shipping_address`,{identifier:r.identifier,shipping_address_id:t,shipping_address_identifier:e,cart_id:i.id,cart_identifier:i.identifier},a):{error:{message:"No cart or invoice found",type:"validation"}}}async addDiscountCode(t,e){const a=this.credentials.getInvoiceCredentials();if(!a)return{error:{message:"No invoice found",type:"validation"}};const i=await this.http.post(`/api/v1/invoices/${a.id}/add_discount_code`,{identifier:a.identifier,discount_code:t.toUpperCase()},e);return i.data&&this.credentials.setDiscountCode(t),i}async assignShippingMethod(t,e){const a=this.credentials.getInvoiceCredentials();return a?this.http.post(`/api/v1/invoices/${a.id}/add_shipping_method`,{identifier:a.identifier,shippings:t},e):{error:{message:"No invoice found",type:"validation"}}}async addDetails(t,e){const a=this.credentials.getInvoiceCredentials();return a?this.http.post(`/api/v1/invoices/${a.id}/add_invoice_details`,{identifier:a.identifier,user_comment:t},e):{error:{message:"No invoice found",type:"validation"}}}async getApplicableShippingMethods(t){const e=this.credentials.getInvoiceCredentials();return e?this.http.get(`/api/v1/invoices/${e.id}/applicable_shipping_methods`,{...t,params:{identifier:e.identifier}}):{error:{message:"No invoice found",type:"validation"}}}clearInvoice(){this.credentials.clearInvoiceCredentials()}}class pt{constructor(t,e){this.http=t,this.credentials=e}async createAddress(t,e){const a=await this.http.post(W,{shipping_address:t},e);return a.data&&this.credentials.setShippingCredentials({id:a.data.id,identifier:a.data.identifier}),a}async updateAddress(t,e){const a=this.credentials.getShippingCredentials();if(!a)return this.createAddress(t,e);const i=await this.http.post(W,{identifier:a.identifier,shipping_address:t},e);return i.data&&this.credentials.setShippingCredentials({id:i.data.id,identifier:i.data.identifier}),i}async getAddress(t){const e=this.credentials.getShippingCredentials();return e?this.http.get(`${W}/${e.id}`,{...t,params:{identifier:e.identifier}}):{error:{message:"No shipping address found",type:"validation"}}}async getMethods(t){return this.http.post("/api/v2/shipping_methods/list",{},t)}clearAddress(){this.credentials.clearShippingCredentials()}}class ut{constructor(t,e){this.http=t,this.credentials=e}async getMethods(t){const e=this.credentials.getInvoiceCredentials();return e?this.http.post(`${Q}/list`,{invoice_id:e.id,invoice_identifier:e.identifier},t):{error:{message:"No invoice found",type:"validation"}}}async create(t,e){const a=this.credentials.getInvoiceCredentials();if(!a)return{error:{message:"No invoice found",type:"validation"}};const i=await this.http.post(Q,{invoice_id:a.id,invoice_identifier:a.identifier,payment_type:t},e);return i.data&&this.credentials.setPaymentCredentials({id:i.data.id,identifier:i.data.identifier}),i}async initialize(t){const e=this.credentials.getPaymentCredentials();return e?this.http.post(`${Q}/${e.id}/process_payment_step`,{payment_identifier:e.identifier},t):{error:{message:"No payment found. Please create a payment first.",type:"validation"}}}async processStep(t,e){const a=this.credentials.getPaymentCredentials();return a?this.http.post(`${Q}/${a.id}/process_payment_step`,{payment_identifier:a.identifier,...t},e):{error:{message:"No payment found",type:"validation"}}}clearPayment(){this.credentials.clearPaymentCredentials()}}class lt{constructor(t){this.http=t}async login(t,e){return this.http.post(`${Z}/login`,t,e)}async requestMobileOTP(t,e){return this.http.post(`${Z}/login_request`,t,e)}async verifyMobileOTP(t,e){return this.http.post(`${Z}/login_request_verification`,t,e)}async requestEmailLogin(t,e){return this.http.post(`${J}/email_login_request`,t,e)}async register(t,e){return this.http.post(`${J}/register`,t,e)}async getCurrentUser(t){return this.http.get(`${J}/current`,t)}async updateProfile(t,e,a){return this.http.put(`${J}/${t}`,e,a)}async requestMobilePhoneUpdate(t,e){return this.http.post(`${J}/update_mobile_phone_request`,t,e)}async verifyMobilePhoneUpdate(t,e){return this.http.post(`${J}/update_mobile_phone_verification`,t,e)}async forgotPassword(t,e){return this.http.post(`${J}/forgot_password`,t,e)}async revivePassword(t,e){return this.http.post(`${J}/revive_password`,t,e)}async mergeUser(t){return this.http.post(`${J}/merge_user`,{},t)}}class ht{constructor(t){this.http=t}transformFilters(t){if(!t)return{};const e={};return void 0!==t.page&&(e.page_number=t.page),void 0!==t.pageSize&&(e.page_size=t.pageSize),void 0!==t.categoryId&&(e.category_id=t.categoryId),void 0!==t.minPrice&&(e.min_price=t.minPrice),void 0!==t.maxPrice&&(e.max_price=t.maxPrice),e}async query(t,e,a){const i=this.transformFilters(e),r=await this.http.get(L,{...a,params:{...i,query:t,page_number:i.page_number??1,page_size:i.page_size??20,search_direction:"center"}});if(r.data){return{data:z(r.data)}}return r}}class mt{constructor(t){this.http=t}transformFilters(t){if(!t)return{};const e={};return void 0!==t.productId&&(e.product_id=t.productId),void 0!==t.page&&(e.page=t.page),void 0!==t.pageSize&&(e.page_size=t.pageSize),e}async list(t,e){return this.http.get(X,{...e,params:this.transformFilters(t)})}async create(t,e){return this.http.post(X,t,e)}async get(t,e){return this.http.get(`${X}/${t}`,e)}}class gt{constructor(t){this.http=t}validateInvoiceId(t){return!Number.isFinite(t)||t<=0?{error:{message:"Invalid invoice ID",type:"validation"}}:null}async getBalance(t){return this.http.get("/api/v1/users/wallet/balance",t)}async listTransactions(t,e){const a=t?.page_number??1,i=t?.page_size??100;return this.http.get("/api/v1/wallet/transactions",{...e,params:{page_number:a,page_size:i}})}async applyCredit(t,e){const a=this.validateInvoiceId(t);return a||this.http.post(`/api/v1/invoices/${t}/add_credit`,{},e)}async removeCredit(t,e){const a=this.validateInvoiceId(t);return a||this.http.post(`/api/v1/invoices/${t}/remove_credit`,{},e)}}class yt{constructor(t){this.http=t}async getPage(t,e){const a=await this.http.get(rt,{...e,params:{url_part:t}}),i=R(a.data);if("cms_page"!==i.entityType||"blog"===i.entity?.cmsPageType)throw new Error(`Expected CMS page at ${t}, but got ${i.entityType}`);return{...a,data:i.entity}}async listPages(t,e){const a=M({...t,cmsPageTypes:"normal"}),i=await this.http.get(tt,{...e,params:a});return{...i,data:K(i.data)}}async getBlogPost(t,e){const a=await this.http.get(rt,{...e,params:{url_part:t}}),i=R(a.data);if("cms_page"!==i.entityType||"blog"!==i.entity?.cmsPageType)throw new Error(`Expected blog post at ${t}, but got ${i.entityType}`);return{...a,data:i.entity}}async listBlogPosts(t,e){const a=M({...t,cmsPageTypes:"blog"}),i=await this.http.get(tt,{...e,params:a});return{...i,data:K(i.data)}}async listAll(t,e){const a=M(t),i=await this.http.get(tt,{...e,params:a});return{...i,data:K(i.data)}}}class _t{constructor(t){this.http=t}async upload(t,e){const a=new FormData;a.append("image",t);const i={...e?.headers};return delete i["Content-Type"],this.http.post(et,a,{...e,headers:i})}async delete(t,e){return this.http.delete(`${et}/${t}`,e)}}class ft{constructor(t){this.http=t}async track(t,e){const a=e??((i=t)&&"object"==typeof i&&("retries"in i||"timeout"in i||"cache"in i||"headers"in i||"signal"in i)?t:void 0);var i;return this.http.post("/api/v1/visits/add",void 0,a)}async trackProduct(t,e,a){return this.track(a)}async trackCategory(t,e,a){return this.track(a)}}class vt{constructor(t){this.http=t}async listEvents(t,e){return this.http.get(at,{...e,params:t})}async getEvent(t,e){return this.http.get(`${at}/${t}`,e)}async createBooking(t,e){return this.http.post(it,t,e)}async listBookings(t){return this.http.get(it,t)}async cancelBooking(t,e){return this.http.post(`${it}/${t}/cancel`,{},e)}}class bt{constructor(t){this.http=t}async resolve(t,e){const a=await this.http.get(rt,{...e,params:{url_part:t}});if(a.data){return{data:R(a.data)}}return a}}class wt{constructor(t){this.http=t}async getHeaderMenu(t="headermenu",e){const a=await this.http.get("/api/v1/trees/fetch_single",{...e,params:{identifier:t}}),i=a.data?F(a.data):a.data,r=i?.tree?.treeStructure?.nodes||[],n=this.convertRawTreeToNavigation(r);return{...a,data:n}}convertRawTreeToNavigation(t){if(!t||0===t.length)return[];return t.map(t=>({name:this.findNodeTitle(t),url:this.findNodeUrl(t),children:this.convertRawTreeToNavigation(t.children||[]),shouldBeDropped:this.shouldDropNode(t)})).filter(t=>!t.shouldBeDropped).map(({shouldBeDropped:t,...e})=>e)}findNodeTitle(t){const{entityType:e,details:a,entity:i}=t;return a&&!a.isTitleDefault&&a.title?a.title:a&&!a.isTitleDefault&&a.name?a.name:"product_category"===e||"product"===e?i?.name||"":("cms_page"===e||"blog_page"===e)&&i?.name||""}findNodeUrl(t){return"product"===t.entityType||"product_category"===t.entityType||"cms_page"===t.entityType||"blog_page"===t.entityType?t.entity?.url||"#":"url"===t.entityType&&t.details?.url||"#"}shouldDropNode(t){return("product"===t.entityType||"product_category"===t.entityType||"cms_page"===t.entityType||"blog_page"===t.entityType)&&!t.entity?.enabled}}class Pt{constructor(t){this.http=t}async getInfo(t){const e=await this.http.get("/api/v2/general/info",t);return e.data?{data:h(e.data)}:e.error?{error:e.error}:{error:{type:"api",message:"No data returned from general info endpoint."}}}async getFeatures(t){const e=await this.getInfo(t);return e.error?{error:e.error}:{data:e.data?.settings?.features}}async getCheckoutConfig(t){const e=await this.getInfo(t);return e.error?{error:e.error}:{data:e.data?.settings?.checkout}}async getWalletConfig(t){const e=await this.getInfo(t);return e.error?{error:e.error}:{data:e.data?.settings?.wallet}}async getTajrobeConfig(t){const e=await this.getInfo(t);return e.error?{error:e.error}:{data:e.data?.settings?.tajrobe}}}class Ct{constructor(t){const a=e(t);this.http=new U(a),this.tokenStorage=this.http.getTokenStorage(),this.credentialsManager=new q,this.products=new nt(this.http),this.categories=new st(this.http),this.cart=new ot(this.http,this.credentialsManager),this.orders=new ct(this.http),this.invoices=new dt(this.http,this.credentialsManager),this.shipping=new pt(this.http,this.credentialsManager),this.payments=new ut(this.http,this.credentialsManager),this.users=new lt(this.http),this.search=new ht(this.http),this.feedbacks=new mt(this.http),this.wallet=new gt(this.http),this.cms=new yt(this.http),this.images=new _t(this.http),this.visits=new ft(this.http),this.booking=new vt(this.http),this.entityRoutes=new bt(this.http),this.menu=new wt(this.http),this.general=new Pt(this.http)}setAuthToken(t){this.tokenStorage.set(t)}getAuthToken(){return this.tokenStorage.get()}clearAuth(){this.tokenStorage.remove()}isAuthenticated(){return null!==this.tokenStorage.get()}clearCache(){this.http.clearCache()}clearCredentials(){this.credentialsManager.clearAll()}clearAll(){this.clearAuth(),this.clearCache(),this.clearCredentials()}async searchQuery(t,e,a){return this.search.query(t,e,a)}}function St(t){return new Ct(t)}function Et(t){return function(t){if(!t||"object"!=typeof t)return!1;const e=t;return e.http instanceof U&&e.credentials instanceof q}(t)?t:function(t){const a=e(t);return{http:new U(a),credentials:new q}}(t)}function At(t){const{http:e}=Et(t);return new nt(e)}function It(t){const{http:e}=Et(t);return new st(e)}function zt(t){const{http:e,credentials:a}=Et(t);return new ot(e,a)}function Tt(t){const{http:e}=Et(t);return new ct(e)}function kt(t){const{http:e,credentials:a}=Et(t);return new dt(e,a)}function Gt(t){const{http:e,credentials:a}=Et(t);return new pt(e,a)}function $t(t){const{http:e,credentials:a}=Et(t);return new ut(e,a)}function Nt(t){const{http:e}=Et(t);return new lt(e)}function Ot(t){const{http:e}=Et(t);return new ht(e)}function Dt(t){const{http:e}=Et(t);return new mt(e)}function Rt(t){const{http:e}=Et(t);return new gt(e)}function xt(t){const{http:e}=Et(t);return new yt(e)}function Kt(t){const{http:e}=Et(t);return new _t(e)}function Mt(t){const{http:e}=Et(t);return new ft(e)}function jt(t){const{http:e}=Et(t);return new vt(e)}function Ft(t){const{http:e}=Et(t);return new bt(e)}function Ut(t){const{http:e}=Et(t);return new wt(e)}function qt(t){const{http:e}=Et(t);return new Pt(e)}export{q as CredentialsManager,U as HttpClient,Ct as SazitoClient,a as TokenStorage,jt as booking,zt as cart,It as categories,xt as cms,jt as createBookingAPI,xt as createCMSAPI,zt as createCartAPI,It as createCategoriesAPI,Ft as createEntityRoutesAPI,Dt as createFeedbacksAPI,qt as createGeneralAPI,Kt as createImagesAPI,kt as createInvoicesAPI,Ut as createMenuAPI,Tt as createOrdersAPI,$t as createPaymentsAPI,At as createProductsAPI,St as createSazitoClient,Ot as createSearchAPI,Gt as createShippingAPI,Nt as createUsersAPI,Mt as createVisitsAPI,Rt as createWalletAPI,Ft as entityRoutes,Dt as feedbacks,qt as general,Kt as images,kt as invoices,Ut as menu,Tt as orders,$t as payments,At as products,Ot as search,Gt as shipping,k as transformAddToCartInput,l as transformApiResponse,C as transformCartResponse,G as transformCreateCartInput,S as transformInvoiceResponse,I as transformProductListResponse,u as transformRequestKeys,p as transformResponseKeys,T as transformShippingAddressInput,Nt as users,Mt as visits,Rt as wallet};
1
+ const t={timeout:3e4,retry:{enabled:!0,retries:3,retryDelay:1e3},cache:{products:{enabled:!0,ttl:6e5},categories:{enabled:!0,ttl:6e5},cart:{enabled:!1},orders:{enabled:!1},search:{enabled:!0,ttl:3e5},cms:{enabled:!0,ttl:6e5},tags:{enabled:!0,ttl:6e5},entityRoutes:{enabled:!0,ttl:6e5}},debug:!1};function e(e){return{...t,...e,retry:{...t.retry,...e.retry},cache:{...t.cache,...e.cache},customFetchApi:e.customFetchApi||("undefined"!=typeof fetch?fetch:void 0)}}class a{constructor(){this.tokenKey="user_id_token"}get(){if("undefined"==typeof window||"undefined"==typeof document)return null;const t=this.getFromLocalStorage();if(t)return t;return this.parseCookies()[this.tokenKey]||null}set(t,e){if("undefined"==typeof window||"undefined"==typeof document)return void console.warn("[Sazito SDK] Cannot set token in SSR environment");this.setInLocalStorage(t);const a={secure:!0,sameSite:"Lax",maxAge:2592e3,path:"/",...e};this.setCookie(this.tokenKey,t,a)}remove(){"undefined"!=typeof window&&"undefined"!=typeof document&&(this.removeFromLocalStorage(),this.setCookie(this.tokenKey,"",{maxAge:-1,path:"/"}))}getFromLocalStorage(){try{return window.localStorage.getItem(this.tokenKey)}catch{return null}}setInLocalStorage(t){try{window.localStorage.setItem(this.tokenKey,t)}catch{}}removeFromLocalStorage(){try{window.localStorage.removeItem(this.tokenKey)}catch{}}parseCookies(){return"undefined"==typeof document?{}:document.cookie.split(";").reduce((t,e)=>{const[a,i]=e.trim().split("=");return a&&i&&(t[a]=decodeURIComponent(i)),t},{})}setCookie(t,e,a){let i=`${t}=${encodeURIComponent(e)}`;void 0!==a.maxAge&&(i+=`; Max-Age=${a.maxAge}`),a.path&&(i+=`; Path=${a.path}`),a.domain&&(i+=`; Domain=${a.domain}`),a.secure&&(i+="; Secure"),a.httpOnly&&(i+="; HttpOnly"),a.sameSite&&(i+=`; SameSite=${a.sameSite}`),document.cookie=i}}class i{constructor(){this.cache=new Map}get(t,e){const a=this.cache.get(t);return a?e&&Date.now()-a.timestamp>e?(this.cache.delete(t),null):a.data:null}set(t,e){this.cache.set(t,{data:e,timestamp:Date.now()})}delete(t){this.cache.delete(t)}deletePattern(t){const e=new RegExp(t),a=[];this.cache.forEach((t,i)=>{e.test(i)&&a.push(i)}),a.forEach(t=>this.cache.delete(t))}clear(){this.cache.clear()}static generateKey(t,e,a){return`${t}:${e}:${a?JSON.stringify(a):""}`}}const r={no_of_items:"quantity",single_item_price:"unitPrice",total_items_price:"lineTotal",items_total_raw_price:"itemsTotalRawPrice",items_discount:"itemsDiscount",customer_profit:"customerProfit",customer_profit_percentage:"customerProfitPercentage",total_amount:"totalAmount",net_total:"netTotal",gross_total:"grossTotal",final_total:"finalTotal",discount_total:"discountTotal",shipping_total:"shippingTotal",tax_total:"taxTotal",unique_identifier:"identifier",invoice_identifier:"identifier",payment_identifier:"identifier",shipping_address_identifier:"identifier",first_name:"firstName",last_name:"lastName",mobile_phone:"mobilePhone",phone_number:"phoneNumber",postal_code:"postalCode",user_comment:"userComment",product_id:"productId",variant_id:"variantId",product_name:"name",product_image:"image",product_variant:"variant",product_variants:"variants",product_categories:"categories",product_attributes:"attributes",product_type:"productType",short_description:"shortDescription",stock_quantity:"stockQuantity",stock_number:"stockQuantity",sale_price:"salePrice",raw_price:"originalPrice",has_max_order:"hasMaxOrder",max_no_of_order:"maxOrderQuantity",min_order_count:"minOrderQuantity",sold_count:"soldCount",static_url:"staticUrl",dynamic_form_id:"dynamicFormId",event_entity_id:"eventEntityId",theme_config:"themeConfig",image_id:"imageId",is_stock_managed:"isStockManaged",commercial_files:"commercialFiles",sort_index:"sortIndex",attribute_type:"attributeType",cart_products:"items",cart_product_id:"cartProductId",min_basket_limit_violated:"minBasketLimitViolated",invoice_items:"items",products:"items",total_count:"total",shipping_method_needed:"needsShipping",shipping_method:"shippingMethod",shipping_address:"shippingAddress",shipping_items:"shippingItems",delivery_time:"deliveryTime",min_delivery_days:"minDays",max_delivery_days:"maxDays",payment_type:"paymentType",payment_types:"paymentTypes",payment_amount:"amount",reference_code:"code",is_default:"isDefault",is_available:"isAvailable",delete_coupon:"deleteCoupon",form_attributes:"formAttributes",booking_attributes:"bookingAttributes",readable_form_attr:"formFields",created_at:"createdAt",updated_at:"updatedAt",page_number:"page",page_size:"pageSize",total_count_raw:"totalCountRaw",max_price:"maxPrice",min_price:"minPrice",stock_alert_limit:"stockAlertLimit",sub_categories:"subCategories",order_number:"orderNumber",sort_order:"sortOrder",pinned_ids:"pinnedIds",region_id:"regionId",city_id:"cityId",parent_id:"parentId",discount_code:"discountCode",entity_name:"entityType",entity_id:"entityId",other_props:"entity",shipping_methods:"shippingMethods",shipping_rates:"shippingRates",grouped_shipping_rates:"groupedShippingRates",items_shipping_rate:"itemsShippingRate",shipping_rate:"shippingRate",rate_id:"rateId",invoice_item_id:"invoiceItemId",invoice_item_ids:"invoiceItemIds",scheduler_booking_attributes:"schedulerBookingAttributes",inventory_count:"inventoryCount",order_identifier:"orderIdentifier",self_only:"selfOnly",coupon:"coupon",discount_usages:"discountUsages",user_set_coordinates_before:"userSetCoordinatesBefore",show_order:"showOrder",alt:"alt",url:"url",activate_add_to_cart_alert:"addToCardAlert",activate_advanced_card_to_card:"advancedCardToCard",activate_ayria_payment_customization:"ayriaPaymentGateway",activate_azki_payment_customization:"azkiPaymentGateway",activate_bazar_payment_customization:"bazarPaymentGateway",activate_blog:"shopBlog",activate_card_to_card_payment:"cardToCardPayment",activate_checkout_dynamic_form:"checkoutDynamicForm",activate_different_register_customization:"multiTypeRegister",activate_digipay_payment:"digipayPaymentGateway",activate_digipay_payment_customization:"digipayPaymentGateway",activate_filter_products:"productFilters",activate_ghesta_payment_customization:"ghestaPaymentGateway",activate_mega_footer:"megaFooter",activate_mellat_payment_customization:"mellatPaymentGateway",activate_min_basket:"checkoutMinimumAmount",activate_novapay_payment_customization:"novapayPaymentGateway",activate_ozon_payment_customization:"ozonPaymentGateway",activate_payment_in_place:"paymentInPlace",activate_payping_payment:"paypingPaymentGateway",activate_pec_payment_customization:"pecPaymentGateway",activate_sabin_payment_customization:"sabinPaymentGateway",activate_sadad_payment_customization:"sadadPaymentGateway",activate_search:"shopSearch",activate_sep_payment_customization:"sepPaymentGateway",activate_shop_vat:"shopVat",activate_snapppay_payment_customization:"snapppayPaymentGateway",activate_tajrobe:"tajrobe",activate_tara_payment_customization:"taraPaymentGateway",activate_theme_config_settings:"themeConfigSettings",activate_toman_payment_customization:"tomanPaymentGateway",activate_torobpay_payment_customization:"torobpayPaymentGateway",activate_up_payment_customization:"asanpardakhtPaymentGateway",activate_vandar_payment_customization:"vandarPaymentGateway",activate_wallet:"wallet",activate_yourgate_payment_customization:"yourgatePaymentGateway",activate_zarinpal_payment:"zarinpalPaymentGateway",activate_zarinplus_payment_customization:"zarinplusPaymentGateway",activate_zibal_payment_customization:"zibalPaymentGateway",activate_zify_payment_customization:"zifyPaymentGateway",disable_ordering:"disableOrdering",pwa:"progressiveWebApp",remove_front_basket:"hideCheckout",remove_front_taint:"sazitoBrandingRemoval"},n=Object.values(r).reduce((t,e)=>(t[e]=(t[e]||0)+1,t),{}),s=Object.entries(r).reduce((t,[e,a])=>(1===n[a]&&(t[a]=e),t),{});function o(t){return t.replace(/_([a-z])/g,(t,e)=>e.toUpperCase())}function d(t){return t.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function c(t){return!(null===t||"object"!=typeof t||Array.isArray(t)||t instanceof Date)}function u(t,e){const a={...t};for(const t of e)delete a[t];return a}function p(t){if(!c(t))return Array.isArray(t)?t.map(t=>p(t)):t;const e={};for(const[a,i]of Object.entries(t)){let t=r[a];t||(t=o(a)),c(i)?e[t]=p(i):Array.isArray(i)?e[t]=i.map(t=>p(t)):e[t]=i}return e}function l(t){if(!c(t))return Array.isArray(t)?t.map(t=>l(t)):t;const e={};for(const[a,i]of Object.entries(t)){let t=s[a];t||(t=d(a)),c(i)?e[t]=l(i):Array.isArray(i)?e[t]=i.map(t=>l(t)):e[t]=i}return e}function m(t){const e=t;if(c(e?.data?.result)){const t=e.data.result,a=Object.keys(t);return 1===a.length&&c(t[a[0]])?p(t[a[0]]):p(t)}return p(t)}function h(t){if(!t)return{};if(!c(t))return{};const{general:e,shop:a,checkout:i,features:r,wallet:n,tajrobe:s,domain:o,enamad:d,google:u,logo:p,social:l,...m}=t,h={...c(e)?e:{},...c(a)?a:{}},{registerType:_,showProductStockNumber:b,...v}=h||{};let I=i;if(c(i)){const t={...i};void 0===t.preventRedirect&&void 0!==t.manual&&(t.preventRedirect=t.manual),delete t.manual,I=t}return{...m,scripts:{enamad:d,google:u},shop:f({...v,domain:o,logo:p,social:l}),settings:{checkout:I,features:w(r),wallet:P(n),tajrobe:A(s),registerType:y(_),showProductStockNumber:g(b)}}}function y(t){return"string"==typeof t?t:""}function g(t){return"boolean"==typeof t?t:c(t)&&Object.prototype.hasOwnProperty.call(t,"enabled")?g(t.enabled):1===t||"1"===t||"true"===t}function f(t){if(!c(t))return{};const e={...t};if(c(e.city)){const t=u(e.city,["createdAt","updatedAt"]);let a=t.region;c(a)&&(a=u(a,["createdAt","updatedAt","cities"])),t.region=a,e.city=t}return e}const _={addToCardAlert:"addToCartAlertEnabled",addToCartAlert:"addToCartAlertEnabled",advancedCardToCard:"advancedCardToCardEnabled",cardToCardPayment:"cardToCardPaymentEnabled",checkoutDynamicForm:"checkoutDynamicFormEnabled",multiTypeRegister:"multiTypeRegisterEnabled",productFilters:"productFiltersEnabled",megaFooter:"megaFooterEnabled",checkoutMinimumAmount:"checkoutMinimumAmountEnabled",paymentInPlace:"paymentInPlaceEnabled",shopBlog:"blogEnabled",shopSearch:"searchEnabled",shopVat:"shopVatEnabled",tajrobe:"tajrobeEnabled",themeConfigSettings:"themeConfigSettingsEnabled",wallet:"walletEnabled",progressiveWebApp:"progressiveWebAppEnabled",disableOrdering:"orderingDisabled",hideCheckout:"checkoutHidden",sazitoBrandingRemoval:"sazitoBrandingRemoved",ayriaPaymentGateway:"ayriaPaymentGatewayEnabled",azkiPaymentGateway:"azkiPaymentGatewayEnabled",bazarPaymentGateway:"bazarPaymentGatewayEnabled",digipayPaymentGateway:"digipayPaymentGatewayEnabled",ghestaPaymentGateway:"ghestaPaymentGatewayEnabled",mellatPaymentGateway:"mellatPaymentGatewayEnabled",novapayPaymentGateway:"novapayPaymentGatewayEnabled",ozonPaymentGateway:"ozonPaymentGatewayEnabled",paypingPaymentGateway:"paypingPaymentGatewayEnabled",pecPaymentGateway:"pecPaymentGatewayEnabled",sabinPaymentGateway:"sabinPaymentGatewayEnabled",sadadPaymentGateway:"sadadPaymentGatewayEnabled",sepPaymentGateway:"sepPaymentGatewayEnabled",snapppayPaymentGateway:"snapppayPaymentGatewayEnabled",taraPaymentGateway:"taraPaymentGatewayEnabled",tomanPaymentGateway:"tomanPaymentGatewayEnabled",torobpayPaymentGateway:"torobpayPaymentGatewayEnabled",asanpardakhtPaymentGateway:"asanpardakhtPaymentGatewayEnabled",vandarPaymentGateway:"vandarPaymentGatewayEnabled",yourgatePaymentGateway:"yourgatePaymentGatewayEnabled",zarinpalPaymentGateway:"zarinpalPaymentGatewayEnabled",zarinplusPaymentGateway:"zarinplusPaymentGatewayEnabled",zibalPaymentGateway:"zibalPaymentGatewayEnabled",zifyPaymentGateway:"zifyPaymentGatewayEnabled",activateEditOrderCustomization:"editOrderEnabled",activateEditOrderCustomizationEnabled:"editOrderEnabled"},b=new Set(["activateAlopeykAdvanced","activate_alopeyk_advanced"]),v=new Set(["auditLogEnabled","editOrderEnabled","rahkaranAccountingCustomizationEnabled","advancedThemeDesignerEnabled","checkoutHidden","eventPublisherEnabled","exportOrdersEnabled","exportProductsEnabled","exportUsersEnabled","fontCustomizationEnabled","forwardShippingEnabled","podroShippingEnabled","postexShippingEnabled","quotaNotificationsEnabled","recaptchaEnabled","rolePoliciesEnabled","sepidarAccountingCustomizationEnabled","shortUrlEnabled","skuSearchEnabled","snappShopCustomizationEnabled","snappboxShippingEnabled","stockAlertNotificationsEnabled","tapsipackShippingEnabled","themeConfigSettingsEnabled","advancedTextEditorEnabled","advancedShippingEnabled","bulkActionEnabled","discountBulkEnabled","discountCodeEnabled","orderBulkActionEnabled","importProductsEnabled","mahakAccountingCustomizationEnabled","millipayPaymentCustomizationEnabled","orderSmsNotificationsEnabled"]);function w(t){if(!c(t))return{};const e={},a=(t,a)=>{if(b.has(t))return;const i=(t=>{if("boolean"==typeof t)return t;if("number"==typeof t)return 1===t||0!==t&&void 0;if("string"==typeof t){const e=t.trim().toLowerCase();return"true"===e||"1"===e||"false"!==e&&"0"!==e&&void 0}})(a);void 0!==i&&(e[t]=i)};c(t.flags)&&Object.entries(t.flags).forEach(([t,e])=>{a(t,e)}),c(t.configurations)&&Object.entries(t.configurations).forEach(([t,e])=>{a(t,e)}),Object.entries(t).forEach(([t,e])=>{"flags"!==t&&"premium"!==t&&"configurations"!==t&&(c(e)&&Object.prototype.hasOwnProperty.call(e,"enabled")?a(t,e.enabled):a(t,e))});const i={};Object.entries(e).forEach(([t,e])=>{const a=function(t){const e=t.includes("_")?o(t):t,a=_[e];if(a)return a;const i=e.startsWith("activate")&&e.length>8?`${e.charAt(8).toLowerCase()}${e.slice(9)}`:e;return i.endsWith("Enabled")||i.endsWith("Disabled")||i.endsWith("Hidden")||i.endsWith("Removed")?i:`${i}Enabled`}(t);v.has(a)||(i[a]=e)});const r={...i};return c(t.premium)&&(r.premium=t.premium),r}function P(t){if(!c(t))return{};const e=c(t.configurations)?{...t,...t.configurations}:{...t},a=t=>"boolean"==typeof t?t:1===t||"1"===t||"true"===t||0!==t&&"0"!==t&&"false"!==t&&void 0;return{enabled:a(e.enabled)??!1,useWithDiscount:a(e.useWithDiscount)??!1,minAmount:(t=>{if("number"==typeof t&&Number.isFinite(t))return t;const e=Number(t);return Number.isFinite(e)?e:void 0})(e.minAmount??e.walletMinAmount)??0,minAmountRequired:a(e.minAmountRequired??e.walletMinStatus)??!1}}function A(t){if(!c(t))return{};const e=c(t.configurations)?{...t,...t.configurations}:{...t};let a=!1;return"boolean"==typeof e.enabled?a=e.enabled:1!==e.enabled&&"1"!==e.enabled&&"true"!==e.enabled||(a=!0),{enabled:a}}function I(t){const e=m(t);if(!c(e))return{};const a=Array.isArray(e.items)?e.items.map(t=>function(t){if(!c(t))return{};const e=x(t),a=R(t.productVariantId??e.variantId)??e.variantId;return{id:F(t.id??t.cartProductId)??"",productVariantId:a,quantity:R(t.quantity)??0,unitPrice:R(t.unitPrice)??0,lineTotal:R(t.lineTotal)??0,product:e,formAttributes:t.formAttributes,formFields:t.formFields,bookingAttributes:t.bookingAttributes}}(t)):[];return{...e,items:a,netTotal:R(e.netTotal)??0,grossTotal:R(e.grossTotal),needsShipping:Boolean(e.needsShipping),minBasketLimitViolated:Boolean(e.minBasketLimitViolated),deleteCoupon:void 0===e.deleteCoupon?void 0:Boolean(e.deleteCoupon)}}function C(t){const e=m(t);if(!c(e))return{};const a=u(e,["shippingMethod","user","userData"]),i=Array.isArray(e.items)?e.items.map(t=>function(t){if(!c(t))return{};const e=x(t),a=R(t.productVariantId??e.variantId)??e.variantId,i=Array.isArray(e.attributes)?e.attributes:[],r=G(e.hasMaxOrder??t.hasMaxOrder);return{id:F(t.id??t.invoiceItemId??t.cartProductId)??"",productVariantId:a,productId:R(e.productId??t.productId),name:D(t.name)??D(e.name)??"",url:D(e.url)??D(t.url),attributes:i,productType:D(e.productType)??D(t.productType),hasMaxOrder:r,maxOrderQuantity:R(e.maxOrderQuantity??t.maxOrderQuantity),minOrderQuantity:R(e.minOrderQuantity??t.minOrderQuantity),image:K(t.image??e.image),quantity:R(t.quantity)??0,unitPrice:R(t.unitPrice)??0,lineTotal:R(t.lineTotal)??0,rawPrice:R(t.rawPrice??t.originalPrice)??0,customerProfit:R(t.customerProfit)??0,commercialFiles:t.commercialFiles,formAttributes:t.formAttributes,bookingAttributes:t.bookingAttributes,formFields:t.formFields}}(t)):[],r=Array.isArray(e.discountUsages)?e.discountUsages:[],n=r[0],s=c(n)&&c(n.discountCode)?D(n.discountCode.code):void 0;return{...a,items:i,shippingAddress:function(t){if(!t)return;const{id:e,city:a,region:i,...r}=t,n={id:i?.id??a.regionId??0,name:i?.name??"",city:a};return{...r,region:n}}(T(e.shippingAddress)),shippingItems:Array.isArray(e.shippingItems)?e.shippingItems.map(t=>function(t){if(!c(t))return{};const e=c(t.rate)?t.rate:c(t.shippingRate)?t.shippingRate:c(t.shippingMethod)?t.shippingMethod:t;return{invoiceItemIds:O(t),rate:J(e)}}(t)):[],discountUsages:r,netTotal:R(e.netTotal)??0,finalTotal:R(e.finalTotal)??0,vat:R(e.vat)??0,vatPercent:R(e.vatPercent)??0,itemsDiscount:R(e.itemsDiscount)??0,discountTotal:R(e.discountTotal)??0,customerProfit:R(e.customerProfit)??0,customerProfitPercentage:R(e.customerProfitPercentage)??0,itemsTotalRawPrice:R(e.itemsTotalRawPrice)??0,couponTotal:R(e.couponTotal)??0,shippingTotal:R(e.shippingTotal)??0,creditTotal:R(e.creditTotal)??0,needsShipping:Boolean(e.needsShipping),userComment:"string"==typeof e.userComment?e.userComment:void 0,discountCode:s}}function S(t){return T(t)}function z(t){const e=m(t);if(c(e))return E(e)}function E(t){if(!t)return;const e=function(t){const e=k(t);if(!e)return;if(1===Object.keys(e).length&&c(e.user))return k(e.user)??e.user;return e}(t);if(!e)return;const a={},i=R(e.id);void 0!==i&&(a.id=i);const r=D(e.email);r&&(a.email=r);const n=D(e.mobilePhone)??D(e.phoneNumber);n&&(a.mobilePhone=n);const s=D(e.phoneNumber);s&&s!==n&&(a.phoneNumber=s);const o=D(e.firstName);o&&(a.firstName=o);const d=D(e.lastName);d&&(a.lastName=d);const u=D(e.birthDate);return u&&(a.birthDate=u),Object.keys(a).length>0?a:void 0}function T(t){if(!t)return;const e=E(t.user),a=k(t.region),i=k(t.city),r=k(i?.region),n=D(t.regionName)??$(t.region),s=N(a??t.region,{fallbackId:R(t.regionId),fallbackName:n})??N(r,{fallbackId:R(t.regionId),fallbackName:n}),o=R(t.regionId)??s?.id,d=D(t.cityName)??D(i?.name)??$(t.city),c=function(t,e={}){if(null==t)return;const a=k(t),i=R(a?.id)??R(t)??e.fallbackId,r=D(a?.name)??$(t)??e.fallbackName;if(void 0===i||!r)return;const n={id:i,name:r},s=R(a?.regionId)??e.fallbackRegionId;void 0!==s&&(n.regionId=s);const o=R(a?.latitude);void 0!==o&&(n.latitude=o);const d=R(a?.longitude);void 0!==d&&(n.longitude=d);return n}(i??t.city,{fallbackId:R(t.cityId),fallbackName:d,fallbackRegionId:o}),u=D(t.firstName)??e?.firstName??"",p=D(t.lastName)??e?.lastName??"",l={id:R(t.id)??0,identifier:D(t.identifier)??"",firstName:u,lastName:p,city:c??{id:R(t.cityId??t.city)??0,name:d??"",...void 0!==o?{regionId:o}:{}},address:D(t.address)??""},m=D(t.mobilePhone)??D(t.phoneNumber)??e?.mobilePhone??e?.phoneNumber,h=D(t.phoneNumber)??e?.phoneNumber;m&&(l.mobilePhone=m),h&&h!==m&&(l.phoneNumber=h);const y=D(t.email)??e?.email;y&&(l.email=y),s&&(l.region=s);const g=D(t.postalCode);g&&(l.postalCode=g);const f=R(t.latitude);void 0!==f&&(l.latitude=f);const _=R(t.longitude);void 0!==_&&(l.longitude=_);const b=G(t.userSetCoordinatesBefore);return void 0!==b&&(l.userSetCoordinatesBefore=b),l}function N(t,e={}){if(null==t)return;const a=k(t),i=R(a?.id)??R(t)??e.fallbackId,r=D(a?.name)??$(t)??e.fallbackName;return void 0!==i&&r?{id:i,name:r}:void 0}function k(t){if(c(t))return c(t.data)?t.data:t}function $(t){const e=D(t);if(e)return void 0===R(e)?e:void 0}function O(t){return(Array.isArray(t.invoiceItemIds)?t.invoiceItemIds:void 0!==t.invoiceItemId?[t.invoiceItemId]:[]).map(t=>F(t)).filter(t=>void 0!==t)}function R(t){if("number"==typeof t&&Number.isFinite(t))return t;if("string"!=typeof t)return;const e=Number(t);return Number.isFinite(e)?e:void 0}function D(t){if("string"!=typeof t)return;const e=t.trim();return e.length>0?e:void 0}function G(t){return"boolean"==typeof t?t:1===t||"1"===t||"true"===t||0!==t&&"0"!==t&&"false"!==t&&void 0}function F(t){if("number"==typeof t&&Number.isFinite(t))return t;if("string"==typeof t){const e=t.trim();return e.length>0?e:void 0}}function x(t){if(!c(t))return{variantId:0,name:"",attributes:[]};const e=c(t.variant)?t.variant:void 0,a=c(e?.product)?e.product:void 0,i=c(t.product)?t.product:void 0,r=R(i?.variantId??e?.id??t.productVariantId??t.variantId)??0,n=Array.isArray(i?.attributes)?i.attributes:Array.isArray(e?.attributes)?e.attributes:Array.isArray(t.attributes)?t.attributes:[];return{variantId:r,productId:R(i?.productId??t.productId??a?.id),name:D(i?.name)??D(t.name)??"",url:D(i?.url)??D(t.url)??D(a?.url),image:K(i?.image??t.image),attributes:n,productType:D(i?.productType)??D(t.productType)??D(a?.productType),hasMaxOrder:i?.hasMaxOrder??t.hasMaxOrder??e?.hasMaxOrder,maxOrderQuantity:R(i?.maxOrderQuantity??t.maxOrderQuantity??e?.maxOrderQuantity),minOrderQuantity:R(i?.minOrderQuantity??t.minOrderQuantity??e?.minOrderQuantity)}}function M(t){if(!c(t))return{};const e=u(t,["staticUrl","summary","tags","slug"]);return e.variants&&Array.isArray(e.variants)&&(e.variants=e.variants.map(t=>c(t)?u(t,["name","title","product","status","soldCount"]):{})),e.categories&&Array.isArray(e.categories)&&(e.categories=e.categories.map(t=>c(t)?{id:t.id,name:t.name,url:t.url}:{})),e.images&&Array.isArray(e.images)&&(e.images=e.images.map(t=>K(t)??{})),e}function K(t){return c(t)?u(t,["widthRatio","heightRatio","thumb","order"]):t}function j(t){const e=M(t);return e?u(e,["themeConfig"]):e}function U(t){const e=m(t);if(e.items&&Array.isArray(e.items)){const t=R(e.total)??e.items.length,a=R(e.pageSize)??e.items.length,i=R(e.page)??1,r=R(e.totalPages)??Math.ceil(t/a);return{items:e.items.map(t=>j(t)),total:t,page:i,pageSize:a,totalPages:r}}return e}function B(t){if(!c(t))return{products:{items:[],total:0,page:1,pageSize:20},blogPages:{items:[],total:0,page:1,pageSize:20},cmsPages:{items:[],total:0,page:1,pageSize:20},productCategories:{items:[],total:0,page:1,pageSize:20}};const e=t,a={products:{items:[],total:0,page:1,pageSize:20},blogPages:{items:[],total:0,page:1,pageSize:20},cmsPages:{items:[],total:0,page:1,pageSize:20},productCategories:{items:[],total:0,page:1,pageSize:20}};return Array.isArray(e.items)&&(a.products.items=e.items.map(t=>j(t)),a.products.total=R(e.productsCount)??0,a.products.page=R(e.productsPageNumber)??1,a.products.pageSize=R(e.productsPageSize)??20),Array.isArray(e.blogPages)&&(a.blogPages.items=e.blogPages.map(t=>et(t)),a.blogPages.total=R(e.blogPagesCount)??0,a.blogPages.page=R(e.blogPagesPageNumber)??1,a.blogPages.pageSize=R(e.blogPagesPageSize)??20),Array.isArray(e.cmsPages)&&(a.cmsPages.items=e.cmsPages.map(t=>et(t)),a.cmsPages.total=R(e.cmsPagesCount)??0,a.cmsPages.page=R(e.cmsPagesPageNumber)??1,a.cmsPages.pageSize=R(e.cmsPagesPageSize)??20),Array.isArray(e.categories)&&(a.productCategories.items=e.categories.map(t=>X(t)),a.productCategories.total=R(e.productCategoriesCount)??0,a.productCategories.page=R(e.productCategoriesPageNumber)??1,a.productCategories.pageSize=R(e.productCategoriesPageSize)??20),a}function q(t){if(c(t)){const e={...t};return delete e.user,{shipping_address:l(e)}}return{shipping_address:l(t)}}function L(t,e,a){const i={product_variants:[{id:t,count:e}]};return a&&(i.form_attributes=l(a)),i}function Y(t){if(!c(t))return{product_variants:[]};const e=t.variants||t.productVariants||[],a={product_variants:Array.isArray(e)?e.map(t=>c(t)?{id:t.id||t.variantId,count:t.count||t.quantity,form_attributes:t.formAttributes?l(t.formAttributes):void 0}:{}):[]};return t.coupon&&(a.coupon=t.coupon),a}function V(t){const e=m(t);if(!c(e))return[];return(Array.isArray(e.paymentTypes)?e.paymentTypes:Array.isArray(e.methods)?e.methods:[]).map(t=>c(t)?{id:R(t.id)??0,code:t.code,isDefault:Boolean(t.isDefault)}:{id:0,code:"",isDefault:!1})}function Q(t){const e=m(t);return(Array.isArray(e)?e:c(e)&&Array.isArray(e.shippingMethods)?e.shippingMethods:[]).map(t=>H(t))}function W(t){const e=m(t);if(!c(e))return{shippingMethods:[],groupedShippingRates:{},itemsShippingRate:[]};const a=c(e.groupedShippingRates)?Object.entries(e.groupedShippingRates).reduce((t,[e,a])=>(t[e]=Array.isArray(a)?a.map(t=>J(t)):[],t),{}):{};return{shippingMethods:Array.isArray(e.shippingMethods)?e.shippingMethods.map(t=>H(t)):[],groupedShippingRates:a,itemsShippingRate:Array.isArray(e.itemsShippingRate)?e.itemsShippingRate.map(t=>c(t)?{invoiceItemId:F(t.invoiceItemId)??O(t)[0]??"",shippingRate:J(t.shippingRate??t.rate??t)}:{invoiceItemId:"",shippingRate:J(void 0)}):[]}}function H(t){return c(t)?{id:R(t.id)??0,name:D(t.name)??"",type:D(t.type)??""}:{id:0,name:"",type:""}}function J(t){return c(t)?{id:R(t.id??t.rateId)??0,name:D(t.name)??"",price:R(t.price??t.amount)??0,icon:D(t.icon),color:D(t.color),type:D(t.type)}:{id:0,name:"",price:0}}function Z(t){return c(t)?u(t,["staticUrl","products","items"]):{}}function X(t){const e=Z(t);return e?u(e,["themeConfig"]):{}}function tt(t){return c(t)?u(t,["staticUrl","urlKey"]):{}}function et(t){const e=tt(t);return e?u(e,["themeConfig"]):{}}function at(t){const e=m(t);if(!e||!e.route)return e??{};const a=c(e.route)?e.route:{};if(a.entity){switch(a.entityType){case"product":a.entity=M(a.entity);break;case"product_category":a.entity=Z(a.entity);break;case"cms_page":case"blog_page":a.entity=tt(a.entity)}c(a.entity)&&(a.entity=u(a.entity,["id"])),!a.url&&c(a.entity)&&a.entity.url&&(a.url=a.entity.url)}return a}function it(t){if(!c(t))return{};const e={...t};return e.entity&&(e.entity=X(e.entity),c(e.entity)&&(e.entity=u(e.entity,["id"]))),e.children&&Array.isArray(e.children)&&(e.children=e.children.map(it)),e}function rt(t){const e=m(t);return e?e.cmsPages&&Array.isArray(e.cmsPages)?{items:e.cmsPages.map(et),total:e.total||e.cmsPages.length,page:e.page||e.pageNumber||1,pageSize:e.pageSize||e.cmsPages.length}:e.items&&Array.isArray(e.items)?{items:e.items.map(t=>et(t)),total:e.total||e.items.length,page:e.page||1,pageSize:e.pageSize||e.items.length}:e:{}}function nt(t){if(!c(t))return{};const e={};if(void 0!==t.page&&(e.page_number=t.page),void 0!==t.pageSize&&(e.page_size=t.pageSize),t.cmsPageTypes){const a=Array.isArray(t.cmsPageTypes)?t.cmsPageTypes[0]:t.cmsPageTypes;e["filters[]"]=JSON.stringify({name:"cms_page_types",value:a})}return e}function st(t){if(!c(t))return{};const e={};if(t.entityType&&(e.entityType=t.entityType),void 0!==t.entityId&&(e.entityId=t.entityId),c(t.entity)){const a=u(t.entity,["staticUrl","id"]);Object.keys(a).length>0&&(e.entity=a)}return t.details&&(e.details=t.details),t.children&&Array.isArray(t.children)&&(e.children=t.children.map(t=>st(t))),e}function ot(t){const e=m(t);if(!e||!e.tree)return e??{};const a=c(e.tree)?e.tree:{};return c(a.treeStructure)&&Array.isArray(a.treeStructure.nodes)&&(a.treeStructure.nodes=a.treeStructure.nodes.map(t=>st(t))),e}class dt{constructor(t){this.config=t,this.baseUrl="http://api.sazito.com:8080",this.domain=t.domain,this.tokenStorage=new a,this.cache=new i,this.fetchApi=t.customFetchApi.bind(globalThis)}async get(t,e){const a=this.buildUrl(t,e?.params),r=i.generateKey("GET",a,e?.params);if(!1!==e?.cache){const e=this.getApiName(t),a=this.config.cache[e];if(a?.enabled&&a.ttl){const e=this.cache.get(r,a.ttl);if(e)return this.config.debug&&console.log("[Sazito SDK] Cache hit:",t),{data:e}}}const n=await this.request("GET",a,e);return n.data&&!1!==e?.cache&&this.cache.set(r,n.data),n}async post(t,e,a){const i=this.buildUrl(t),r=this.isMultipartBody(e),n=e?r?e:l(e):void 0,s=this.getApiName(t);return this.cache.deletePattern(`GET:.*${s}`),this.request("POST",i,{...a,body:n,rawBody:r,omitJsonContentType:r})}async put(t,e,a){const i=this.buildUrl(t),r=this.isMultipartBody(e),n=e?r?e:l(e):void 0,s=this.getApiName(t);return this.cache.deletePattern(`GET:.*${s}`),this.request("PUT",i,{...a,body:n,rawBody:r,omitJsonContentType:r})}async delete(t,e){const a=this.buildUrl(t),i=this.getApiName(t);return this.cache.deletePattern(`GET:.*${i}`),this.request("DELETE",a,e)}async request(t,e,a,i=0){const r=new AbortController,n=a?.signal||r.signal,s=a?.timeout||this.config.timeout,o=setTimeout(()=>r.abort(),s);try{const r=await this.fetchApi(e,{method:t,headers:this.getHeaders(a?.headers,a?.omitJsonContentType),body:a?.body?a.rawBody?a.body:JSON.stringify(a.body):void 0,signal:n});clearTimeout(o);const s=void 0!==a?.retries?a.retries:this.config.retry.retries;if(!r.ok&&this.shouldRetry(r.status)&&i<s)return this.config.debug&&console.log(`[Sazito SDK] Retrying request (${i+1}/${s}):`,e),await this.delay(this.config.retry.retryDelay*(i+1)),this.request(t,e,a,i+1);const d=r.headers.get("content-type");let c;c=d?.includes("application/json")?await r.json():await r.text();const u=void 0!==c?.result?c.result:c;this.config.debug&&console.log(`[Sazito SDK] ${t} ${e}:`,{status:r.status,data:u});let l=u?p(u):u;const m=["cart","product","user","order","invoice","payment","shippingAddress"];if(l&&"object"==typeof l&&!Array.isArray(l)){const t=Object.keys(l);1===t.length&&m.includes(t[0])&&"object"==typeof l[t[0]]&&null!==l[t[0]]&&(l=l[t[0]])}return r.ok?{data:l}:{error:{status:r.status,message:l?.message||u?.message||r.statusText||"Request failed",type:"api",details:l}}}catch(t){return clearTimeout(o),this.config.debug&&console.error("[Sazito SDK] Request failed:",t),{error:{message:"AbortError"===t.name?"Request timeout":t.message||"Network error",type:"network",details:t}}}}buildUrl(t,e){const a=`${this.baseUrl}${t}`;if(!e||0===Object.keys(e).length)return a;const i=new URLSearchParams;return Object.entries(e).forEach(([t,e])=>{null!=e&&i.append(t,String(e))}),`${a}?${i.toString()}`}getHeaders(t,e=!1){const a={"x-forwarded-host":this.domain,...t};e?delete a["Content-Type"]:a["Content-Type"]=a["Content-Type"]||"application/json";const i=this.tokenStorage.get();return i&&(a.Authorization=i),a}isMultipartBody(t){return"undefined"!=typeof FormData&&t instanceof FormData}shouldRetry(t){return t>=500&&t<600}delay(t){return new Promise(e=>setTimeout(e,t))}getApiName(t){return t.includes("/products")?"products":t.includes("/product_categories")?"categories":t.includes("/cart")?"cart":t.includes("/orders")?"orders":t.includes("/search")?"search":t.includes("/tags")?"tags":t.includes("/entity_route")?"entityRoutes":"cms"}getTokenStorage(){return this.tokenStorage}clearCache(){this.cache.clear()}}class ct{constructor(){this.CART_KEY="CART_CREDENTIALS",this.INVOICE_KEY="INVOICE_CREDENTIALS",this.SHIPPING_KEY="SHIPPING_ADDRESS_CREDENTIALS",this.PAYMENT_KEY="PAYMENT_CREDENTIALS",this.DISCOUNT_KEY="DISCOUNT_CODE_INFO"}getCartCredentials(){return this.getItem(this.CART_KEY)}setCartCredentials(t){this.setItem(this.CART_KEY,t)}clearCartCredentials(){this.removeItem(this.CART_KEY)}getInvoiceCredentials(){return this.getItem(this.INVOICE_KEY)}setInvoiceCredentials(t){this.setItem(this.INVOICE_KEY,t)}clearInvoiceCredentials(){this.removeItem(this.INVOICE_KEY)}getShippingCredentials(){return this.getItem(this.SHIPPING_KEY)}setShippingCredentials(t){this.setItem(this.SHIPPING_KEY,t)}clearShippingCredentials(){this.removeItem(this.SHIPPING_KEY)}getPaymentCredentials(){return this.getItem(this.PAYMENT_KEY)}setPaymentCredentials(t){this.setItem(this.PAYMENT_KEY,t)}clearPaymentCredentials(){this.removeItem(this.PAYMENT_KEY)}getDiscountCode(){return this.getItem(this.DISCOUNT_KEY)}setDiscountCode(t){this.setItem(this.DISCOUNT_KEY,t)}clearDiscountCode(){this.removeItem(this.DISCOUNT_KEY)}clearAll(){this.clearCartCredentials(),this.clearInvoiceCredentials(),this.clearShippingCredentials(),this.clearPaymentCredentials(),this.clearDiscountCode()}getItem(t){if("undefined"==typeof localStorage)return null;try{const e=localStorage.getItem(t);return e?JSON.parse(e):null}catch(e){return console.error(`[Sazito SDK] Error reading ${t} from localStorage:`,e),null}}setItem(t,e){if("undefined"!=typeof localStorage)try{localStorage.setItem(t,JSON.stringify(e))}catch(e){console.error(`[Sazito SDK] Error writing ${t} to localStorage:`,e)}else console.warn("[Sazito SDK] localStorage not available")}removeItem(t){if("undefined"!=typeof localStorage)try{localStorage.removeItem(t)}catch(e){console.error(`[Sazito SDK] Error removing ${t} from localStorage:`,e)}}}const ut="/api/v1/product_categories",pt="/api/v1/search",lt="/api/v2/carts",mt="/api/v2/invoices",ht="/api/v2/shipping_addresses",yt="/api/v2/payments",gt="/api/v1/orders",ft="/api/v1/users",_t="/api/v1/sessions",bt="/api/v1/feedbacks",vt="/api/v1/cms_pages",wt="/api/v1/images",Pt="/api/v1/scheduler/events",At="/api/v1/scheduler/bookings",It="/api/v1/entity_route/route",Ct="/api/v1/feedbacks/comments/details";class St{constructor(t){this.http=t}mapSortToApi(t){if(!t)return null;return{newest:{sort:"date"},"best-selling":{sort:"sold"},availability:{sort:"stock_status"},discount:{sort:"raw_price"},"!price":{sort:"price",sortOrder:"asc"},price:{sort:"price"}}[t]||null}transformFilters(t){if(!t)return{};const e={},a=[];if(t.categories){const e=Array.isArray(t.categories)?t.categories:[t.categories];e.length>0&&a.push({name:"product_categories",value:e.join(",")})}if(!1===t.availableOnly&&a.push({name:"in_stock"}),t.discountedOnly&&a.push({name:"has_raw_price",value:!0}),t.similarTo&&a.push({name:"similar_to",value:{entity_name:"product",entity_id:t.similarTo}}),a.length>0&&(e["filters[]"]=JSON.stringify(a)),t.pinnedIds&&t.pinnedIds.length>0&&(e.pinned_ids=JSON.stringify(t.pinnedIds)),t.sort){const a=this.mapSortToApi(t.sort);a&&(e.sort=a.sort,a.sortOrder&&(e.sort_order=a.sortOrder))}return void 0!==t.priceMin&&(e.min_price=t.priceMin),void 0!==t.priceMax&&(e.max_price=t.priceMax),t.page&&(e.page=t.page),t.pageSize&&(e.page_size=t.pageSize),e}async get(t,e){const a=t.startsWith("/product/")?t:`/product/${t}`,i=await this.http.get(It,{...e,params:{url_part:a}});if(i.data){const t=at(i.data);return"product"===t.entityType&&t.entity?{data:t.entity}:"unknown"===t.entityType?{error:{message:"Product not found",type:"api",status:404}}:{error:{message:`Invalid entity type: expected 'product', got '${t.entityType}'`,type:"api",status:400}}}return i.error?{error:i.error}:{error:{message:"No data returned from product endpoint",type:"api"}}}async list(t,e){const a=this.transformFilters(t),i=await this.http.get("/api/v1/products",{...e,params:a});if(i.data){return{data:U(i.data)}}return i}async search(t,e,a){const i={query:t,search_direction:"center",page_size:e?.pageSize||20,page_number:e?.page||1},r=await this.http.get(pt,{...a,params:i});if(r.data){return{data:B(r.data)}}return r}}class zt{constructor(t){this.http=t}async get(t,e){const a=await this.http.get(`${ut}/${t}`,e);if(a.data){const t=function(t){const e=m(t);return e?Z(e.productCategory||e):{}}(a.data);return{data:t}}return a}async list(t,e){const a={};void 0!==t?.page&&(a.page_number=t.page),void 0!==t?.pageSize&&(a.page_size=t.pageSize);const i=await this.http.get(ut,{...e,params:a});if(i.data){const t=function(t){const e=m(t);return e?(e.categories&&Array.isArray(e.categories)&&(e.categories=e.categories.map(X)),c(e.tree)&&c(e.tree.treeStructure)&&Array.isArray(e.tree.treeStructure.nodes)&&(e.tree.treeStructure.nodes=e.tree.treeStructure.nodes.map(it)),e):{}}(i.data);return{data:t}}return i}}class Et{constructor(t,e){this.http=t,this.credentials=e}persistCartCredentials(t){this.credentials.setCartCredentials({id:t.id,identifier:t.identifier})}async get(t){const e=this.credentials.getCartCredentials();if(!e)return{error:{message:"No cart found. Please create a cart first.",type:"validation"}};const a=await this.http.get(`${lt}/${e.id}`,{...t,params:{identifier:e.identifier}});return a.data?{data:I(a.data)}:(a.error&&this.clearCart(),a)}async create(t,e){const a=await this.http.post(lt,t,e);if(!a.data)return a;const i=I(a.data);return this.persistCartCredentials(i),{data:i}}async addItem(t,e,a,i){return this.addItemWithAttributes(t,e,{formAttributes:a},i)}async addItemWithAttributes(t,e,a,i){const r=this.credentials.getCartCredentials();if(!r)return this.create({variants:[{id:t,count:e,formAttributes:a?.formAttributes}],schedulerBookingAttributes:a?.schedulerBookingAttributes,coupon:a?.coupon},i);const n=await this.http.post(`${lt}/${r.id}/add_products_to_cart`,{identifier:r.identifier,variants:[{id:t,count:e}],formAttributes:a?.formAttributes,schedulerBookingAttributes:a?.schedulerBookingAttributes,coupon:a?.coupon},i);if(n.data){const t=I(n.data);return this.persistCartCredentials(t),{data:t}}return 422===n.error?.status&&this.clearCart(),n}async updateItem(t,e,a,i,r){return this.updateItemWithAttributes(t,e,a,{formAttributes:i},r)}async updateItemWithAttributes(t,e,a,i,r){const n=this.credentials.getCartCredentials();if(!n)return{error:{message:"No cart found",type:"validation"}};const s=await this.http.post(`${lt}/${n.id}/update_products_in_cart`,{identifier:n.identifier,cartProductId:String(t),variants:[{id:e,count:a}],formAttributes:i?.formAttributes,coupon:i?.coupon,deleteCoupon:i?.deleteCoupon},r);if(s.data){const t=I(s.data);return this.persistCartCredentials(t),{data:t}}return s}async removeItem(t,e,a){const i=this.credentials.getCartCredentials();if(!i)return{error:{message:"No cart found",type:"validation"}};const r=await this.http.post(`${lt}/${i.id}/remove_products_from_cart`,{identifier:i.identifier,cartProductId:String(t),variants:[{id:e}]},a);if(r.data){const t=I(r.data);return this.persistCartCredentials(t),{data:t}}return r}clearCart(){this.credentials.clearCartCredentials()}}class Tt{constructor(t){this.http=t}async list(t,e){const a={page_number:t?.pageNumber??1,page_size:t?.pageSize??100};return t?.filters&&t.filters.length>0&&(a.filters=JSON.stringify(t.filters)),this.http.get(gt,{...e,params:a})}async get(t,e){return this.http.get(`${gt}/${t}`,e)}}class Nt{constructor(t,e){this.http=t,this.credentials=e}normalizeInvoiceResponse(t){return t.data?{data:C(t.data)}:(423===t.error?.status&&this.credentials.clearInvoiceCredentials(),t)}async get(t){const e=this.credentials.getCartCredentials(),a=this.credentials.getInvoiceCredentials();if(!a)return{error:{message:"No invoice found. Please create an invoice first.",type:"validation"}};if(!e)return{error:{message:"No cart found. Please create or restore cart credentials first.",type:"validation"}};const i=await this.http.post(`${mt}/${a.id}/refresh`,{cart_id:String(e.id),cart_identifier:e.identifier,identifier:a.identifier},t);return this.normalizeInvoiceResponse(i)}async create(t){const e=this.credentials.getCartCredentials();if(!e)return{error:{message:"No cart found. Please create a cart first.",type:"validation"}};const a=await this.http.post(mt,{cart_id:String(e.id),cart_identifier:e.identifier},t);if(a.data){const t=C(a.data);return this.credentials.setInvoiceCredentials({id:t.id,identifier:t.identifier}),{data:t}}return a}async refresh(t){const e=this.credentials.getCartCredentials(),a=this.credentials.getInvoiceCredentials();if(!e||!a)return{error:{message:"No cart or invoice found",type:"validation"}};const i=await this.http.post(`${mt}/${a.id}/refresh`,{cart_id:String(e.id),cart_identifier:e.identifier,identifier:a.identifier},t);return this.normalizeInvoiceResponse(i)}async addShippingAddress(t,e,a){const i=this.credentials.getCartCredentials(),r=this.credentials.getInvoiceCredentials();if(!i||!r)return{error:{message:"No cart or invoice found",type:"validation"}};const n=await this.http.post(`${mt}/${r.id}/add_shipping_address`,{identifier:r.identifier,shipping_address_id:t,shipping_address_identifier:e,cart_id:i.id,cart_identifier:i.identifier},a);return this.normalizeInvoiceResponse(n)}async addDiscountCode(t,e){const a=this.credentials.getInvoiceCredentials();if(!a)return{error:{message:"No invoice found",type:"validation"}};const i=await this.http.post(`${mt}/${a.id}/add_discount_code`,{identifier:a.identifier,discount_code:t.toUpperCase()},e);return i.data?(this.credentials.setDiscountCode(t.toUpperCase()),{data:C(i.data)}):i}async assignShippingMethod(t,e){const a=this.credentials.getInvoiceCredentials();if(!a)return{error:{message:"No invoice found",type:"validation"}};const i=t.map(t=>({...t,invoiceItemIds:t.invoiceItemIds.map(t=>String(t))})),r=await this.http.post(`${mt}/${a.id}/add_shipping_method`,{identifier:a.identifier,shippings:i},e);return this.normalizeInvoiceResponse(r)}async addDetails(t,e){const a=this.credentials.getInvoiceCredentials();if(!a)return{error:{message:"No invoice found",type:"validation"}};const i=await this.http.post(`${mt}/${a.id}/add_invoice_details`,{identifier:a.identifier,user_comment:t},e);return this.normalizeInvoiceResponse(i)}async addForm(t,e){const a=this.credentials.getInvoiceCredentials();if(!a)return{error:{message:"No invoice found",type:"validation"}};const i=await this.http.post(`${mt}/${a.id}/add_form`,{invoiceIdentifier:t.invoiceIdentifier||t.identifier||a.identifier,formAttributes:t.formAttributes},e);return this.normalizeInvoiceResponse(i)}async addCredit(t){const e=this.credentials.getInvoiceCredentials();if(!e)return{error:{message:"No invoice found",type:"validation"}};const a=await this.http.post(`${mt}/${e.id}/add_credit`,{identifier:e.identifier},t);return this.normalizeInvoiceResponse(a)}async removeCredit(t){const e=this.credentials.getInvoiceCredentials();if(!e)return{error:{message:"No invoice found",type:"validation"}};const a=await this.http.post(`${mt}/${e.id}/remove_credit`,{identifier:e.identifier},t);return this.normalizeInvoiceResponse(a)}async toggleCredit(t){const e=await this.get(t);return e.data?e.data.creditTotal>0?this.removeCredit(t):this.addCredit(t):e}async getApplicableShippingMethods(t){const e=this.credentials.getInvoiceCredentials();if(!e)return{error:{message:"No invoice found",type:"validation"}};const a=await this.http.get(`${mt}/${e.id}/applicable_shipping_methods`,{...t,params:{identifier:e.identifier}});return a.data?{data:W(a.data)}:a}clearInvoice(){this.credentials.clearInvoiceCredentials()}}class kt{constructor(t,e){this.http=t,this.credentials=e}sanitizeAddressInput(t){const e={...t};return delete e.user,e}async createAddress(t,e){const a=this.sanitizeAddressInput(t),i=await this.http.post(ht,{shipping_address:a},e);if(i.data){const t=S(i.data);return t?(this.credentials.setShippingCredentials({id:t.id,identifier:t.identifier}),{data:t}):i}return i}async updateAddress(t,e){const a=this.credentials.getShippingCredentials();if(!a)return this.createAddress(t,e);const i=this.sanitizeAddressInput(t),r=await this.http.post(ht,{identifier:a.identifier,shipping_address:i},e);if(r.data){const t=S(r.data);return t?(this.credentials.setShippingCredentials({id:t.id,identifier:t.identifier}),{data:t}):r}return r}async getAddress(t){const e=this.credentials.getShippingCredentials();if(!e)return{error:{message:"No shipping address found",type:"validation"}};const a=await this.http.get(`${ht}/${e.id}`,{...t,params:{identifier:e.identifier}});if(a.data){const t=S(a.data);return t?{data:t}:a}return a}async getMethods(t){const e=await this.http.get("/api/v2/shipping_methods",t);return e.data?{data:Q(e.data)}:e.error?{error:e.error}:{data:[]}}clearAddress(){this.credentials.clearShippingCredentials()}}class $t{constructor(t,e){this.http=t,this.credentials=e,this.pinchedPayments=new Set}async getMethods(t){const e=this.credentials.getInvoiceCredentials();if(!e)return{error:{message:"No invoice found",type:"validation"}};const a=await this.http.post(`${yt}/list`,{invoice_identifier:e.identifier},t);return a.data?{data:V(a.data)}:a.error?{error:a.error}:{data:[]}}async create(t,e){if(!Number.isInteger(t)||t<=0)return{error:{message:"Invalid paymentTypeId. Provide a positive integer from payments.getMethods().",type:"validation"}};const a=this.credentials.getInvoiceCredentials();if(!a)return{error:{message:"No invoice found",type:"validation"}};const i=await this.http.post(yt,{invoice_identifier:a.identifier,payment_type:t},e);if(i.data){const t=this.normalizePayment(i.data);return this.credentials.setPaymentCredentials({id:t.id,identifier:t.identifier}),{data:t}}return i}async initialize(t){const e=this.credentials.getPaymentCredentials();if(!e)return{error:{message:"No payment found. Please create a payment first.",type:"validation"}};const a=await this.http.post(`${yt}/${e.id}/process_payment_step`,{paymentIdentifier:e.identifier},this.withExactJsonHeader(t));if(!a.data)return a;const i=this.normalizeAction(a.data);return await this.callPinchAfterSuccessfulPayment(i,e.id,t),{data:i}}async processStep(t,e){const a=this.credentials.getPaymentCredentials();if(!a)return{error:{message:"No payment found",type:"validation"}};const{paymentIdentifier:i,...r}=t,n=await this.http.post(`${yt}/${a.id}/process_payment_step`,{paymentIdentifier:i||a.identifier,...r},this.withExactJsonHeader(e));if(!n.data)return n;const s=this.normalizeAction(n.data);return await this.callPinchAfterSuccessfulPayment(s,a.id,e),{data:s}}async processStepForm(t,e){const a=this.credentials.getPaymentCredentials();if(!a)return{error:{message:"No payment found",type:"validation"}};const i=this.buildProcessStepFormData(t,a.identifier);if(!i)return{error:{message:"FormData is not available in this runtime.",type:"validation"}};const r=await this.http.post(`${yt}/${a.id}/process_payment_step`,i,e);if(!r.data)return r;const n=this.normalizeAction(r.data);return await this.callPinchAfterSuccessfulPayment(n,a.id,e),{data:n}}async pollUntilSettled(t,e=15e3){let a=!0;for(;a;){const i=await this.initialize(t);if(!i.data)return i;if("pending"!==i.data.action)return a=!1,i;await new Promise(t=>setTimeout(t,e))}return{error:{message:"Payment polling exited unexpectedly",type:"network"}}}clearPayment(){this.credentials.clearPaymentCredentials()}withExactJsonHeader(t){const e={...t?.headers||{}};return delete e["Content-Type"],delete e["content-type"],{...t,headers:{...e,"Content-Type":"application/json"}}}buildProcessStepFormData(t,e){if("undefined"==typeof FormData)return null;if(t instanceof FormData)return t.has("payment_identifier")||t.append("payment_identifier",e),t;const a=l(t),i=new FormData;return Object.entries(a).forEach(([t,e])=>{this.appendFormValue(i,t,e)}),i.has("payment_identifier")||i.append("payment_identifier",e),i}appendFormValue(t,e,a){void 0!==a&&(null!==a?Array.isArray(a)?a.forEach(a=>this.appendFormValue(t,e,a)):"object"!=typeof a?t.append(e,String(a)):t.append(e,JSON.stringify(a)):t.append(e,""))}normalizePayment(t){if(!t||"object"!=typeof t)return t;if("paymentType"in t&&t.paymentType&&"object"==typeof t.paymentType&&"title"in t.paymentType){const e={...t.paymentType};return delete e.title,{...t,paymentType:e}}return t}normalizeAction(t){return"show_order"===t?.action?{...t,action:"showOrder"}:t}async callPinchAfterSuccessfulPayment(t,e,a){if("showOrder"!==t.action)return;if(this.pinchedPayments.has(e))return;this.pinchedPayments.add(e);(await this.http.post("/api/v1/pinch/order",{},a)).error&&this.pinchedPayments.delete(e)}}class Ot{constructor(t){this.http=t}normalizeUserResponse(t){if(!t.data)return t;const e=z(t.data);return e?{data:e}:t}normalizeLoginResponse(t){if(!t.data||!t.data.user)return t;const e=z(t.data.user);return e?{data:{...t.data,user:e}}:t}async login(t,e){const a=await this.http.post(`${_t}/login`,t,e);return this.normalizeLoginResponse(a)}async requestMobileOTP(t,e){return this.http.post(`${_t}/login_request`,t,e)}async verifyMobileOTP(t,e){const a=await this.http.post(`${_t}/login_request_verification`,t,e);return this.normalizeLoginResponse(a)}async requestEmailLogin(t,e){return this.http.post(`${ft}/email_login_request`,t,e)}async register(t,e){const a=await this.http.post(`${ft}/register`,t,e);return this.normalizeUserResponse(a)}async getCurrentUser(t){const e=await this.http.get(`${ft}/current`,t);return this.normalizeUserResponse(e)}async updateProfile(t,e,a){const i=await this.http.put(`${ft}/${t}`,e,a);return this.normalizeUserResponse(i)}async requestMobilePhoneUpdate(t,e){return this.http.post(`${ft}/update_mobile_phone_request`,t,e)}async verifyMobilePhoneUpdate(t,e){const a=await this.http.post(`${ft}/update_mobile_phone_verification`,t,e);return this.normalizeUserResponse(a)}async forgotPassword(t,e){return this.http.post(`${ft}/forgot_password`,t,e)}async revivePassword(t,e){const a=await this.http.post(`${ft}/revive_password`,t,e);return this.normalizeLoginResponse(a)}async mergeUser(t){return this.http.post(`${ft}/merge_user`,{},t)}}class Rt{constructor(t){this.http=t}transformFilters(t){if(!t)return{};const e={};return void 0!==t.page&&(e.page_number=t.page),void 0!==t.pageSize&&(e.page_size=t.pageSize),void 0!==t.categoryId&&(e.category_id=t.categoryId),void 0!==t.minPrice&&(e.min_price=t.minPrice),void 0!==t.maxPrice&&(e.max_price=t.maxPrice),e}async query(t,e,a){const i=this.transformFilters(e),r=await this.http.get(pt,{...a,params:{...i,query:t,page_number:i.page_number??1,page_size:i.page_size??20,search_direction:"center"}});if(r.data){return{data:B(r.data)}}return r}}class Dt{constructor(t){this.http=t}normalizeSeedItem(t){return{productId:String(t?.productId??""),productVariantId:String(t?.productVariantId??""),productName:String(t?.productName??t?.name??""),productAttributes:Array.isArray(t?.productAttributes)?t.productAttributes:Array.isArray(t?.attributes)?t.attributes:[],productImage:t?.productImage||t?.image||{url:"",alt:""}}}normalizeSeed(t){const e=Array.isArray(t?.items)?t.items:[];return{orderId:String(t?.orderId??""),orderIdentifier:String(t?.orderIdentifier??""),hasCommentAlready:Boolean(t?.hasCommentAlready),items:e.map(t=>this.normalizeSeedItem(t))}}normalizeProductReview(t){const e=t?.metadata||{};return{...t,metadata:{variantOptions:Array.isArray(e.variantOptions)?e.variantOptions:[],productName:String(e.productName??e.name??""),variantId:String(e.variantId??"")}}}normalizeProductReviewsResponse(t){const e=Array.isArray(t?.entities)?t.entities:[],a=t?.recommendations||{};return{entities:e.map(t=>this.normalizeProductReview(t)),pageNumber:Number(t?.pageNumber??1),pageSize:Number(t?.pageSize??10),totalCount:Number(t?.totalCount??e.length),averageRate:Number(t?.averageRate??0),recommendations:{recommendedPercentage:Number(a.recommendedPercentage??0),recommendedTotalCount:Number(a.recommendedTotalCount??0)}}}transformLegacyFilters(t){if(!t)return{};const e={};return void 0!==t.productId&&(e.product_id=t.productId),void 0!==t.page&&(e.page=t.page),void 0!==t.pageSize&&(e.page_size=t.pageSize),e}async getSeed(t,e){const a=await this.http.get(`/api/v1/feedbacks/seed/${t}`,e);if(a.data){const t=a.data.seed||a.data.data||a.data;return{data:this.normalizeSeed(t)}}return a}async createOrderRating(t,e){const a=await this.http.post("/api/v1/feedbacks/comments",t,e);if(a.data){const t=a.data.id??a.data.commentId??a.data.comment?.id;return{data:{id:String(t??"")}}}return a}async submitProductReview(t,e){return this.http.post(Ct,t,e)}async getProductStatistics(t,e){const a=await this.http.get(`${Ct}/${t}`,{...e,params:{exclude:"comments"}});if(a.data){return{data:{productStatistics:a.data.productStatistics||a.data.data?.productStatistics||a.data}}}return a}async getProductReviews(t,e,a){const i=await this.http.get(`${Ct}/${t}`,{...a,params:{page_number:e?.pageNumber??1,page_size:e?.pageSize??10}});if(i.data){const t=i.data.data||i.data;return{data:this.normalizeProductReviewsResponse(t)}}return i}async uploadReviewImages(t,e){const a=new FormData;t.forEach((t,e)=>{a.append("images[][file]",t.file),a.append("images[][name]",t.name||`image-${e+1}`),a.append("images[][alt]",t.alt||t.name||`image-${e+1}`)});const i=await this.http.post("/api/v1/service/filemanager/uploads/public/tajrobe",a,e);if(i.data){return{data:{images:Array.isArray(i.data.images)?i.data.images:Array.isArray(i.data.data?.images)?i.data.data.images:Array.isArray(i.data.result?.images)?i.data.result.images:[]}}}return i}async list(t,e){return this.http.get(bt,{...e,params:this.transformLegacyFilters(t)})}async create(t,e){return this.http.post(bt,t,e)}async get(t,e){return this.http.get(`${bt}/${t}`,e)}}class Gt{constructor(t){this.http=t}validateInvoiceId(t){return!Number.isFinite(t)||t<=0?{error:{message:"Invalid invoice ID",type:"validation"}}:null}async getBalance(t){return this.http.get("/api/v1/users/wallet/balance",t)}async listTransactions(t,e){const a=t?.page_number??1,i=t?.page_size??100;return this.http.get("/api/v1/wallet/transactions",{...e,params:{page_number:a,page_size:i}})}async applyCredit(t,e){const a=this.validateInvoiceId(t);return a||this.http.post(`${mt}/${t}/add_credit`,{},e)}async removeCredit(t,e){const a=this.validateInvoiceId(t);return a||this.http.post(`${mt}/${t}/remove_credit`,{},e)}}class Ft{constructor(t){this.http=t}async getPage(t,e){const a=await this.http.get(It,{...e,params:{url_part:t}}),i=at(a.data);if("cms_page"!==i.entityType)throw new Error(`Expected CMS page at ${t}, but got ${i.entityType}`);if("blog"===i.entity.cmsPageType)throw new Error(`Expected CMS page at ${t}, but got blog page`);return{...a,data:i.entity}}async listPages(t,e){const a=nt({...t,cmsPageTypes:"normal"}),i=await this.http.get(vt,{...e,params:a});return{...i,data:rt(i.data)}}async getBlogPost(t,e){const a=await this.http.get(It,{...e,params:{url_part:t}}),i=at(a.data);if("cms_page"!==i.entityType)throw new Error(`Expected blog post at ${t}, but got ${i.entityType}`);if("blog"!==i.entity.cmsPageType)throw new Error(`Expected blog post at ${t}, but got CMS page`);return{...a,data:i.entity}}async listBlogPosts(t,e){const a=nt({...t,cmsPageTypes:"blog"}),i=await this.http.get(vt,{...e,params:a});return{...i,data:rt(i.data)}}async listAll(t,e){const a=nt(t),i=await this.http.get(vt,{...e,params:a});return{...i,data:rt(i.data)}}}class xt{constructor(t){this.http=t}async upload(t,e){const a=new FormData;a.append("image",t);const i={...e?.headers};return delete i["Content-Type"],this.http.post(wt,a,{...e,headers:i})}async delete(t,e){return this.http.delete(`${wt}/${t}`,e)}}class Mt{constructor(t){this.http=t}async track(t,e){const a=e??((i=t)&&"object"==typeof i&&("retries"in i||"timeout"in i||"cache"in i||"headers"in i||"signal"in i)?t:void 0);var i;return this.http.post("/api/v1/visits/add",void 0,a)}async trackProduct(t,e,a){return this.track(a)}async trackCategory(t,e,a){return this.track(a)}}class Kt{constructor(t){this.http=t}transformEventFilters(t){if(!t)return{};const e={};return void 0===t.startDate&&void 0===t.start_date||(e.start_date=t.startDate??t.start_date),void 0===t.endDate&&void 0===t.end_date||(e.end_date=t.endDate??t.end_date),void 0===t.availableOnly&&void 0===t.available_only||(e.available_only=t.availableOnly??t.available_only),void 0!==t.page&&(e.page=t.page),void 0===t.pageSize&&void 0===t.page_size||(e.page_size=t.pageSize??t.page_size),e}async listEvents(t,e){return this.http.get(Pt,{...e,params:this.transformEventFilters(t)})}async getEvent(t,e){const a=await this.http.get(`${Pt}/${t}`,e);if(a.data){return{data:a.data.event||a.data}}return a}async getEventAvailabilities(t,e){const a=await this.http.get("/api/v1/scheduler/availabilities",{...e,params:{eventEntityId:t.eventEntityId,duration:t.duration,fromDate:t.fromDate,toDate:t.toDate,timezone:t.timezone}});if(a.data){return{data:{availableDays:a.data.availableDays||a.data.data?.availableDays||[]}}}return a}async createBooking(t,e){return this.http.post(At,t,e)}async listBookings(t){return this.http.get(At,t)}async cancelBooking(t,e){return this.http.post(`${At}/${t}/cancel`,{},e)}}class jt{constructor(t){this.http=t}async resolve(t,e){const a=await this.http.get(It,{...e,params:{url_part:t}});if(a.data){return{data:at(a.data)}}return a}}class Ut{constructor(t){this.http=t}async getHeaderMenu(t="headermenu",e){const a=await this.http.get("/api/v1/trees/fetch_single",{...e,params:{identifier:t}}),i=a.data?ot(a.data):a.data,r=i?.tree?.treeStructure?.nodes||[],n=this.convertRawTreeToNavigation(r);return{...a,data:n}}convertRawTreeToNavigation(t){if(!t||0===t.length)return[];return t.map(t=>({name:this.findNodeTitle(t),url:this.findNodeUrl(t),children:this.convertRawTreeToNavigation(t.children||[]),shouldBeDropped:this.shouldDropNode(t)})).filter(t=>!t.shouldBeDropped).map(({shouldBeDropped:t,...e})=>e)}findNodeTitle(t){const{entityType:e,details:a,entity:i}=t;return a&&!a.isTitleDefault&&a.title?a.title:a&&!a.isTitleDefault&&a.name?a.name:"product_category"===e||"product"===e?i?.name||"":("cms_page"===e||"blog_page"===e)&&i?.name||""}findNodeUrl(t){return"product"===t.entityType||"product_category"===t.entityType||"cms_page"===t.entityType||"blog_page"===t.entityType?t.entity?.url||"#":"url"===t.entityType&&t.details?.url||"#"}shouldDropNode(t){return("product"===t.entityType||"product_category"===t.entityType||"cms_page"===t.entityType||"blog_page"===t.entityType)&&!t.entity?.enabled}}class Bt{constructor(t){this.http=t}async getInfo(t){const e=await this.http.get("/api/v2/general/info",t);return e.data?{data:h(e.data)}:e.error?{error:e.error}:{error:{type:"api",message:"No data returned from general info endpoint."}}}async getFeatures(t){const e=await this.getInfo(t);return e.error?{error:e.error}:{data:e.data?.settings?.features}}async getCheckoutConfig(t){const e=await this.getInfo(t);return e.error?{error:e.error}:{data:e.data?.settings?.checkout}}async getWalletConfig(t){const e=await this.getInfo(t);return e.error?{error:e.error}:{data:e.data?.settings?.wallet}}async getTajrobeConfig(t){const e=await this.getInfo(t);return e.error?{error:e.error}:{data:e.data?.settings?.tajrobe}}}class qt{constructor(t){this.http=t}normalizeField(t){return{key:String(t?.key??""),name:String(t?.name??""),type:t?.type,label:String(t?.label??""),value:t?.value,placeholder:String(t?.placeholder??""),required:Boolean(t?.required),inputOptions:Array.isArray(t?.inputOptions)?t.inputOptions:[],allowedExtensions:Array.isArray(t?.allowedExtensions)?t.allowedExtensions:[]}}normalizeForm(t){const e=Array.isArray(t?.fields)?t.fields:[];return{id:Number(t?.id??0),title:String(t?.title??t?.name??""),description:String(t?.description??""),fields:e.map(t=>this.normalizeField(t))}}async getForm(t,e){const a=await this.http.get(`/api/v1/dynamic_form/${t}`,e);if(a.data){const t=a.data.form||a.data.data||a.data;return{data:this.normalizeForm(t)}}return a}async uploadProductFormFile(t,e){const a=new FormData;a.append("file",t);const i=await this.http.post("/api/v1/service/filemanager/uploads/private/productform",a,e);if(i.data){const t=i.data?.data?.file?.serveKey||i.data?.file?.serveKey||i.data?.serveKey;return{data:{serveKey:String(t??"")}}}return i}}function Lt(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function Yt(t){if("number"==typeof t&&Number.isFinite(t))return t;if("string"==typeof t){const e=Number(t);return Number.isFinite(e)?e:0}return 0}function Vt(t){return"string"==typeof t?t.trim():""}class Qt{constructor(t){this.http=t}normalizeCity(t){return Lt(t)?{id:Yt(t.id),name:Vt(t.name),latitude:Yt(t.latitude),longitude:Yt(t.longitude)}:{id:0,name:"",latitude:0,longitude:0}}normalizeRegion(t){if(!Lt(t))return{id:0,name:"",cities:[]};const e=Array.isArray(t.cities)?t.cities:[];return{id:Yt(t.id),name:Vt(t.name),cities:e.map(t=>this.normalizeCity(t)).filter(t=>t.id>0&&t.name.length>0)}}extractRegions(t){return Array.isArray(t)?t:Lt(t)?Array.isArray(t.regions)?t.regions:Array.isArray(t.items)?t.items:[]:[]}sortAlphabetically(t){return[...t].map(t=>({...t,cities:[...t.cities].sort((t,e)=>t.name.localeCompare(e.name,"fa"))})).sort((t,e)=>t.name.localeCompare(e.name,"fa"))}async list(t){const e=await this.http.get("/api/v2/regions",t);if(e.error)return{error:e.error};const a=this.extractRegions(e.data).map(t=>this.normalizeRegion(t)).filter(t=>t.id>0&&t.name.length>0);return{data:this.sortAlphabetically(a)}}}class Wt{constructor(t){const a=e(t);this.http=new dt(a),this.tokenStorage=this.http.getTokenStorage(),this.credentialsManager=new ct,this.products=new St(this.http),this.categories=new zt(this.http),this.cart=new Et(this.http,this.credentialsManager),this.invoices=new Nt(this.http,this.credentialsManager),this.shipping=new kt(this.http,this.credentialsManager),this.payments=new $t(this.http,this.credentialsManager),this.orders=new Tt(this.http),this.users=new Ot(this.http),this.search=new Rt(this.http),this.feedbacks=new Dt(this.http),this.wallet=new Gt(this.http),this.cms=new Ft(this.http),this.images=new xt(this.http),this.visits=new Mt(this.http),this.booking=new Kt(this.http),this.entityRoutes=new jt(this.http),this.menu=new Ut(this.http),this.general=new Bt(this.http),this.dynamicForms=new qt(this.http),this.regions=new Qt(this.http)}setAuthToken(t){this.tokenStorage.set(t)}getAuthToken(){return this.tokenStorage.get()}clearAuth(){this.tokenStorage.remove()}isAuthenticated(){return null!==this.tokenStorage.get()}clearCache(){this.http.clearCache()}clearCredentials(){this.credentialsManager.clearAll()}clearAll(){this.clearAuth(),this.clearCache(),this.clearCredentials()}async searchQuery(t,e,a){return this.search.query(t,e,a)}}function Ht(t){return new Wt(t)}function Jt(t){return function(t){if(!t||"object"!=typeof t)return!1;const e=t;return e.http instanceof dt&&e.credentials instanceof ct}(t)?t:function(t){const a=e(t);return{http:new dt(a),credentials:new ct}}(t)}function Zt(t){const{http:e}=Jt(t);return new St(e)}function Xt(t){const{http:e}=Jt(t);return new zt(e)}function te(t){const{http:e,credentials:a}=Jt(t);return new Et(e,a)}function ee(t){const{http:e}=Jt(t);return new Tt(e)}function ae(t){const{http:e,credentials:a}=Jt(t);return new Nt(e,a)}function ie(t){const{http:e,credentials:a}=Jt(t);return new kt(e,a)}function re(t){const{http:e,credentials:a}=Jt(t);return new $t(e,a)}function ne(t){const{http:e}=Jt(t);return new Ot(e)}function se(t){const{http:e}=Jt(t);return new Rt(e)}function oe(t){const{http:e}=Jt(t);return new Dt(e)}function de(t){const{http:e}=Jt(t);return new Gt(e)}function ce(t){const{http:e}=Jt(t);return new Ft(e)}function ue(t){const{http:e}=Jt(t);return new xt(e)}function pe(t){const{http:e}=Jt(t);return new Mt(e)}function le(t){const{http:e}=Jt(t);return new Kt(e)}function me(t){const{http:e}=Jt(t);return new jt(e)}function he(t){const{http:e}=Jt(t);return new Ut(e)}function ye(t){const{http:e}=Jt(t);return new Bt(e)}function ge(t){const{http:e}=Jt(t);return new qt(e)}function fe(t){const{http:e}=Jt(t);return new Qt(e)}export{ct as CredentialsManager,dt as HttpClient,Wt as SazitoClient,a as TokenStorage,le as booking,te as cart,Xt as categories,ce as cms,le as createBookingAPI,ce as createCMSAPI,te as createCartAPI,Xt as createCategoriesAPI,ge as createDynamicFormsAPI,me as createEntityRoutesAPI,oe as createFeedbacksAPI,ye as createGeneralAPI,ue as createImagesAPI,ae as createInvoicesAPI,he as createMenuAPI,ee as createOrdersAPI,re as createPaymentsAPI,Zt as createProductsAPI,fe as createRegionsAPI,Ht as createSazitoClient,se as createSearchAPI,ie as createShippingAPI,ne as createUsersAPI,pe as createVisitsAPI,de as createWalletAPI,ge as dynamicForms,me as entityRoutes,oe as feedbacks,ye as general,ue as images,ae as invoices,he as menu,ee as orders,re as payments,Zt as products,fe as regions,se as search,ie as shipping,L as transformAddToCartInput,m as transformApiResponse,I as transformCartResponse,Y as transformCreateCartInput,C as transformInvoiceResponse,U as transformProductListResponse,l as transformRequestKeys,p as transformResponseKeys,q as transformShippingAddressInput,ne as users,pe as visits,de as wallet};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";const t={timeout:3e4,retry:{enabled:!0,retries:3,retryDelay:1e3},cache:{products:{enabled:!0,ttl:6e5},categories:{enabled:!0,ttl:6e5},cart:{enabled:!1},orders:{enabled:!1},search:{enabled:!0,ttl:3e5},cms:{enabled:!0,ttl:6e5},tags:{enabled:!0,ttl:6e5},entityRoutes:{enabled:!0,ttl:6e5}},debug:!1};function e(e){return{...t,...e,retry:{...t.retry,...e.retry},cache:{...t.cache,...e.cache},customFetchApi:e.customFetchApi||("undefined"!=typeof fetch?fetch:void 0)}}class a{constructor(){this.tokenKey="user_id_token"}get(){if("undefined"==typeof window||"undefined"==typeof document)return null;const t=this.getFromLocalStorage();if(t)return t;return this.parseCookies()[this.tokenKey]||null}set(t,e){if("undefined"==typeof window||"undefined"==typeof document)return void console.warn("[Sazito SDK] Cannot set token in SSR environment");this.setInLocalStorage(t);const a={secure:!0,sameSite:"Lax",maxAge:2592e3,path:"/",...e};this.setCookie(this.tokenKey,t,a)}remove(){"undefined"!=typeof window&&"undefined"!=typeof document&&(this.removeFromLocalStorage(),this.setCookie(this.tokenKey,"",{maxAge:-1,path:"/"}))}getFromLocalStorage(){try{return window.localStorage.getItem(this.tokenKey)}catch{return null}}setInLocalStorage(t){try{window.localStorage.setItem(this.tokenKey,t)}catch{}}removeFromLocalStorage(){try{window.localStorage.removeItem(this.tokenKey)}catch{}}parseCookies(){return"undefined"==typeof document?{}:document.cookie.split(";").reduce((t,e)=>{const[a,i]=e.trim().split("=");return a&&i&&(t[a]=decodeURIComponent(i)),t},{})}setCookie(t,e,a){let i=`${t}=${encodeURIComponent(e)}`;void 0!==a.maxAge&&(i+=`; Max-Age=${a.maxAge}`),a.path&&(i+=`; Path=${a.path}`),a.domain&&(i+=`; Domain=${a.domain}`),a.secure&&(i+="; Secure"),a.httpOnly&&(i+="; HttpOnly"),a.sameSite&&(i+=`; SameSite=${a.sameSite}`),document.cookie=i}}class i{constructor(){this.cache=new Map}get(t,e){const a=this.cache.get(t);return a?e&&Date.now()-a.timestamp>e?(this.cache.delete(t),null):a.data:null}set(t,e){this.cache.set(t,{data:e,timestamp:Date.now()})}delete(t){this.cache.delete(t)}deletePattern(t){const e=new RegExp(t),a=[];this.cache.forEach((t,i)=>{e.test(i)&&a.push(i)}),a.forEach(t=>this.cache.delete(t))}clear(){this.cache.clear()}static generateKey(t,e,a){return`${t}:${e}:${a?JSON.stringify(a):""}`}}const r={no_of_items:"quantity",single_item_price:"unitPrice",total_items_price:"lineTotal",items_total_raw_price:"totalOriginalPrice",items_discount:"totalDiscount",customer_profit:"savings",customer_profit_percentage:"savingsPercentage",total_amount:"totalAmount",net_total:"subtotal",gross_total:"total",final_total:"finalTotal",discount_total:"discountTotal",shipping_total:"shippingTotal",tax_total:"taxTotal",unique_identifier:"identifier",invoice_identifier:"identifier",payment_identifier:"identifier",shipping_address_identifier:"identifier",first_name:"firstName",last_name:"lastName",mobile_phone:"mobilePhone",phone_number:"phoneNumber",postal_code:"postalCode",user_comment:"comment",product_id:"productId",variant_id:"variantId",product_name:"name",product_image:"image",product_variant:"variant",product_variants:"variants",product_categories:"categories",product_attributes:"attributes",product_type:"productType",title:"name",short_description:"shortDescription",stock_quantity:"stockQuantity",stock_number:"stockQuantity",sale_price:"salePrice",raw_price:"originalPrice",has_max_order:"hasMaxOrder",max_no_of_order:"maxOrderQuantity",min_order_count:"minOrderQuantity",sold_count:"soldCount",static_url:"staticUrl",dynamic_form_id:"dynamicFormId",event_entity_id:"eventEntityId",theme_config:"themeConfig",image_id:"imageId",is_stock_managed:"isStockManaged",commercial_files:"commercialFiles",sort_index:"sortIndex",attribute_type:"attributeType",cart_products:"items",cart_product_id:"cartProductId",invoice_items:"items",products:"items",total_count:"total",shipping_method_needed:"needsShipping",shipping_method:"shippingMethod",shipping_address:"shippingAddress",shipping_items:"shippingItems",delivery_time:"deliveryTime",min_delivery_days:"minDays",max_delivery_days:"maxDays",payment_type:"paymentType",payment_types:"methods",reference_code:"code",is_default:"isDefault",is_available:"isAvailable",delete_coupon:"deleteCoupon",form_attributes:"formAttributes",booking_attributes:"bookingAttributes",readable_form_attr:"formFields",created_at:"createdAt",updated_at:"updatedAt",page_number:"page",page_size:"pageSize",total_count_raw:"totalCountRaw",max_price:"maxPrice",min_price:"minPrice",stock_alert_limit:"stockAlertLimit",sub_categories:"subCategories",order_number:"orderNumber",sort_order:"sortOrder",pinned_ids:"pinnedIds",region_id:"regionId",city_id:"cityId",parent_id:"parentId",discount_code:"discountCode",entity_name:"entityType",entity_id:"entityId",other_props:"entity",shipping_methods:"shippingMethods",shipping_rates:"shippingRates",grouped_shipping_rates:"groupedShippingRates",items_shipping_rate:"itemsShippingRate",shipping_rate:"shippingRate",rate_id:"rateId",invoice_item_id:"invoiceItemId",invoice_item_ids:"invoiceItemIds",scheduler_booking_attributes:"schedulerBookingAttributes",inventory_count:"inventoryCount",order_identifier:"orderIdentifier",self_only:"selfOnly",coupon:"coupon",user_set_coordinates_before:"userSetCoordinatesBefore",alt:"alt",url:"url",activate_add_to_cart_alert:"addToCardAlert",activate_advanced_card_to_card:"advancedCardToCard",activate_ayria_payment_customization:"ayriaPaymentGateway",activate_azki_payment_customization:"azkiPaymentGateway",activate_bazar_payment_customization:"bazarPaymentGateway",activate_blog:"shopBlog",activate_card_to_card_payment:"cardToCardPayment",activate_checkout_dynamic_form:"checkoutDynamicForm",activate_different_register_customization:"multiTypeRegister",activate_digipay_payment:"digipayPaymentGateway",activate_digipay_payment_customization:"digipayPaymentGateway",activate_filter_products:"productFilters",activate_ghesta_payment_customization:"ghestaPaymentGateway",activate_mega_footer:"megaFooter",activate_mellat_payment_customization:"mellatPaymentGateway",activate_min_basket:"checkoutMinimumAmount",activate_novapay_payment_customization:"novapayPaymentGateway",activate_ozon_payment_customization:"ozonPaymentGateway",activate_payment_in_place:"paymentInPlace",activate_payping_payment:"paypingPaymentGateway",activate_pec_payment_customization:"pecPaymentGateway",activate_sabin_payment_customization:"sabinPaymentGateway",activate_sadad_payment_customization:"sadadPaymentGateway",activate_search:"shopSearch",activate_sep_payment_customization:"sepPaymentGateway",activate_shop_vat:"shopVat",activate_snapppay_payment_customization:"snapppayPaymentGateway",activate_tajrobe:"tajrobe",activate_tara_payment_customization:"taraPaymentGateway",activate_theme_config_settings:"themeConfigSettings",activate_toman_payment_customization:"tomanPaymentGateway",activate_torobpay_payment_customization:"torobpayPaymentGateway",activate_up_payment_customization:"asanpardakhtPaymentGateway",activate_vandar_payment_customization:"vandarPaymentGateway",activate_wallet:"wallet",activate_yourgate_payment_customization:"yourgatePaymentGateway",activate_zarinpal_payment:"zarinpalPaymentGateway",activate_zarinplus_payment_customization:"zarinplusPaymentGateway",activate_zibal_payment_customization:"zibalPaymentGateway",activate_zify_payment_customization:"zifyPaymentGateway",disable_ordering:"disableOrdering",pwa:"progressiveWebApp",remove_front_basket:"hideCheckout",remove_front_taint:"sazitoBrandingRemoval"},n=Object.entries(r).reduce((t,[e,a])=>(t[a]||(t[a]=e),t),{});function s(t){return t.replace(/_([a-z])/g,(t,e)=>e.toUpperCase())}function o(t){return t.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function c(t){return!(null===t||"object"!=typeof t||Array.isArray(t)||t instanceof Date)}function d(t,e){const a={...t};for(const t of e)delete a[t];return a}function p(t){if(!c(t))return Array.isArray(t)?t.map(t=>p(t)):t;const e={};for(const[a,i]of Object.entries(t)){let t=r[a];t||(t=s(a)),c(i)?e[t]=p(i):Array.isArray(i)?e[t]=i.map(t=>p(t)):e[t]=i}return e}function u(t){if(!c(t))return Array.isArray(t)?t.map(t=>u(t)):t;const e={};for(const[a,i]of Object.entries(t)){let t=n[a];t||(t=o(a)),c(i)?e[t]=u(i):Array.isArray(i)?e[t]=i.map(t=>u(t)):e[t]=i}return e}function l(t){if(t?.data?.result){const e=t.data.result,a=Object.keys(e);return 1===a.length&&c(e[a[0]])?p(e[a[0]]):p(e)}return p(t)}function h(t){if(!t)return t;const{general:e,shop:a,checkout:i,features:r,wallet:n,tajrobe:s,domain:o,enamad:d,google:p,logo:u,social:l,...h}=t,_={...e,...a},{registerType:f,showProductStockNumber:v,...C}=_||{};let S=i;if(c(i)){const t={...i};void 0===t.preventRedirect&&void 0!==t.manual&&(t.preventRedirect=t.manual),delete t.manual,S=t}return{...h,scripts:{enamad:d,google:p},shop:y({...C,domain:o,logo:u,social:l}),settings:{checkout:S,features:b(r),wallet:P(n),tajrobe:w(s),registerType:m(f),showProductStockNumber:g(v)}}}function m(t){return"string"==typeof t?t:""}function g(t){return"boolean"==typeof t?t:c(t)&&Object.prototype.hasOwnProperty.call(t,"enabled")?g(t.enabled):1===t||"1"===t||"true"===t}function y(t){if(!c(t))return t;const e={...t};if(c(e.city)){const t=d(e.city,["createdAt","updatedAt"]);let a=t.region;c(a)&&(a=d(a,["createdAt","updatedAt","cities"])),t.region=a,e.city=t}return e}const _={addToCardAlert:"addToCartAlertEnabled",addToCartAlert:"addToCartAlertEnabled",advancedCardToCard:"advancedCardToCardEnabled",cardToCardPayment:"cardToCardPaymentEnabled",checkoutDynamicForm:"checkoutDynamicFormEnabled",multiTypeRegister:"multiTypeRegisterEnabled",productFilters:"productFiltersEnabled",megaFooter:"megaFooterEnabled",checkoutMinimumAmount:"checkoutMinimumAmountEnabled",paymentInPlace:"paymentInPlaceEnabled",shopBlog:"blogEnabled",shopSearch:"searchEnabled",shopVat:"shopVatEnabled",tajrobe:"tajrobeEnabled",themeConfigSettings:"themeConfigSettingsEnabled",wallet:"walletEnabled",progressiveWebApp:"progressiveWebAppEnabled",disableOrdering:"orderingDisabled",hideCheckout:"checkoutHidden",sazitoBrandingRemoval:"sazitoBrandingRemoved",ayriaPaymentGateway:"ayriaPaymentGatewayEnabled",azkiPaymentGateway:"azkiPaymentGatewayEnabled",bazarPaymentGateway:"bazarPaymentGatewayEnabled",digipayPaymentGateway:"digipayPaymentGatewayEnabled",ghestaPaymentGateway:"ghestaPaymentGatewayEnabled",mellatPaymentGateway:"mellatPaymentGatewayEnabled",novapayPaymentGateway:"novapayPaymentGatewayEnabled",ozonPaymentGateway:"ozonPaymentGatewayEnabled",paypingPaymentGateway:"paypingPaymentGatewayEnabled",pecPaymentGateway:"pecPaymentGatewayEnabled",sabinPaymentGateway:"sabinPaymentGatewayEnabled",sadadPaymentGateway:"sadadPaymentGatewayEnabled",sepPaymentGateway:"sepPaymentGatewayEnabled",snapppayPaymentGateway:"snapppayPaymentGatewayEnabled",taraPaymentGateway:"taraPaymentGatewayEnabled",tomanPaymentGateway:"tomanPaymentGatewayEnabled",torobpayPaymentGateway:"torobpayPaymentGatewayEnabled",asanpardakhtPaymentGateway:"asanpardakhtPaymentGatewayEnabled",vandarPaymentGateway:"vandarPaymentGatewayEnabled",yourgatePaymentGateway:"yourgatePaymentGatewayEnabled",zarinpalPaymentGateway:"zarinpalPaymentGatewayEnabled",zarinplusPaymentGateway:"zarinplusPaymentGatewayEnabled",zibalPaymentGateway:"zibalPaymentGatewayEnabled",zifyPaymentGateway:"zifyPaymentGatewayEnabled",activateEditOrderCustomization:"editOrderEnabled",activateEditOrderCustomizationEnabled:"editOrderEnabled"},f=new Set(["activateAlopeykAdvanced","activate_alopeyk_advanced"]),v=new Set(["auditLogEnabled","editOrderEnabled","rahkaranAccountingCustomizationEnabled","advancedThemeDesignerEnabled","checkoutHidden","eventPublisherEnabled","exportOrdersEnabled","exportProductsEnabled","exportUsersEnabled","fontCustomizationEnabled","forwardShippingEnabled","podroShippingEnabled","postexShippingEnabled","quotaNotificationsEnabled","recaptchaEnabled","rolePoliciesEnabled","sepidarAccountingCustomizationEnabled","shortUrlEnabled","skuSearchEnabled","snappShopCustomizationEnabled","snappboxShippingEnabled","stockAlertNotificationsEnabled","tapsipackShippingEnabled","themeConfigSettingsEnabled","advancedTextEditorEnabled","advancedShippingEnabled","bulkActionEnabled","discountBulkEnabled","discountCodeEnabled","orderBulkActionEnabled","importProductsEnabled","mahakAccountingCustomizationEnabled","millipayPaymentCustomizationEnabled","orderSmsNotificationsEnabled"]);function b(t){if(!c(t))return{};const e={},a=(t,a)=>{if(f.has(t))return;const i=(t=>{if("boolean"==typeof t)return t;if("number"==typeof t)return 1===t||0!==t&&void 0;if("string"==typeof t){const e=t.trim().toLowerCase();return"true"===e||"1"===e||"false"!==e&&"0"!==e&&void 0}})(a);void 0!==i&&(e[t]=i)};c(t.flags)&&Object.entries(t.flags).forEach(([t,e])=>{a(t,e)}),c(t.configurations)&&Object.entries(t.configurations).forEach(([t,e])=>{a(t,e)}),Object.entries(t).forEach(([t,e])=>{"flags"!==t&&"premium"!==t&&"configurations"!==t&&(c(e)&&Object.prototype.hasOwnProperty.call(e,"enabled")?a(t,e.enabled):a(t,e))});const i={};Object.entries(e).forEach(([t,e])=>{const a=function(t){const e=t.includes("_")?s(t):t,a=_[e];if(a)return a;const i=e.startsWith("activate")&&e.length>8?`${e.charAt(8).toLowerCase()}${e.slice(9)}`:e;return i.endsWith("Enabled")||i.endsWith("Disabled")||i.endsWith("Hidden")||i.endsWith("Removed")?i:`${i}Enabled`}(t);v.has(a)||(i[a]=e)});const r={...i};return c(t.premium)&&(r.premium=t.premium),r}function P(t){if(!c(t))return t;const e=c(t.configurations)?{...t,...t.configurations}:{...t},a=t=>"boolean"==typeof t?t:1===t||"1"===t||"true"===t||0!==t&&"0"!==t&&"false"!==t&&void 0;return{enabled:a(e.enabled)??!1,useWithDiscount:a(e.useWithDiscount)??!1,minAmount:(t=>{if("number"==typeof t&&Number.isFinite(t))return t;const e=Number(t);return Number.isFinite(e)?e:void 0})(e.minAmount??e.walletMinAmount)??0,minAmountRequired:a(e.minAmountRequired??e.walletMinStatus)??!1}}function w(t){if(!c(t))return t;const e=c(t.configurations)?{...t,...t.configurations}:{...t};let a=!1;return"boolean"==typeof e.enabled?a=e.enabled:1!==e.enabled&&"1"!==e.enabled&&"true"!==e.enabled||(a=!0),{enabled:a}}function C(t){if(!t)return t;const e=d(t,["staticUrl","summary","tags","slug"]);return e.variants&&Array.isArray(e.variants)&&(e.variants=e.variants.map(t=>d(t,["name","title","product","status","soldCount"]))),e.categories&&Array.isArray(e.categories)&&(e.categories=e.categories.map(t=>({id:t.id,name:t.name,url:t.url}))),e.images&&Array.isArray(e.images)&&(e.images=e.images.map(t=>d(t,["widthRatio","heightRatio","thumb"]))),e}function S(t){const e=C(t);return e?d(e,["themeConfig"]):e}function A(t){const e=l(t);return e.items&&Array.isArray(e.items)?{items:e.items.map(t=>S(t)),total:e.total||e.items.length,page:e.page||1,pageSize:e.pageSize||e.items.length,totalPages:e.totalPages||Math.ceil((e.total||e.items.length)/(e.pageSize||e.items.length))}:e}function I(t){if(!t)return t;const e={products:{items:[],total:0,page:1,pageSize:20},blogPages:{items:[],total:0,page:1,pageSize:20},cmsPages:{items:[],total:0,page:1,pageSize:20},productCategories:{items:[],total:0,page:1,pageSize:20}};return t.items&&Array.isArray(t.items)&&(e.products.items=t.items.map(t=>S(t)),e.products.total=t.productsCount||0,e.products.page=t.productsPageNumber||1,e.products.pageSize=t.productsPageSize||20),t.blogPages&&Array.isArray(t.blogPages)&&(e.blogPages.items=t.blogPages.map(t=>k(t)),e.blogPages.total=t.blogPagesCount||0,e.blogPages.page=t.blogPagesPageNumber||1,e.blogPages.pageSize=t.blogPagesPageSize||20),t.cmsPages&&Array.isArray(t.cmsPages)&&(e.cmsPages.items=t.cmsPages.map(t=>k(t)),e.cmsPages.total=t.cmsPagesCount||0,e.cmsPages.page=t.cmsPagesPageNumber||1,e.cmsPages.pageSize=t.cmsPagesPageSize||20),t.categories&&Array.isArray(t.categories)&&(e.productCategories.items=t.categories.map(t=>z(t)),e.productCategories.total=t.productCategoriesCount||0,e.productCategories.page=t.productCategoriesPageNumber||1,e.productCategories.pageSize=t.productCategoriesPageSize||20),e}function E(t){return t?d(t,["staticUrl","products","items"]):t}function z(t){const e=E(t);return e?d(e,["themeConfig"]):e}function T(t){return t?d(t,["staticUrl","urlKey"]):t}function k(t){const e=T(t);return e?d(e,["themeConfig"]):e}function x(t){const e=l(t);if(!e||!e.route)return e;const a=e.route;if(a.entity){switch(a.entityType){case"product":a.entity=C(a.entity);break;case"product_category":a.entity=E(a.entity);break;case"cms_page":case"blog_page":a.entity=T(a.entity)}a.entity=d(a.entity,["id"]),!a.url&&a.entity.url&&(a.url=a.entity.url)}return a}function G(t){if(!t)return t;const e={...t};return e.entity&&(e.entity=z(e.entity),e.entity&&"object"==typeof e.entity&&(e.entity=d(e.entity,["id"]))),e.children&&Array.isArray(e.children)&&(e.children=e.children.map(G)),e}function $(t){const e=l(t);return e?e.cmsPages&&Array.isArray(e.cmsPages)?{items:e.cmsPages.map(k),total:e.total||e.cmsPages.length,page:e.page||e.pageNumber||1,pageSize:e.pageSize||e.cmsPages.length}:e.items&&Array.isArray(e.items)?{items:e.items.map(t=>k(t)),total:e.total||e.items.length,page:e.page||1,pageSize:e.pageSize||e.items.length}:e:e}function N(t){if(!t)return{};const e={};if(void 0!==t.page&&(e.page_number=t.page),void 0!==t.pageSize&&(e.page_size=t.pageSize),t.cmsPageTypes){const a=Array.isArray(t.cmsPageTypes)?t.cmsPageTypes[0]:t.cmsPageTypes;e["filters[]"]=JSON.stringify({name:"cms_page_types",value:a})}return e}function O(t){if(!t)return t;const e={};if(t.entityType&&(e.entityType=t.entityType),void 0!==t.entityId&&(e.entityId=t.entityId),t.entity){const a=d(t.entity,["staticUrl","id"]);Object.keys(a).length>0&&(e.entity=a)}return t.details&&(e.details=t.details),t.children&&Array.isArray(t.children)&&(e.children=t.children.map(t=>O(t))),e}function D(t){const e=l(t);if(!e||!e.tree)return e;const a=e.tree;return a.treeStructure&&a.treeStructure.nodes&&(a.treeStructure.nodes=a.treeStructure.nodes.map(t=>O(t))),e}class R{constructor(t){this.config=t,this.baseUrl="http://api.sazito.com:8080",this.domain=t.domain,this.tokenStorage=new a,this.cache=new i,this.fetchApi=t.customFetchApi.bind(globalThis)}async get(t,e){const a=this.buildUrl(t,e?.params),r=i.generateKey("GET",a,e?.params);if(!1!==e?.cache){const e=this.getApiName(t),a=this.config.cache[e];if(a?.enabled&&a.ttl){const e=this.cache.get(r,a.ttl);if(e)return this.config.debug&&console.log("[Sazito SDK] Cache hit:",t),{data:e}}}const n=await this.request("GET",a,e);return n.data&&!1!==e?.cache&&this.cache.set(r,n.data),n}async post(t,e,a){const i=this.buildUrl(t),r=e?u(e):void 0,n=this.getApiName(t);return this.cache.deletePattern(`GET:.*${n}`),this.request("POST",i,{...a,body:r})}async put(t,e,a){const i=this.buildUrl(t),r=e?u(e):void 0,n=this.getApiName(t);return this.cache.deletePattern(`GET:.*${n}`),this.request("PUT",i,{...a,body:r})}async delete(t,e){const a=this.buildUrl(t),i=this.getApiName(t);return this.cache.deletePattern(`GET:.*${i}`),this.request("DELETE",a,e)}async request(t,e,a,i=0){const r=new AbortController,n=a?.signal||r.signal,s=a?.timeout||this.config.timeout,o=setTimeout(()=>r.abort(),s);try{const r=await this.fetchApi(e,{method:t,headers:this.getHeaders(a?.headers),body:a?.body?JSON.stringify(a.body):void 0,signal:n});clearTimeout(o);const s=void 0!==a?.retries?a.retries:this.config.retry.retries;if(!r.ok&&this.shouldRetry(r.status)&&i<s)return this.config.debug&&console.log(`[Sazito SDK] Retrying request (${i+1}/${s}):`,e),await this.delay(this.config.retry.retryDelay*(i+1)),this.request(t,e,a,i+1);const c=r.headers.get("content-type");let d;d=c?.includes("application/json")?await r.json():await r.text();const u=void 0!==d?.result?d.result:d;this.config.debug&&console.log(`[Sazito SDK] ${t} ${e}:`,{status:r.status,data:u});let l=u?p(u):u;const h=["cart","product","user","order","invoice","payment","shipping"];if(l&&"object"==typeof l&&!Array.isArray(l)){const t=Object.keys(l);1===t.length&&h.includes(t[0])&&"object"==typeof l[t[0]]&&null!==l[t[0]]&&(l=l[t[0]])}return r.ok?{data:l}:{error:{status:r.status,message:l?.message||u?.message||r.statusText||"Request failed",type:"api",details:l}}}catch(t){return clearTimeout(o),this.config.debug&&console.error("[Sazito SDK] Request failed:",t),{error:{message:"AbortError"===t.name?"Request timeout":t.message||"Network error",type:"network",details:t}}}}buildUrl(t,e){const a=`${this.baseUrl}${t}`;if(!e||0===Object.keys(e).length)return a;const i=new URLSearchParams;return Object.entries(e).forEach(([t,e])=>{null!=e&&i.append(t,String(e))}),`${a}?${i.toString()}`}getHeaders(t){const e={"Content-Type":"application/json","x-forwarded-host":this.domain,...t},a=this.tokenStorage.get();return a&&(e.Authorization=a),e}shouldRetry(t){return t>=500&&t<600}delay(t){return new Promise(e=>setTimeout(e,t))}getApiName(t){return t.includes("/products")?"products":t.includes("/product_categories")?"categories":t.includes("/cart")?"cart":t.includes("/orders")?"orders":t.includes("/search")?"search":t.includes("/tags")?"tags":t.includes("/entity_route")?"entityRoutes":"cms"}getTokenStorage(){return this.tokenStorage}clearCache(){this.cache.clear()}}class M{constructor(){this.CART_KEY="CART_CREDENTIALS",this.INVOICE_KEY="INVOICE_CREDENTIALS",this.SHIPPING_KEY="SHIPPING_ADDRESS_CREDENTIALS",this.PAYMENT_KEY="PAYMENT_CREDENTIALS",this.DISCOUNT_KEY="DISCOUNT_CODE_INFO"}getCartCredentials(){return this.getItem(this.CART_KEY)}setCartCredentials(t){this.setItem(this.CART_KEY,t)}clearCartCredentials(){this.removeItem(this.CART_KEY)}getInvoiceCredentials(){return this.getItem(this.INVOICE_KEY)}setInvoiceCredentials(t){this.setItem(this.INVOICE_KEY,t)}clearInvoiceCredentials(){this.removeItem(this.INVOICE_KEY)}getShippingCredentials(){return this.getItem(this.SHIPPING_KEY)}setShippingCredentials(t){this.setItem(this.SHIPPING_KEY,t)}clearShippingCredentials(){this.removeItem(this.SHIPPING_KEY)}getPaymentCredentials(){return this.getItem(this.PAYMENT_KEY)}setPaymentCredentials(t){this.setItem(this.PAYMENT_KEY,t)}clearPaymentCredentials(){this.removeItem(this.PAYMENT_KEY)}getDiscountCode(){return this.getItem(this.DISCOUNT_KEY)}setDiscountCode(t){this.setItem(this.DISCOUNT_KEY,t)}clearDiscountCode(){this.removeItem(this.DISCOUNT_KEY)}clearAll(){this.clearCartCredentials(),this.clearInvoiceCredentials(),this.clearShippingCredentials(),this.clearPaymentCredentials(),this.clearDiscountCode()}getItem(t){if("undefined"==typeof localStorage)return null;try{const e=localStorage.getItem(t);return e?JSON.parse(e):null}catch(e){return console.error(`[Sazito SDK] Error reading ${t} from localStorage:`,e),null}}setItem(t,e){if("undefined"!=typeof localStorage)try{localStorage.setItem(t,JSON.stringify(e))}catch(e){console.error(`[Sazito SDK] Error writing ${t} to localStorage:`,e)}else console.warn("[Sazito SDK] localStorage not available")}removeItem(t){if("undefined"!=typeof localStorage)try{localStorage.removeItem(t)}catch(e){console.error(`[Sazito SDK] Error removing ${t} from localStorage:`,e)}}}const K="/api/v1/product_categories",j="/api/v1/search",F="/api/v2/carts",U="/api/v2/invoices",q="/api/v2/shipping_addresses",Y="/api/v2/payments",L="/api/v1/orders",B="/api/v1/users",H="/api/v1/sessions",W="/api/v1/feedbacks",V="/api/v1/cms_pages",Q="/api/v1/images",J="/api/v1/scheduler/events",Z="/api/v1/scheduler/bookings",X="/api/v1/entity_route/route";class tt{constructor(t){this.http=t}mapSortToApi(t){if(!t)return null;return{newest:{sort:"date"},"best-selling":{sort:"sold"},availability:{sort:"stock_status"},discount:{sort:"raw_price"},"!price":{sort:"price",sortOrder:"asc"},price:{sort:"price"}}[t]||null}transformFilters(t){if(!t)return{};const e={},a=[];if(t.categories){const e=Array.isArray(t.categories)?t.categories:[t.categories];e.length>0&&a.push({name:"product_categories",value:e.join(",")})}if(!1===t.availableOnly&&a.push({name:"in_stock"}),t.discountedOnly&&a.push({name:"has_raw_price",value:!0}),t.similarTo&&a.push({name:"similar_to",value:{entity_name:"product",entity_id:t.similarTo}}),a.length>0&&(e["filters[]"]=JSON.stringify(a)),t.pinnedIds&&t.pinnedIds.length>0&&(e.pinned_ids=JSON.stringify(t.pinnedIds)),t.sort){const a=this.mapSortToApi(t.sort);a&&(e.sort=a.sort,a.sortOrder&&(e.sort_order=a.sortOrder))}return void 0!==t.priceMin&&(e.min_price=t.priceMin),void 0!==t.priceMax&&(e.max_price=t.priceMax),t.page&&(e.page=t.page),t.pageSize&&(e.page_size=t.pageSize),e}async get(t,e){const a=t.startsWith("/product/")?t:`/product/${t}`,i=await this.http.get(X,{...e,params:{url_part:a}});if(i.data){const t=x(i.data);return"product"===t.entityType&&t.entity?{data:t.entity}:"unknown"===t.entityType?{error:{message:"Product not found",type:"api",status:404}}:{error:{message:`Invalid entity type: expected 'product', got '${t.entityType}'`,type:"api",status:400}}}return i}async list(t,e){const a=this.transformFilters(t),i=await this.http.get("/api/v1/products",{...e,params:a});if(i.data){return{data:A(i.data)}}return i}async search(t,e,a){const i={query:t,search_direction:"center",page_size:e?.pageSize||20,page_number:e?.page||1},r=await this.http.get(j,{...a,params:i});if(r.data){return{data:I(r.data)}}return r}}class et{constructor(t){this.http=t}async get(t,e){const a=await this.http.get(`${K}/${t}`,e);if(a.data){const t=function(t){const e=l(t);return e?E(e.productCategory||e):e}(a.data);return{data:t}}return a}async list(t,e){const a={};void 0!==t?.page&&(a.page_number=t.page),void 0!==t?.pageSize&&(a.page_size=t.pageSize);const i=await this.http.get(K,{...e,params:a});if(i.data){const t=function(t){const e=l(t);return e?(e.categories&&Array.isArray(e.categories)&&(e.categories=e.categories.map(z)),e.tree&&e.tree.treeStructure&&e.tree.treeStructure.nodes&&(e.tree.treeStructure.nodes=e.tree.treeStructure.nodes.map(G)),e):e}(i.data);return{data:t}}return i}}class at{constructor(t,e){this.http=t,this.credentials=e}async get(t){const e=this.credentials.getCartCredentials();return e?this.http.get(`${F}/${e.id}`,{...t,params:{identifier:e.identifier}}):{error:{message:"No cart found. Please create a cart first.",type:"validation"}}}async create(t,e){const a=await this.http.post(F,t,e);return a.data&&this.credentials.setCartCredentials({id:a.data.id,identifier:a.data.identifier}),a}async addItem(t,e,a,i){const r=this.credentials.getCartCredentials();if(!r)return this.create({variants:[{id:t,count:e,formAttributes:a}]},i);return await this.http.post(`${F}/${r.id}/add_products_to_cart`,{identifier:r.identifier,variants:[{id:t,count:e}],formAttributes:a},i)}async updateItem(t,e,a){const i=this.credentials.getCartCredentials();return i?this.http.post(`${F}/${i.id}/update_products_in_cart`,{identifier:i.identifier,cartProductId:t,variants:[{id:t,count:e}]},a):{error:{message:"No cart found",type:"validation"}}}async removeItem(t,e,a){const i=this.credentials.getCartCredentials();return i?this.http.post(`${F}/${i.id}/remove_products_from_cart`,{identifier:i.identifier,cartProductId:t,variants:[{id:e}]},a):{error:{message:"No cart found",type:"validation"}}}clearCart(){this.credentials.clearCartCredentials()}}class it{constructor(t){this.http=t}async list(t,e){return this.http.get(L,{...e,params:t})}async get(t,e){return this.http.get(`${L}/${t}`,e)}}class rt{constructor(t,e){this.http=t,this.credentials=e}async get(t){const e=this.credentials.getInvoiceCredentials();return e?this.http.get(`${U}/${e.id}`,{...t,params:{identifier:e.identifier}}):{error:{message:"No invoice found. Please create an invoice first.",type:"validation"}}}async create(t){const e=this.credentials.getCartCredentials();if(!e)return{error:{message:"No cart found. Please create a cart first.",type:"validation"}};const a=await this.http.post(U,{cart_id:e.id,cart_identifier:e.identifier},t);return a.data&&this.credentials.setInvoiceCredentials({id:a.data.id,identifier:a.data.identifier}),a}async refresh(t){const e=this.credentials.getCartCredentials(),a=this.credentials.getInvoiceCredentials();return e&&a?this.http.post(`/api/v1/invoices/${a.id}/refresh`,{cart_id:e.id,cart_identifier:e.identifier,identifier:a.identifier},t):{error:{message:"No cart or invoice found",type:"validation"}}}async addShippingAddress(t,e,a){const i=this.credentials.getCartCredentials(),r=this.credentials.getInvoiceCredentials();return i&&r?this.http.post(`/api/v1/invoices/${r.id}/add_shipping_address`,{identifier:r.identifier,shipping_address_id:t,shipping_address_identifier:e,cart_id:i.id,cart_identifier:i.identifier},a):{error:{message:"No cart or invoice found",type:"validation"}}}async addDiscountCode(t,e){const a=this.credentials.getInvoiceCredentials();if(!a)return{error:{message:"No invoice found",type:"validation"}};const i=await this.http.post(`/api/v1/invoices/${a.id}/add_discount_code`,{identifier:a.identifier,discount_code:t.toUpperCase()},e);return i.data&&this.credentials.setDiscountCode(t),i}async assignShippingMethod(t,e){const a=this.credentials.getInvoiceCredentials();return a?this.http.post(`/api/v1/invoices/${a.id}/add_shipping_method`,{identifier:a.identifier,shippings:t},e):{error:{message:"No invoice found",type:"validation"}}}async addDetails(t,e){const a=this.credentials.getInvoiceCredentials();return a?this.http.post(`/api/v1/invoices/${a.id}/add_invoice_details`,{identifier:a.identifier,user_comment:t},e):{error:{message:"No invoice found",type:"validation"}}}async getApplicableShippingMethods(t){const e=this.credentials.getInvoiceCredentials();return e?this.http.get(`/api/v1/invoices/${e.id}/applicable_shipping_methods`,{...t,params:{identifier:e.identifier}}):{error:{message:"No invoice found",type:"validation"}}}clearInvoice(){this.credentials.clearInvoiceCredentials()}}class nt{constructor(t,e){this.http=t,this.credentials=e}async createAddress(t,e){const a=await this.http.post(q,{shipping_address:t},e);return a.data&&this.credentials.setShippingCredentials({id:a.data.id,identifier:a.data.identifier}),a}async updateAddress(t,e){const a=this.credentials.getShippingCredentials();if(!a)return this.createAddress(t,e);const i=await this.http.post(q,{identifier:a.identifier,shipping_address:t},e);return i.data&&this.credentials.setShippingCredentials({id:i.data.id,identifier:i.data.identifier}),i}async getAddress(t){const e=this.credentials.getShippingCredentials();return e?this.http.get(`${q}/${e.id}`,{...t,params:{identifier:e.identifier}}):{error:{message:"No shipping address found",type:"validation"}}}async getMethods(t){return this.http.post("/api/v2/shipping_methods/list",{},t)}clearAddress(){this.credentials.clearShippingCredentials()}}class st{constructor(t,e){this.http=t,this.credentials=e}async getMethods(t){const e=this.credentials.getInvoiceCredentials();return e?this.http.post(`${Y}/list`,{invoice_id:e.id,invoice_identifier:e.identifier},t):{error:{message:"No invoice found",type:"validation"}}}async create(t,e){const a=this.credentials.getInvoiceCredentials();if(!a)return{error:{message:"No invoice found",type:"validation"}};const i=await this.http.post(Y,{invoice_id:a.id,invoice_identifier:a.identifier,payment_type:t},e);return i.data&&this.credentials.setPaymentCredentials({id:i.data.id,identifier:i.data.identifier}),i}async initialize(t){const e=this.credentials.getPaymentCredentials();return e?this.http.post(`${Y}/${e.id}/process_payment_step`,{payment_identifier:e.identifier},t):{error:{message:"No payment found. Please create a payment first.",type:"validation"}}}async processStep(t,e){const a=this.credentials.getPaymentCredentials();return a?this.http.post(`${Y}/${a.id}/process_payment_step`,{payment_identifier:a.identifier,...t},e):{error:{message:"No payment found",type:"validation"}}}clearPayment(){this.credentials.clearPaymentCredentials()}}class ot{constructor(t){this.http=t}async login(t,e){return this.http.post(`${H}/login`,t,e)}async requestMobileOTP(t,e){return this.http.post(`${H}/login_request`,t,e)}async verifyMobileOTP(t,e){return this.http.post(`${H}/login_request_verification`,t,e)}async requestEmailLogin(t,e){return this.http.post(`${B}/email_login_request`,t,e)}async register(t,e){return this.http.post(`${B}/register`,t,e)}async getCurrentUser(t){return this.http.get(`${B}/current`,t)}async updateProfile(t,e,a){return this.http.put(`${B}/${t}`,e,a)}async requestMobilePhoneUpdate(t,e){return this.http.post(`${B}/update_mobile_phone_request`,t,e)}async verifyMobilePhoneUpdate(t,e){return this.http.post(`${B}/update_mobile_phone_verification`,t,e)}async forgotPassword(t,e){return this.http.post(`${B}/forgot_password`,t,e)}async revivePassword(t,e){return this.http.post(`${B}/revive_password`,t,e)}async mergeUser(t){return this.http.post(`${B}/merge_user`,{},t)}}class ct{constructor(t){this.http=t}transformFilters(t){if(!t)return{};const e={};return void 0!==t.page&&(e.page_number=t.page),void 0!==t.pageSize&&(e.page_size=t.pageSize),void 0!==t.categoryId&&(e.category_id=t.categoryId),void 0!==t.minPrice&&(e.min_price=t.minPrice),void 0!==t.maxPrice&&(e.max_price=t.maxPrice),e}async query(t,e,a){const i=this.transformFilters(e),r=await this.http.get(j,{...a,params:{...i,query:t,page_number:i.page_number??1,page_size:i.page_size??20,search_direction:"center"}});if(r.data){return{data:I(r.data)}}return r}}class dt{constructor(t){this.http=t}transformFilters(t){if(!t)return{};const e={};return void 0!==t.productId&&(e.product_id=t.productId),void 0!==t.page&&(e.page=t.page),void 0!==t.pageSize&&(e.page_size=t.pageSize),e}async list(t,e){return this.http.get(W,{...e,params:this.transformFilters(t)})}async create(t,e){return this.http.post(W,t,e)}async get(t,e){return this.http.get(`${W}/${t}`,e)}}class pt{constructor(t){this.http=t}validateInvoiceId(t){return!Number.isFinite(t)||t<=0?{error:{message:"Invalid invoice ID",type:"validation"}}:null}async getBalance(t){return this.http.get("/api/v1/users/wallet/balance",t)}async listTransactions(t,e){const a=t?.page_number??1,i=t?.page_size??100;return this.http.get("/api/v1/wallet/transactions",{...e,params:{page_number:a,page_size:i}})}async applyCredit(t,e){const a=this.validateInvoiceId(t);return a||this.http.post(`/api/v1/invoices/${t}/add_credit`,{},e)}async removeCredit(t,e){const a=this.validateInvoiceId(t);return a||this.http.post(`/api/v1/invoices/${t}/remove_credit`,{},e)}}class ut{constructor(t){this.http=t}async getPage(t,e){const a=await this.http.get(X,{...e,params:{url_part:t}}),i=x(a.data);if("cms_page"!==i.entityType||"blog"===i.entity?.cmsPageType)throw new Error(`Expected CMS page at ${t}, but got ${i.entityType}`);return{...a,data:i.entity}}async listPages(t,e){const a=N({...t,cmsPageTypes:"normal"}),i=await this.http.get(V,{...e,params:a});return{...i,data:$(i.data)}}async getBlogPost(t,e){const a=await this.http.get(X,{...e,params:{url_part:t}}),i=x(a.data);if("cms_page"!==i.entityType||"blog"!==i.entity?.cmsPageType)throw new Error(`Expected blog post at ${t}, but got ${i.entityType}`);return{...a,data:i.entity}}async listBlogPosts(t,e){const a=N({...t,cmsPageTypes:"blog"}),i=await this.http.get(V,{...e,params:a});return{...i,data:$(i.data)}}async listAll(t,e){const a=N(t),i=await this.http.get(V,{...e,params:a});return{...i,data:$(i.data)}}}class lt{constructor(t){this.http=t}async upload(t,e){const a=new FormData;a.append("image",t);const i={...e?.headers};return delete i["Content-Type"],this.http.post(Q,a,{...e,headers:i})}async delete(t,e){return this.http.delete(`${Q}/${t}`,e)}}class ht{constructor(t){this.http=t}async track(t,e){const a=e??((i=t)&&"object"==typeof i&&("retries"in i||"timeout"in i||"cache"in i||"headers"in i||"signal"in i)?t:void 0);var i;return this.http.post("/api/v1/visits/add",void 0,a)}async trackProduct(t,e,a){return this.track(a)}async trackCategory(t,e,a){return this.track(a)}}class mt{constructor(t){this.http=t}async listEvents(t,e){return this.http.get(J,{...e,params:t})}async getEvent(t,e){return this.http.get(`${J}/${t}`,e)}async createBooking(t,e){return this.http.post(Z,t,e)}async listBookings(t){return this.http.get(Z,t)}async cancelBooking(t,e){return this.http.post(`${Z}/${t}/cancel`,{},e)}}class gt{constructor(t){this.http=t}async resolve(t,e){const a=await this.http.get(X,{...e,params:{url_part:t}});if(a.data){return{data:x(a.data)}}return a}}class yt{constructor(t){this.http=t}async getHeaderMenu(t="headermenu",e){const a=await this.http.get("/api/v1/trees/fetch_single",{...e,params:{identifier:t}}),i=a.data?D(a.data):a.data,r=i?.tree?.treeStructure?.nodes||[],n=this.convertRawTreeToNavigation(r);return{...a,data:n}}convertRawTreeToNavigation(t){if(!t||0===t.length)return[];return t.map(t=>({name:this.findNodeTitle(t),url:this.findNodeUrl(t),children:this.convertRawTreeToNavigation(t.children||[]),shouldBeDropped:this.shouldDropNode(t)})).filter(t=>!t.shouldBeDropped).map(({shouldBeDropped:t,...e})=>e)}findNodeTitle(t){const{entityType:e,details:a,entity:i}=t;return a&&!a.isTitleDefault&&a.title?a.title:a&&!a.isTitleDefault&&a.name?a.name:"product_category"===e||"product"===e?i?.name||"":("cms_page"===e||"blog_page"===e)&&i?.name||""}findNodeUrl(t){return"product"===t.entityType||"product_category"===t.entityType||"cms_page"===t.entityType||"blog_page"===t.entityType?t.entity?.url||"#":"url"===t.entityType&&t.details?.url||"#"}shouldDropNode(t){return("product"===t.entityType||"product_category"===t.entityType||"cms_page"===t.entityType||"blog_page"===t.entityType)&&!t.entity?.enabled}}class _t{constructor(t){this.http=t}async getInfo(t){const e=await this.http.get("/api/v2/general/info",t);return e.data?{data:h(e.data)}:e.error?{error:e.error}:{error:{type:"api",message:"No data returned from general info endpoint."}}}async getFeatures(t){const e=await this.getInfo(t);return e.error?{error:e.error}:{data:e.data?.settings?.features}}async getCheckoutConfig(t){const e=await this.getInfo(t);return e.error?{error:e.error}:{data:e.data?.settings?.checkout}}async getWalletConfig(t){const e=await this.getInfo(t);return e.error?{error:e.error}:{data:e.data?.settings?.wallet}}async getTajrobeConfig(t){const e=await this.getInfo(t);return e.error?{error:e.error}:{data:e.data?.settings?.tajrobe}}}class ft{constructor(t){const a=e(t);this.http=new R(a),this.tokenStorage=this.http.getTokenStorage(),this.credentialsManager=new M,this.products=new tt(this.http),this.categories=new et(this.http),this.cart=new at(this.http,this.credentialsManager),this.orders=new it(this.http),this.invoices=new rt(this.http,this.credentialsManager),this.shipping=new nt(this.http,this.credentialsManager),this.payments=new st(this.http,this.credentialsManager),this.users=new ot(this.http),this.search=new ct(this.http),this.feedbacks=new dt(this.http),this.wallet=new pt(this.http),this.cms=new ut(this.http),this.images=new lt(this.http),this.visits=new ht(this.http),this.booking=new mt(this.http),this.entityRoutes=new gt(this.http),this.menu=new yt(this.http),this.general=new _t(this.http)}setAuthToken(t){this.tokenStorage.set(t)}getAuthToken(){return this.tokenStorage.get()}clearAuth(){this.tokenStorage.remove()}isAuthenticated(){return null!==this.tokenStorage.get()}clearCache(){this.http.clearCache()}clearCredentials(){this.credentialsManager.clearAll()}clearAll(){this.clearAuth(),this.clearCache(),this.clearCredentials()}async searchQuery(t,e,a){return this.search.query(t,e,a)}}function vt(t){return function(t){if(!t||"object"!=typeof t)return!1;const e=t;return e.http instanceof R&&e.credentials instanceof M}(t)?t:function(t){const a=e(t);return{http:new R(a),credentials:new M}}(t)}function bt(t){const{http:e}=vt(t);return new tt(e)}function Pt(t){const{http:e}=vt(t);return new et(e)}function wt(t){const{http:e,credentials:a}=vt(t);return new at(e,a)}function Ct(t){const{http:e}=vt(t);return new it(e)}function St(t){const{http:e,credentials:a}=vt(t);return new rt(e,a)}function At(t){const{http:e,credentials:a}=vt(t);return new nt(e,a)}function It(t){const{http:e,credentials:a}=vt(t);return new st(e,a)}function Et(t){const{http:e}=vt(t);return new ot(e)}function zt(t){const{http:e}=vt(t);return new ct(e)}function Tt(t){const{http:e}=vt(t);return new dt(e)}function kt(t){const{http:e}=vt(t);return new pt(e)}function xt(t){const{http:e}=vt(t);return new ut(e)}function Gt(t){const{http:e}=vt(t);return new lt(e)}function $t(t){const{http:e}=vt(t);return new ht(e)}function Nt(t){const{http:e}=vt(t);return new mt(e)}function Ot(t){const{http:e}=vt(t);return new gt(e)}function Dt(t){const{http:e}=vt(t);return new yt(e)}function Rt(t){const{http:e}=vt(t);return new _t(e)}exports.CredentialsManager=M,exports.HttpClient=R,exports.SazitoClient=ft,exports.TokenStorage=a,exports.booking=Nt,exports.cart=wt,exports.categories=Pt,exports.cms=xt,exports.createBookingAPI=Nt,exports.createCMSAPI=xt,exports.createCartAPI=wt,exports.createCategoriesAPI=Pt,exports.createEntityRoutesAPI=Ot,exports.createFeedbacksAPI=Tt,exports.createGeneralAPI=Rt,exports.createImagesAPI=Gt,exports.createInvoicesAPI=St,exports.createMenuAPI=Dt,exports.createOrdersAPI=Ct,exports.createPaymentsAPI=It,exports.createProductsAPI=bt,exports.createSazitoClient=function(t){return new ft(t)},exports.createSearchAPI=zt,exports.createShippingAPI=At,exports.createUsersAPI=Et,exports.createVisitsAPI=$t,exports.createWalletAPI=kt,exports.entityRoutes=Ot,exports.feedbacks=Tt,exports.general=Rt,exports.images=Gt,exports.invoices=St,exports.menu=Dt,exports.orders=Ct,exports.payments=It,exports.products=bt,exports.search=zt,exports.shipping=At,exports.transformAddToCartInput=function(t,e,a){const i={product_variants:[{id:t,count:e}]};return a&&(i.form_attributes=u(a)),i},exports.transformApiResponse=l,exports.transformCartResponse=function(t){const e=l(t);return e.items&&Array.isArray(e.items)&&(e.items=e.items.map(t=>({...t,product:{variantId:t.variant?.id||t.product?.variantId,productId:t.variant?.product?.id||t.product?.productId,name:t.name||t.product?.name,image:t.image||t.product?.image,attributes:t.attributes||t.product?.attributes||[],hasMaxOrder:t.product?.hasMaxOrder||!1,maxOrderQuantity:t.product?.maxOrderQuantity,minOrderQuantity:t.product?.minOrderQuantity}}))),e},exports.transformCreateCartInput=function(t){const e={product_variants:t.productVariants?.map(t=>({id:t.id||t.variantId,count:t.count||t.quantity,form_attributes:t.formAttributes?u(t.formAttributes):void 0}))||[]};return t.coupon&&(e.coupon=t.coupon),e},exports.transformInvoiceResponse=function(t){const e=l(t);return e.items&&Array.isArray(e.items)&&(e.items=e.items.map(t=>({...t,discount:t.discount||(t.originalPrice?t.originalPrice-t.unitPrice:0)}))),e},exports.transformProductListResponse=A,exports.transformRequestKeys=u,exports.transformResponseKeys=p,exports.transformShippingAddressInput=function(t){return{shipping_address:u(t)}},exports.users=Et,exports.visits=$t,exports.wallet=kt;
1
+ "use strict";const t={timeout:3e4,retry:{enabled:!0,retries:3,retryDelay:1e3},cache:{products:{enabled:!0,ttl:6e5},categories:{enabled:!0,ttl:6e5},cart:{enabled:!1},orders:{enabled:!1},search:{enabled:!0,ttl:3e5},cms:{enabled:!0,ttl:6e5},tags:{enabled:!0,ttl:6e5},entityRoutes:{enabled:!0,ttl:6e5}},debug:!1};function e(e){return{...t,...e,retry:{...t.retry,...e.retry},cache:{...t.cache,...e.cache},customFetchApi:e.customFetchApi||("undefined"!=typeof fetch?fetch:void 0)}}class a{constructor(){this.tokenKey="user_id_token"}get(){if("undefined"==typeof window||"undefined"==typeof document)return null;const t=this.getFromLocalStorage();if(t)return t;return this.parseCookies()[this.tokenKey]||null}set(t,e){if("undefined"==typeof window||"undefined"==typeof document)return void console.warn("[Sazito SDK] Cannot set token in SSR environment");this.setInLocalStorage(t);const a={secure:!0,sameSite:"Lax",maxAge:2592e3,path:"/",...e};this.setCookie(this.tokenKey,t,a)}remove(){"undefined"!=typeof window&&"undefined"!=typeof document&&(this.removeFromLocalStorage(),this.setCookie(this.tokenKey,"",{maxAge:-1,path:"/"}))}getFromLocalStorage(){try{return window.localStorage.getItem(this.tokenKey)}catch{return null}}setInLocalStorage(t){try{window.localStorage.setItem(this.tokenKey,t)}catch{}}removeFromLocalStorage(){try{window.localStorage.removeItem(this.tokenKey)}catch{}}parseCookies(){return"undefined"==typeof document?{}:document.cookie.split(";").reduce((t,e)=>{const[a,i]=e.trim().split("=");return a&&i&&(t[a]=decodeURIComponent(i)),t},{})}setCookie(t,e,a){let i=`${t}=${encodeURIComponent(e)}`;void 0!==a.maxAge&&(i+=`; Max-Age=${a.maxAge}`),a.path&&(i+=`; Path=${a.path}`),a.domain&&(i+=`; Domain=${a.domain}`),a.secure&&(i+="; Secure"),a.httpOnly&&(i+="; HttpOnly"),a.sameSite&&(i+=`; SameSite=${a.sameSite}`),document.cookie=i}}class i{constructor(){this.cache=new Map}get(t,e){const a=this.cache.get(t);return a?e&&Date.now()-a.timestamp>e?(this.cache.delete(t),null):a.data:null}set(t,e){this.cache.set(t,{data:e,timestamp:Date.now()})}delete(t){this.cache.delete(t)}deletePattern(t){const e=new RegExp(t),a=[];this.cache.forEach((t,i)=>{e.test(i)&&a.push(i)}),a.forEach(t=>this.cache.delete(t))}clear(){this.cache.clear()}static generateKey(t,e,a){return`${t}:${e}:${a?JSON.stringify(a):""}`}}const r={no_of_items:"quantity",single_item_price:"unitPrice",total_items_price:"lineTotal",items_total_raw_price:"itemsTotalRawPrice",items_discount:"itemsDiscount",customer_profit:"customerProfit",customer_profit_percentage:"customerProfitPercentage",total_amount:"totalAmount",net_total:"netTotal",gross_total:"grossTotal",final_total:"finalTotal",discount_total:"discountTotal",shipping_total:"shippingTotal",tax_total:"taxTotal",unique_identifier:"identifier",invoice_identifier:"identifier",payment_identifier:"identifier",shipping_address_identifier:"identifier",first_name:"firstName",last_name:"lastName",mobile_phone:"mobilePhone",phone_number:"phoneNumber",postal_code:"postalCode",user_comment:"userComment",product_id:"productId",variant_id:"variantId",product_name:"name",product_image:"image",product_variant:"variant",product_variants:"variants",product_categories:"categories",product_attributes:"attributes",product_type:"productType",short_description:"shortDescription",stock_quantity:"stockQuantity",stock_number:"stockQuantity",sale_price:"salePrice",raw_price:"originalPrice",has_max_order:"hasMaxOrder",max_no_of_order:"maxOrderQuantity",min_order_count:"minOrderQuantity",sold_count:"soldCount",static_url:"staticUrl",dynamic_form_id:"dynamicFormId",event_entity_id:"eventEntityId",theme_config:"themeConfig",image_id:"imageId",is_stock_managed:"isStockManaged",commercial_files:"commercialFiles",sort_index:"sortIndex",attribute_type:"attributeType",cart_products:"items",cart_product_id:"cartProductId",min_basket_limit_violated:"minBasketLimitViolated",invoice_items:"items",products:"items",total_count:"total",shipping_method_needed:"needsShipping",shipping_method:"shippingMethod",shipping_address:"shippingAddress",shipping_items:"shippingItems",delivery_time:"deliveryTime",min_delivery_days:"minDays",max_delivery_days:"maxDays",payment_type:"paymentType",payment_types:"paymentTypes",payment_amount:"amount",reference_code:"code",is_default:"isDefault",is_available:"isAvailable",delete_coupon:"deleteCoupon",form_attributes:"formAttributes",booking_attributes:"bookingAttributes",readable_form_attr:"formFields",created_at:"createdAt",updated_at:"updatedAt",page_number:"page",page_size:"pageSize",total_count_raw:"totalCountRaw",max_price:"maxPrice",min_price:"minPrice",stock_alert_limit:"stockAlertLimit",sub_categories:"subCategories",order_number:"orderNumber",sort_order:"sortOrder",pinned_ids:"pinnedIds",region_id:"regionId",city_id:"cityId",parent_id:"parentId",discount_code:"discountCode",entity_name:"entityType",entity_id:"entityId",other_props:"entity",shipping_methods:"shippingMethods",shipping_rates:"shippingRates",grouped_shipping_rates:"groupedShippingRates",items_shipping_rate:"itemsShippingRate",shipping_rate:"shippingRate",rate_id:"rateId",invoice_item_id:"invoiceItemId",invoice_item_ids:"invoiceItemIds",scheduler_booking_attributes:"schedulerBookingAttributes",inventory_count:"inventoryCount",order_identifier:"orderIdentifier",self_only:"selfOnly",coupon:"coupon",discount_usages:"discountUsages",user_set_coordinates_before:"userSetCoordinatesBefore",show_order:"showOrder",alt:"alt",url:"url",activate_add_to_cart_alert:"addToCardAlert",activate_advanced_card_to_card:"advancedCardToCard",activate_ayria_payment_customization:"ayriaPaymentGateway",activate_azki_payment_customization:"azkiPaymentGateway",activate_bazar_payment_customization:"bazarPaymentGateway",activate_blog:"shopBlog",activate_card_to_card_payment:"cardToCardPayment",activate_checkout_dynamic_form:"checkoutDynamicForm",activate_different_register_customization:"multiTypeRegister",activate_digipay_payment:"digipayPaymentGateway",activate_digipay_payment_customization:"digipayPaymentGateway",activate_filter_products:"productFilters",activate_ghesta_payment_customization:"ghestaPaymentGateway",activate_mega_footer:"megaFooter",activate_mellat_payment_customization:"mellatPaymentGateway",activate_min_basket:"checkoutMinimumAmount",activate_novapay_payment_customization:"novapayPaymentGateway",activate_ozon_payment_customization:"ozonPaymentGateway",activate_payment_in_place:"paymentInPlace",activate_payping_payment:"paypingPaymentGateway",activate_pec_payment_customization:"pecPaymentGateway",activate_sabin_payment_customization:"sabinPaymentGateway",activate_sadad_payment_customization:"sadadPaymentGateway",activate_search:"shopSearch",activate_sep_payment_customization:"sepPaymentGateway",activate_shop_vat:"shopVat",activate_snapppay_payment_customization:"snapppayPaymentGateway",activate_tajrobe:"tajrobe",activate_tara_payment_customization:"taraPaymentGateway",activate_theme_config_settings:"themeConfigSettings",activate_toman_payment_customization:"tomanPaymentGateway",activate_torobpay_payment_customization:"torobpayPaymentGateway",activate_up_payment_customization:"asanpardakhtPaymentGateway",activate_vandar_payment_customization:"vandarPaymentGateway",activate_wallet:"wallet",activate_yourgate_payment_customization:"yourgatePaymentGateway",activate_zarinpal_payment:"zarinpalPaymentGateway",activate_zarinplus_payment_customization:"zarinplusPaymentGateway",activate_zibal_payment_customization:"zibalPaymentGateway",activate_zify_payment_customization:"zifyPaymentGateway",disable_ordering:"disableOrdering",pwa:"progressiveWebApp",remove_front_basket:"hideCheckout",remove_front_taint:"sazitoBrandingRemoval"},n=Object.values(r).reduce((t,e)=>(t[e]=(t[e]||0)+1,t),{}),s=Object.entries(r).reduce((t,[e,a])=>(1===n[a]&&(t[a]=e),t),{});function o(t){return t.replace(/_([a-z])/g,(t,e)=>e.toUpperCase())}function c(t){return t.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function d(t){return!(null===t||"object"!=typeof t||Array.isArray(t)||t instanceof Date)}function p(t,e){const a={...t};for(const t of e)delete a[t];return a}function u(t){if(!d(t))return Array.isArray(t)?t.map(t=>u(t)):t;const e={};for(const[a,i]of Object.entries(t)){let t=r[a];t||(t=o(a)),d(i)?e[t]=u(i):Array.isArray(i)?e[t]=i.map(t=>u(t)):e[t]=i}return e}function l(t){if(!d(t))return Array.isArray(t)?t.map(t=>l(t)):t;const e={};for(const[a,i]of Object.entries(t)){let t=s[a];t||(t=c(a)),d(i)?e[t]=l(i):Array.isArray(i)?e[t]=i.map(t=>l(t)):e[t]=i}return e}function m(t){const e=t;if(d(e?.data?.result)){const t=e.data.result,a=Object.keys(t);return 1===a.length&&d(t[a[0]])?u(t[a[0]]):u(t)}return u(t)}function h(t){if(!t)return{};if(!d(t))return{};const{general:e,shop:a,checkout:i,features:r,wallet:n,tajrobe:s,domain:o,enamad:c,google:p,logo:u,social:l,...m}=t,h={...d(e)?e:{},...d(a)?a:{}},{registerType:_,showProductStockNumber:b,...v}=h||{};let I=i;if(d(i)){const t={...i};void 0===t.preventRedirect&&void 0!==t.manual&&(t.preventRedirect=t.manual),delete t.manual,I=t}return{...m,scripts:{enamad:c,google:p},shop:f({...v,domain:o,logo:u,social:l}),settings:{checkout:I,features:w(r),wallet:P(n),tajrobe:A(s),registerType:y(_),showProductStockNumber:g(b)}}}function y(t){return"string"==typeof t?t:""}function g(t){return"boolean"==typeof t?t:d(t)&&Object.prototype.hasOwnProperty.call(t,"enabled")?g(t.enabled):1===t||"1"===t||"true"===t}function f(t){if(!d(t))return{};const e={...t};if(d(e.city)){const t=p(e.city,["createdAt","updatedAt"]);let a=t.region;d(a)&&(a=p(a,["createdAt","updatedAt","cities"])),t.region=a,e.city=t}return e}const _={addToCardAlert:"addToCartAlertEnabled",addToCartAlert:"addToCartAlertEnabled",advancedCardToCard:"advancedCardToCardEnabled",cardToCardPayment:"cardToCardPaymentEnabled",checkoutDynamicForm:"checkoutDynamicFormEnabled",multiTypeRegister:"multiTypeRegisterEnabled",productFilters:"productFiltersEnabled",megaFooter:"megaFooterEnabled",checkoutMinimumAmount:"checkoutMinimumAmountEnabled",paymentInPlace:"paymentInPlaceEnabled",shopBlog:"blogEnabled",shopSearch:"searchEnabled",shopVat:"shopVatEnabled",tajrobe:"tajrobeEnabled",themeConfigSettings:"themeConfigSettingsEnabled",wallet:"walletEnabled",progressiveWebApp:"progressiveWebAppEnabled",disableOrdering:"orderingDisabled",hideCheckout:"checkoutHidden",sazitoBrandingRemoval:"sazitoBrandingRemoved",ayriaPaymentGateway:"ayriaPaymentGatewayEnabled",azkiPaymentGateway:"azkiPaymentGatewayEnabled",bazarPaymentGateway:"bazarPaymentGatewayEnabled",digipayPaymentGateway:"digipayPaymentGatewayEnabled",ghestaPaymentGateway:"ghestaPaymentGatewayEnabled",mellatPaymentGateway:"mellatPaymentGatewayEnabled",novapayPaymentGateway:"novapayPaymentGatewayEnabled",ozonPaymentGateway:"ozonPaymentGatewayEnabled",paypingPaymentGateway:"paypingPaymentGatewayEnabled",pecPaymentGateway:"pecPaymentGatewayEnabled",sabinPaymentGateway:"sabinPaymentGatewayEnabled",sadadPaymentGateway:"sadadPaymentGatewayEnabled",sepPaymentGateway:"sepPaymentGatewayEnabled",snapppayPaymentGateway:"snapppayPaymentGatewayEnabled",taraPaymentGateway:"taraPaymentGatewayEnabled",tomanPaymentGateway:"tomanPaymentGatewayEnabled",torobpayPaymentGateway:"torobpayPaymentGatewayEnabled",asanpardakhtPaymentGateway:"asanpardakhtPaymentGatewayEnabled",vandarPaymentGateway:"vandarPaymentGatewayEnabled",yourgatePaymentGateway:"yourgatePaymentGatewayEnabled",zarinpalPaymentGateway:"zarinpalPaymentGatewayEnabled",zarinplusPaymentGateway:"zarinplusPaymentGatewayEnabled",zibalPaymentGateway:"zibalPaymentGatewayEnabled",zifyPaymentGateway:"zifyPaymentGatewayEnabled",activateEditOrderCustomization:"editOrderEnabled",activateEditOrderCustomizationEnabled:"editOrderEnabled"},b=new Set(["activateAlopeykAdvanced","activate_alopeyk_advanced"]),v=new Set(["auditLogEnabled","editOrderEnabled","rahkaranAccountingCustomizationEnabled","advancedThemeDesignerEnabled","checkoutHidden","eventPublisherEnabled","exportOrdersEnabled","exportProductsEnabled","exportUsersEnabled","fontCustomizationEnabled","forwardShippingEnabled","podroShippingEnabled","postexShippingEnabled","quotaNotificationsEnabled","recaptchaEnabled","rolePoliciesEnabled","sepidarAccountingCustomizationEnabled","shortUrlEnabled","skuSearchEnabled","snappShopCustomizationEnabled","snappboxShippingEnabled","stockAlertNotificationsEnabled","tapsipackShippingEnabled","themeConfigSettingsEnabled","advancedTextEditorEnabled","advancedShippingEnabled","bulkActionEnabled","discountBulkEnabled","discountCodeEnabled","orderBulkActionEnabled","importProductsEnabled","mahakAccountingCustomizationEnabled","millipayPaymentCustomizationEnabled","orderSmsNotificationsEnabled"]);function w(t){if(!d(t))return{};const e={},a=(t,a)=>{if(b.has(t))return;const i=(t=>{if("boolean"==typeof t)return t;if("number"==typeof t)return 1===t||0!==t&&void 0;if("string"==typeof t){const e=t.trim().toLowerCase();return"true"===e||"1"===e||"false"!==e&&"0"!==e&&void 0}})(a);void 0!==i&&(e[t]=i)};d(t.flags)&&Object.entries(t.flags).forEach(([t,e])=>{a(t,e)}),d(t.configurations)&&Object.entries(t.configurations).forEach(([t,e])=>{a(t,e)}),Object.entries(t).forEach(([t,e])=>{"flags"!==t&&"premium"!==t&&"configurations"!==t&&(d(e)&&Object.prototype.hasOwnProperty.call(e,"enabled")?a(t,e.enabled):a(t,e))});const i={};Object.entries(e).forEach(([t,e])=>{const a=function(t){const e=t.includes("_")?o(t):t,a=_[e];if(a)return a;const i=e.startsWith("activate")&&e.length>8?`${e.charAt(8).toLowerCase()}${e.slice(9)}`:e;return i.endsWith("Enabled")||i.endsWith("Disabled")||i.endsWith("Hidden")||i.endsWith("Removed")?i:`${i}Enabled`}(t);v.has(a)||(i[a]=e)});const r={...i};return d(t.premium)&&(r.premium=t.premium),r}function P(t){if(!d(t))return{};const e=d(t.configurations)?{...t,...t.configurations}:{...t},a=t=>"boolean"==typeof t?t:1===t||"1"===t||"true"===t||0!==t&&"0"!==t&&"false"!==t&&void 0;return{enabled:a(e.enabled)??!1,useWithDiscount:a(e.useWithDiscount)??!1,minAmount:(t=>{if("number"==typeof t&&Number.isFinite(t))return t;const e=Number(t);return Number.isFinite(e)?e:void 0})(e.minAmount??e.walletMinAmount)??0,minAmountRequired:a(e.minAmountRequired??e.walletMinStatus)??!1}}function A(t){if(!d(t))return{};const e=d(t.configurations)?{...t,...t.configurations}:{...t};let a=!1;return"boolean"==typeof e.enabled?a=e.enabled:1!==e.enabled&&"1"!==e.enabled&&"true"!==e.enabled||(a=!0),{enabled:a}}function I(t){const e=m(t);if(!d(e))return{};const a=Array.isArray(e.items)?e.items.map(t=>function(t){if(!d(t))return{};const e=F(t),a=R(t.productVariantId??e.variantId)??e.variantId;return{id:G(t.id??t.cartProductId)??"",productVariantId:a,quantity:R(t.quantity)??0,unitPrice:R(t.unitPrice)??0,lineTotal:R(t.lineTotal)??0,product:e,formAttributes:t.formAttributes,formFields:t.formFields,bookingAttributes:t.bookingAttributes}}(t)):[];return{...e,items:a,netTotal:R(e.netTotal)??0,grossTotal:R(e.grossTotal),needsShipping:Boolean(e.needsShipping),minBasketLimitViolated:Boolean(e.minBasketLimitViolated),deleteCoupon:void 0===e.deleteCoupon?void 0:Boolean(e.deleteCoupon)}}function C(t){const e=m(t);if(!d(e))return{};const a=p(e,["shippingMethod","user","userData"]),i=Array.isArray(e.items)?e.items.map(t=>function(t){if(!d(t))return{};const e=F(t),a=R(t.productVariantId??e.variantId)??e.variantId,i=Array.isArray(e.attributes)?e.attributes:[],r=D(e.hasMaxOrder??t.hasMaxOrder);return{id:G(t.id??t.invoiceItemId??t.cartProductId)??"",productVariantId:a,productId:R(e.productId??t.productId),name:O(t.name)??O(e.name)??"",url:O(e.url)??O(t.url),attributes:i,productType:O(e.productType)??O(t.productType),hasMaxOrder:r,maxOrderQuantity:R(e.maxOrderQuantity??t.maxOrderQuantity),minOrderQuantity:R(e.minOrderQuantity??t.minOrderQuantity),image:K(t.image??e.image),quantity:R(t.quantity)??0,unitPrice:R(t.unitPrice)??0,lineTotal:R(t.lineTotal)??0,rawPrice:R(t.rawPrice??t.originalPrice)??0,customerProfit:R(t.customerProfit)??0,commercialFiles:t.commercialFiles,formAttributes:t.formAttributes,bookingAttributes:t.bookingAttributes,formFields:t.formFields}}(t)):[],r=Array.isArray(e.discountUsages)?e.discountUsages:[],n=r[0],s=d(n)&&d(n.discountCode)?O(n.discountCode.code):void 0;return{...a,items:i,shippingAddress:function(t){if(!t)return;const{id:e,city:a,region:i,...r}=t,n={id:i?.id??a.regionId??0,name:i?.name??"",city:a};return{...r,region:n}}(T(e.shippingAddress)),shippingItems:Array.isArray(e.shippingItems)?e.shippingItems.map(t=>function(t){if(!d(t))return{};const e=d(t.rate)?t.rate:d(t.shippingRate)?t.shippingRate:d(t.shippingMethod)?t.shippingMethod:t;return{invoiceItemIds:$(t),rate:Q(e)}}(t)):[],discountUsages:r,netTotal:R(e.netTotal)??0,finalTotal:R(e.finalTotal)??0,vat:R(e.vat)??0,vatPercent:R(e.vatPercent)??0,itemsDiscount:R(e.itemsDiscount)??0,discountTotal:R(e.discountTotal)??0,customerProfit:R(e.customerProfit)??0,customerProfitPercentage:R(e.customerProfitPercentage)??0,itemsTotalRawPrice:R(e.itemsTotalRawPrice)??0,couponTotal:R(e.couponTotal)??0,shippingTotal:R(e.shippingTotal)??0,creditTotal:R(e.creditTotal)??0,needsShipping:Boolean(e.needsShipping),userComment:"string"==typeof e.userComment?e.userComment:void 0,discountCode:s}}function S(t){return T(t)}function z(t){const e=m(t);if(d(e))return E(e)}function E(t){if(!t)return;const e=function(t){const e=N(t);if(!e)return;if(1===Object.keys(e).length&&d(e.user))return N(e.user)??e.user;return e}(t);if(!e)return;const a={},i=R(e.id);void 0!==i&&(a.id=i);const r=O(e.email);r&&(a.email=r);const n=O(e.mobilePhone)??O(e.phoneNumber);n&&(a.mobilePhone=n);const s=O(e.phoneNumber);s&&s!==n&&(a.phoneNumber=s);const o=O(e.firstName);o&&(a.firstName=o);const c=O(e.lastName);c&&(a.lastName=c);const p=O(e.birthDate);return p&&(a.birthDate=p),Object.keys(a).length>0?a:void 0}function T(t){if(!t)return;const e=E(t.user),a=N(t.region),i=N(t.city),r=N(i?.region),n=O(t.regionName)??x(t.region),s=k(a??t.region,{fallbackId:R(t.regionId),fallbackName:n})??k(r,{fallbackId:R(t.regionId),fallbackName:n}),o=R(t.regionId)??s?.id,c=O(t.cityName)??O(i?.name)??x(t.city),d=function(t,e={}){if(null==t)return;const a=N(t),i=R(a?.id)??R(t)??e.fallbackId,r=O(a?.name)??x(t)??e.fallbackName;if(void 0===i||!r)return;const n={id:i,name:r},s=R(a?.regionId)??e.fallbackRegionId;void 0!==s&&(n.regionId=s);const o=R(a?.latitude);void 0!==o&&(n.latitude=o);const c=R(a?.longitude);void 0!==c&&(n.longitude=c);return n}(i??t.city,{fallbackId:R(t.cityId),fallbackName:c,fallbackRegionId:o}),p=O(t.firstName)??e?.firstName??"",u=O(t.lastName)??e?.lastName??"",l={id:R(t.id)??0,identifier:O(t.identifier)??"",firstName:p,lastName:u,city:d??{id:R(t.cityId??t.city)??0,name:c??"",...void 0!==o?{regionId:o}:{}},address:O(t.address)??""},m=O(t.mobilePhone)??O(t.phoneNumber)??e?.mobilePhone??e?.phoneNumber,h=O(t.phoneNumber)??e?.phoneNumber;m&&(l.mobilePhone=m),h&&h!==m&&(l.phoneNumber=h);const y=O(t.email)??e?.email;y&&(l.email=y),s&&(l.region=s);const g=O(t.postalCode);g&&(l.postalCode=g);const f=R(t.latitude);void 0!==f&&(l.latitude=f);const _=R(t.longitude);void 0!==_&&(l.longitude=_);const b=D(t.userSetCoordinatesBefore);return void 0!==b&&(l.userSetCoordinatesBefore=b),l}function k(t,e={}){if(null==t)return;const a=N(t),i=R(a?.id)??R(t)??e.fallbackId,r=O(a?.name)??x(t)??e.fallbackName;return void 0!==i&&r?{id:i,name:r}:void 0}function N(t){if(d(t))return d(t.data)?t.data:t}function x(t){const e=O(t);if(e)return void 0===R(e)?e:void 0}function $(t){return(Array.isArray(t.invoiceItemIds)?t.invoiceItemIds:void 0!==t.invoiceItemId?[t.invoiceItemId]:[]).map(t=>G(t)).filter(t=>void 0!==t)}function R(t){if("number"==typeof t&&Number.isFinite(t))return t;if("string"!=typeof t)return;const e=Number(t);return Number.isFinite(e)?e:void 0}function O(t){if("string"!=typeof t)return;const e=t.trim();return e.length>0?e:void 0}function D(t){return"boolean"==typeof t?t:1===t||"1"===t||"true"===t||0!==t&&"0"!==t&&"false"!==t&&void 0}function G(t){if("number"==typeof t&&Number.isFinite(t))return t;if("string"==typeof t){const e=t.trim();return e.length>0?e:void 0}}function F(t){if(!d(t))return{variantId:0,name:"",attributes:[]};const e=d(t.variant)?t.variant:void 0,a=d(e?.product)?e.product:void 0,i=d(t.product)?t.product:void 0,r=R(i?.variantId??e?.id??t.productVariantId??t.variantId)??0,n=Array.isArray(i?.attributes)?i.attributes:Array.isArray(e?.attributes)?e.attributes:Array.isArray(t.attributes)?t.attributes:[];return{variantId:r,productId:R(i?.productId??t.productId??a?.id),name:O(i?.name)??O(t.name)??"",url:O(i?.url)??O(t.url)??O(a?.url),image:K(i?.image??t.image),attributes:n,productType:O(i?.productType)??O(t.productType)??O(a?.productType),hasMaxOrder:i?.hasMaxOrder??t.hasMaxOrder??e?.hasMaxOrder,maxOrderQuantity:R(i?.maxOrderQuantity??t.maxOrderQuantity??e?.maxOrderQuantity),minOrderQuantity:R(i?.minOrderQuantity??t.minOrderQuantity??e?.minOrderQuantity)}}function M(t){if(!d(t))return{};const e=p(t,["staticUrl","summary","tags","slug"]);return e.variants&&Array.isArray(e.variants)&&(e.variants=e.variants.map(t=>d(t)?p(t,["name","title","product","status","soldCount"]):{})),e.categories&&Array.isArray(e.categories)&&(e.categories=e.categories.map(t=>d(t)?{id:t.id,name:t.name,url:t.url}:{})),e.images&&Array.isArray(e.images)&&(e.images=e.images.map(t=>K(t)??{})),e}function K(t){return d(t)?p(t,["widthRatio","heightRatio","thumb","order"]):t}function U(t){const e=M(t);return e?p(e,["themeConfig"]):e}function j(t){const e=m(t);if(e.items&&Array.isArray(e.items)){const t=R(e.total)??e.items.length,a=R(e.pageSize)??e.items.length,i=R(e.page)??1,r=R(e.totalPages)??Math.ceil(t/a);return{items:e.items.map(t=>U(t)),total:t,page:i,pageSize:a,totalPages:r}}return e}function B(t){if(!d(t))return{products:{items:[],total:0,page:1,pageSize:20},blogPages:{items:[],total:0,page:1,pageSize:20},cmsPages:{items:[],total:0,page:1,pageSize:20},productCategories:{items:[],total:0,page:1,pageSize:20}};const e=t,a={products:{items:[],total:0,page:1,pageSize:20},blogPages:{items:[],total:0,page:1,pageSize:20},cmsPages:{items:[],total:0,page:1,pageSize:20},productCategories:{items:[],total:0,page:1,pageSize:20}};return Array.isArray(e.items)&&(a.products.items=e.items.map(t=>U(t)),a.products.total=R(e.productsCount)??0,a.products.page=R(e.productsPageNumber)??1,a.products.pageSize=R(e.productsPageSize)??20),Array.isArray(e.blogPages)&&(a.blogPages.items=e.blogPages.map(t=>Z(t)),a.blogPages.total=R(e.blogPagesCount)??0,a.blogPages.page=R(e.blogPagesPageNumber)??1,a.blogPages.pageSize=R(e.blogPagesPageSize)??20),Array.isArray(e.cmsPages)&&(a.cmsPages.items=e.cmsPages.map(t=>Z(t)),a.cmsPages.total=R(e.cmsPagesCount)??0,a.cmsPages.page=R(e.cmsPagesPageNumber)??1,a.cmsPages.pageSize=R(e.cmsPagesPageSize)??20),Array.isArray(e.categories)&&(a.productCategories.items=e.categories.map(t=>H(t)),a.productCategories.total=R(e.productCategoriesCount)??0,a.productCategories.page=R(e.productCategoriesPageNumber)??1,a.productCategories.pageSize=R(e.productCategoriesPageSize)??20),a}function q(t){const e=m(t);if(!d(e))return[];return(Array.isArray(e.paymentTypes)?e.paymentTypes:Array.isArray(e.methods)?e.methods:[]).map(t=>d(t)?{id:R(t.id)??0,code:t.code,isDefault:Boolean(t.isDefault)}:{id:0,code:"",isDefault:!1})}function L(t){const e=m(t);return(Array.isArray(e)?e:d(e)&&Array.isArray(e.shippingMethods)?e.shippingMethods:[]).map(t=>V(t))}function Y(t){const e=m(t);if(!d(e))return{shippingMethods:[],groupedShippingRates:{},itemsShippingRate:[]};const a=d(e.groupedShippingRates)?Object.entries(e.groupedShippingRates).reduce((t,[e,a])=>(t[e]=Array.isArray(a)?a.map(t=>Q(t)):[],t),{}):{};return{shippingMethods:Array.isArray(e.shippingMethods)?e.shippingMethods.map(t=>V(t)):[],groupedShippingRates:a,itemsShippingRate:Array.isArray(e.itemsShippingRate)?e.itemsShippingRate.map(t=>d(t)?{invoiceItemId:G(t.invoiceItemId)??$(t)[0]??"",shippingRate:Q(t.shippingRate??t.rate??t)}:{invoiceItemId:"",shippingRate:Q(void 0)}):[]}}function V(t){return d(t)?{id:R(t.id)??0,name:O(t.name)??"",type:O(t.type)??""}:{id:0,name:"",type:""}}function Q(t){return d(t)?{id:R(t.id??t.rateId)??0,name:O(t.name)??"",price:R(t.price??t.amount)??0,icon:O(t.icon),color:O(t.color),type:O(t.type)}:{id:0,name:"",price:0}}function W(t){return d(t)?p(t,["staticUrl","products","items"]):{}}function H(t){const e=W(t);return e?p(e,["themeConfig"]):{}}function J(t){return d(t)?p(t,["staticUrl","urlKey"]):{}}function Z(t){const e=J(t);return e?p(e,["themeConfig"]):{}}function X(t){const e=m(t);if(!e||!e.route)return e??{};const a=d(e.route)?e.route:{};if(a.entity){switch(a.entityType){case"product":a.entity=M(a.entity);break;case"product_category":a.entity=W(a.entity);break;case"cms_page":case"blog_page":a.entity=J(a.entity)}d(a.entity)&&(a.entity=p(a.entity,["id"])),!a.url&&d(a.entity)&&a.entity.url&&(a.url=a.entity.url)}return a}function tt(t){if(!d(t))return{};const e={...t};return e.entity&&(e.entity=H(e.entity),d(e.entity)&&(e.entity=p(e.entity,["id"]))),e.children&&Array.isArray(e.children)&&(e.children=e.children.map(tt)),e}function et(t){const e=m(t);return e?e.cmsPages&&Array.isArray(e.cmsPages)?{items:e.cmsPages.map(Z),total:e.total||e.cmsPages.length,page:e.page||e.pageNumber||1,pageSize:e.pageSize||e.cmsPages.length}:e.items&&Array.isArray(e.items)?{items:e.items.map(t=>Z(t)),total:e.total||e.items.length,page:e.page||1,pageSize:e.pageSize||e.items.length}:e:{}}function at(t){if(!d(t))return{};const e={};if(void 0!==t.page&&(e.page_number=t.page),void 0!==t.pageSize&&(e.page_size=t.pageSize),t.cmsPageTypes){const a=Array.isArray(t.cmsPageTypes)?t.cmsPageTypes[0]:t.cmsPageTypes;e["filters[]"]=JSON.stringify({name:"cms_page_types",value:a})}return e}function it(t){if(!d(t))return{};const e={};if(t.entityType&&(e.entityType=t.entityType),void 0!==t.entityId&&(e.entityId=t.entityId),d(t.entity)){const a=p(t.entity,["staticUrl","id"]);Object.keys(a).length>0&&(e.entity=a)}return t.details&&(e.details=t.details),t.children&&Array.isArray(t.children)&&(e.children=t.children.map(t=>it(t))),e}function rt(t){const e=m(t);if(!e||!e.tree)return e??{};const a=d(e.tree)?e.tree:{};return d(a.treeStructure)&&Array.isArray(a.treeStructure.nodes)&&(a.treeStructure.nodes=a.treeStructure.nodes.map(t=>it(t))),e}class nt{constructor(t){this.config=t,this.baseUrl="http://api.sazito.com:8080",this.domain=t.domain,this.tokenStorage=new a,this.cache=new i,this.fetchApi=t.customFetchApi.bind(globalThis)}async get(t,e){const a=this.buildUrl(t,e?.params),r=i.generateKey("GET",a,e?.params);if(!1!==e?.cache){const e=this.getApiName(t),a=this.config.cache[e];if(a?.enabled&&a.ttl){const e=this.cache.get(r,a.ttl);if(e)return this.config.debug&&console.log("[Sazito SDK] Cache hit:",t),{data:e}}}const n=await this.request("GET",a,e);return n.data&&!1!==e?.cache&&this.cache.set(r,n.data),n}async post(t,e,a){const i=this.buildUrl(t),r=this.isMultipartBody(e),n=e?r?e:l(e):void 0,s=this.getApiName(t);return this.cache.deletePattern(`GET:.*${s}`),this.request("POST",i,{...a,body:n,rawBody:r,omitJsonContentType:r})}async put(t,e,a){const i=this.buildUrl(t),r=this.isMultipartBody(e),n=e?r?e:l(e):void 0,s=this.getApiName(t);return this.cache.deletePattern(`GET:.*${s}`),this.request("PUT",i,{...a,body:n,rawBody:r,omitJsonContentType:r})}async delete(t,e){const a=this.buildUrl(t),i=this.getApiName(t);return this.cache.deletePattern(`GET:.*${i}`),this.request("DELETE",a,e)}async request(t,e,a,i=0){const r=new AbortController,n=a?.signal||r.signal,s=a?.timeout||this.config.timeout,o=setTimeout(()=>r.abort(),s);try{const r=await this.fetchApi(e,{method:t,headers:this.getHeaders(a?.headers,a?.omitJsonContentType),body:a?.body?a.rawBody?a.body:JSON.stringify(a.body):void 0,signal:n});clearTimeout(o);const s=void 0!==a?.retries?a.retries:this.config.retry.retries;if(!r.ok&&this.shouldRetry(r.status)&&i<s)return this.config.debug&&console.log(`[Sazito SDK] Retrying request (${i+1}/${s}):`,e),await this.delay(this.config.retry.retryDelay*(i+1)),this.request(t,e,a,i+1);const c=r.headers.get("content-type");let d;d=c?.includes("application/json")?await r.json():await r.text();const p=void 0!==d?.result?d.result:d;this.config.debug&&console.log(`[Sazito SDK] ${t} ${e}:`,{status:r.status,data:p});let l=p?u(p):p;const m=["cart","product","user","order","invoice","payment","shippingAddress"];if(l&&"object"==typeof l&&!Array.isArray(l)){const t=Object.keys(l);1===t.length&&m.includes(t[0])&&"object"==typeof l[t[0]]&&null!==l[t[0]]&&(l=l[t[0]])}return r.ok?{data:l}:{error:{status:r.status,message:l?.message||p?.message||r.statusText||"Request failed",type:"api",details:l}}}catch(t){return clearTimeout(o),this.config.debug&&console.error("[Sazito SDK] Request failed:",t),{error:{message:"AbortError"===t.name?"Request timeout":t.message||"Network error",type:"network",details:t}}}}buildUrl(t,e){const a=`${this.baseUrl}${t}`;if(!e||0===Object.keys(e).length)return a;const i=new URLSearchParams;return Object.entries(e).forEach(([t,e])=>{null!=e&&i.append(t,String(e))}),`${a}?${i.toString()}`}getHeaders(t,e=!1){const a={"x-forwarded-host":this.domain,...t};e?delete a["Content-Type"]:a["Content-Type"]=a["Content-Type"]||"application/json";const i=this.tokenStorage.get();return i&&(a.Authorization=i),a}isMultipartBody(t){return"undefined"!=typeof FormData&&t instanceof FormData}shouldRetry(t){return t>=500&&t<600}delay(t){return new Promise(e=>setTimeout(e,t))}getApiName(t){return t.includes("/products")?"products":t.includes("/product_categories")?"categories":t.includes("/cart")?"cart":t.includes("/orders")?"orders":t.includes("/search")?"search":t.includes("/tags")?"tags":t.includes("/entity_route")?"entityRoutes":"cms"}getTokenStorage(){return this.tokenStorage}clearCache(){this.cache.clear()}}class st{constructor(){this.CART_KEY="CART_CREDENTIALS",this.INVOICE_KEY="INVOICE_CREDENTIALS",this.SHIPPING_KEY="SHIPPING_ADDRESS_CREDENTIALS",this.PAYMENT_KEY="PAYMENT_CREDENTIALS",this.DISCOUNT_KEY="DISCOUNT_CODE_INFO"}getCartCredentials(){return this.getItem(this.CART_KEY)}setCartCredentials(t){this.setItem(this.CART_KEY,t)}clearCartCredentials(){this.removeItem(this.CART_KEY)}getInvoiceCredentials(){return this.getItem(this.INVOICE_KEY)}setInvoiceCredentials(t){this.setItem(this.INVOICE_KEY,t)}clearInvoiceCredentials(){this.removeItem(this.INVOICE_KEY)}getShippingCredentials(){return this.getItem(this.SHIPPING_KEY)}setShippingCredentials(t){this.setItem(this.SHIPPING_KEY,t)}clearShippingCredentials(){this.removeItem(this.SHIPPING_KEY)}getPaymentCredentials(){return this.getItem(this.PAYMENT_KEY)}setPaymentCredentials(t){this.setItem(this.PAYMENT_KEY,t)}clearPaymentCredentials(){this.removeItem(this.PAYMENT_KEY)}getDiscountCode(){return this.getItem(this.DISCOUNT_KEY)}setDiscountCode(t){this.setItem(this.DISCOUNT_KEY,t)}clearDiscountCode(){this.removeItem(this.DISCOUNT_KEY)}clearAll(){this.clearCartCredentials(),this.clearInvoiceCredentials(),this.clearShippingCredentials(),this.clearPaymentCredentials(),this.clearDiscountCode()}getItem(t){if("undefined"==typeof localStorage)return null;try{const e=localStorage.getItem(t);return e?JSON.parse(e):null}catch(e){return console.error(`[Sazito SDK] Error reading ${t} from localStorage:`,e),null}}setItem(t,e){if("undefined"!=typeof localStorage)try{localStorage.setItem(t,JSON.stringify(e))}catch(e){console.error(`[Sazito SDK] Error writing ${t} to localStorage:`,e)}else console.warn("[Sazito SDK] localStorage not available")}removeItem(t){if("undefined"!=typeof localStorage)try{localStorage.removeItem(t)}catch(e){console.error(`[Sazito SDK] Error removing ${t} from localStorage:`,e)}}}const ot="/api/v1/product_categories",ct="/api/v1/search",dt="/api/v2/carts",pt="/api/v2/invoices",ut="/api/v2/shipping_addresses",lt="/api/v2/payments",mt="/api/v1/orders",ht="/api/v1/users",yt="/api/v1/sessions",gt="/api/v1/feedbacks",ft="/api/v1/cms_pages",_t="/api/v1/images",bt="/api/v1/scheduler/events",vt="/api/v1/scheduler/bookings",wt="/api/v1/entity_route/route",Pt="/api/v1/feedbacks/comments/details";class At{constructor(t){this.http=t}mapSortToApi(t){if(!t)return null;return{newest:{sort:"date"},"best-selling":{sort:"sold"},availability:{sort:"stock_status"},discount:{sort:"raw_price"},"!price":{sort:"price",sortOrder:"asc"},price:{sort:"price"}}[t]||null}transformFilters(t){if(!t)return{};const e={},a=[];if(t.categories){const e=Array.isArray(t.categories)?t.categories:[t.categories];e.length>0&&a.push({name:"product_categories",value:e.join(",")})}if(!1===t.availableOnly&&a.push({name:"in_stock"}),t.discountedOnly&&a.push({name:"has_raw_price",value:!0}),t.similarTo&&a.push({name:"similar_to",value:{entity_name:"product",entity_id:t.similarTo}}),a.length>0&&(e["filters[]"]=JSON.stringify(a)),t.pinnedIds&&t.pinnedIds.length>0&&(e.pinned_ids=JSON.stringify(t.pinnedIds)),t.sort){const a=this.mapSortToApi(t.sort);a&&(e.sort=a.sort,a.sortOrder&&(e.sort_order=a.sortOrder))}return void 0!==t.priceMin&&(e.min_price=t.priceMin),void 0!==t.priceMax&&(e.max_price=t.priceMax),t.page&&(e.page=t.page),t.pageSize&&(e.page_size=t.pageSize),e}async get(t,e){const a=t.startsWith("/product/")?t:`/product/${t}`,i=await this.http.get(wt,{...e,params:{url_part:a}});if(i.data){const t=X(i.data);return"product"===t.entityType&&t.entity?{data:t.entity}:"unknown"===t.entityType?{error:{message:"Product not found",type:"api",status:404}}:{error:{message:`Invalid entity type: expected 'product', got '${t.entityType}'`,type:"api",status:400}}}return i.error?{error:i.error}:{error:{message:"No data returned from product endpoint",type:"api"}}}async list(t,e){const a=this.transformFilters(t),i=await this.http.get("/api/v1/products",{...e,params:a});if(i.data){return{data:j(i.data)}}return i}async search(t,e,a){const i={query:t,search_direction:"center",page_size:e?.pageSize||20,page_number:e?.page||1},r=await this.http.get(ct,{...a,params:i});if(r.data){return{data:B(r.data)}}return r}}class It{constructor(t){this.http=t}async get(t,e){const a=await this.http.get(`${ot}/${t}`,e);if(a.data){const t=function(t){const e=m(t);return e?W(e.productCategory||e):{}}(a.data);return{data:t}}return a}async list(t,e){const a={};void 0!==t?.page&&(a.page_number=t.page),void 0!==t?.pageSize&&(a.page_size=t.pageSize);const i=await this.http.get(ot,{...e,params:a});if(i.data){const t=function(t){const e=m(t);return e?(e.categories&&Array.isArray(e.categories)&&(e.categories=e.categories.map(H)),d(e.tree)&&d(e.tree.treeStructure)&&Array.isArray(e.tree.treeStructure.nodes)&&(e.tree.treeStructure.nodes=e.tree.treeStructure.nodes.map(tt)),e):{}}(i.data);return{data:t}}return i}}class Ct{constructor(t,e){this.http=t,this.credentials=e}persistCartCredentials(t){this.credentials.setCartCredentials({id:t.id,identifier:t.identifier})}async get(t){const e=this.credentials.getCartCredentials();if(!e)return{error:{message:"No cart found. Please create a cart first.",type:"validation"}};const a=await this.http.get(`${dt}/${e.id}`,{...t,params:{identifier:e.identifier}});return a.data?{data:I(a.data)}:(a.error&&this.clearCart(),a)}async create(t,e){const a=await this.http.post(dt,t,e);if(!a.data)return a;const i=I(a.data);return this.persistCartCredentials(i),{data:i}}async addItem(t,e,a,i){return this.addItemWithAttributes(t,e,{formAttributes:a},i)}async addItemWithAttributes(t,e,a,i){const r=this.credentials.getCartCredentials();if(!r)return this.create({variants:[{id:t,count:e,formAttributes:a?.formAttributes}],schedulerBookingAttributes:a?.schedulerBookingAttributes,coupon:a?.coupon},i);const n=await this.http.post(`${dt}/${r.id}/add_products_to_cart`,{identifier:r.identifier,variants:[{id:t,count:e}],formAttributes:a?.formAttributes,schedulerBookingAttributes:a?.schedulerBookingAttributes,coupon:a?.coupon},i);if(n.data){const t=I(n.data);return this.persistCartCredentials(t),{data:t}}return 422===n.error?.status&&this.clearCart(),n}async updateItem(t,e,a,i,r){return this.updateItemWithAttributes(t,e,a,{formAttributes:i},r)}async updateItemWithAttributes(t,e,a,i,r){const n=this.credentials.getCartCredentials();if(!n)return{error:{message:"No cart found",type:"validation"}};const s=await this.http.post(`${dt}/${n.id}/update_products_in_cart`,{identifier:n.identifier,cartProductId:String(t),variants:[{id:e,count:a}],formAttributes:i?.formAttributes,coupon:i?.coupon,deleteCoupon:i?.deleteCoupon},r);if(s.data){const t=I(s.data);return this.persistCartCredentials(t),{data:t}}return s}async removeItem(t,e,a){const i=this.credentials.getCartCredentials();if(!i)return{error:{message:"No cart found",type:"validation"}};const r=await this.http.post(`${dt}/${i.id}/remove_products_from_cart`,{identifier:i.identifier,cartProductId:String(t),variants:[{id:e}]},a);if(r.data){const t=I(r.data);return this.persistCartCredentials(t),{data:t}}return r}clearCart(){this.credentials.clearCartCredentials()}}class St{constructor(t){this.http=t}async list(t,e){const a={page_number:t?.pageNumber??1,page_size:t?.pageSize??100};return t?.filters&&t.filters.length>0&&(a.filters=JSON.stringify(t.filters)),this.http.get(mt,{...e,params:a})}async get(t,e){return this.http.get(`${mt}/${t}`,e)}}class zt{constructor(t,e){this.http=t,this.credentials=e}normalizeInvoiceResponse(t){return t.data?{data:C(t.data)}:(423===t.error?.status&&this.credentials.clearInvoiceCredentials(),t)}async get(t){const e=this.credentials.getCartCredentials(),a=this.credentials.getInvoiceCredentials();if(!a)return{error:{message:"No invoice found. Please create an invoice first.",type:"validation"}};if(!e)return{error:{message:"No cart found. Please create or restore cart credentials first.",type:"validation"}};const i=await this.http.post(`${pt}/${a.id}/refresh`,{cart_id:String(e.id),cart_identifier:e.identifier,identifier:a.identifier},t);return this.normalizeInvoiceResponse(i)}async create(t){const e=this.credentials.getCartCredentials();if(!e)return{error:{message:"No cart found. Please create a cart first.",type:"validation"}};const a=await this.http.post(pt,{cart_id:String(e.id),cart_identifier:e.identifier},t);if(a.data){const t=C(a.data);return this.credentials.setInvoiceCredentials({id:t.id,identifier:t.identifier}),{data:t}}return a}async refresh(t){const e=this.credentials.getCartCredentials(),a=this.credentials.getInvoiceCredentials();if(!e||!a)return{error:{message:"No cart or invoice found",type:"validation"}};const i=await this.http.post(`${pt}/${a.id}/refresh`,{cart_id:String(e.id),cart_identifier:e.identifier,identifier:a.identifier},t);return this.normalizeInvoiceResponse(i)}async addShippingAddress(t,e,a){const i=this.credentials.getCartCredentials(),r=this.credentials.getInvoiceCredentials();if(!i||!r)return{error:{message:"No cart or invoice found",type:"validation"}};const n=await this.http.post(`${pt}/${r.id}/add_shipping_address`,{identifier:r.identifier,shipping_address_id:t,shipping_address_identifier:e,cart_id:i.id,cart_identifier:i.identifier},a);return this.normalizeInvoiceResponse(n)}async addDiscountCode(t,e){const a=this.credentials.getInvoiceCredentials();if(!a)return{error:{message:"No invoice found",type:"validation"}};const i=await this.http.post(`${pt}/${a.id}/add_discount_code`,{identifier:a.identifier,discount_code:t.toUpperCase()},e);return i.data?(this.credentials.setDiscountCode(t.toUpperCase()),{data:C(i.data)}):i}async assignShippingMethod(t,e){const a=this.credentials.getInvoiceCredentials();if(!a)return{error:{message:"No invoice found",type:"validation"}};const i=t.map(t=>({...t,invoiceItemIds:t.invoiceItemIds.map(t=>String(t))})),r=await this.http.post(`${pt}/${a.id}/add_shipping_method`,{identifier:a.identifier,shippings:i},e);return this.normalizeInvoiceResponse(r)}async addDetails(t,e){const a=this.credentials.getInvoiceCredentials();if(!a)return{error:{message:"No invoice found",type:"validation"}};const i=await this.http.post(`${pt}/${a.id}/add_invoice_details`,{identifier:a.identifier,user_comment:t},e);return this.normalizeInvoiceResponse(i)}async addForm(t,e){const a=this.credentials.getInvoiceCredentials();if(!a)return{error:{message:"No invoice found",type:"validation"}};const i=await this.http.post(`${pt}/${a.id}/add_form`,{invoiceIdentifier:t.invoiceIdentifier||t.identifier||a.identifier,formAttributes:t.formAttributes},e);return this.normalizeInvoiceResponse(i)}async addCredit(t){const e=this.credentials.getInvoiceCredentials();if(!e)return{error:{message:"No invoice found",type:"validation"}};const a=await this.http.post(`${pt}/${e.id}/add_credit`,{identifier:e.identifier},t);return this.normalizeInvoiceResponse(a)}async removeCredit(t){const e=this.credentials.getInvoiceCredentials();if(!e)return{error:{message:"No invoice found",type:"validation"}};const a=await this.http.post(`${pt}/${e.id}/remove_credit`,{identifier:e.identifier},t);return this.normalizeInvoiceResponse(a)}async toggleCredit(t){const e=await this.get(t);return e.data?e.data.creditTotal>0?this.removeCredit(t):this.addCredit(t):e}async getApplicableShippingMethods(t){const e=this.credentials.getInvoiceCredentials();if(!e)return{error:{message:"No invoice found",type:"validation"}};const a=await this.http.get(`${pt}/${e.id}/applicable_shipping_methods`,{...t,params:{identifier:e.identifier}});return a.data?{data:Y(a.data)}:a}clearInvoice(){this.credentials.clearInvoiceCredentials()}}class Et{constructor(t,e){this.http=t,this.credentials=e}sanitizeAddressInput(t){const e={...t};return delete e.user,e}async createAddress(t,e){const a=this.sanitizeAddressInput(t),i=await this.http.post(ut,{shipping_address:a},e);if(i.data){const t=S(i.data);return t?(this.credentials.setShippingCredentials({id:t.id,identifier:t.identifier}),{data:t}):i}return i}async updateAddress(t,e){const a=this.credentials.getShippingCredentials();if(!a)return this.createAddress(t,e);const i=this.sanitizeAddressInput(t),r=await this.http.post(ut,{identifier:a.identifier,shipping_address:i},e);if(r.data){const t=S(r.data);return t?(this.credentials.setShippingCredentials({id:t.id,identifier:t.identifier}),{data:t}):r}return r}async getAddress(t){const e=this.credentials.getShippingCredentials();if(!e)return{error:{message:"No shipping address found",type:"validation"}};const a=await this.http.get(`${ut}/${e.id}`,{...t,params:{identifier:e.identifier}});if(a.data){const t=S(a.data);return t?{data:t}:a}return a}async getMethods(t){const e=await this.http.get("/api/v2/shipping_methods",t);return e.data?{data:L(e.data)}:e.error?{error:e.error}:{data:[]}}clearAddress(){this.credentials.clearShippingCredentials()}}class Tt{constructor(t,e){this.http=t,this.credentials=e,this.pinchedPayments=new Set}async getMethods(t){const e=this.credentials.getInvoiceCredentials();if(!e)return{error:{message:"No invoice found",type:"validation"}};const a=await this.http.post(`${lt}/list`,{invoice_identifier:e.identifier},t);return a.data?{data:q(a.data)}:a.error?{error:a.error}:{data:[]}}async create(t,e){if(!Number.isInteger(t)||t<=0)return{error:{message:"Invalid paymentTypeId. Provide a positive integer from payments.getMethods().",type:"validation"}};const a=this.credentials.getInvoiceCredentials();if(!a)return{error:{message:"No invoice found",type:"validation"}};const i=await this.http.post(lt,{invoice_identifier:a.identifier,payment_type:t},e);if(i.data){const t=this.normalizePayment(i.data);return this.credentials.setPaymentCredentials({id:t.id,identifier:t.identifier}),{data:t}}return i}async initialize(t){const e=this.credentials.getPaymentCredentials();if(!e)return{error:{message:"No payment found. Please create a payment first.",type:"validation"}};const a=await this.http.post(`${lt}/${e.id}/process_payment_step`,{paymentIdentifier:e.identifier},this.withExactJsonHeader(t));if(!a.data)return a;const i=this.normalizeAction(a.data);return await this.callPinchAfterSuccessfulPayment(i,e.id,t),{data:i}}async processStep(t,e){const a=this.credentials.getPaymentCredentials();if(!a)return{error:{message:"No payment found",type:"validation"}};const{paymentIdentifier:i,...r}=t,n=await this.http.post(`${lt}/${a.id}/process_payment_step`,{paymentIdentifier:i||a.identifier,...r},this.withExactJsonHeader(e));if(!n.data)return n;const s=this.normalizeAction(n.data);return await this.callPinchAfterSuccessfulPayment(s,a.id,e),{data:s}}async processStepForm(t,e){const a=this.credentials.getPaymentCredentials();if(!a)return{error:{message:"No payment found",type:"validation"}};const i=this.buildProcessStepFormData(t,a.identifier);if(!i)return{error:{message:"FormData is not available in this runtime.",type:"validation"}};const r=await this.http.post(`${lt}/${a.id}/process_payment_step`,i,e);if(!r.data)return r;const n=this.normalizeAction(r.data);return await this.callPinchAfterSuccessfulPayment(n,a.id,e),{data:n}}async pollUntilSettled(t,e=15e3){let a=!0;for(;a;){const i=await this.initialize(t);if(!i.data)return i;if("pending"!==i.data.action)return a=!1,i;await new Promise(t=>setTimeout(t,e))}return{error:{message:"Payment polling exited unexpectedly",type:"network"}}}clearPayment(){this.credentials.clearPaymentCredentials()}withExactJsonHeader(t){const e={...t?.headers||{}};return delete e["Content-Type"],delete e["content-type"],{...t,headers:{...e,"Content-Type":"application/json"}}}buildProcessStepFormData(t,e){if("undefined"==typeof FormData)return null;if(t instanceof FormData)return t.has("payment_identifier")||t.append("payment_identifier",e),t;const a=l(t),i=new FormData;return Object.entries(a).forEach(([t,e])=>{this.appendFormValue(i,t,e)}),i.has("payment_identifier")||i.append("payment_identifier",e),i}appendFormValue(t,e,a){void 0!==a&&(null!==a?Array.isArray(a)?a.forEach(a=>this.appendFormValue(t,e,a)):"object"!=typeof a?t.append(e,String(a)):t.append(e,JSON.stringify(a)):t.append(e,""))}normalizePayment(t){if(!t||"object"!=typeof t)return t;if("paymentType"in t&&t.paymentType&&"object"==typeof t.paymentType&&"title"in t.paymentType){const e={...t.paymentType};return delete e.title,{...t,paymentType:e}}return t}normalizeAction(t){return"show_order"===t?.action?{...t,action:"showOrder"}:t}async callPinchAfterSuccessfulPayment(t,e,a){if("showOrder"!==t.action)return;if(this.pinchedPayments.has(e))return;this.pinchedPayments.add(e);(await this.http.post("/api/v1/pinch/order",{},a)).error&&this.pinchedPayments.delete(e)}}class kt{constructor(t){this.http=t}normalizeUserResponse(t){if(!t.data)return t;const e=z(t.data);return e?{data:e}:t}normalizeLoginResponse(t){if(!t.data||!t.data.user)return t;const e=z(t.data.user);return e?{data:{...t.data,user:e}}:t}async login(t,e){const a=await this.http.post(`${yt}/login`,t,e);return this.normalizeLoginResponse(a)}async requestMobileOTP(t,e){return this.http.post(`${yt}/login_request`,t,e)}async verifyMobileOTP(t,e){const a=await this.http.post(`${yt}/login_request_verification`,t,e);return this.normalizeLoginResponse(a)}async requestEmailLogin(t,e){return this.http.post(`${ht}/email_login_request`,t,e)}async register(t,e){const a=await this.http.post(`${ht}/register`,t,e);return this.normalizeUserResponse(a)}async getCurrentUser(t){const e=await this.http.get(`${ht}/current`,t);return this.normalizeUserResponse(e)}async updateProfile(t,e,a){const i=await this.http.put(`${ht}/${t}`,e,a);return this.normalizeUserResponse(i)}async requestMobilePhoneUpdate(t,e){return this.http.post(`${ht}/update_mobile_phone_request`,t,e)}async verifyMobilePhoneUpdate(t,e){const a=await this.http.post(`${ht}/update_mobile_phone_verification`,t,e);return this.normalizeUserResponse(a)}async forgotPassword(t,e){return this.http.post(`${ht}/forgot_password`,t,e)}async revivePassword(t,e){const a=await this.http.post(`${ht}/revive_password`,t,e);return this.normalizeLoginResponse(a)}async mergeUser(t){return this.http.post(`${ht}/merge_user`,{},t)}}class Nt{constructor(t){this.http=t}transformFilters(t){if(!t)return{};const e={};return void 0!==t.page&&(e.page_number=t.page),void 0!==t.pageSize&&(e.page_size=t.pageSize),void 0!==t.categoryId&&(e.category_id=t.categoryId),void 0!==t.minPrice&&(e.min_price=t.minPrice),void 0!==t.maxPrice&&(e.max_price=t.maxPrice),e}async query(t,e,a){const i=this.transformFilters(e),r=await this.http.get(ct,{...a,params:{...i,query:t,page_number:i.page_number??1,page_size:i.page_size??20,search_direction:"center"}});if(r.data){return{data:B(r.data)}}return r}}class xt{constructor(t){this.http=t}normalizeSeedItem(t){return{productId:String(t?.productId??""),productVariantId:String(t?.productVariantId??""),productName:String(t?.productName??t?.name??""),productAttributes:Array.isArray(t?.productAttributes)?t.productAttributes:Array.isArray(t?.attributes)?t.attributes:[],productImage:t?.productImage||t?.image||{url:"",alt:""}}}normalizeSeed(t){const e=Array.isArray(t?.items)?t.items:[];return{orderId:String(t?.orderId??""),orderIdentifier:String(t?.orderIdentifier??""),hasCommentAlready:Boolean(t?.hasCommentAlready),items:e.map(t=>this.normalizeSeedItem(t))}}normalizeProductReview(t){const e=t?.metadata||{};return{...t,metadata:{variantOptions:Array.isArray(e.variantOptions)?e.variantOptions:[],productName:String(e.productName??e.name??""),variantId:String(e.variantId??"")}}}normalizeProductReviewsResponse(t){const e=Array.isArray(t?.entities)?t.entities:[],a=t?.recommendations||{};return{entities:e.map(t=>this.normalizeProductReview(t)),pageNumber:Number(t?.pageNumber??1),pageSize:Number(t?.pageSize??10),totalCount:Number(t?.totalCount??e.length),averageRate:Number(t?.averageRate??0),recommendations:{recommendedPercentage:Number(a.recommendedPercentage??0),recommendedTotalCount:Number(a.recommendedTotalCount??0)}}}transformLegacyFilters(t){if(!t)return{};const e={};return void 0!==t.productId&&(e.product_id=t.productId),void 0!==t.page&&(e.page=t.page),void 0!==t.pageSize&&(e.page_size=t.pageSize),e}async getSeed(t,e){const a=await this.http.get(`/api/v1/feedbacks/seed/${t}`,e);if(a.data){const t=a.data.seed||a.data.data||a.data;return{data:this.normalizeSeed(t)}}return a}async createOrderRating(t,e){const a=await this.http.post("/api/v1/feedbacks/comments",t,e);if(a.data){const t=a.data.id??a.data.commentId??a.data.comment?.id;return{data:{id:String(t??"")}}}return a}async submitProductReview(t,e){return this.http.post(Pt,t,e)}async getProductStatistics(t,e){const a=await this.http.get(`${Pt}/${t}`,{...e,params:{exclude:"comments"}});if(a.data){return{data:{productStatistics:a.data.productStatistics||a.data.data?.productStatistics||a.data}}}return a}async getProductReviews(t,e,a){const i=await this.http.get(`${Pt}/${t}`,{...a,params:{page_number:e?.pageNumber??1,page_size:e?.pageSize??10}});if(i.data){const t=i.data.data||i.data;return{data:this.normalizeProductReviewsResponse(t)}}return i}async uploadReviewImages(t,e){const a=new FormData;t.forEach((t,e)=>{a.append("images[][file]",t.file),a.append("images[][name]",t.name||`image-${e+1}`),a.append("images[][alt]",t.alt||t.name||`image-${e+1}`)});const i=await this.http.post("/api/v1/service/filemanager/uploads/public/tajrobe",a,e);if(i.data){return{data:{images:Array.isArray(i.data.images)?i.data.images:Array.isArray(i.data.data?.images)?i.data.data.images:Array.isArray(i.data.result?.images)?i.data.result.images:[]}}}return i}async list(t,e){return this.http.get(gt,{...e,params:this.transformLegacyFilters(t)})}async create(t,e){return this.http.post(gt,t,e)}async get(t,e){return this.http.get(`${gt}/${t}`,e)}}class $t{constructor(t){this.http=t}validateInvoiceId(t){return!Number.isFinite(t)||t<=0?{error:{message:"Invalid invoice ID",type:"validation"}}:null}async getBalance(t){return this.http.get("/api/v1/users/wallet/balance",t)}async listTransactions(t,e){const a=t?.page_number??1,i=t?.page_size??100;return this.http.get("/api/v1/wallet/transactions",{...e,params:{page_number:a,page_size:i}})}async applyCredit(t,e){const a=this.validateInvoiceId(t);return a||this.http.post(`${pt}/${t}/add_credit`,{},e)}async removeCredit(t,e){const a=this.validateInvoiceId(t);return a||this.http.post(`${pt}/${t}/remove_credit`,{},e)}}class Rt{constructor(t){this.http=t}async getPage(t,e){const a=await this.http.get(wt,{...e,params:{url_part:t}}),i=X(a.data);if("cms_page"!==i.entityType)throw new Error(`Expected CMS page at ${t}, but got ${i.entityType}`);if("blog"===i.entity.cmsPageType)throw new Error(`Expected CMS page at ${t}, but got blog page`);return{...a,data:i.entity}}async listPages(t,e){const a=at({...t,cmsPageTypes:"normal"}),i=await this.http.get(ft,{...e,params:a});return{...i,data:et(i.data)}}async getBlogPost(t,e){const a=await this.http.get(wt,{...e,params:{url_part:t}}),i=X(a.data);if("cms_page"!==i.entityType)throw new Error(`Expected blog post at ${t}, but got ${i.entityType}`);if("blog"!==i.entity.cmsPageType)throw new Error(`Expected blog post at ${t}, but got CMS page`);return{...a,data:i.entity}}async listBlogPosts(t,e){const a=at({...t,cmsPageTypes:"blog"}),i=await this.http.get(ft,{...e,params:a});return{...i,data:et(i.data)}}async listAll(t,e){const a=at(t),i=await this.http.get(ft,{...e,params:a});return{...i,data:et(i.data)}}}class Ot{constructor(t){this.http=t}async upload(t,e){const a=new FormData;a.append("image",t);const i={...e?.headers};return delete i["Content-Type"],this.http.post(_t,a,{...e,headers:i})}async delete(t,e){return this.http.delete(`${_t}/${t}`,e)}}class Dt{constructor(t){this.http=t}async track(t,e){const a=e??((i=t)&&"object"==typeof i&&("retries"in i||"timeout"in i||"cache"in i||"headers"in i||"signal"in i)?t:void 0);var i;return this.http.post("/api/v1/visits/add",void 0,a)}async trackProduct(t,e,a){return this.track(a)}async trackCategory(t,e,a){return this.track(a)}}class Gt{constructor(t){this.http=t}transformEventFilters(t){if(!t)return{};const e={};return void 0===t.startDate&&void 0===t.start_date||(e.start_date=t.startDate??t.start_date),void 0===t.endDate&&void 0===t.end_date||(e.end_date=t.endDate??t.end_date),void 0===t.availableOnly&&void 0===t.available_only||(e.available_only=t.availableOnly??t.available_only),void 0!==t.page&&(e.page=t.page),void 0===t.pageSize&&void 0===t.page_size||(e.page_size=t.pageSize??t.page_size),e}async listEvents(t,e){return this.http.get(bt,{...e,params:this.transformEventFilters(t)})}async getEvent(t,e){const a=await this.http.get(`${bt}/${t}`,e);if(a.data){return{data:a.data.event||a.data}}return a}async getEventAvailabilities(t,e){const a=await this.http.get("/api/v1/scheduler/availabilities",{...e,params:{eventEntityId:t.eventEntityId,duration:t.duration,fromDate:t.fromDate,toDate:t.toDate,timezone:t.timezone}});if(a.data){return{data:{availableDays:a.data.availableDays||a.data.data?.availableDays||[]}}}return a}async createBooking(t,e){return this.http.post(vt,t,e)}async listBookings(t){return this.http.get(vt,t)}async cancelBooking(t,e){return this.http.post(`${vt}/${t}/cancel`,{},e)}}class Ft{constructor(t){this.http=t}async resolve(t,e){const a=await this.http.get(wt,{...e,params:{url_part:t}});if(a.data){return{data:X(a.data)}}return a}}class Mt{constructor(t){this.http=t}async getHeaderMenu(t="headermenu",e){const a=await this.http.get("/api/v1/trees/fetch_single",{...e,params:{identifier:t}}),i=a.data?rt(a.data):a.data,r=i?.tree?.treeStructure?.nodes||[],n=this.convertRawTreeToNavigation(r);return{...a,data:n}}convertRawTreeToNavigation(t){if(!t||0===t.length)return[];return t.map(t=>({name:this.findNodeTitle(t),url:this.findNodeUrl(t),children:this.convertRawTreeToNavigation(t.children||[]),shouldBeDropped:this.shouldDropNode(t)})).filter(t=>!t.shouldBeDropped).map(({shouldBeDropped:t,...e})=>e)}findNodeTitle(t){const{entityType:e,details:a,entity:i}=t;return a&&!a.isTitleDefault&&a.title?a.title:a&&!a.isTitleDefault&&a.name?a.name:"product_category"===e||"product"===e?i?.name||"":("cms_page"===e||"blog_page"===e)&&i?.name||""}findNodeUrl(t){return"product"===t.entityType||"product_category"===t.entityType||"cms_page"===t.entityType||"blog_page"===t.entityType?t.entity?.url||"#":"url"===t.entityType&&t.details?.url||"#"}shouldDropNode(t){return("product"===t.entityType||"product_category"===t.entityType||"cms_page"===t.entityType||"blog_page"===t.entityType)&&!t.entity?.enabled}}class Kt{constructor(t){this.http=t}async getInfo(t){const e=await this.http.get("/api/v2/general/info",t);return e.data?{data:h(e.data)}:e.error?{error:e.error}:{error:{type:"api",message:"No data returned from general info endpoint."}}}async getFeatures(t){const e=await this.getInfo(t);return e.error?{error:e.error}:{data:e.data?.settings?.features}}async getCheckoutConfig(t){const e=await this.getInfo(t);return e.error?{error:e.error}:{data:e.data?.settings?.checkout}}async getWalletConfig(t){const e=await this.getInfo(t);return e.error?{error:e.error}:{data:e.data?.settings?.wallet}}async getTajrobeConfig(t){const e=await this.getInfo(t);return e.error?{error:e.error}:{data:e.data?.settings?.tajrobe}}}class Ut{constructor(t){this.http=t}normalizeField(t){return{key:String(t?.key??""),name:String(t?.name??""),type:t?.type,label:String(t?.label??""),value:t?.value,placeholder:String(t?.placeholder??""),required:Boolean(t?.required),inputOptions:Array.isArray(t?.inputOptions)?t.inputOptions:[],allowedExtensions:Array.isArray(t?.allowedExtensions)?t.allowedExtensions:[]}}normalizeForm(t){const e=Array.isArray(t?.fields)?t.fields:[];return{id:Number(t?.id??0),title:String(t?.title??t?.name??""),description:String(t?.description??""),fields:e.map(t=>this.normalizeField(t))}}async getForm(t,e){const a=await this.http.get(`/api/v1/dynamic_form/${t}`,e);if(a.data){const t=a.data.form||a.data.data||a.data;return{data:this.normalizeForm(t)}}return a}async uploadProductFormFile(t,e){const a=new FormData;a.append("file",t);const i=await this.http.post("/api/v1/service/filemanager/uploads/private/productform",a,e);if(i.data){const t=i.data?.data?.file?.serveKey||i.data?.file?.serveKey||i.data?.serveKey;return{data:{serveKey:String(t??"")}}}return i}}function jt(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function Bt(t){if("number"==typeof t&&Number.isFinite(t))return t;if("string"==typeof t){const e=Number(t);return Number.isFinite(e)?e:0}return 0}function qt(t){return"string"==typeof t?t.trim():""}class Lt{constructor(t){this.http=t}normalizeCity(t){return jt(t)?{id:Bt(t.id),name:qt(t.name),latitude:Bt(t.latitude),longitude:Bt(t.longitude)}:{id:0,name:"",latitude:0,longitude:0}}normalizeRegion(t){if(!jt(t))return{id:0,name:"",cities:[]};const e=Array.isArray(t.cities)?t.cities:[];return{id:Bt(t.id),name:qt(t.name),cities:e.map(t=>this.normalizeCity(t)).filter(t=>t.id>0&&t.name.length>0)}}extractRegions(t){return Array.isArray(t)?t:jt(t)?Array.isArray(t.regions)?t.regions:Array.isArray(t.items)?t.items:[]:[]}sortAlphabetically(t){return[...t].map(t=>({...t,cities:[...t.cities].sort((t,e)=>t.name.localeCompare(e.name,"fa"))})).sort((t,e)=>t.name.localeCompare(e.name,"fa"))}async list(t){const e=await this.http.get("/api/v2/regions",t);if(e.error)return{error:e.error};const a=this.extractRegions(e.data).map(t=>this.normalizeRegion(t)).filter(t=>t.id>0&&t.name.length>0);return{data:this.sortAlphabetically(a)}}}class Yt{constructor(t){const a=e(t);this.http=new nt(a),this.tokenStorage=this.http.getTokenStorage(),this.credentialsManager=new st,this.products=new At(this.http),this.categories=new It(this.http),this.cart=new Ct(this.http,this.credentialsManager),this.invoices=new zt(this.http,this.credentialsManager),this.shipping=new Et(this.http,this.credentialsManager),this.payments=new Tt(this.http,this.credentialsManager),this.orders=new St(this.http),this.users=new kt(this.http),this.search=new Nt(this.http),this.feedbacks=new xt(this.http),this.wallet=new $t(this.http),this.cms=new Rt(this.http),this.images=new Ot(this.http),this.visits=new Dt(this.http),this.booking=new Gt(this.http),this.entityRoutes=new Ft(this.http),this.menu=new Mt(this.http),this.general=new Kt(this.http),this.dynamicForms=new Ut(this.http),this.regions=new Lt(this.http)}setAuthToken(t){this.tokenStorage.set(t)}getAuthToken(){return this.tokenStorage.get()}clearAuth(){this.tokenStorage.remove()}isAuthenticated(){return null!==this.tokenStorage.get()}clearCache(){this.http.clearCache()}clearCredentials(){this.credentialsManager.clearAll()}clearAll(){this.clearAuth(),this.clearCache(),this.clearCredentials()}async searchQuery(t,e,a){return this.search.query(t,e,a)}}function Vt(t){return function(t){if(!t||"object"!=typeof t)return!1;const e=t;return e.http instanceof nt&&e.credentials instanceof st}(t)?t:function(t){const a=e(t);return{http:new nt(a),credentials:new st}}(t)}function Qt(t){const{http:e}=Vt(t);return new At(e)}function Wt(t){const{http:e}=Vt(t);return new It(e)}function Ht(t){const{http:e,credentials:a}=Vt(t);return new Ct(e,a)}function Jt(t){const{http:e}=Vt(t);return new St(e)}function Zt(t){const{http:e,credentials:a}=Vt(t);return new zt(e,a)}function Xt(t){const{http:e,credentials:a}=Vt(t);return new Et(e,a)}function te(t){const{http:e,credentials:a}=Vt(t);return new Tt(e,a)}function ee(t){const{http:e}=Vt(t);return new kt(e)}function ae(t){const{http:e}=Vt(t);return new Nt(e)}function ie(t){const{http:e}=Vt(t);return new xt(e)}function re(t){const{http:e}=Vt(t);return new $t(e)}function ne(t){const{http:e}=Vt(t);return new Rt(e)}function se(t){const{http:e}=Vt(t);return new Ot(e)}function oe(t){const{http:e}=Vt(t);return new Dt(e)}function ce(t){const{http:e}=Vt(t);return new Gt(e)}function de(t){const{http:e}=Vt(t);return new Ft(e)}function pe(t){const{http:e}=Vt(t);return new Mt(e)}function ue(t){const{http:e}=Vt(t);return new Kt(e)}function le(t){const{http:e}=Vt(t);return new Ut(e)}function me(t){const{http:e}=Vt(t);return new Lt(e)}exports.CredentialsManager=st,exports.HttpClient=nt,exports.SazitoClient=Yt,exports.TokenStorage=a,exports.booking=ce,exports.cart=Ht,exports.categories=Wt,exports.cms=ne,exports.createBookingAPI=ce,exports.createCMSAPI=ne,exports.createCartAPI=Ht,exports.createCategoriesAPI=Wt,exports.createDynamicFormsAPI=le,exports.createEntityRoutesAPI=de,exports.createFeedbacksAPI=ie,exports.createGeneralAPI=ue,exports.createImagesAPI=se,exports.createInvoicesAPI=Zt,exports.createMenuAPI=pe,exports.createOrdersAPI=Jt,exports.createPaymentsAPI=te,exports.createProductsAPI=Qt,exports.createRegionsAPI=me,exports.createSazitoClient=function(t){return new Yt(t)},exports.createSearchAPI=ae,exports.createShippingAPI=Xt,exports.createUsersAPI=ee,exports.createVisitsAPI=oe,exports.createWalletAPI=re,exports.dynamicForms=le,exports.entityRoutes=de,exports.feedbacks=ie,exports.general=ue,exports.images=se,exports.invoices=Zt,exports.menu=pe,exports.orders=Jt,exports.payments=te,exports.products=Qt,exports.regions=me,exports.search=ae,exports.shipping=Xt,exports.transformAddToCartInput=function(t,e,a){const i={product_variants:[{id:t,count:e}]};return a&&(i.form_attributes=l(a)),i},exports.transformApiResponse=m,exports.transformCartResponse=I,exports.transformCreateCartInput=function(t){if(!d(t))return{product_variants:[]};const e=t.variants||t.productVariants||[],a={product_variants:Array.isArray(e)?e.map(t=>d(t)?{id:t.id||t.variantId,count:t.count||t.quantity,form_attributes:t.formAttributes?l(t.formAttributes):void 0}:{}):[]};return t.coupon&&(a.coupon=t.coupon),a},exports.transformInvoiceResponse=C,exports.transformProductListResponse=j,exports.transformRequestKeys=l,exports.transformResponseKeys=u,exports.transformShippingAddressInput=function(t){if(d(t)){const e={...t};return delete e.user,{shipping_address:l(e)}}return{shipping_address:l(t)}},exports.users=ee,exports.visits=oe,exports.wallet=re;