@sazito/client-sdk 1.2.4 → 1.2.5

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/README.md CHANGED
@@ -438,6 +438,22 @@ pnpm lint # ESLint on src/
438
438
  pnpm validate # typecheck + lint
439
439
  ```
440
440
 
441
+ ### Releases
442
+
443
+ Run releases from a clean Git worktree. The release script checks npm authentication,
444
+ validates each package, bumps its version, publishes it, creates a package-specific
445
+ commit and tag, and pushes the resulting refs. When releasing both packages, the SDK
446
+ is published before checkout.
447
+
448
+ ```bash
449
+ pnpm release:checkout -- patch
450
+ pnpm release:sdk -- patch
451
+ pnpm release:all -- patch
452
+ ```
453
+
454
+ Use `minor` or `major` instead of `patch` when needed. Pass `--no-push` to leave the
455
+ release commits and tags local, or `--yes` to skip confirmation in CI.
456
+
441
457
  ## Fumadocs Documentation Site
442
458
 
443
459
  SDK docs are implemented as a separate Fumadocs app in `docs/`.
package/dist/index.d.mts CHANGED
@@ -238,6 +238,9 @@ interface UploadedFormFileAttribute {
238
238
  type FormAttributeValue = string | number | boolean | null | UploadedFormFileAttribute;
239
239
  interface CartProduct {
240
240
  id: number | string;
241
+ /** When this line was first added to the cart. */
242
+ createdAt?: string;
243
+ updatedAt?: string;
241
244
  productVariantId: number;
242
245
  quantity: number;
243
246
  unitPrice: number;
@@ -481,6 +484,8 @@ interface Order {
481
484
  }
482
485
  interface OrdersListResponse {
483
486
  orders: Order[];
487
+ pageNumber?: number;
488
+ pageSize?: number;
484
489
  totalCount: number;
485
490
  totalCountRaw: number;
486
491
  totalNotSeen: number;
@@ -1598,11 +1603,18 @@ interface Wallet extends WalletBalance {
1598
1603
  transactions?: WalletTransaction[];
1599
1604
  }
1600
1605
  interface TransactionFilters {
1606
+ pageNumber?: number;
1607
+ pageSize?: number;
1608
+ /** @deprecated Use `pageNumber`. */
1601
1609
  page_number?: number;
1610
+ /** @deprecated Use `pageSize`. */
1602
1611
  page_size?: number;
1603
1612
  }
1604
1613
  interface WalletTransactionsResponse {
1605
1614
  transactions: WalletTransaction[];
1615
+ pageNumber?: number;
1616
+ pageSize?: number;
1617
+ totalCount?: number;
1606
1618
  }
1607
1619
  declare class WalletAPI {
1608
1620
  private http;
package/dist/index.d.ts CHANGED
@@ -238,6 +238,9 @@ interface UploadedFormFileAttribute {
238
238
  type FormAttributeValue = string | number | boolean | null | UploadedFormFileAttribute;
239
239
  interface CartProduct {
240
240
  id: number | string;
241
+ /** When this line was first added to the cart. */
242
+ createdAt?: string;
243
+ updatedAt?: string;
241
244
  productVariantId: number;
242
245
  quantity: number;
243
246
  unitPrice: number;
@@ -481,6 +484,8 @@ interface Order {
481
484
  }
482
485
  interface OrdersListResponse {
483
486
  orders: Order[];
487
+ pageNumber?: number;
488
+ pageSize?: number;
484
489
  totalCount: number;
485
490
  totalCountRaw: number;
486
491
  totalNotSeen: number;
@@ -1598,11 +1603,18 @@ interface Wallet extends WalletBalance {
1598
1603
  transactions?: WalletTransaction[];
1599
1604
  }
1600
1605
  interface TransactionFilters {
1606
+ pageNumber?: number;
1607
+ pageSize?: number;
1608
+ /** @deprecated Use `pageNumber`. */
1601
1609
  page_number?: number;
1610
+ /** @deprecated Use `pageSize`. */
1602
1611
  page_size?: number;
1603
1612
  }
1604
1613
  interface WalletTransactionsResponse {
1605
1614
  transactions: WalletTransaction[];
1615
+ pageNumber?: number;
1616
+ pageSize?: number;
1617
+ totalCount?: number;
1606
1618
  }
1607
1619
  declare class WalletAPI {
1608
1620
  private http;
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,r]=e.trim().split("=");return a&&r&&(t[a]=decodeURIComponent(r)),t},{})}setCookie(t,e,a){let r=`${t}=${encodeURIComponent(e)}`;void 0!==a.maxAge&&(r+=`; Max-Age=${a.maxAge}`),a.path&&(r+=`; Path=${a.path}`),a.domain&&(r+=`; Domain=${a.domain}`),a.secure&&(r+="; Secure"),a.httpOnly&&(r+="; HttpOnly"),a.sameSite&&(r+=`; SameSite=${a.sameSite}`),document.cookie=r}}class r{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,r)=>{e.test(r)&&a.push(r)}),a.forEach(t=>this.cache.delete(t))}clear(){this.cache.clear()}static generateKey(t,e,a){return`${t}:${e}:${a?JSON.stringify(a):""}`}}const i=new Set(["mobile_phone","phone_number"]);function n(t){return t.replace(/[۰-۹٠-٩]/g,t=>{const e=t.charCodeAt(0);return String(e>=1776?e-1776:e-1632)})}const s={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"},o=Object.values(s).reduce((t,e)=>(t[e]=(t[e]||0)+1,t),{}),d=Object.entries(s).reduce((t,[e,a])=>(1===o[a]&&(t[a]=e),t),{});function c(t){return t.replace(/_([a-z])/g,(t,e)=>e.toUpperCase())}function p(t){return t.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function u(t){return!(null===t||"object"!=typeof t||Array.isArray(t)||t instanceof Date)}function l(t,e){const a={...t};for(const t of e)delete a[t];return a}function m(t){if(!u(t))return Array.isArray(t)?t.map(t=>m(t)):t;const e={};for(const[a,r]of Object.entries(t)){let t=s[a];t||(t=c(a)),u(r)?e[t]=m(r):Array.isArray(r)?e[t]=r.map(t=>m(t)):e[t]=r}return e}function h(t){if(!u(t))return Array.isArray(t)?t.map(t=>h(t)):t;const e={};for(const[a,r]of Object.entries(t)){let t=d[a];t||(t=p(a)),u(r)?e[t]=h(r):Array.isArray(r)?e[t]=r.map(t=>h(t)):e[t]="string"==typeof r&&i.has(t)?n(r):r}return e}function y(t){const e=t;if(u(e?.data?.result)){const t=e.data.result,a=Object.keys(t);return 1===a.length&&u(t[a[0]])?m(t[a[0]]):m(t)}return m(t)}function g(t){if(!t)return{};if(!u(t))return{};const{general:e,shop:a,checkout:r,features:i,wallet:n,tajrobe:s,domain:o,enamad:d,google:c,logo:p,social:l,...m}=t,h={...u(e)?e:{},...u(a)?a:{}},{registerType:y,showProductStockNumber:g,...w}=h||{};return{...m,scripts:{enamad:d,google:c},shop:v({...w,domain:o,logo:p,social:l}),settings:{checkout:f(r),features:I(i),wallet:C(n),tajrobe:S(s),registerType:_(y),showProductStockNumber:b(g)}}}function f(t){if(!u(t))return{};const e=u(t.minBasket)?t.minBasket:{},a=e.minAmount??e.minBasket,r="number"==typeof a?a:Number(a),i={...t,addToCartAlert:b(t.addToCartAlert),dynamicForm:b(t.dynamicForm),emailOptional:b(t.emailOptional??t.email_optional),preventRedirect:b(t.preventRedirect??t.manual),minBasket:{enabled:b(e.enabled),minAmount:Number.isFinite(r)?r:0},miniCart:b(t.miniCart),postalCodeMandatory:b(t.postalCodeMandatory),quickAddToCart:b(t.quickAddToCart)};return delete i.manual,i}function _(t){return"string"==typeof t?t:""}function b(t){return"boolean"==typeof t?t:u(t)&&Object.prototype.hasOwnProperty.call(t,"enabled")?b(t.enabled):1===t||"1"===t||"true"===t}function v(t){if(!u(t))return{};const e={...t};if(u(e.city)){const t=l(e.city,["createdAt","updatedAt"]);let a=t.region;u(a)&&(a=l(a,["createdAt","updatedAt","cities"])),t.region=a,e.city=t}return e}const w={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"},A=new Set(["activateAlopeykAdvanced","activate_alopeyk_advanced"]),P=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 I(t){if(!u(t))return{};const e={},a=(t,a)=>{if(A.has(t))return;const r=(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!==r&&(e[t]=r)};u(t.flags)&&Object.entries(t.flags).forEach(([t,e])=>{a(t,e)}),u(t.configurations)&&Object.entries(t.configurations).forEach(([t,e])=>{a(t,e)}),Object.entries(t).forEach(([t,e])=>{"flags"!==t&&"premium"!==t&&"configurations"!==t&&(u(e)&&Object.prototype.hasOwnProperty.call(e,"enabled")?a(t,e.enabled):a(t,e))});const r={};Object.entries(e).forEach(([t,e])=>{const a=function(t){const e=t.includes("_")?c(t):t,a=w[e];if(a)return a;const r=e.startsWith("activate")&&e.length>8?`${e.charAt(8).toLowerCase()}${e.slice(9)}`:e;return r.endsWith("Enabled")||r.endsWith("Disabled")||r.endsWith("Hidden")||r.endsWith("Removed")?r:`${r}Enabled`}(t);P.has(a)||(r[a]=e)});const i={...r};return u(t.premium)&&(i.premium=t.premium),i}function C(t){if(!u(t))return{};const e=u(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 S(t){if(!u(t))return{};const e=u(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 z(t){const e=y(t);if(!u(e))return{};const a=Array.isArray(e.items)?e.items.map(t=>function(t){if(!u(t))return{};const e=B(t),a=G(t.productVariantId??e.variantId)??e.variantId;return{id:j(t.id??t.cartProductId)??"",productVariantId:a,quantity:G(t.quantity)??0,unitPrice:G(t.unitPrice)??0,lineTotal:G(t.lineTotal)??0,product:e,formAttributes:t.formAttributes,formFields:t.formFields,bookingAttributes:t.bookingAttributes}}(t)):[];return{...e,items:a,netTotal:G(e.netTotal)??0,grossTotal:G(e.grossTotal),needsShipping:Boolean(e.needsShipping),minBasketLimitViolated:Boolean(e.minBasketLimitViolated),deleteCoupon:void 0===e.deleteCoupon?void 0:Boolean(e.deleteCoupon)}}function E(t){const e=y(t);if(!u(e))return{};const a=l(e,["shippingMethod","user","userData"]),r=Array.isArray(e.items)?e.items.map(t=>function(t){if(!u(t))return{};const e=B(t),a=G(t.productVariantId??e.variantId)??e.variantId,r=Array.isArray(e.attributes)?e.attributes:[],i=M(e.hasMaxOrder??t.hasMaxOrder);return{id:j(t.id??t.invoiceItemId??t.cartProductId)??"",productVariantId:a,productId:G(e.productId??t.productId),name:F(t.name)??F(e.name)??"",url:F(e.url)??F(t.url),attributes:r,productType:F(e.productType)??F(t.productType),hasMaxOrder:i,maxOrderQuantity:G(e.maxOrderQuantity??t.maxOrderQuantity),minOrderQuantity:G(e.minOrderQuantity??t.minOrderQuantity),image:K(t.image??e.image),quantity:G(t.quantity)??0,unitPrice:G(t.unitPrice)??0,lineTotal:G(t.lineTotal)??0,rawPrice:G(t.rawPrice??t.originalPrice)??0,customerProfit:G(t.customerProfit)??0,commercialFiles:t.commercialFiles,formAttributes:t.formAttributes,bookingAttributes:t.bookingAttributes,formFields:t.formFields}}(t)):[],i=Array.isArray(e.discountUsages)?e.discountUsages:[],n=i[0],s=u(n)&&u(n.discountCode)?F(n.discountCode.code):void 0;return{...a,items:r,shippingAddress:function(t){if(!t)return;const{id:e,city:a,region:r,...i}=t,n={id:r?.id??a.regionId??0,name:r?.name??"",city:a};return{...i,region:n}}(x(e.shippingAddress)),shippingItems:Array.isArray(e.shippingItems)?e.shippingItems.map(t=>function(t){if(!u(t))return{};const e=u(t.rate)?t.rate:u(t.shippingRate)?t.shippingRate:u(t.shippingMethod)?t.shippingMethod:t;return{invoiceItemIds:D(t),rate:H(e)}}(t)):[],discountUsages:i,netTotal:G(e.netTotal)??0,finalTotal:G(e.finalTotal)??0,vat:G(e.vat)??0,vatPercent:G(e.vatPercent)??0,itemsDiscount:G(e.itemsDiscount)??0,discountTotal:G(e.discountTotal)??0,customerProfit:G(e.customerProfit)??0,customerProfitPercentage:G(e.customerProfitPercentage)??0,itemsTotalRawPrice:G(e.itemsTotalRawPrice)??0,couponTotal:G(e.couponTotal)??0,shippingTotal:G(e.shippingTotal)??0,creditTotal:G(e.creditTotal)??0,needsShipping:Boolean(e.needsShipping),userComment:"string"==typeof e.userComment?e.userComment:void 0,discountCode:s}}function T(t){return x(t)}function k(t){const e=y(t);if(u(e))return N(e)}function N(t){if(!t)return;const e=function(t){const e=O(t);if(!e)return;if(1===Object.keys(e).length&&u(e.user))return O(e.user)??e.user;return e}(t);if(!e)return;const a={},r=G(e.id);void 0!==r&&(a.id=r);const i=F(e.email);i&&(a.email=i);const n=F(e.mobilePhone)??F(e.phoneNumber);n&&(a.mobilePhone=n);const s=F(e.phoneNumber);s&&s!==n&&(a.phoneNumber=s);const o=F(e.firstName);o&&(a.firstName=o);const d=F(e.lastName);d&&(a.lastName=d);const c=F(e.birthDate);return c&&(a.birthDate=c),Object.keys(a).length>0?a:void 0}function x(t){if(!t||0===Object.keys(t).length)return;const e=N(t.user),a=O(t.region),r=O(t.city),i=O(r?.region),n=F(t.regionName)??$(t.region),s=R(a??t.region,{fallbackId:G(t.regionId),fallbackName:n})??R(i,{fallbackId:G(t.regionId),fallbackName:n}),o=G(t.regionId)??s?.id,d=F(t.cityName)??F(r?.name)??$(t.city),c=function(t,e={}){if(null==t)return;const a=O(t),r=G(a?.id)??G(t)??e.fallbackId,i=F(a?.name)??$(t)??e.fallbackName;if(void 0===r||!i)return;const n={id:r,name:i},s=G(a?.regionId)??e.fallbackRegionId;void 0!==s&&(n.regionId=s);const o=G(a?.latitude);void 0!==o&&(n.latitude=o);const d=G(a?.longitude);void 0!==d&&(n.longitude=d);return n}(r??t.city,{fallbackId:G(t.cityId),fallbackName:d,fallbackRegionId:o}),p=F(t.firstName)??e?.firstName??"",u=F(t.lastName)??e?.lastName??"",l={id:G(t.id)??0,identifier:F(t.identifier)??"",firstName:p,lastName:u,city:c??{id:G(t.cityId??t.city)??0,name:d??"",...void 0!==o?{regionId:o}:{}},address:F(t.address)??""},m=F(t.mobilePhone)??F(t.phoneNumber)??e?.mobilePhone??e?.phoneNumber,h=F(t.phoneNumber)??e?.phoneNumber;m&&(l.mobilePhone=m),h&&h!==m&&(l.phoneNumber=h);const y=F(t.email)??e?.email;y&&(l.email=y),s&&(l.region=s);const g=F(t.postalCode);g&&(l.postalCode=g);const f=F(t.description);f&&(l.description=f);const _=G(t.latitude);void 0!==_&&(l.latitude=_);const b=G(t.longitude);void 0!==b&&(l.longitude=b);const v=M(t.userSetCoordinatesBefore);return void 0!==v&&(l.userSetCoordinatesBefore=v),l}function R(t,e={}){if(null==t)return;const a=O(t),r=G(a?.id)??G(t)??e.fallbackId,i=F(a?.name)??$(t)??e.fallbackName;return void 0!==r&&i?{id:r,name:i}:void 0}function O(t){if(u(t))return u(t.data)?t.data:t}function $(t){const e=F(t);if(e)return void 0===G(e)?e:void 0}function D(t){return(Array.isArray(t.invoiceItemIds)?t.invoiceItemIds:void 0!==t.invoiceItemId?[t.invoiceItemId]:[]).map(t=>j(t)).filter(t=>void 0!==t)}function G(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 F(t){if("string"!=typeof t)return;const e=t.trim();return e.length>0?e:void 0}function M(t){return"boolean"==typeof t?t:1===t||"1"===t||"true"===t||0!==t&&"0"!==t&&"false"!==t&&void 0}function j(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 B(t){if(!u(t))return{variantId:0,name:"",attributes:[]};const e=u(t.variant)?t.variant:void 0,a=u(e?.product)?e.product:void 0,r=u(t.product)?t.product:void 0,i=G(r?.variantId??e?.id??t.productVariantId??t.variantId)??0,n=Array.isArray(r?.attributes)?r.attributes:Array.isArray(e?.attributes)?e.attributes:Array.isArray(t.attributes)?t.attributes:[];return{variantId:i,productId:G(r?.productId??t.productId??a?.id),name:F(r?.name)??F(t.name)??"",url:F(r?.url)??F(t.url)??F(a?.url),image:K(r?.image??t.image),attributes:n,productType:F(r?.productType)??F(t.productType)??F(a?.productType),hasMaxOrder:r?.hasMaxOrder??t.hasMaxOrder??e?.hasMaxOrder,maxOrderQuantity:G(r?.maxOrderQuantity??t.maxOrderQuantity??e?.maxOrderQuantity),minOrderQuantity:G(r?.minOrderQuantity??t.minOrderQuantity??e?.minOrderQuantity)}}function U(t){if(!u(t))return{};const e=l(t,["staticUrl","summary","tags","slug"]);return e.variants&&Array.isArray(e.variants)&&(e.variants=e.variants.map(t=>u(t)?l(t,["name","title","product","status","soldCount"]):{})),e.categories&&Array.isArray(e.categories)&&(e.categories=e.categories.map(t=>u(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 u(t)?l(t,["widthRatio","heightRatio","thumb","order"]):t}function q(t){const e=U(t);return e?l(e,["themeConfig"]):e}function L(t){const e=y(t);if(e.items&&Array.isArray(e.items)){const t=G(e.total)??e.items.length,a=G(e.pageSize)??e.items.length,r=G(e.page)??1,i=G(e.totalPages)??Math.ceil(t/a);return{items:e.items.map(t=>q(t)),total:t,page:r,pageSize:a,totalPages:i}}return e}function Y(t){if(!u(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=>q(t)),a.products.total=G(e.productsCount)??0,a.products.page=G(e.productsPageNumber)??1,a.products.pageSize=G(e.productsPageSize)??20),Array.isArray(e.blogPages)&&(a.blogPages.items=e.blogPages.map(t=>tt(t)),a.blogPages.total=G(e.blogPagesCount)??0,a.blogPages.page=G(e.blogPagesPageNumber)??1,a.blogPages.pageSize=G(e.blogPagesPageSize)??20),Array.isArray(e.cmsPages)&&(a.cmsPages.items=e.cmsPages.map(t=>tt(t)),a.cmsPages.total=G(e.cmsPagesCount)??0,a.cmsPages.page=G(e.cmsPagesPageNumber)??1,a.cmsPages.pageSize=G(e.cmsPagesPageSize)??20),Array.isArray(e.categories)&&(a.productCategories.items=e.categories.map(t=>Z(t)),a.productCategories.total=G(e.productCategoriesCount)??0,a.productCategories.page=G(e.productCategoriesPageNumber)??1,a.productCategories.pageSize=G(e.productCategoriesPageSize)??20),a}function V(t){const e=y(t);if(!u(e))return[];return(Array.isArray(e.paymentTypes)?e.paymentTypes:Array.isArray(e.methods)?e.methods:[]).map(t=>u(t)?{id:G(t.id)??0,code:t.code,title:"string"==typeof t.title?t.title:"",titleFa:"string"==typeof t.titleFa?t.titleFa:"",description:"string"==typeof t.description?t.description:null,paymentSubType:G(t.paymentSubType)??null,order:G(t.order)??0,isDefault:Boolean(t.isDefault)}:{id:0,code:"",title:"",titleFa:"",description:null,paymentSubType:null,order:0,isDefault:!1})}function Q(t){const e=y(t);return(Array.isArray(e)?e:u(e)&&Array.isArray(e.shippingMethods)?e.shippingMethods:[]).map(t=>function(t){if(!u(t))return{id:0,name:"",type:""};return{id:G(t.id)??0,name:F(t.name)??"",type:F(t.type)??""}}(t))}function W(t){const e=y(t);if(!u(e))return{shippingMethods:[],groupedShippingRates:{},itemsShippingRate:[]};const a={};if(Array.isArray(e.shippingMethods)&&e.shippingMethods.forEach((t,e)=>{if(!u(t))return;const r=Array.isArray(t.shippingRate)?t.shippingRate.map(t=>H(t)):[];if(0===r.length)return;const i=Array.isArray(t.invoiceItemIds)?t.invoiceItemIds:[],n=i.length>0?i.map(String).sort().join(","):String(e);a[n]=r}),0===Object.keys(a).length&&u(e.groupedShippingRates))for(const[t,r]of Object.entries(e.groupedShippingRates))a[t]=Array.isArray(r)?r.map(t=>H(t)):[];return{shippingMethods:[],groupedShippingRates:a,itemsShippingRate:Array.isArray(e.itemsShippingRate)?e.itemsShippingRate.map(t=>u(t)?{invoiceItemId:j(t.invoiceItemId)??D(t)[0]??"",shippingRate:H(t.shippingRate??t.rate??t)}:{invoiceItemId:"",shippingRate:H(void 0)}):[]}}function H(t){return u(t)?{id:G(t.id??t.rateId)??0,name:F(t.name)??"",price:G(t.price??t.amount)??0,description:F(t.description??t.deliveryDescription??t.details),icon:F(t.icon??t.iconUrl??t.logo),color:F(t.color??t.bgColor??t.backgroundColor??t.iconColor),type:F(t.type)}:{id:0,name:"",price:0}}function J(t){return u(t)?l(t,["staticUrl","products","items"]):{}}function Z(t){const e=J(t);return e?l(e,["themeConfig"]):{}}function X(t){return u(t)?l(t,["staticUrl","urlKey"]):{}}function tt(t){const e=X(t);return e?l(e,["themeConfig"]):{}}function et(t){const e=y(t);if(!e||!e.route)return e??{};const a=u(e.route)?e.route:{};if(a.entity){switch(a.entityType){case"product":a.entity=U(a.entity);break;case"product_category":a.entity=J(a.entity);break;case"cms_page":case"blog_page":a.entity=X(a.entity)}u(a.entity)&&(a.entity=l(a.entity,["id"])),!a.url&&u(a.entity)&&a.entity.url&&(a.url=a.entity.url)}return a}function at(t){if(!u(t))return{};const e={...t};return e.entity&&(e.entity=Z(e.entity),u(e.entity)&&(e.entity=l(e.entity,["id"]))),e.children&&Array.isArray(e.children)&&(e.children=e.children.map(at)),e}function rt(t){const e=y(t);return e?e.cmsPages&&Array.isArray(e.cmsPages)?{items:e.cmsPages.map(tt),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=>tt(t)),total:e.total||e.items.length,page:e.page||1,pageSize:e.pageSize||e.items.length}:e:{}}function it(t){if(!u(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 nt(t){if(!u(t))return{};const e={};if(t.entityType&&(e.entityType=t.entityType),void 0!==t.entityId&&(e.entityId=t.entityId),u(t.entity)){const a=l(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=>nt(t))),e}function st(t){const e=y(t);if(!e||!e.tree)return e??{};const a=u(e.tree)?e.tree:{};return u(a.treeStructure)&&Array.isArray(a.treeStructure.nodes)&&(a.treeStructure.nodes=a.treeStructure.nodes.map(t=>nt(t))),e}class ot{constructor(t){this.config=t,this.baseUrl="http://api.sazito.com:8080",this.domain=t.domain,this.tokenStorage=new a,this.cache=new r,this.fetchApi=t.customFetchApi.bind(globalThis)}async get(t,e){const a=this.buildUrl(t,e?.params),i=r.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(i,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(i,n.data),n}async post(t,e,a){const r=this.buildUrl(t),i=this.isMultipartBody(e),n=e?i?e:h(e):void 0,s=this.getApiName(t);return this.cache.deletePattern(`GET:.*${s}`),this.request("POST",r,{...a,body:n,rawBody:i,omitJsonContentType:i})}async put(t,e,a){const r=this.buildUrl(t),i=this.isMultipartBody(e),n=e?i?e:h(e):void 0,s=this.getApiName(t);return this.cache.deletePattern(`GET:.*${s}`),this.request("PUT",r,{...a,body:n,rawBody:i,omitJsonContentType:i})}async delete(t,e){const a=this.buildUrl(t),r=this.getApiName(t);return this.cache.deletePattern(`GET:.*${r}`),this.request("DELETE",a,e)}async request(t,e,a,r=0){const i=new AbortController,n=a?.signal||i.signal,s=a?.timeout||this.config.timeout,o=setTimeout(()=>i.abort(),s);try{const i=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(!i.ok&&this.shouldRetry(i.status)&&r<s)return this.config.debug&&console.log(`[Sazito SDK] Retrying request (${r+1}/${s}):`,e),await this.delay(this.config.retry.retryDelay*(r+1)),this.request(t,e,a,r+1);const d=i.headers.get("content-type");let c;if(c=d?.includes("application/json")?await i.json():await i.text(),a?.skipTransform&&i.ok)return{data:c};const p=void 0!==c?.result?c.result:c;this.config.debug&&console.log(`[Sazito SDK] ${t} ${e}:`,{status:i.status,data:p});let u=p?m(p):p;const l=["cart","product","user","order","invoice","payment","shippingAddress"];if(u&&"object"==typeof u&&!Array.isArray(u)){const t=Object.keys(u);1===t.length&&l.includes(t[0])&&"object"==typeof u[t[0]]&&null!==u[t[0]]&&(u=u[t[0]])}return i.ok?{data:u}:{error:{status:i.status,message:u?.message||p?.message||i.statusText||"Request failed",type:"api",details:u}}}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 r=new URLSearchParams;return Object.entries(e).forEach(([t,e])=>{null!=e&&r.append(t,String(e))}),`${a}?${r.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 r=this.tokenStorage.get();return r&&(a.Authorization=r),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 dt{constructor(){this.data=new Map}getItem(t){return this.data.get(t)??null}setItem(t,e){this.data.set(t,e)}removeItem(t){this.data.delete(t)}}class ct{constructor(t){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",this.storage=t??("undefined"!=typeof window&&"undefined"!=typeof localStorage&&"function"==typeof localStorage.getItem?localStorage:new dt)}getCartCredentials(){const t=this.getItem(this.CART_KEY),e=t?.identifier?.trim();return e?{identifier:e}:null}setCartCredentials(t){const e=t.identifier.trim();if(!e)throw new Error("Cart identifier is required.");this.setItem(this.CART_KEY,{identifier:e})}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){try{const e=this.storage.getItem(t);return e?JSON.parse(e):null}catch{return null}}setItem(t,e){try{this.storage.setItem(t,JSON.stringify(e))}catch{}}removeItem(t){try{this.storage.removeItem(t)}catch{}}}const pt="/api/v1/product_categories",ut="/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",At="/api/v1/scheduler/events",Pt="/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}`,r=await this.http.get(It,{...e,params:{url_part:a}});if(r.data){const t=et(r.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 r.error?{error:r.error}:{error:{message:"No data returned from product endpoint",type:"api"}}}async list(t,e){const a=this.transformFilters(t),r=await this.http.get("/api/v1/products",{...e,params:a});if(r.data){return{data:L(r.data)}}return r}async search(t,e,a){const r={query:t,search_direction:"center",page_size:e?.pageSize||20,page_number:e?.page||1},i=await this.http.get(ut,{...a,params:r});if(i.data){return{data:Y(i.data)}}return i}}class zt{constructor(t){this.http=t}async get(t,e){const a=await this.http.get(`${pt}/${t}`,e);if(a.data){const t=function(t){const e=y(t);return e?J(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 r=await this.http.get(pt,{...e,params:a});if(r.data){const t=function(t){const e=y(t);return e?(e.categories&&Array.isArray(e.categories)&&(e.categories=e.categories.map(Z)),u(e.tree)&&u(e.tree.treeStructure)&&Array.isArray(e.tree.treeStructure.nodes)&&(e.tree.treeStructure.nodes=e.tree.treeStructure.nodes.map(at)),e):{}}(r.data);return{data:t}}return r}}class Et{constructor(t,e){this.http=t,this.credentials=e}persistCartCredentials(t){this.credentials.setCartCredentials({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}/0`,{...t,params:{identifier:e.identifier}});return a.data?{data:z(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 r=z(a.data);return this.persistCartCredentials(r),{data:r}}async addItem(t,e,a,r){return this.addItemWithAttributes(t,e,{formAttributes:a},r)}async addItemWithAttributes(t,e,a,r){const i=this.credentials.getCartCredentials();if(!i)return this.create({variants:[{id:t,count:e,formAttributes:a?.formAttributes}],schedulerBookingAttributes:a?.schedulerBookingAttributes,coupon:a?.coupon},r);const n=await this.http.post(`${lt}/0/add_products_to_cart`,{identifier:i.identifier,variants:[{id:t,count:e}],formAttributes:a?.formAttributes,schedulerBookingAttributes:a?.schedulerBookingAttributes,coupon:a?.coupon},r);if(n.data){const t=z(n.data);return this.persistCartCredentials(t),{data:t}}return 422===n.error?.status&&this.clearCart(),n}async updateItem(t,e,a,r,i){return this.updateItemWithAttributes(t,e,a,{formAttributes:r},i)}async updateItemWithAttributes(t,e,a,r,i){const n=this.credentials.getCartCredentials();if(!n)return{error:{message:"No cart found",type:"validation"}};const s=await this.http.post(`${lt}/0/update_products_in_cart`,{identifier:n.identifier,cartProductId:String(t),variants:[{id:e,count:a}],formAttributes:r?.formAttributes,coupon:r?.coupon,deleteCoupon:r?.deleteCoupon},i);if(s.data){const t=z(s.data);return this.persistCartCredentials(t),{data:t}}return s}async removeItem(t,e,a){const r=this.credentials.getCartCredentials();if(!r)return{error:{message:"No cart found",type:"validation"}};const i=await this.http.post(`${lt}/0/remove_products_from_cart`,{identifier:r.identifier,cartProductId:String(t),variants:[{id:e}]},a);if(i.data){const t=z(i.data);return this.persistCartCredentials(t),{data:t}}return i}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 kt{constructor(t,e){this.http=t,this.credentials=e}normalizeInvoiceResponse(t){return t.data?{data:E(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 r=await this.http.post(`${mt}/${a.id}/refresh`,{cart_id:String(0),cart_identifier:e.identifier,identifier:a.identifier},t);return this.normalizeInvoiceResponse(r)}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(0),cart_identifier:e.identifier},t);if(a.data){const t=E(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 r=await this.http.post(`${mt}/${a.id}/refresh`,{cart_id:String(0),cart_identifier:e.identifier,identifier:a.identifier},t);return this.normalizeInvoiceResponse(r)}async addShippingAddress(t,e,a){const r=this.credentials.getCartCredentials(),i=this.credentials.getInvoiceCredentials();if(!r||!i)return{error:{message:"No cart or invoice found",type:"validation"}};const n=await this.http.post(`${mt}/${i.id}/add_shipping_address`,{identifier:i.identifier,shipping_address_identifier:e,cart_id:0,cart_identifier:r.identifier,...t>0?{shipping_address_id:t}:{}},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 r=await this.http.post(`${mt}/${a.id}/add_discount_code`,{identifier:a.identifier,discount_code:t.toUpperCase()},e);return r.data?(this.credentials.setDiscountCode(t.toUpperCase()),{data:E(r.data)}):r}async assignShippingMethod(t,e){const a=this.credentials.getInvoiceCredentials();if(!a)return{error:{message:"No invoice found",type:"validation"}};const r=t.map(t=>({...t,invoiceItemIds:t.invoiceItemIds.map(t=>String(t))})),i=await this.http.post(`${mt}/${a.id}/add_shipping_method`,{identifier:a.identifier,shippings:r},e);return this.normalizeInvoiceResponse(i)}async addDetails(t,e){const a=this.credentials.getInvoiceCredentials();if(!a)return{error:{message:"No invoice found",type:"validation"}};const r=await this.http.post(`${mt}/${a.id}/add_invoice_details`,{identifier:a.identifier,user_comment:t},e);return this.normalizeInvoiceResponse(r)}async addForm(t,e){const a=this.credentials.getInvoiceCredentials();if(!a)return{error:{message:"No invoice found",type:"validation"}};const r=await this.http.post(`${mt}/${a.id}/add_form`,{invoiceIdentifier:t.invoiceIdentifier||t.identifier||a.identifier,formAttributes:t.formAttributes},e);return this.normalizeInvoiceResponse(r)}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,cache:t?.cache??!1,params:{identifier:e.identifier}});return a.data?{data:W(a.data)}:a}clearInvoice(){this.credentials.clearInvoiceCredentials()}}class Nt{constructor(t,e){this.http=t,this.credentials=e}sanitizeAddressInput(t){const e={...t};return delete e.user,e}unwrapAddressPayload(t){let e=t;const a=new Set;for(;e&&"object"==typeof e&&!Array.isArray(e)&&!a.has(e);){a.add(e);const t=e,r=t.shippingAddress??t.shipping_address??t.data;if(void 0===r)break;e=r}return e}extractAddressList(t){if(Array.isArray(t))return t;if(!t||"object"!=typeof t)return[];const e=t,a=[e.shippingAddresses,e.addresses,e.items,e.data];for(const t of a)if(Array.isArray(t))return t;return[]}async createAddress(t,e){const a=this.sanitizeAddressInput(t),r=await this.http.post(ht,{shipping_address:a},e);if(r.data){const t=T(this.unwrapAddressPayload(r.data));return t?(this.credentials.setShippingCredentials({id:t.id,identifier:t.identifier}),{data:t}):r}return r}async updateAddress(t,e){const a=this.credentials.getShippingCredentials();if(!a)return this.createAddress(t,e);const r=this.sanitizeAddressInput(t),i=await this.http.post(ht,{identifier:a.identifier,shipping_address:r},e);if(i.data){const t=T(this.unwrapAddressPayload(i.data));return t?(this.credentials.setShippingCredentials({id:t.id,identifier:t.identifier}),{data:t}):i}return i}async listAddresses(t){const e=await this.http.get(ht,{...t,cache:t?.cache??!1});if(e.error)return{error:e.error};return{data:this.extractAddressList(e.data).map(t=>T(this.unwrapAddressPayload(t))).filter(t=>Boolean(t?.identifier)).sort((t,e)=>e.id-t.id)}}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=T(this.unwrapAddressPayload(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 xt{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 r=await this.http.post(yt,{invoice_identifier:a.identifier,payment_type:t},{...e,skipTransform:!0});if(r.error)return{error:r.error};if(r.data){const t=r.data,e=t&&"object"==typeof t&&"result"in t?t.result?.payment:t.payment;if(e&&"object"==typeof e){const t=String(e.payment_identifier??""),a=Number(e.id??0),r=e.payment_type,i={id:a,identifier:t,amount:Number(e.payment_amount??0),paymentType:{id:null!=r?.id?Number(r.id):void 0,code:r?.reference_code??""}};return t&&this.credentials.setPaymentCredentials({id:a,identifier:t}),{data:i}}}return{data:r.data}}async initialize(t){return this.submitPaymentStep(void 0,t)}async verify(t,e){return this.submitPaymentStep(t,e)}async processStep(t,e){return this.submitPaymentStep(t,e)}async submitPaymentStep(t,e){const a=this.credentials.getPaymentCredentials();if(!a)return{error:{message:"No payment found. Please create a payment first.",type:"validation"}};const{paymentIdentifier:r,...i}=t??{},n=await this.http.post(`${yt}/${a.id}/process_payment_step`,{paymentIdentifier:r||a.identifier,...i},this.withExactJsonHeader(e));return this.finalizeStepResponse(n,a.id,e)}async processStepForm(t,e){const a=this.credentials.getPaymentCredentials();if(!a)return{error:{message:"No payment found",type:"validation"}};const r=this.buildProcessStepFormData(t,a.identifier);if(!r)return{error:{message:"FormData is not available in this runtime.",type:"validation"}};const i=await this.http.post(`${yt}/${a.id}/process_payment_step`,r,e);return this.finalizeStepResponse(i,a.id,e)}async pollUntilSettled(t,e=15e3){let a=!0;for(;a;){const r=await this.verify(void 0,t);if(!r.data)return r;if("pending"!==r.data.action)return a=!1,r;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=h(t),r=new FormData;return Object.entries(a).forEach(([t,e])=>{this.appendFormValue(r,t,e)}),r.has("payment_identifier")||r.append("payment_identifier",e),r}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,""))}async finalizeStepResponse(t,e,a){if(!t.data)return t;const r=t=>!!t&&"object"==typeof t&&!Array.isArray(t);let i=t.data;if("string"==typeof i)try{i=JSON.parse(i)}catch{return{error:{message:"Invalid payment step response",type:"api"}}}const n=i;if(r(n)){const t="string"==typeof n.error?n.error:"",e=Number(n.error_code??0);if(t||e)return{error:{message:t||"Payment step failed",type:"api",status:Number(n.status)||void 0}}}const s=r(n)&&r(n.result)?n.result:n,o=this.normalizeAction(s);return await this.callPinchAfterSuccessfulPayment(o,e,a),{data:o}}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 Rt{constructor(t){this.http=t}normalizeUserResponse(t){if(!t.data)return t;const e=k(t.data);return e?{data:e}:t}normalizeLoginResponse(t){if(!t.data||!t.data.user)return t;const e=k(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 r=await this.http.put(`${ft}/${t}`,e,a);return this.normalizeUserResponse(r)}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 Ot{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 r=this.transformFilters(e),i=await this.http.get(ut,{...a,params:{...r,query:t,page_number:r.page_number??1,page_size:r.page_size??20,search_direction:"center"}});if(i.data){return{data:Y(i.data)}}return i}}class $t{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 r=await this.http.get(`${Ct}/${t}`,{...a,params:{page_number:e?.pageNumber??1,page_size:e?.pageSize??10}});if(r.data){const t=r.data.data||r.data;return{data:this.normalizeProductReviewsResponse(t)}}return r}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 r=await this.http.post("/api/v1/service/filemanager/uploads/public/tajrobe",a,e);if(r.data){return{data:{images:Array.isArray(r.data.images)?r.data.images:Array.isArray(r.data.data?.images)?r.data.data.images:Array.isArray(r.data.result?.images)?r.data.result.images:[]}}}return r}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 Dt{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,r=t?.page_size??100;return this.http.get("/api/v1/wallet/transactions",{...e,params:{page_number:a,page_size:r}})}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 Gt{constructor(t){this.http=t}async getPage(t,e){const a=await this.http.get(It,{...e,params:{url_part:t}}),r=et(a.data);if("cms_page"!==r.entityType)throw new Error(`Expected CMS page at ${t}, but got ${r.entityType}`);if("blog"===r.entity.cmsPageType)throw new Error(`Expected CMS page at ${t}, but got blog page`);return{...a,data:r.entity}}async listPages(t,e){const a=it({...t,cmsPageTypes:"normal"}),r=await this.http.get(vt,{...e,params:a});return{...r,data:rt(r.data)}}async getBlogPost(t,e){const a=await this.http.get(It,{...e,params:{url_part:t}}),r=et(a.data);if("cms_page"!==r.entityType)throw new Error(`Expected blog post at ${t}, but got ${r.entityType}`);if("blog"!==r.entity.cmsPageType)throw new Error(`Expected blog post at ${t}, but got CMS page`);return{...a,data:r.entity}}async listBlogPosts(t,e){const a=it({...t,cmsPageTypes:"blog"}),r=await this.http.get(vt,{...e,params:a});return{...r,data:rt(r.data)}}async listAll(t,e){const a=it(t),r=await this.http.get(vt,{...e,params:a});return{...r,data:rt(r.data)}}}class Ft{constructor(t){this.http=t}async upload(t,e){const a=new FormData;a.append("image",t);const r={...e?.headers};return delete r["Content-Type"],this.http.post(wt,a,{...e,headers:r})}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??((r=t)&&"object"==typeof r&&("retries"in r||"timeout"in r||"cache"in r||"headers"in r||"signal"in r)?t:void 0);var r;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 jt{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(At,{...e,params:this.transformEventFilters(t)})}async getEvent(t,e){const a=await this.http.get(`${At}/${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(Pt,t,e)}async listBookings(t){return this.http.get(Pt,t)}async cancelBooking(t,e){return this.http.post(`${Pt}/${t}/cancel`,{},e)}}class Bt{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:et(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}}),r=a.data?st(a.data):a.data,i=r?.tree?.treeStructure?.nodes||[],n=this.convertRawTreeToNavigation(i);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{details:e,entity:a}=t,r=this.firstNonEmpty(e?.title,e?.name),i=this.firstNonEmpty(a?.title,a?.name);return!0===e?.isTitleDefault?i||r:r||i}firstNonEmpty(...t){return t.find(t=>"string"==typeof t&&t.trim().length>0)||""}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:g(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 r=await this.http.post("/api/v1/service/filemanager/uploads/private/productform",a,e);if(r.data){const t=r.data?.data?.file?.serveKey||r.data?.file?.serveKey||r.data?.serveKey;return{data:{serveKey:String(t??"")}}}return r}}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,a){const r=e(t);this.http=new ot(r),this.tokenStorage=this.http.getTokenStorage(),this.credentialsManager=a??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 kt(this.http,this.credentialsManager),this.shipping=new Nt(this.http,this.credentialsManager),this.payments=new xt(this.http,this.credentialsManager),this.orders=new Tt(this.http),this.users=new Rt(this.http),this.search=new Ot(this.http),this.feedbacks=new $t(this.http),this.wallet=new Dt(this.http),this.cms=new Gt(this.http),this.images=new Ft(this.http),this.visits=new Mt(this.http),this.booking=new jt(this.http),this.entityRoutes=new Bt(this.http),this.menu=new Ut(this.http),this.general=new Kt(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()}getCredentialsManager(){return this.credentialsManager}clearAll(){this.clearAuth(),this.clearCache(),this.clearCredentials()}async searchQuery(t,e,a){return this.search.query(t,e,a)}}function Ht(t){return function(t){if(!t||"object"!=typeof t)return!1;const e=t;return e.http instanceof ot&&e.credentials instanceof ct}(t)?t:function(t){const a=e(t);return{http:new ot(a),credentials:new ct}}(t)}function Jt(t){const{http:e}=Ht(t);return new St(e)}function Zt(t){const{http:e}=Ht(t);return new zt(e)}function Xt(t){const{http:e,credentials:a}=Ht(t);return new Et(e,a)}function te(t){const{http:e}=Ht(t);return new Tt(e)}function ee(t){const{http:e,credentials:a}=Ht(t);return new kt(e,a)}function ae(t){const{http:e,credentials:a}=Ht(t);return new Nt(e,a)}function re(t){const{http:e,credentials:a}=Ht(t);return new xt(e,a)}function ie(t){const{http:e}=Ht(t);return new Rt(e)}function ne(t){const{http:e}=Ht(t);return new Ot(e)}function se(t){const{http:e}=Ht(t);return new $t(e)}function oe(t){const{http:e}=Ht(t);return new Dt(e)}function de(t){const{http:e}=Ht(t);return new Gt(e)}function ce(t){const{http:e}=Ht(t);return new Ft(e)}function pe(t){const{http:e}=Ht(t);return new Mt(e)}function ue(t){const{http:e}=Ht(t);return new jt(e)}function le(t){const{http:e}=Ht(t);return new Bt(e)}function me(t){const{http:e}=Ht(t);return new Ut(e)}function he(t){const{http:e}=Ht(t);return new Kt(e)}function ye(t){const{http:e}=Ht(t);return new qt(e)}function ge(t){const{http:e}=Ht(t);return new Qt(e)}exports.CredentialsManager=ct,exports.HttpClient=ot,exports.MemoryStorage=dt,exports.SazitoClient=Wt,exports.TokenStorage=a,exports.booking=ue,exports.cart=Xt,exports.categories=Zt,exports.cms=de,exports.createBookingAPI=ue,exports.createCMSAPI=de,exports.createCartAPI=Xt,exports.createCategoriesAPI=Zt,exports.createDynamicFormsAPI=ye,exports.createEntityRoutesAPI=le,exports.createFeedbacksAPI=se,exports.createGeneralAPI=he,exports.createImagesAPI=ce,exports.createInvoicesAPI=ee,exports.createMenuAPI=me,exports.createOrdersAPI=te,exports.createPaymentsAPI=re,exports.createProductsAPI=Jt,exports.createRegionsAPI=ge,exports.createSazitoClient=function(t,e){return new Wt(t,e)},exports.createSearchAPI=ne,exports.createShippingAPI=ae,exports.createUsersAPI=ie,exports.createVisitsAPI=pe,exports.createWalletAPI=oe,exports.dynamicForms=ye,exports.entityRoutes=le,exports.feedbacks=se,exports.general=he,exports.images=ce,exports.invoices=ee,exports.menu=me,exports.orders=te,exports.payments=re,exports.products=Jt,exports.regions=ge,exports.search=ne,exports.shipping=ae,exports.toEnglishDigits=n,exports.transformAddToCartInput=function(t,e,a){const r={product_variants:[{id:t,count:e}]};return a&&(r.form_attributes=h(a)),r},exports.transformApiResponse=y,exports.transformCartResponse=z,exports.transformCreateCartInput=function(t){if(!u(t))return{product_variants:[]};const e=t.variants||t.productVariants||[],a={product_variants:Array.isArray(e)?e.map(t=>u(t)?{id:t.id||t.variantId,count:t.count||t.quantity,form_attributes:t.formAttributes?h(t.formAttributes):void 0}:{}):[]};return t.coupon&&(a.coupon=t.coupon),a},exports.transformInvoiceResponse=E,exports.transformProductListResponse=L,exports.transformRequestKeys=h,exports.transformResponseKeys=m,exports.transformShippingAddressInput=function(t){if(u(t)){const e={...t};return delete e.user,{shipping_address:h(e)}}return{shipping_address:h(t)}},exports.users=ie,exports.visits=pe,exports.wallet=oe;
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,r]=e.trim().split("=");return a&&r&&(t[a]=decodeURIComponent(r)),t},{})}setCookie(t,e,a){let r=`${t}=${encodeURIComponent(e)}`;void 0!==a.maxAge&&(r+=`; Max-Age=${a.maxAge}`),a.path&&(r+=`; Path=${a.path}`),a.domain&&(r+=`; Domain=${a.domain}`),a.secure&&(r+="; Secure"),a.httpOnly&&(r+="; HttpOnly"),a.sameSite&&(r+=`; SameSite=${a.sameSite}`),document.cookie=r}}class r{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,r)=>{e.test(r)&&a.push(r)}),a.forEach(t=>this.cache.delete(t))}clear(){this.cache.clear()}static generateKey(t,e,a){return`${t}:${e}:${a?JSON.stringify(a):""}`}}const i=new Set(["mobile_phone","phone_number"]);function n(t){return t.replace(/[۰-۹٠-٩]/g,t=>{const e=t.charCodeAt(0);return String(e>=1776?e-1776:e-1632)})}const s={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"},o=Object.values(s).reduce((t,e)=>(t[e]=(t[e]||0)+1,t),{}),d=Object.entries(s).reduce((t,[e,a])=>(1===o[a]&&(t[a]=e),t),{});function c(t){return t.replace(/_([a-z])/g,(t,e)=>e.toUpperCase())}function p(t){return t.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function u(t){return!(null===t||"object"!=typeof t||Array.isArray(t)||t instanceof Date)}function l(t,e){const a={...t};for(const t of e)delete a[t];return a}function m(t){if(!u(t))return Array.isArray(t)?t.map(t=>m(t)):t;const e={};for(const[a,r]of Object.entries(t)){let t=s[a];t||(t=c(a)),u(r)?e[t]=m(r):Array.isArray(r)?e[t]=r.map(t=>m(t)):e[t]=r}return e}function h(t){if(!u(t))return Array.isArray(t)?t.map(t=>h(t)):t;const e={};for(const[a,r]of Object.entries(t)){let t=d[a];t||(t=p(a)),u(r)?e[t]=h(r):Array.isArray(r)?e[t]=r.map(t=>h(t)):e[t]="string"==typeof r&&i.has(t)?n(r):r}return e}function y(t){const e=t;if(u(e?.data?.result)){const t=e.data.result,a=Object.keys(t);return 1===a.length&&u(t[a[0]])?m(t[a[0]]):m(t)}return m(t)}function g(t){if(!t)return{};if(!u(t))return{};const{general:e,shop:a,checkout:r,features:i,wallet:n,tajrobe:s,domain:o,enamad:d,google:c,logo:p,social:l,...m}=t,h={...u(e)?e:{},...u(a)?a:{}},{registerType:y,showProductStockNumber:g,...w}=h||{};return{...m,scripts:{enamad:d,google:c},shop:v({...w,domain:o,logo:p,social:l}),settings:{checkout:f(r),features:I(i),wallet:C(n),tajrobe:S(s),registerType:b(y),showProductStockNumber:_(g)}}}function f(t){if(!u(t))return{};const e=u(t.minBasket)?t.minBasket:{},a=e.minAmount??e.minBasket,r="number"==typeof a?a:Number(a),i={...t,addToCartAlert:_(t.addToCartAlert),dynamicForm:_(t.dynamicForm),emailOptional:_(t.emailOptional??t.email_optional),preventRedirect:_(t.preventRedirect??t.manual),minBasket:{enabled:_(e.enabled),minAmount:Number.isFinite(r)?r:0},miniCart:_(t.miniCart),postalCodeMandatory:_(t.postalCodeMandatory),quickAddToCart:_(t.quickAddToCart)};return delete i.manual,i}function b(t){return"string"==typeof t?t:""}function _(t){return"boolean"==typeof t?t:u(t)&&Object.prototype.hasOwnProperty.call(t,"enabled")?_(t.enabled):1===t||"1"===t||"true"===t}function v(t){if(!u(t))return{};const e={...t};if(u(e.city)){const t=l(e.city,["createdAt","updatedAt"]);let a=t.region;u(a)&&(a=l(a,["createdAt","updatedAt","cities"])),t.region=a,e.city=t}return e}const w={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"},A=new Set(["activateAlopeykAdvanced","activate_alopeyk_advanced"]),P=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 I(t){if(!u(t))return{};const e={},a=(t,a)=>{if(A.has(t))return;const r=(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!==r&&(e[t]=r)};u(t.flags)&&Object.entries(t.flags).forEach(([t,e])=>{a(t,e)}),u(t.configurations)&&Object.entries(t.configurations).forEach(([t,e])=>{a(t,e)}),Object.entries(t).forEach(([t,e])=>{"flags"!==t&&"premium"!==t&&"configurations"!==t&&(u(e)&&Object.prototype.hasOwnProperty.call(e,"enabled")?a(t,e.enabled):a(t,e))});const r={};Object.entries(e).forEach(([t,e])=>{const a=function(t){const e=t.includes("_")?c(t):t,a=w[e];if(a)return a;const r=e.startsWith("activate")&&e.length>8?`${e.charAt(8).toLowerCase()}${e.slice(9)}`:e;return r.endsWith("Enabled")||r.endsWith("Disabled")||r.endsWith("Hidden")||r.endsWith("Removed")?r:`${r}Enabled`}(t);P.has(a)||(r[a]=e)});const i={...r};return u(t.premium)&&(i.premium=t.premium),i}function C(t){if(!u(t))return{};const e=u(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 S(t){if(!u(t))return{};const e=u(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 z(t){const e=y(t);if(!u(e))return{};const a=Array.isArray(e.items)?e.items.map(t=>function(t){if(!u(t))return{};const e=q(t),a=j(t.productVariantId??e.variantId)??e.variantId;return{id:K(t.id??t.cartProductId)??"",createdAt:B(t.createdAt),updatedAt:B(t.updatedAt),productVariantId:a,quantity:j(t.quantity)??0,unitPrice:j(t.unitPrice)??0,lineTotal:j(t.lineTotal)??0,product:e,formAttributes:t.formAttributes,formFields:t.formFields,bookingAttributes:t.bookingAttributes}}(t)):[];return{...e,items:a,netTotal:j(e.netTotal)??0,grossTotal:j(e.grossTotal),needsShipping:Boolean(e.needsShipping),minBasketLimitViolated:Boolean(e.minBasketLimitViolated),deleteCoupon:void 0===e.deleteCoupon?void 0:Boolean(e.deleteCoupon)}}function T(t){const e=y(t);if(!u(e))return{};const a=l(e,["shippingMethod","user","userData"]),r=Array.isArray(e.items)?e.items.map(t=>function(t){if(!u(t))return{};const e=q(t),a=j(t.productVariantId??e.variantId)??e.variantId,r=Array.isArray(e.attributes)?e.attributes:[],i=U(e.hasMaxOrder??t.hasMaxOrder);return{id:K(t.id??t.invoiceItemId??t.cartProductId)??"",productVariantId:a,productId:j(e.productId??t.productId),name:B(t.name)??B(e.name)??"",url:B(e.url)??B(t.url),attributes:r,productType:B(e.productType)??B(t.productType),hasMaxOrder:i,maxOrderQuantity:j(e.maxOrderQuantity??t.maxOrderQuantity),minOrderQuantity:j(e.minOrderQuantity??t.minOrderQuantity),image:Y(t.image??e.image),quantity:j(t.quantity)??0,unitPrice:j(t.unitPrice)??0,lineTotal:j(t.lineTotal)??0,rawPrice:j(t.rawPrice??t.originalPrice)??0,customerProfit:j(t.customerProfit)??0,commercialFiles:t.commercialFiles,formAttributes:t.formAttributes,bookingAttributes:t.bookingAttributes,formFields:t.formFields}}(t)):[],i=Array.isArray(e.discountUsages)?e.discountUsages:[],n=i[0],s=u(n)&&u(n.discountCode)?B(n.discountCode.code):void 0;return{...a,items:r,shippingAddress:function(t){if(!t)return;const{id:e,city:a,region:r,...i}=t,n={id:r?.id??a.regionId??0,name:r?.name??"",city:a};return{...i,region:n}}($(e.shippingAddress)),shippingItems:Array.isArray(e.shippingItems)?e.shippingItems.map(t=>function(t){if(!u(t))return{};const e=u(t.rate)?t.rate:u(t.shippingRate)?t.shippingRate:u(t.shippingMethod)?t.shippingMethod:t;return{invoiceItemIds:M(t),rate:X(e)}}(t)):[],discountUsages:i,netTotal:j(e.netTotal)??0,finalTotal:j(e.finalTotal)??0,vat:j(e.vat)??0,vatPercent:j(e.vatPercent)??0,itemsDiscount:j(e.itemsDiscount)??0,discountTotal:j(e.discountTotal)??0,customerProfit:j(e.customerProfit)??0,customerProfitPercentage:j(e.customerProfitPercentage)??0,itemsTotalRawPrice:j(e.itemsTotalRawPrice)??0,couponTotal:j(e.couponTotal)??0,shippingTotal:j(e.shippingTotal)??0,creditTotal:j(e.creditTotal)??0,needsShipping:Boolean(e.needsShipping),userComment:"string"==typeof e.userComment?e.userComment:void 0,discountCode:s}}function E(t){const e=y(t);if(!u(e))return{};if(!u(e.invoice))return e;const a=T(e.invoice),{items:r,...i}=a;return{...e,invoice:{...i,invoiceItems:Array.isArray(r)?r:[]}}}function N(t){const e=y(t);if(!u(e))return{};const a=Array.isArray(e.orders)?e.orders.map(t=>E(t)):[],r=j(e.pageNumber??e.page),i=j(e.pageSize),n=j(e.totalCount??e.total)??a.length;return{...l(e,["page","total"]),orders:a,totalCount:n,...void 0!==r?{pageNumber:r}:{},...void 0!==i?{pageSize:i}:{}}}function k(t){const e=y(t);if(!u(e))return{};const a=Array.isArray(e.transactions)?e.transactions:Array.isArray(e.walletTransactions)?e.walletTransactions:[],r=j(e.pageNumber??e.page),i=j(e.pageSize),n=j(e.totalCount??e.total);return{...l(e,["page","total","walletTransactions"]),transactions:a,...void 0!==r?{pageNumber:r}:{},...void 0!==i?{pageSize:i}:{},...void 0!==n?{totalCount:n}:{}}}function x(t){return $(t)}function R(t){const e=y(t);if(u(e))return O(e)}function O(t){if(!t)return;const e=function(t){const e=G(t);if(!e)return;if(1===Object.keys(e).length&&u(e.user))return G(e.user)??e.user;return e}(t);if(!e)return;const a={},r=j(e.id);void 0!==r&&(a.id=r);const i=B(e.email);i&&(a.email=i);const n=B(e.mobilePhone)??B(e.phoneNumber);n&&(a.mobilePhone=n);const s=B(e.phoneNumber);s&&s!==n&&(a.phoneNumber=s);const o=B(e.firstName);o&&(a.firstName=o);const d=B(e.lastName);d&&(a.lastName=d);const c=B(e.birthDate);return c&&(a.birthDate=c),Object.keys(a).length>0?a:void 0}function $(t){if(!t||0===Object.keys(t).length)return;const e=O(t.user),a=G(t.region),r=G(t.city),i=G(r?.region),n=B(t.regionName)??F(t.region),s=D(a??t.region,{fallbackId:j(t.regionId),fallbackName:n})??D(i,{fallbackId:j(t.regionId),fallbackName:n}),o=j(t.regionId)??s?.id,d=B(t.cityName)??B(r?.name)??F(t.city),c=function(t,e={}){if(null==t)return;const a=G(t),r=j(a?.id)??j(t)??e.fallbackId,i=B(a?.name)??F(t)??e.fallbackName;if(void 0===r||!i)return;const n={id:r,name:i},s=j(a?.regionId)??e.fallbackRegionId;void 0!==s&&(n.regionId=s);const o=j(a?.latitude);void 0!==o&&(n.latitude=o);const d=j(a?.longitude);void 0!==d&&(n.longitude=d);return n}(r??t.city,{fallbackId:j(t.cityId),fallbackName:d,fallbackRegionId:o}),p=B(t.firstName)??e?.firstName??"",u=B(t.lastName)??e?.lastName??"",l={id:j(t.id)??0,identifier:B(t.identifier)??"",firstName:p,lastName:u,city:c??{id:j(t.cityId??t.city)??0,name:d??"",...void 0!==o?{regionId:o}:{}},address:B(t.address)??""},m=B(t.mobilePhone)??B(t.phoneNumber)??e?.mobilePhone??e?.phoneNumber,h=B(t.phoneNumber)??e?.phoneNumber;m&&(l.mobilePhone=m),h&&h!==m&&(l.phoneNumber=h);const y=B(t.email)??e?.email;y&&(l.email=y),s&&(l.region=s);const g=B(t.postalCode);g&&(l.postalCode=g);const f=B(t.description);f&&(l.description=f);const b=j(t.latitude);void 0!==b&&(l.latitude=b);const _=j(t.longitude);void 0!==_&&(l.longitude=_);const v=U(t.userSetCoordinatesBefore);return void 0!==v&&(l.userSetCoordinatesBefore=v),l}function D(t,e={}){if(null==t)return;const a=G(t),r=j(a?.id)??j(t)??e.fallbackId,i=B(a?.name)??F(t)??e.fallbackName;return void 0!==r&&i?{id:r,name:i}:void 0}function G(t){if(u(t))return u(t.data)?t.data:t}function F(t){const e=B(t);if(e)return void 0===j(e)?e:void 0}function M(t){return(Array.isArray(t.invoiceItemIds)?t.invoiceItemIds:void 0!==t.invoiceItemId?[t.invoiceItemId]:[]).map(t=>K(t)).filter(t=>void 0!==t)}function j(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 B(t){if("string"!=typeof t)return;const e=t.trim();return e.length>0?e:void 0}function U(t){return"boolean"==typeof t?t:1===t||"1"===t||"true"===t||0!==t&&"0"!==t&&"false"!==t&&void 0}function K(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 q(t){if(!u(t))return{variantId:0,name:"",attributes:[]};const e=u(t.variant)?t.variant:void 0,a=u(e?.product)?e.product:void 0,r=u(t.product)?t.product:void 0,i=j(r?.variantId??e?.id??t.productVariantId??t.variantId)??0,n=Array.isArray(r?.attributes)?r.attributes:Array.isArray(e?.attributes)?e.attributes:Array.isArray(t.attributes)?t.attributes:[];return{variantId:i,productId:j(r?.productId??t.productId??a?.id),name:B(r?.name)??B(t.name)??"",url:B(r?.url)??B(t.url)??B(a?.url),image:Y(r?.image??t.image),attributes:n,productType:B(r?.productType)??B(t.productType)??B(a?.productType),hasMaxOrder:r?.hasMaxOrder??t.hasMaxOrder??e?.hasMaxOrder,maxOrderQuantity:j(r?.maxOrderQuantity??t.maxOrderQuantity??e?.maxOrderQuantity),minOrderQuantity:j(r?.minOrderQuantity??t.minOrderQuantity??e?.minOrderQuantity)}}function L(t){if(!u(t))return{};const e=l(t,["staticUrl","summary","tags","slug"]);return e.variants&&Array.isArray(e.variants)&&(e.variants=e.variants.map(t=>u(t)?l(t,["name","title","product","status","soldCount"]):{})),e.categories&&Array.isArray(e.categories)&&(e.categories=e.categories.map(t=>u(t)?{id:t.id,name:t.name,url:t.url}:{})),e.images&&Array.isArray(e.images)&&(e.images=e.images.map(t=>Y(t)??{})),e}function Y(t){return u(t)?l(t,["widthRatio","heightRatio","thumb","order"]):t}function V(t){const e=L(t);return e?l(e,["themeConfig"]):e}function Q(t){const e=y(t);if(e.items&&Array.isArray(e.items)){const t=j(e.total)??e.items.length,a=j(e.pageSize)??e.items.length,r=j(e.page)??1,i=j(e.totalPages)??Math.ceil(t/a);return{items:e.items.map(t=>V(t)),total:t,page:r,pageSize:a,totalPages:i}}return e}function W(t){if(!u(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=>V(t)),a.products.total=j(e.productsCount)??0,a.products.page=j(e.productsPageNumber)??1,a.products.pageSize=j(e.productsPageSize)??20),Array.isArray(e.blogPages)&&(a.blogPages.items=e.blogPages.map(t=>rt(t)),a.blogPages.total=j(e.blogPagesCount)??0,a.blogPages.page=j(e.blogPagesPageNumber)??1,a.blogPages.pageSize=j(e.blogPagesPageSize)??20),Array.isArray(e.cmsPages)&&(a.cmsPages.items=e.cmsPages.map(t=>rt(t)),a.cmsPages.total=j(e.cmsPagesCount)??0,a.cmsPages.page=j(e.cmsPagesPageNumber)??1,a.cmsPages.pageSize=j(e.cmsPagesPageSize)??20),Array.isArray(e.categories)&&(a.productCategories.items=e.categories.map(t=>et(t)),a.productCategories.total=j(e.productCategoriesCount)??0,a.productCategories.page=j(e.productCategoriesPageNumber)??1,a.productCategories.pageSize=j(e.productCategoriesPageSize)??20),a}function H(t){const e=y(t);if(!u(e))return[];return(Array.isArray(e.paymentTypes)?e.paymentTypes:Array.isArray(e.methods)?e.methods:[]).map(t=>u(t)?{id:j(t.id)??0,code:t.code,title:"string"==typeof t.title?t.title:"",titleFa:"string"==typeof t.titleFa?t.titleFa:"",description:"string"==typeof t.description?t.description:null,paymentSubType:j(t.paymentSubType)??null,order:j(t.order)??0,isDefault:Boolean(t.isDefault)}:{id:0,code:"",title:"",titleFa:"",description:null,paymentSubType:null,order:0,isDefault:!1})}function J(t){const e=y(t);return(Array.isArray(e)?e:u(e)&&Array.isArray(e.shippingMethods)?e.shippingMethods:[]).map(t=>function(t){if(!u(t))return{id:0,name:"",type:""};return{id:j(t.id)??0,name:B(t.name)??"",type:B(t.type)??""}}(t))}function Z(t){const e=y(t);if(!u(e))return{shippingMethods:[],groupedShippingRates:{},itemsShippingRate:[]};const a={};if(Array.isArray(e.shippingMethods)&&e.shippingMethods.forEach((t,e)=>{if(!u(t))return;const r=Array.isArray(t.shippingRate)?t.shippingRate.map(t=>X(t)):[];if(0===r.length)return;const i=Array.isArray(t.invoiceItemIds)?t.invoiceItemIds:[],n=i.length>0?i.map(String).sort().join(","):String(e);a[n]=r}),0===Object.keys(a).length&&u(e.groupedShippingRates))for(const[t,r]of Object.entries(e.groupedShippingRates))a[t]=Array.isArray(r)?r.map(t=>X(t)):[];return{shippingMethods:[],groupedShippingRates:a,itemsShippingRate:Array.isArray(e.itemsShippingRate)?e.itemsShippingRate.map(t=>u(t)?{invoiceItemId:K(t.invoiceItemId)??M(t)[0]??"",shippingRate:X(t.shippingRate??t.rate??t)}:{invoiceItemId:"",shippingRate:X(void 0)}):[]}}function X(t){return u(t)?{id:j(t.id??t.rateId)??0,name:B(t.name)??"",price:j(t.price??t.amount)??0,description:B(t.description??t.deliveryDescription??t.details),icon:B(t.icon??t.iconUrl??t.logo),color:B(t.color??t.bgColor??t.backgroundColor??t.iconColor),type:B(t.type)}:{id:0,name:"",price:0}}function tt(t){return u(t)?l(t,["staticUrl","products","items"]):{}}function et(t){const e=tt(t);return e?l(e,["themeConfig"]):{}}function at(t){return u(t)?l(t,["staticUrl","urlKey"]):{}}function rt(t){const e=at(t);return e?l(e,["themeConfig"]):{}}function it(t){const e=y(t);if(!e||!e.route)return e??{};const a=u(e.route)?e.route:{};if(a.entity){switch(a.entityType){case"product":a.entity=L(a.entity);break;case"product_category":a.entity=tt(a.entity);break;case"cms_page":case"blog_page":a.entity=at(a.entity)}u(a.entity)&&(a.entity=l(a.entity,["id"])),!a.url&&u(a.entity)&&a.entity.url&&(a.url=a.entity.url)}return a}function nt(t){if(!u(t))return{};const e={...t};return e.entity&&(e.entity=et(e.entity),u(e.entity)&&(e.entity=l(e.entity,["id"]))),e.children&&Array.isArray(e.children)&&(e.children=e.children.map(nt)),e}function st(t){const e=y(t);return e?e.cmsPages&&Array.isArray(e.cmsPages)?{items:e.cmsPages.map(rt),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=>rt(t)),total:e.total||e.items.length,page:e.page||1,pageSize:e.pageSize||e.items.length}:e:{}}function ot(t){if(!u(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 dt(t){if(!u(t))return{};const e={};if(t.entityType&&(e.entityType=t.entityType),void 0!==t.entityId&&(e.entityId=t.entityId),u(t.entity)){const a=l(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=>dt(t))),e}function ct(t){const e=y(t);if(!e||!e.tree)return e??{};const a=u(e.tree)?e.tree:{};return u(a.treeStructure)&&Array.isArray(a.treeStructure.nodes)&&(a.treeStructure.nodes=a.treeStructure.nodes.map(t=>dt(t))),e}class pt{constructor(t){this.config=t,this.baseUrl="http://api.sazito.com:8080",this.domain=t.domain,this.tokenStorage=new a,this.cache=new r,this.fetchApi=t.customFetchApi.bind(globalThis)}async get(t,e){const a=e?.params?h(e.params):void 0,i=this.buildUrl(t,a),n=r.generateKey("GET",i,a);if(!1!==e?.cache){const e=this.getApiName(t),a=this.config.cache[e];if(a?.enabled&&a.ttl){const e=this.cache.get(n,a.ttl);if(e)return this.config.debug&&console.log("[Sazito SDK] Cache hit:",t),{data:e}}}const s=await this.request("GET",i,e);return s.data&&!1!==e?.cache&&this.cache.set(n,s.data),s}async post(t,e,a){const r=this.buildUrl(t),i=this.isMultipartBody(e),n=e?i?e:h(e):void 0,s=this.getApiName(t);return this.cache.deletePattern(`GET:.*${s}`),this.request("POST",r,{...a,body:n,rawBody:i,omitJsonContentType:i})}async put(t,e,a){const r=this.buildUrl(t),i=this.isMultipartBody(e),n=e?i?e:h(e):void 0,s=this.getApiName(t);return this.cache.deletePattern(`GET:.*${s}`),this.request("PUT",r,{...a,body:n,rawBody:i,omitJsonContentType:i})}async delete(t,e){const a=this.buildUrl(t),r=this.getApiName(t);return this.cache.deletePattern(`GET:.*${r}`),this.request("DELETE",a,e)}async request(t,e,a,r=0){const i=new AbortController,n=a?.signal||i.signal,s=a?.timeout||this.config.timeout,o=setTimeout(()=>i.abort(),s);try{const i=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(!i.ok&&this.shouldRetry(i.status)&&r<s)return this.config.debug&&console.log(`[Sazito SDK] Retrying request (${r+1}/${s}):`,e),await this.delay(this.config.retry.retryDelay*(r+1)),this.request(t,e,a,r+1);const d=i.headers.get("content-type");let c;if(c=d?.includes("application/json")?await i.json():await i.text(),a?.skipTransform&&i.ok)return{data:c};const p=void 0!==c?.result?c.result:c;this.config.debug&&console.log(`[Sazito SDK] ${t} ${e}:`,{status:i.status,data:p});let u=p?m(p):p;const l=["cart","product","user","order","invoice","payment","shippingAddress"];if(u&&"object"==typeof u&&!Array.isArray(u)){const t=Object.keys(u);1===t.length&&l.includes(t[0])&&"object"==typeof u[t[0]]&&null!==u[t[0]]&&(u=u[t[0]])}return i.ok?{data:u}:{error:{status:i.status,message:u?.message||p?.message||i.statusText||"Request failed",type:"api",details:u}}}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 r=new URLSearchParams;return Object.entries(e).forEach(([t,e])=>{null!=e&&r.append(t,String(e))}),`${a}?${r.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 r=this.tokenStorage.get();return r&&(a.Authorization=r),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 ut{constructor(){this.data=new Map}getItem(t){return this.data.get(t)??null}setItem(t,e){this.data.set(t,e)}removeItem(t){this.data.delete(t)}}class lt{constructor(t){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",this.storage=t??("undefined"!=typeof window&&"undefined"!=typeof localStorage&&"function"==typeof localStorage.getItem?localStorage:new ut)}getCartCredentials(){const t=this.getItem(this.CART_KEY),e=t?.identifier?.trim();return e?{identifier:e}:null}setCartCredentials(t){const e=t.identifier.trim();if(!e)throw new Error("Cart identifier is required.");this.setItem(this.CART_KEY,{identifier:e})}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){try{const e=this.storage.getItem(t);return e?JSON.parse(e):null}catch{return null}}setItem(t,e){try{this.storage.setItem(t,JSON.stringify(e))}catch{}}removeItem(t){try{this.storage.removeItem(t)}catch{}}}const mt="/api/v1/product_categories",ht="/api/v1/search",yt="/api/v2/carts",gt="/api/v2/invoices",ft="/api/v2/shipping_addresses",bt="/api/v2/payments",_t="/api/v1/orders",vt="/api/v1/users",wt="/api/v1/sessions",At="/api/v1/feedbacks",Pt="/api/v1/cms_pages",It="/api/v1/images",Ct="/api/v1/scheduler/events",St="/api/v1/scheduler/bookings",zt="/api/v1/entity_route/route",Tt="/api/v1/feedbacks/comments/details";class Et{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}`,r=await this.http.get(zt,{...e,params:{url_part:a}});if(r.data){const t=it(r.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 r.error?{error:r.error}:{error:{message:"No data returned from product endpoint",type:"api"}}}async list(t,e){const a=this.transformFilters(t),r=await this.http.get("/api/v1/products",{...e,params:a});if(r.data){return{data:Q(r.data)}}return r}async search(t,e,a){const r={query:t,search_direction:"center",page_size:e?.pageSize||20,page_number:e?.page||1},i=await this.http.get(ht,{...a,params:r});if(i.data){return{data:W(i.data)}}return i}}class Nt{constructor(t){this.http=t}async get(t,e){const a=await this.http.get(`${mt}/${t}`,e);if(a.data){const t=function(t){const e=y(t);return e?tt(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 r=await this.http.get(mt,{...e,params:a});if(r.data){const t=function(t){const e=y(t);return e?(e.categories&&Array.isArray(e.categories)&&(e.categories=e.categories.map(et)),u(e.tree)&&u(e.tree.treeStructure)&&Array.isArray(e.tree.treeStructure.nodes)&&(e.tree.treeStructure.nodes=e.tree.treeStructure.nodes.map(nt)),e):{}}(r.data);return{data:t}}return r}}class kt{constructor(t,e){this.http=t,this.credentials=e}persistCartCredentials(t){this.credentials.setCartCredentials({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(`${yt}/0`,{...t,params:{identifier:e.identifier}});return a.data?{data:z(a.data)}:(a.error&&this.clearCart(),a)}async create(t,e){const a=await this.http.post(yt,t,e);if(!a.data)return a;const r=z(a.data);return this.persistCartCredentials(r),{data:r}}async addItem(t,e,a,r){return this.addItemWithAttributes(t,e,{formAttributes:a},r)}async addItemWithAttributes(t,e,a,r){const i=this.credentials.getCartCredentials();if(!i)return this.create({variants:[{id:t,count:e,formAttributes:a?.formAttributes}],schedulerBookingAttributes:a?.schedulerBookingAttributes,coupon:a?.coupon},r);const n=await this.http.post(`${yt}/0/add_products_to_cart`,{identifier:i.identifier,variants:[{id:t,count:e}],formAttributes:a?.formAttributes,schedulerBookingAttributes:a?.schedulerBookingAttributes,coupon:a?.coupon},r);if(n.data){const t=z(n.data);return this.persistCartCredentials(t),{data:t}}return 422===n.error?.status&&this.clearCart(),n}async updateItem(t,e,a,r,i){return this.updateItemWithAttributes(t,e,a,{formAttributes:r},i)}async updateItemWithAttributes(t,e,a,r,i){const n=this.credentials.getCartCredentials();if(!n)return{error:{message:"No cart found",type:"validation"}};const s=await this.http.post(`${yt}/0/update_products_in_cart`,{identifier:n.identifier,cartProductId:String(t),variants:[{id:e,count:a}],formAttributes:r?.formAttributes,coupon:r?.coupon,deleteCoupon:r?.deleteCoupon},i);if(s.data){const t=z(s.data);return this.persistCartCredentials(t),{data:t}}return s}async removeItem(t,e,a){const r=this.credentials.getCartCredentials();if(!r)return{error:{message:"No cart found",type:"validation"}};const i=await this.http.post(`${yt}/0/remove_products_from_cart`,{identifier:r.identifier,cartProductId:String(t),variants:[{id:e}]},a);if(i.data){const t=z(i.data);return this.persistCartCredentials(t),{data:t}}return i}clearCart(){this.credentials.clearCartCredentials()}}class xt{constructor(t){this.http=t}async list(t,e){const a={pageNumber:t?.pageNumber??1,pageSize:t?.pageSize??20};t?.filters&&t.filters.length>0&&(a.filters=JSON.stringify(t.filters));const r=await this.http.get(_t,{...e,params:a});return r.data?{data:N(r.data)}:r}async get(t,e){const a=await this.http.get(`${_t}/${t}`,e);return a.data?{data:E(a.data)}:a}}class Rt{constructor(t,e){this.http=t,this.credentials=e}normalizeInvoiceResponse(t){return t.data?{data:T(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 r=await this.http.post(`${gt}/${a.id}/refresh`,{cart_id:String(0),cart_identifier:e.identifier,identifier:a.identifier},t);return this.normalizeInvoiceResponse(r)}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(gt,{cart_id:String(0),cart_identifier:e.identifier},t);if(a.data){const t=T(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 r=await this.http.post(`${gt}/${a.id}/refresh`,{cart_id:String(0),cart_identifier:e.identifier,identifier:a.identifier},t);return this.normalizeInvoiceResponse(r)}async addShippingAddress(t,e,a){const r=this.credentials.getCartCredentials(),i=this.credentials.getInvoiceCredentials();if(!r||!i)return{error:{message:"No cart or invoice found",type:"validation"}};const n=await this.http.post(`${gt}/${i.id}/add_shipping_address`,{identifier:i.identifier,shipping_address_identifier:e,cart_id:0,cart_identifier:r.identifier,...t>0?{shipping_address_id:t}:{}},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 r=await this.http.post(`${gt}/${a.id}/add_discount_code`,{identifier:a.identifier,discount_code:t.toUpperCase()},e);return r.data?(this.credentials.setDiscountCode(t.toUpperCase()),{data:T(r.data)}):r}async assignShippingMethod(t,e){const a=this.credentials.getInvoiceCredentials();if(!a)return{error:{message:"No invoice found",type:"validation"}};const r=t.map(t=>({...t,invoiceItemIds:t.invoiceItemIds.map(t=>String(t))})),i=await this.http.post(`${gt}/${a.id}/add_shipping_method`,{identifier:a.identifier,shippings:r},e);return this.normalizeInvoiceResponse(i)}async addDetails(t,e){const a=this.credentials.getInvoiceCredentials();if(!a)return{error:{message:"No invoice found",type:"validation"}};const r=await this.http.post(`${gt}/${a.id}/add_invoice_details`,{identifier:a.identifier,user_comment:t},e);return this.normalizeInvoiceResponse(r)}async addForm(t,e){const a=this.credentials.getInvoiceCredentials();if(!a)return{error:{message:"No invoice found",type:"validation"}};const r=await this.http.post(`${gt}/${a.id}/add_form`,{invoiceIdentifier:t.invoiceIdentifier||t.identifier||a.identifier,formAttributes:t.formAttributes},e);return this.normalizeInvoiceResponse(r)}async addCredit(t){const e=this.credentials.getInvoiceCredentials();if(!e)return{error:{message:"No invoice found",type:"validation"}};const a=await this.http.post(`${gt}/${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(`${gt}/${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(`${gt}/${e.id}/applicable_shipping_methods`,{...t,cache:t?.cache??!1,params:{identifier:e.identifier}});return a.data?{data:Z(a.data)}:a}clearInvoice(){this.credentials.clearInvoiceCredentials()}}class Ot{constructor(t,e){this.http=t,this.credentials=e}sanitizeAddressInput(t){const e={...t};return delete e.user,e}unwrapAddressPayload(t){let e=t;const a=new Set;for(;e&&"object"==typeof e&&!Array.isArray(e)&&!a.has(e);){a.add(e);const t=e,r=t.shippingAddress??t.shipping_address??t.data;if(void 0===r)break;e=r}return e}extractAddressList(t){if(Array.isArray(t))return t;if(!t||"object"!=typeof t)return[];const e=t,a=[e.shippingAddresses,e.addresses,e.items,e.data];for(const t of a)if(Array.isArray(t))return t;return[]}async createAddress(t,e){const a=this.sanitizeAddressInput(t),r=await this.http.post(ft,{shipping_address:a},e);if(r.data){const t=x(this.unwrapAddressPayload(r.data));return t?(this.credentials.setShippingCredentials({id:t.id,identifier:t.identifier}),{data:t}):r}return r}async updateAddress(t,e){const a=this.credentials.getShippingCredentials();if(!a)return this.createAddress(t,e);const r=this.sanitizeAddressInput(t),i=await this.http.post(ft,{identifier:a.identifier,shipping_address:r},e);if(i.data){const t=x(this.unwrapAddressPayload(i.data));return t?(this.credentials.setShippingCredentials({id:t.id,identifier:t.identifier}),{data:t}):i}return i}async listAddresses(t){const e=await this.http.get(ft,{...t,cache:t?.cache??!1});if(e.error)return{error:e.error};return{data:this.extractAddressList(e.data).map(t=>x(this.unwrapAddressPayload(t))).filter(t=>Boolean(t?.identifier)).sort((t,e)=>e.id-t.id)}}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(`${ft}/${e.id}`,{...t,params:{identifier:e.identifier}});if(a.data){const t=x(this.unwrapAddressPayload(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:J(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(`${bt}/list`,{invoice_identifier:e.identifier},t);return a.data?{data:H(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 r=await this.http.post(bt,{invoice_identifier:a.identifier,payment_type:t},{...e,skipTransform:!0});if(r.error)return{error:r.error};if(r.data){const t=r.data,e=t&&"object"==typeof t&&"result"in t?t.result?.payment:t.payment;if(e&&"object"==typeof e){const t=String(e.payment_identifier??""),a=Number(e.id??0),r=e.payment_type,i={id:a,identifier:t,amount:Number(e.payment_amount??0),paymentType:{id:null!=r?.id?Number(r.id):void 0,code:r?.reference_code??""}};return t&&this.credentials.setPaymentCredentials({id:a,identifier:t}),{data:i}}}return{data:r.data}}async initialize(t){return this.submitPaymentStep(void 0,t)}async verify(t,e){return this.submitPaymentStep(t,e)}async processStep(t,e){return this.submitPaymentStep(t,e)}async submitPaymentStep(t,e){const a=this.credentials.getPaymentCredentials();if(!a)return{error:{message:"No payment found. Please create a payment first.",type:"validation"}};const{paymentIdentifier:r,...i}=t??{},n=await this.http.post(`${bt}/${a.id}/process_payment_step`,{paymentIdentifier:r||a.identifier,...i},this.withExactJsonHeader(e));return this.finalizeStepResponse(n,a.id,e)}async processStepForm(t,e){const a=this.credentials.getPaymentCredentials();if(!a)return{error:{message:"No payment found",type:"validation"}};const r=this.buildProcessStepFormData(t,a.identifier);if(!r)return{error:{message:"FormData is not available in this runtime.",type:"validation"}};const i=await this.http.post(`${bt}/${a.id}/process_payment_step`,r,e);return this.finalizeStepResponse(i,a.id,e)}async pollUntilSettled(t,e=15e3){let a=!0;for(;a;){const r=await this.verify(void 0,t);if(!r.data)return r;if("pending"!==r.data.action)return a=!1,r;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=h(t),r=new FormData;return Object.entries(a).forEach(([t,e])=>{this.appendFormValue(r,t,e)}),r.has("payment_identifier")||r.append("payment_identifier",e),r}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,""))}async finalizeStepResponse(t,e,a){if(!t.data)return t;const r=t=>!!t&&"object"==typeof t&&!Array.isArray(t);let i=t.data;if("string"==typeof i)try{i=JSON.parse(i)}catch{return{error:{message:"Invalid payment step response",type:"api"}}}const n=i;if(r(n)){const t="string"==typeof n.error?n.error:"",e=Number(n.error_code??0);if(t||e)return{error:{message:t||"Payment step failed",type:"api",status:Number(n.status)||void 0}}}const s=r(n)&&r(n.result)?n.result:n,o=this.normalizeAction(s);return await this.callPinchAfterSuccessfulPayment(o,e,a),{data:o}}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 Dt{constructor(t){this.http=t}normalizeUserResponse(t){if(!t.data)return t;const e=R(t.data);return e?{data:e}:t}normalizeLoginResponse(t){if(!t.data||!t.data.user)return t;const e=R(t.data.user);return e?{data:{...t.data,user:e}}:t}async login(t,e){const a=await this.http.post(`${wt}/login`,t,e);return this.normalizeLoginResponse(a)}async requestMobileOTP(t,e){return this.http.post(`${wt}/login_request`,t,e)}async verifyMobileOTP(t,e){const a=await this.http.post(`${wt}/login_request_verification`,t,e);return this.normalizeLoginResponse(a)}async requestEmailLogin(t,e){return this.http.post(`${vt}/email_login_request`,t,e)}async register(t,e){const a=await this.http.post(`${vt}/register`,t,e);return this.normalizeUserResponse(a)}async getCurrentUser(t){const e=await this.http.get(`${vt}/current`,t);return this.normalizeUserResponse(e)}async updateProfile(t,e,a){const r=await this.http.put(`${vt}/${t}`,e,a);return this.normalizeUserResponse(r)}async requestMobilePhoneUpdate(t,e){return this.http.post(`${vt}/update_mobile_phone_request`,t,e)}async verifyMobilePhoneUpdate(t,e){const a=await this.http.post(`${vt}/update_mobile_phone_verification`,t,e);return this.normalizeUserResponse(a)}async forgotPassword(t,e){return this.http.post(`${vt}/forgot_password`,t,e)}async revivePassword(t,e){const a=await this.http.post(`${vt}/revive_password`,t,e);return this.normalizeLoginResponse(a)}async mergeUser(t){return this.http.post(`${vt}/merge_user`,{},t)}}class Gt{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 r=this.transformFilters(e),i=await this.http.get(ht,{...a,params:{...r,query:t,page_number:r.page_number??1,page_size:r.page_size??20,search_direction:"center"}});if(i.data){return{data:W(i.data)}}return i}}class Ft{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(Tt,t,e)}async getProductStatistics(t,e){const a=await this.http.get(`${Tt}/${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 r=await this.http.get(`${Tt}/${t}`,{...a,params:{page_number:e?.pageNumber??1,page_size:e?.pageSize??10}});if(r.data){const t=r.data.data||r.data;return{data:this.normalizeProductReviewsResponse(t)}}return r}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 r=await this.http.post("/api/v1/service/filemanager/uploads/public/tajrobe",a,e);if(r.data){return{data:{images:Array.isArray(r.data.images)?r.data.images:Array.isArray(r.data.data?.images)?r.data.data.images:Array.isArray(r.data.result?.images)?r.data.result.images:[]}}}return r}async list(t,e){return this.http.get(At,{...e,params:this.transformLegacyFilters(t)})}async create(t,e){return this.http.post(At,t,e)}async get(t,e){return this.http.get(`${At}/${t}`,e)}}class Mt{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?.pageNumber??t?.page_number??1,r=t?.pageSize??t?.page_size??20,i=await this.http.get("/api/v1/wallet/transactions",{...e,params:{pageNumber:a,pageSize:r}});return i.data?{data:k(i.data)}:i}async applyCredit(t,e){const a=this.validateInvoiceId(t);if(a)return a;const r=await this.http.post(`${gt}/${t}/add_credit`,{},e);return r.data?{data:T(r.data)}:r}async removeCredit(t,e){const a=this.validateInvoiceId(t);if(a)return a;const r=await this.http.post(`${gt}/${t}/remove_credit`,{},e);return r.data?{data:T(r.data)}:r}}class jt{constructor(t){this.http=t}async getPage(t,e){const a=await this.http.get(zt,{...e,params:{url_part:t}}),r=it(a.data);if("cms_page"!==r.entityType)throw new Error(`Expected CMS page at ${t}, but got ${r.entityType}`);if("blog"===r.entity.cmsPageType)throw new Error(`Expected CMS page at ${t}, but got blog page`);return{...a,data:r.entity}}async listPages(t,e){const a=ot({...t,cmsPageTypes:"normal"}),r=await this.http.get(Pt,{...e,params:a});return{...r,data:st(r.data)}}async getBlogPost(t,e){const a=await this.http.get(zt,{...e,params:{url_part:t}}),r=it(a.data);if("cms_page"!==r.entityType)throw new Error(`Expected blog post at ${t}, but got ${r.entityType}`);if("blog"!==r.entity.cmsPageType)throw new Error(`Expected blog post at ${t}, but got CMS page`);return{...a,data:r.entity}}async listBlogPosts(t,e){const a=ot({...t,cmsPageTypes:"blog"}),r=await this.http.get(Pt,{...e,params:a});return{...r,data:st(r.data)}}async listAll(t,e){const a=ot(t),r=await this.http.get(Pt,{...e,params:a});return{...r,data:st(r.data)}}}class Bt{constructor(t){this.http=t}async upload(t,e){const a=new FormData;a.append("image",t);const r={...e?.headers};return delete r["Content-Type"],this.http.post(It,a,{...e,headers:r})}async delete(t,e){return this.http.delete(`${It}/${t}`,e)}}class Ut{constructor(t){this.http=t}async track(t,e){const a=e??((r=t)&&"object"==typeof r&&("retries"in r||"timeout"in r||"cache"in r||"headers"in r||"signal"in r)?t:void 0);var r;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(Ct,{...e,params:this.transformEventFilters(t)})}async getEvent(t,e){const a=await this.http.get(`${Ct}/${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(St,t,e)}async listBookings(t){return this.http.get(St,t)}async cancelBooking(t,e){return this.http.post(`${St}/${t}/cancel`,{},e)}}class qt{constructor(t){this.http=t}async resolve(t,e){const a=await this.http.get(zt,{...e,params:{url_part:t}});if(a.data){return{data:it(a.data)}}return a}}class Lt{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}}),r=a.data?ct(a.data):a.data,i=r?.tree?.treeStructure?.nodes||[],n=this.convertRawTreeToNavigation(i);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{details:e,entity:a}=t,r=this.firstNonEmpty(e?.title,e?.name),i=this.firstNonEmpty(a?.title,a?.name);return!0===e?.isTitleDefault?i||r:r||i}firstNonEmpty(...t){return t.find(t=>"string"==typeof t&&t.trim().length>0)||""}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 Yt{constructor(t){this.http=t}async getInfo(t){const e=await this.http.get("/api/v2/general/info",t);return e.data?{data:g(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 Vt{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 r=await this.http.post("/api/v1/service/filemanager/uploads/private/productform",a,e);if(r.data){const t=r.data?.data?.file?.serveKey||r.data?.file?.serveKey||r.data?.serveKey;return{data:{serveKey:String(t??"")}}}return r}}function Qt(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function Wt(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 Ht(t){return"string"==typeof t?t.trim():""}class Jt{constructor(t){this.http=t}normalizeCity(t){return Qt(t)?{id:Wt(t.id),name:Ht(t.name),latitude:Wt(t.latitude),longitude:Wt(t.longitude)}:{id:0,name:"",latitude:0,longitude:0}}normalizeRegion(t){if(!Qt(t))return{id:0,name:"",cities:[]};const e=Array.isArray(t.cities)?t.cities:[];return{id:Wt(t.id),name:Ht(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:Qt(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 Zt{constructor(t,a){const r=e(t);this.http=new pt(r),this.tokenStorage=this.http.getTokenStorage(),this.credentialsManager=a??new lt,this.products=new Et(this.http),this.categories=new Nt(this.http),this.cart=new kt(this.http,this.credentialsManager),this.invoices=new Rt(this.http,this.credentialsManager),this.shipping=new Ot(this.http,this.credentialsManager),this.payments=new $t(this.http,this.credentialsManager),this.orders=new xt(this.http),this.users=new Dt(this.http),this.search=new Gt(this.http),this.feedbacks=new Ft(this.http),this.wallet=new Mt(this.http),this.cms=new jt(this.http),this.images=new Bt(this.http),this.visits=new Ut(this.http),this.booking=new Kt(this.http),this.entityRoutes=new qt(this.http),this.menu=new Lt(this.http),this.general=new Yt(this.http),this.dynamicForms=new Vt(this.http),this.regions=new Jt(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()}getCredentialsManager(){return this.credentialsManager}clearAll(){this.clearAuth(),this.clearCache(),this.clearCredentials()}async searchQuery(t,e,a){return this.search.query(t,e,a)}}function Xt(t){return function(t){if(!t||"object"!=typeof t)return!1;const e=t;return e.http instanceof pt&&e.credentials instanceof lt}(t)?t:function(t){const a=e(t);return{http:new pt(a),credentials:new lt}}(t)}function te(t){const{http:e}=Xt(t);return new Et(e)}function ee(t){const{http:e}=Xt(t);return new Nt(e)}function ae(t){const{http:e,credentials:a}=Xt(t);return new kt(e,a)}function re(t){const{http:e}=Xt(t);return new xt(e)}function ie(t){const{http:e,credentials:a}=Xt(t);return new Rt(e,a)}function ne(t){const{http:e,credentials:a}=Xt(t);return new Ot(e,a)}function se(t){const{http:e,credentials:a}=Xt(t);return new $t(e,a)}function oe(t){const{http:e}=Xt(t);return new Dt(e)}function de(t){const{http:e}=Xt(t);return new Gt(e)}function ce(t){const{http:e}=Xt(t);return new Ft(e)}function pe(t){const{http:e}=Xt(t);return new Mt(e)}function ue(t){const{http:e}=Xt(t);return new jt(e)}function le(t){const{http:e}=Xt(t);return new Bt(e)}function me(t){const{http:e}=Xt(t);return new Ut(e)}function he(t){const{http:e}=Xt(t);return new Kt(e)}function ye(t){const{http:e}=Xt(t);return new qt(e)}function ge(t){const{http:e}=Xt(t);return new Lt(e)}function fe(t){const{http:e}=Xt(t);return new Yt(e)}function be(t){const{http:e}=Xt(t);return new Vt(e)}function _e(t){const{http:e}=Xt(t);return new Jt(e)}exports.CredentialsManager=lt,exports.HttpClient=pt,exports.MemoryStorage=ut,exports.SazitoClient=Zt,exports.TokenStorage=a,exports.booking=he,exports.cart=ae,exports.categories=ee,exports.cms=ue,exports.createBookingAPI=he,exports.createCMSAPI=ue,exports.createCartAPI=ae,exports.createCategoriesAPI=ee,exports.createDynamicFormsAPI=be,exports.createEntityRoutesAPI=ye,exports.createFeedbacksAPI=ce,exports.createGeneralAPI=fe,exports.createImagesAPI=le,exports.createInvoicesAPI=ie,exports.createMenuAPI=ge,exports.createOrdersAPI=re,exports.createPaymentsAPI=se,exports.createProductsAPI=te,exports.createRegionsAPI=_e,exports.createSazitoClient=function(t,e){return new Zt(t,e)},exports.createSearchAPI=de,exports.createShippingAPI=ne,exports.createUsersAPI=oe,exports.createVisitsAPI=me,exports.createWalletAPI=pe,exports.dynamicForms=be,exports.entityRoutes=ye,exports.feedbacks=ce,exports.general=fe,exports.images=le,exports.invoices=ie,exports.menu=ge,exports.orders=re,exports.payments=se,exports.products=te,exports.regions=_e,exports.search=de,exports.shipping=ne,exports.toEnglishDigits=n,exports.transformAddToCartInput=function(t,e,a){const r={product_variants:[{id:t,count:e}]};return a&&(r.form_attributes=h(a)),r},exports.transformApiResponse=y,exports.transformCartResponse=z,exports.transformCreateCartInput=function(t){if(!u(t))return{product_variants:[]};const e=t.variants||t.productVariants||[],a={product_variants:Array.isArray(e)?e.map(t=>u(t)?{id:t.id||t.variantId,count:t.count||t.quantity,form_attributes:t.formAttributes?h(t.formAttributes):void 0}:{}):[]};return t.coupon&&(a.coupon=t.coupon),a},exports.transformInvoiceResponse=T,exports.transformProductListResponse=Q,exports.transformRequestKeys=h,exports.transformResponseKeys=m,exports.transformShippingAddressInput=function(t){if(u(t)){const e={...t};return delete e.user,{shipping_address:h(e)}}return{shipping_address:h(t)}},exports.users=oe,exports.visits=me,exports.wallet=pe;
package/dist/index.mjs 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=new Set(["mobile_phone","phone_number"]);function n(t){return t.replace(/[۰-۹٠-٩]/g,t=>{const e=t.charCodeAt(0);return String(e>=1776?e-1776:e-1632)})}const s={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"},o=Object.values(s).reduce((t,e)=>(t[e]=(t[e]||0)+1,t),{}),d=Object.entries(s).reduce((t,[e,a])=>(1===o[a]&&(t[a]=e),t),{});function c(t){return t.replace(/_([a-z])/g,(t,e)=>e.toUpperCase())}function p(t){return t.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function u(t){return!(null===t||"object"!=typeof t||Array.isArray(t)||t instanceof Date)}function l(t,e){const a={...t};for(const t of e)delete a[t];return a}function m(t){if(!u(t))return Array.isArray(t)?t.map(t=>m(t)):t;const e={};for(const[a,i]of Object.entries(t)){let t=s[a];t||(t=c(a)),u(i)?e[t]=m(i):Array.isArray(i)?e[t]=i.map(t=>m(t)):e[t]=i}return e}function h(t){if(!u(t))return Array.isArray(t)?t.map(t=>h(t)):t;const e={};for(const[a,i]of Object.entries(t)){let t=d[a];t||(t=p(a)),u(i)?e[t]=h(i):Array.isArray(i)?e[t]=i.map(t=>h(t)):e[t]="string"==typeof i&&r.has(t)?n(i):i}return e}function y(t){const e=t;if(u(e?.data?.result)){const t=e.data.result,a=Object.keys(t);return 1===a.length&&u(t[a[0]])?m(t[a[0]]):m(t)}return m(t)}function g(t){if(!t)return{};if(!u(t))return{};const{general:e,shop:a,checkout:i,features:r,wallet:n,tajrobe:s,domain:o,enamad:d,google:c,logo:p,social:l,...m}=t,h={...u(e)?e:{},...u(a)?a:{}},{registerType:y,showProductStockNumber:g,...w}=h||{};return{...m,scripts:{enamad:d,google:c},shop:v({...w,domain:o,logo:p,social:l}),settings:{checkout:f(i),features:C(r),wallet:I(n),tajrobe:S(s),registerType:_(y),showProductStockNumber:b(g)}}}function f(t){if(!u(t))return{};const e=u(t.minBasket)?t.minBasket:{},a=e.minAmount??e.minBasket,i="number"==typeof a?a:Number(a),r={...t,addToCartAlert:b(t.addToCartAlert),dynamicForm:b(t.dynamicForm),emailOptional:b(t.emailOptional??t.email_optional),preventRedirect:b(t.preventRedirect??t.manual),minBasket:{enabled:b(e.enabled),minAmount:Number.isFinite(i)?i:0},miniCart:b(t.miniCart),postalCodeMandatory:b(t.postalCodeMandatory),quickAddToCart:b(t.quickAddToCart)};return delete r.manual,r}function _(t){return"string"==typeof t?t:""}function b(t){return"boolean"==typeof t?t:u(t)&&Object.prototype.hasOwnProperty.call(t,"enabled")?b(t.enabled):1===t||"1"===t||"true"===t}function v(t){if(!u(t))return{};const e={...t};if(u(e.city)){const t=l(e.city,["createdAt","updatedAt"]);let a=t.region;u(a)&&(a=l(a,["createdAt","updatedAt","cities"])),t.region=a,e.city=t}return e}const w={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"},A=new Set(["activateAlopeykAdvanced","activate_alopeyk_advanced"]),P=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 C(t){if(!u(t))return{};const e={},a=(t,a)=>{if(A.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)};u(t.flags)&&Object.entries(t.flags).forEach(([t,e])=>{a(t,e)}),u(t.configurations)&&Object.entries(t.configurations).forEach(([t,e])=>{a(t,e)}),Object.entries(t).forEach(([t,e])=>{"flags"!==t&&"premium"!==t&&"configurations"!==t&&(u(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("_")?c(t):t,a=w[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);P.has(a)||(i[a]=e)});const r={...i};return u(t.premium)&&(r.premium=t.premium),r}function I(t){if(!u(t))return{};const e=u(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 S(t){if(!u(t))return{};const e=u(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 z(t){const e=y(t);if(!u(e))return{};const a=Array.isArray(e.items)?e.items.map(t=>function(t){if(!u(t))return{};const e=B(t),a=F(t.productVariantId??e.variantId)??e.variantId;return{id:j(t.id??t.cartProductId)??"",productVariantId:a,quantity:F(t.quantity)??0,unitPrice:F(t.unitPrice)??0,lineTotal:F(t.lineTotal)??0,product:e,formAttributes:t.formAttributes,formFields:t.formFields,bookingAttributes:t.bookingAttributes}}(t)):[];return{...e,items:a,netTotal:F(e.netTotal)??0,grossTotal:F(e.grossTotal),needsShipping:Boolean(e.needsShipping),minBasketLimitViolated:Boolean(e.minBasketLimitViolated),deleteCoupon:void 0===e.deleteCoupon?void 0:Boolean(e.deleteCoupon)}}function E(t){const e=y(t);if(!u(e))return{};const a=l(e,["shippingMethod","user","userData"]),i=Array.isArray(e.items)?e.items.map(t=>function(t){if(!u(t))return{};const e=B(t),a=F(t.productVariantId??e.variantId)??e.variantId,i=Array.isArray(e.attributes)?e.attributes:[],r=M(e.hasMaxOrder??t.hasMaxOrder);return{id:j(t.id??t.invoiceItemId??t.cartProductId)??"",productVariantId:a,productId:F(e.productId??t.productId),name:x(t.name)??x(e.name)??"",url:x(e.url)??x(t.url),attributes:i,productType:x(e.productType)??x(t.productType),hasMaxOrder:r,maxOrderQuantity:F(e.maxOrderQuantity??t.maxOrderQuantity),minOrderQuantity:F(e.minOrderQuantity??t.minOrderQuantity),image:K(t.image??e.image),quantity:F(t.quantity)??0,unitPrice:F(t.unitPrice)??0,lineTotal:F(t.lineTotal)??0,rawPrice:F(t.rawPrice??t.originalPrice)??0,customerProfit:F(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=u(n)&&u(n.discountCode)?x(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}}(O(e.shippingAddress)),shippingItems:Array.isArray(e.shippingItems)?e.shippingItems.map(t=>function(t){if(!u(t))return{};const e=u(t.rate)?t.rate:u(t.shippingRate)?t.shippingRate:u(t.shippingMethod)?t.shippingMethod:t;return{invoiceItemIds:D(t),rate:X(e)}}(t)):[],discountUsages:r,netTotal:F(e.netTotal)??0,finalTotal:F(e.finalTotal)??0,vat:F(e.vat)??0,vatPercent:F(e.vatPercent)??0,itemsDiscount:F(e.itemsDiscount)??0,discountTotal:F(e.discountTotal)??0,customerProfit:F(e.customerProfit)??0,customerProfitPercentage:F(e.customerProfitPercentage)??0,itemsTotalRawPrice:F(e.itemsTotalRawPrice)??0,couponTotal:F(e.couponTotal)??0,shippingTotal:F(e.shippingTotal)??0,creditTotal:F(e.creditTotal)??0,needsShipping:Boolean(e.needsShipping),userComment:"string"==typeof e.userComment?e.userComment:void 0,discountCode:s}}function T(t){return O(t)}function k(t){const e=y(t);if(u(e))return N(e)}function N(t){if(!t)return;const e=function(t){const e=$(t);if(!e)return;if(1===Object.keys(e).length&&u(e.user))return $(e.user)??e.user;return e}(t);if(!e)return;const a={},i=F(e.id);void 0!==i&&(a.id=i);const r=x(e.email);r&&(a.email=r);const n=x(e.mobilePhone)??x(e.phoneNumber);n&&(a.mobilePhone=n);const s=x(e.phoneNumber);s&&s!==n&&(a.phoneNumber=s);const o=x(e.firstName);o&&(a.firstName=o);const d=x(e.lastName);d&&(a.lastName=d);const c=x(e.birthDate);return c&&(a.birthDate=c),Object.keys(a).length>0?a:void 0}function O(t){if(!t||0===Object.keys(t).length)return;const e=N(t.user),a=$(t.region),i=$(t.city),r=$(i?.region),n=x(t.regionName)??G(t.region),s=R(a??t.region,{fallbackId:F(t.regionId),fallbackName:n})??R(r,{fallbackId:F(t.regionId),fallbackName:n}),o=F(t.regionId)??s?.id,d=x(t.cityName)??x(i?.name)??G(t.city),c=function(t,e={}){if(null==t)return;const a=$(t),i=F(a?.id)??F(t)??e.fallbackId,r=x(a?.name)??G(t)??e.fallbackName;if(void 0===i||!r)return;const n={id:i,name:r},s=F(a?.regionId)??e.fallbackRegionId;void 0!==s&&(n.regionId=s);const o=F(a?.latitude);void 0!==o&&(n.latitude=o);const d=F(a?.longitude);void 0!==d&&(n.longitude=d);return n}(i??t.city,{fallbackId:F(t.cityId),fallbackName:d,fallbackRegionId:o}),p=x(t.firstName)??e?.firstName??"",u=x(t.lastName)??e?.lastName??"",l={id:F(t.id)??0,identifier:x(t.identifier)??"",firstName:p,lastName:u,city:c??{id:F(t.cityId??t.city)??0,name:d??"",...void 0!==o?{regionId:o}:{}},address:x(t.address)??""},m=x(t.mobilePhone)??x(t.phoneNumber)??e?.mobilePhone??e?.phoneNumber,h=x(t.phoneNumber)??e?.phoneNumber;m&&(l.mobilePhone=m),h&&h!==m&&(l.phoneNumber=h);const y=x(t.email)??e?.email;y&&(l.email=y),s&&(l.region=s);const g=x(t.postalCode);g&&(l.postalCode=g);const f=x(t.description);f&&(l.description=f);const _=F(t.latitude);void 0!==_&&(l.latitude=_);const b=F(t.longitude);void 0!==b&&(l.longitude=b);const v=M(t.userSetCoordinatesBefore);return void 0!==v&&(l.userSetCoordinatesBefore=v),l}function R(t,e={}){if(null==t)return;const a=$(t),i=F(a?.id)??F(t)??e.fallbackId,r=x(a?.name)??G(t)??e.fallbackName;return void 0!==i&&r?{id:i,name:r}:void 0}function $(t){if(u(t))return u(t.data)?t.data:t}function G(t){const e=x(t);if(e)return void 0===F(e)?e:void 0}function D(t){return(Array.isArray(t.invoiceItemIds)?t.invoiceItemIds:void 0!==t.invoiceItemId?[t.invoiceItemId]:[]).map(t=>j(t)).filter(t=>void 0!==t)}function F(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 x(t){if("string"!=typeof t)return;const e=t.trim();return e.length>0?e:void 0}function M(t){return"boolean"==typeof t?t:1===t||"1"===t||"true"===t||0!==t&&"0"!==t&&"false"!==t&&void 0}function j(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 B(t){if(!u(t))return{variantId:0,name:"",attributes:[]};const e=u(t.variant)?t.variant:void 0,a=u(e?.product)?e.product:void 0,i=u(t.product)?t.product:void 0,r=F(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:F(i?.productId??t.productId??a?.id),name:x(i?.name)??x(t.name)??"",url:x(i?.url)??x(t.url)??x(a?.url),image:K(i?.image??t.image),attributes:n,productType:x(i?.productType)??x(t.productType)??x(a?.productType),hasMaxOrder:i?.hasMaxOrder??t.hasMaxOrder??e?.hasMaxOrder,maxOrderQuantity:F(i?.maxOrderQuantity??t.maxOrderQuantity??e?.maxOrderQuantity),minOrderQuantity:F(i?.minOrderQuantity??t.minOrderQuantity??e?.minOrderQuantity)}}function U(t){if(!u(t))return{};const e=l(t,["staticUrl","summary","tags","slug"]);return e.variants&&Array.isArray(e.variants)&&(e.variants=e.variants.map(t=>u(t)?l(t,["name","title","product","status","soldCount"]):{})),e.categories&&Array.isArray(e.categories)&&(e.categories=e.categories.map(t=>u(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 u(t)?l(t,["widthRatio","heightRatio","thumb","order"]):t}function q(t){const e=U(t);return e?l(e,["themeConfig"]):e}function L(t){const e=y(t);if(e.items&&Array.isArray(e.items)){const t=F(e.total)??e.items.length,a=F(e.pageSize)??e.items.length,i=F(e.page)??1,r=F(e.totalPages)??Math.ceil(t/a);return{items:e.items.map(t=>q(t)),total:t,page:i,pageSize:a,totalPages:r}}return e}function Y(t){if(!u(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=>q(t)),a.products.total=F(e.productsCount)??0,a.products.page=F(e.productsPageNumber)??1,a.products.pageSize=F(e.productsPageSize)??20),Array.isArray(e.blogPages)&&(a.blogPages.items=e.blogPages.map(t=>it(t)),a.blogPages.total=F(e.blogPagesCount)??0,a.blogPages.page=F(e.blogPagesPageNumber)??1,a.blogPages.pageSize=F(e.blogPagesPageSize)??20),Array.isArray(e.cmsPages)&&(a.cmsPages.items=e.cmsPages.map(t=>it(t)),a.cmsPages.total=F(e.cmsPagesCount)??0,a.cmsPages.page=F(e.cmsPagesPageNumber)??1,a.cmsPages.pageSize=F(e.cmsPagesPageSize)??20),Array.isArray(e.categories)&&(a.productCategories.items=e.categories.map(t=>et(t)),a.productCategories.total=F(e.productCategoriesCount)??0,a.productCategories.page=F(e.productCategoriesPageNumber)??1,a.productCategories.pageSize=F(e.productCategoriesPageSize)??20),a}function V(t){if(u(t)){const e={...t};return delete e.user,{shipping_address:h(e)}}return{shipping_address:h(t)}}function Q(t,e,a){const i={product_variants:[{id:t,count:e}]};return a&&(i.form_attributes=h(a)),i}function W(t){if(!u(t))return{product_variants:[]};const e=t.variants||t.productVariants||[],a={product_variants:Array.isArray(e)?e.map(t=>u(t)?{id:t.id||t.variantId,count:t.count||t.quantity,form_attributes:t.formAttributes?h(t.formAttributes):void 0}:{}):[]};return t.coupon&&(a.coupon=t.coupon),a}function J(t){const e=y(t);if(!u(e))return[];return(Array.isArray(e.paymentTypes)?e.paymentTypes:Array.isArray(e.methods)?e.methods:[]).map(t=>u(t)?{id:F(t.id)??0,code:t.code,title:"string"==typeof t.title?t.title:"",titleFa:"string"==typeof t.titleFa?t.titleFa:"",description:"string"==typeof t.description?t.description:null,paymentSubType:F(t.paymentSubType)??null,order:F(t.order)??0,isDefault:Boolean(t.isDefault)}:{id:0,code:"",title:"",titleFa:"",description:null,paymentSubType:null,order:0,isDefault:!1})}function H(t){const e=y(t);return(Array.isArray(e)?e:u(e)&&Array.isArray(e.shippingMethods)?e.shippingMethods:[]).map(t=>function(t){if(!u(t))return{id:0,name:"",type:""};return{id:F(t.id)??0,name:x(t.name)??"",type:x(t.type)??""}}(t))}function Z(t){const e=y(t);if(!u(e))return{shippingMethods:[],groupedShippingRates:{},itemsShippingRate:[]};const a={};if(Array.isArray(e.shippingMethods)&&e.shippingMethods.forEach((t,e)=>{if(!u(t))return;const i=Array.isArray(t.shippingRate)?t.shippingRate.map(t=>X(t)):[];if(0===i.length)return;const r=Array.isArray(t.invoiceItemIds)?t.invoiceItemIds:[],n=r.length>0?r.map(String).sort().join(","):String(e);a[n]=i}),0===Object.keys(a).length&&u(e.groupedShippingRates))for(const[t,i]of Object.entries(e.groupedShippingRates))a[t]=Array.isArray(i)?i.map(t=>X(t)):[];return{shippingMethods:[],groupedShippingRates:a,itemsShippingRate:Array.isArray(e.itemsShippingRate)?e.itemsShippingRate.map(t=>u(t)?{invoiceItemId:j(t.invoiceItemId)??D(t)[0]??"",shippingRate:X(t.shippingRate??t.rate??t)}:{invoiceItemId:"",shippingRate:X(void 0)}):[]}}function X(t){return u(t)?{id:F(t.id??t.rateId)??0,name:x(t.name)??"",price:F(t.price??t.amount)??0,description:x(t.description??t.deliveryDescription??t.details),icon:x(t.icon??t.iconUrl??t.logo),color:x(t.color??t.bgColor??t.backgroundColor??t.iconColor),type:x(t.type)}:{id:0,name:"",price:0}}function tt(t){return u(t)?l(t,["staticUrl","products","items"]):{}}function et(t){const e=tt(t);return e?l(e,["themeConfig"]):{}}function at(t){return u(t)?l(t,["staticUrl","urlKey"]):{}}function it(t){const e=at(t);return e?l(e,["themeConfig"]):{}}function rt(t){const e=y(t);if(!e||!e.route)return e??{};const a=u(e.route)?e.route:{};if(a.entity){switch(a.entityType){case"product":a.entity=U(a.entity);break;case"product_category":a.entity=tt(a.entity);break;case"cms_page":case"blog_page":a.entity=at(a.entity)}u(a.entity)&&(a.entity=l(a.entity,["id"])),!a.url&&u(a.entity)&&a.entity.url&&(a.url=a.entity.url)}return a}function nt(t){if(!u(t))return{};const e={...t};return e.entity&&(e.entity=et(e.entity),u(e.entity)&&(e.entity=l(e.entity,["id"]))),e.children&&Array.isArray(e.children)&&(e.children=e.children.map(nt)),e}function st(t){const e=y(t);return e?e.cmsPages&&Array.isArray(e.cmsPages)?{items:e.cmsPages.map(it),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=>it(t)),total:e.total||e.items.length,page:e.page||1,pageSize:e.pageSize||e.items.length}:e:{}}function ot(t){if(!u(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 dt(t){if(!u(t))return{};const e={};if(t.entityType&&(e.entityType=t.entityType),void 0!==t.entityId&&(e.entityId=t.entityId),u(t.entity)){const a=l(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=>dt(t))),e}function ct(t){const e=y(t);if(!e||!e.tree)return e??{};const a=u(e.tree)?e.tree:{};return u(a.treeStructure)&&Array.isArray(a.treeStructure.nodes)&&(a.treeStructure.nodes=a.treeStructure.nodes.map(t=>dt(t))),e}class pt{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:h(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:h(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;if(c=d?.includes("application/json")?await r.json():await r.text(),a?.skipTransform&&r.ok)return{data:c};const p=void 0!==c?.result?c.result:c;this.config.debug&&console.log(`[Sazito SDK] ${t} ${e}:`,{status:r.status,data:p});let u=p?m(p):p;const l=["cart","product","user","order","invoice","payment","shippingAddress"];if(u&&"object"==typeof u&&!Array.isArray(u)){const t=Object.keys(u);1===t.length&&l.includes(t[0])&&"object"==typeof u[t[0]]&&null!==u[t[0]]&&(u=u[t[0]])}return r.ok?{data:u}:{error:{status:r.status,message:u?.message||p?.message||r.statusText||"Request failed",type:"api",details:u}}}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 ut{constructor(){this.data=new Map}getItem(t){return this.data.get(t)??null}setItem(t,e){this.data.set(t,e)}removeItem(t){this.data.delete(t)}}class lt{constructor(t){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",this.storage=t??("undefined"!=typeof window&&"undefined"!=typeof localStorage&&"function"==typeof localStorage.getItem?localStorage:new ut)}getCartCredentials(){const t=this.getItem(this.CART_KEY),e=t?.identifier?.trim();return e?{identifier:e}:null}setCartCredentials(t){const e=t.identifier.trim();if(!e)throw new Error("Cart identifier is required.");this.setItem(this.CART_KEY,{identifier:e})}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){try{const e=this.storage.getItem(t);return e?JSON.parse(e):null}catch{return null}}setItem(t,e){try{this.storage.setItem(t,JSON.stringify(e))}catch{}}removeItem(t){try{this.storage.removeItem(t)}catch{}}}const mt="/api/v1/product_categories",ht="/api/v1/search",yt="/api/v2/carts",gt="/api/v2/invoices",ft="/api/v2/shipping_addresses",_t="/api/v2/payments",bt="/api/v1/orders",vt="/api/v1/users",wt="/api/v1/sessions",At="/api/v1/feedbacks",Pt="/api/v1/cms_pages",Ct="/api/v1/images",It="/api/v1/scheduler/events",St="/api/v1/scheduler/bookings",zt="/api/v1/entity_route/route",Et="/api/v1/feedbacks/comments/details";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(zt,{...e,params:{url_part:a}});if(i.data){const t=rt(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:L(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(ht,{...a,params:i});if(r.data){return{data:Y(r.data)}}return r}}class kt{constructor(t){this.http=t}async get(t,e){const a=await this.http.get(`${mt}/${t}`,e);if(a.data){const t=function(t){const e=y(t);return e?tt(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(mt,{...e,params:a});if(i.data){const t=function(t){const e=y(t);return e?(e.categories&&Array.isArray(e.categories)&&(e.categories=e.categories.map(et)),u(e.tree)&&u(e.tree.treeStructure)&&Array.isArray(e.tree.treeStructure.nodes)&&(e.tree.treeStructure.nodes=e.tree.treeStructure.nodes.map(nt)),e):{}}(i.data);return{data:t}}return i}}class Nt{constructor(t,e){this.http=t,this.credentials=e}persistCartCredentials(t){this.credentials.setCartCredentials({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(`${yt}/0`,{...t,params:{identifier:e.identifier}});return a.data?{data:z(a.data)}:(a.error&&this.clearCart(),a)}async create(t,e){const a=await this.http.post(yt,t,e);if(!a.data)return a;const i=z(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(`${yt}/0/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=z(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(`${yt}/0/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=z(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(`${yt}/0/remove_products_from_cart`,{identifier:i.identifier,cartProductId:String(t),variants:[{id:e}]},a);if(r.data){const t=z(r.data);return this.persistCartCredentials(t),{data:t}}return r}clearCart(){this.credentials.clearCartCredentials()}}class Ot{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(bt,{...e,params:a})}async get(t,e){return this.http.get(`${bt}/${t}`,e)}}class Rt{constructor(t,e){this.http=t,this.credentials=e}normalizeInvoiceResponse(t){return t.data?{data:E(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(`${gt}/${a.id}/refresh`,{cart_id:String(0),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(gt,{cart_id:String(0),cart_identifier:e.identifier},t);if(a.data){const t=E(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(`${gt}/${a.id}/refresh`,{cart_id:String(0),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(`${gt}/${r.id}/add_shipping_address`,{identifier:r.identifier,shipping_address_identifier:e,cart_id:0,cart_identifier:i.identifier,...t>0?{shipping_address_id:t}:{}},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(`${gt}/${a.id}/add_discount_code`,{identifier:a.identifier,discount_code:t.toUpperCase()},e);return i.data?(this.credentials.setDiscountCode(t.toUpperCase()),{data:E(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(`${gt}/${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(`${gt}/${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(`${gt}/${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(`${gt}/${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(`${gt}/${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(`${gt}/${e.id}/applicable_shipping_methods`,{...t,cache:t?.cache??!1,params:{identifier:e.identifier}});return a.data?{data:Z(a.data)}:a}clearInvoice(){this.credentials.clearInvoiceCredentials()}}class $t{constructor(t,e){this.http=t,this.credentials=e}sanitizeAddressInput(t){const e={...t};return delete e.user,e}unwrapAddressPayload(t){let e=t;const a=new Set;for(;e&&"object"==typeof e&&!Array.isArray(e)&&!a.has(e);){a.add(e);const t=e,i=t.shippingAddress??t.shipping_address??t.data;if(void 0===i)break;e=i}return e}extractAddressList(t){if(Array.isArray(t))return t;if(!t||"object"!=typeof t)return[];const e=t,a=[e.shippingAddresses,e.addresses,e.items,e.data];for(const t of a)if(Array.isArray(t))return t;return[]}async createAddress(t,e){const a=this.sanitizeAddressInput(t),i=await this.http.post(ft,{shipping_address:a},e);if(i.data){const t=T(this.unwrapAddressPayload(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(ft,{identifier:a.identifier,shipping_address:i},e);if(r.data){const t=T(this.unwrapAddressPayload(r.data));return t?(this.credentials.setShippingCredentials({id:t.id,identifier:t.identifier}),{data:t}):r}return r}async listAddresses(t){const e=await this.http.get(ft,{...t,cache:t?.cache??!1});if(e.error)return{error:e.error};return{data:this.extractAddressList(e.data).map(t=>T(this.unwrapAddressPayload(t))).filter(t=>Boolean(t?.identifier)).sort((t,e)=>e.id-t.id)}}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(`${ft}/${e.id}`,{...t,params:{identifier:e.identifier}});if(a.data){const t=T(this.unwrapAddressPayload(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:H(e.data)}:e.error?{error:e.error}:{data:[]}}clearAddress(){this.credentials.clearShippingCredentials()}}class Gt{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(`${_t}/list`,{invoice_identifier:e.identifier},t);return a.data?{data:J(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(_t,{invoice_identifier:a.identifier,payment_type:t},{...e,skipTransform:!0});if(i.error)return{error:i.error};if(i.data){const t=i.data,e=t&&"object"==typeof t&&"result"in t?t.result?.payment:t.payment;if(e&&"object"==typeof e){const t=String(e.payment_identifier??""),a=Number(e.id??0),i=e.payment_type,r={id:a,identifier:t,amount:Number(e.payment_amount??0),paymentType:{id:null!=i?.id?Number(i.id):void 0,code:i?.reference_code??""}};return t&&this.credentials.setPaymentCredentials({id:a,identifier:t}),{data:r}}}return{data:i.data}}async initialize(t){return this.submitPaymentStep(void 0,t)}async verify(t,e){return this.submitPaymentStep(t,e)}async processStep(t,e){return this.submitPaymentStep(t,e)}async submitPaymentStep(t,e){const a=this.credentials.getPaymentCredentials();if(!a)return{error:{message:"No payment found. Please create a payment first.",type:"validation"}};const{paymentIdentifier:i,...r}=t??{},n=await this.http.post(`${_t}/${a.id}/process_payment_step`,{paymentIdentifier:i||a.identifier,...r},this.withExactJsonHeader(e));return this.finalizeStepResponse(n,a.id,e)}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(`${_t}/${a.id}/process_payment_step`,i,e);return this.finalizeStepResponse(r,a.id,e)}async pollUntilSettled(t,e=15e3){let a=!0;for(;a;){const i=await this.verify(void 0,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=h(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,""))}async finalizeStepResponse(t,e,a){if(!t.data)return t;const i=t=>!!t&&"object"==typeof t&&!Array.isArray(t);let r=t.data;if("string"==typeof r)try{r=JSON.parse(r)}catch{return{error:{message:"Invalid payment step response",type:"api"}}}const n=r;if(i(n)){const t="string"==typeof n.error?n.error:"",e=Number(n.error_code??0);if(t||e)return{error:{message:t||"Payment step failed",type:"api",status:Number(n.status)||void 0}}}const s=i(n)&&i(n.result)?n.result:n,o=this.normalizeAction(s);return await this.callPinchAfterSuccessfulPayment(o,e,a),{data:o}}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 Dt{constructor(t){this.http=t}normalizeUserResponse(t){if(!t.data)return t;const e=k(t.data);return e?{data:e}:t}normalizeLoginResponse(t){if(!t.data||!t.data.user)return t;const e=k(t.data.user);return e?{data:{...t.data,user:e}}:t}async login(t,e){const a=await this.http.post(`${wt}/login`,t,e);return this.normalizeLoginResponse(a)}async requestMobileOTP(t,e){return this.http.post(`${wt}/login_request`,t,e)}async verifyMobileOTP(t,e){const a=await this.http.post(`${wt}/login_request_verification`,t,e);return this.normalizeLoginResponse(a)}async requestEmailLogin(t,e){return this.http.post(`${vt}/email_login_request`,t,e)}async register(t,e){const a=await this.http.post(`${vt}/register`,t,e);return this.normalizeUserResponse(a)}async getCurrentUser(t){const e=await this.http.get(`${vt}/current`,t);return this.normalizeUserResponse(e)}async updateProfile(t,e,a){const i=await this.http.put(`${vt}/${t}`,e,a);return this.normalizeUserResponse(i)}async requestMobilePhoneUpdate(t,e){return this.http.post(`${vt}/update_mobile_phone_request`,t,e)}async verifyMobilePhoneUpdate(t,e){const a=await this.http.post(`${vt}/update_mobile_phone_verification`,t,e);return this.normalizeUserResponse(a)}async forgotPassword(t,e){return this.http.post(`${vt}/forgot_password`,t,e)}async revivePassword(t,e){const a=await this.http.post(`${vt}/revive_password`,t,e);return this.normalizeLoginResponse(a)}async mergeUser(t){return this.http.post(`${vt}/merge_user`,{},t)}}class Ft{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(ht,{...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:Y(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(Et,t,e)}async getProductStatistics(t,e){const a=await this.http.get(`${Et}/${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(`${Et}/${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(At,{...e,params:this.transformLegacyFilters(t)})}async create(t,e){return this.http.post(At,t,e)}async get(t,e){return this.http.get(`${At}/${t}`,e)}}class Mt{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(`${gt}/${t}/add_credit`,{},e)}async removeCredit(t,e){const a=this.validateInvoiceId(t);return a||this.http.post(`${gt}/${t}/remove_credit`,{},e)}}class jt{constructor(t){this.http=t}async getPage(t,e){const a=await this.http.get(zt,{...e,params:{url_part:t}}),i=rt(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=ot({...t,cmsPageTypes:"normal"}),i=await this.http.get(Pt,{...e,params:a});return{...i,data:st(i.data)}}async getBlogPost(t,e){const a=await this.http.get(zt,{...e,params:{url_part:t}}),i=rt(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=ot({...t,cmsPageTypes:"blog"}),i=await this.http.get(Pt,{...e,params:a});return{...i,data:st(i.data)}}async listAll(t,e){const a=ot(t),i=await this.http.get(Pt,{...e,params:a});return{...i,data:st(i.data)}}}class Bt{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(Ct,a,{...e,headers:i})}async delete(t,e){return this.http.delete(`${Ct}/${t}`,e)}}class Ut{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(It,{...e,params:this.transformEventFilters(t)})}async getEvent(t,e){const a=await this.http.get(`${It}/${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(St,t,e)}async listBookings(t){return this.http.get(St,t)}async cancelBooking(t,e){return this.http.post(`${St}/${t}/cancel`,{},e)}}class qt{constructor(t){this.http=t}async resolve(t,e){const a=await this.http.get(zt,{...e,params:{url_part:t}});if(a.data){return{data:rt(a.data)}}return a}}class Lt{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?ct(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{details:e,entity:a}=t,i=this.firstNonEmpty(e?.title,e?.name),r=this.firstNonEmpty(a?.title,a?.name);return!0===e?.isTitleDefault?r||i:i||r}firstNonEmpty(...t){return t.find(t=>"string"==typeof t&&t.trim().length>0)||""}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 Yt{constructor(t){this.http=t}async getInfo(t){const e=await this.http.get("/api/v2/general/info",t);return e.data?{data:g(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 Vt{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 Qt(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function Wt(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 Jt(t){return"string"==typeof t?t.trim():""}class Ht{constructor(t){this.http=t}normalizeCity(t){return Qt(t)?{id:Wt(t.id),name:Jt(t.name),latitude:Wt(t.latitude),longitude:Wt(t.longitude)}:{id:0,name:"",latitude:0,longitude:0}}normalizeRegion(t){if(!Qt(t))return{id:0,name:"",cities:[]};const e=Array.isArray(t.cities)?t.cities:[];return{id:Wt(t.id),name:Jt(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:Qt(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 Zt{constructor(t,a){const i=e(t);this.http=new pt(i),this.tokenStorage=this.http.getTokenStorage(),this.credentialsManager=a??new lt,this.products=new Tt(this.http),this.categories=new kt(this.http),this.cart=new Nt(this.http,this.credentialsManager),this.invoices=new Rt(this.http,this.credentialsManager),this.shipping=new $t(this.http,this.credentialsManager),this.payments=new Gt(this.http,this.credentialsManager),this.orders=new Ot(this.http),this.users=new Dt(this.http),this.search=new Ft(this.http),this.feedbacks=new xt(this.http),this.wallet=new Mt(this.http),this.cms=new jt(this.http),this.images=new Bt(this.http),this.visits=new Ut(this.http),this.booking=new Kt(this.http),this.entityRoutes=new qt(this.http),this.menu=new Lt(this.http),this.general=new Yt(this.http),this.dynamicForms=new Vt(this.http),this.regions=new Ht(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()}getCredentialsManager(){return this.credentialsManager}clearAll(){this.clearAuth(),this.clearCache(),this.clearCredentials()}async searchQuery(t,e,a){return this.search.query(t,e,a)}}function Xt(t,e){return new Zt(t,e)}function te(t){return function(t){if(!t||"object"!=typeof t)return!1;const e=t;return e.http instanceof pt&&e.credentials instanceof lt}(t)?t:function(t){const a=e(t);return{http:new pt(a),credentials:new lt}}(t)}function ee(t){const{http:e}=te(t);return new Tt(e)}function ae(t){const{http:e}=te(t);return new kt(e)}function ie(t){const{http:e,credentials:a}=te(t);return new Nt(e,a)}function re(t){const{http:e}=te(t);return new Ot(e)}function ne(t){const{http:e,credentials:a}=te(t);return new Rt(e,a)}function se(t){const{http:e,credentials:a}=te(t);return new $t(e,a)}function oe(t){const{http:e,credentials:a}=te(t);return new Gt(e,a)}function de(t){const{http:e}=te(t);return new Dt(e)}function ce(t){const{http:e}=te(t);return new Ft(e)}function pe(t){const{http:e}=te(t);return new xt(e)}function ue(t){const{http:e}=te(t);return new Mt(e)}function le(t){const{http:e}=te(t);return new jt(e)}function me(t){const{http:e}=te(t);return new Bt(e)}function he(t){const{http:e}=te(t);return new Ut(e)}function ye(t){const{http:e}=te(t);return new Kt(e)}function ge(t){const{http:e}=te(t);return new qt(e)}function fe(t){const{http:e}=te(t);return new Lt(e)}function _e(t){const{http:e}=te(t);return new Yt(e)}function be(t){const{http:e}=te(t);return new Vt(e)}function ve(t){const{http:e}=te(t);return new Ht(e)}export{lt as CredentialsManager,pt as HttpClient,ut as MemoryStorage,Zt as SazitoClient,a as TokenStorage,ye as booking,ie as cart,ae as categories,le as cms,ye as createBookingAPI,le as createCMSAPI,ie as createCartAPI,ae as createCategoriesAPI,be as createDynamicFormsAPI,ge as createEntityRoutesAPI,pe as createFeedbacksAPI,_e as createGeneralAPI,me as createImagesAPI,ne as createInvoicesAPI,fe as createMenuAPI,re as createOrdersAPI,oe as createPaymentsAPI,ee as createProductsAPI,ve as createRegionsAPI,Xt as createSazitoClient,ce as createSearchAPI,se as createShippingAPI,de as createUsersAPI,he as createVisitsAPI,ue as createWalletAPI,be as dynamicForms,ge as entityRoutes,pe as feedbacks,_e as general,me as images,ne as invoices,fe as menu,re as orders,oe as payments,ee as products,ve as regions,ce as search,se as shipping,n as toEnglishDigits,Q as transformAddToCartInput,y as transformApiResponse,z as transformCartResponse,W as transformCreateCartInput,E as transformInvoiceResponse,L as transformProductListResponse,h as transformRequestKeys,m as transformResponseKeys,V as transformShippingAddressInput,de as users,he as visits,ue 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=new Set(["mobile_phone","phone_number"]);function n(t){return t.replace(/[۰-۹٠-٩]/g,t=>{const e=t.charCodeAt(0);return String(e>=1776?e-1776:e-1632)})}const s={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"},o=Object.values(s).reduce((t,e)=>(t[e]=(t[e]||0)+1,t),{}),d=Object.entries(s).reduce((t,[e,a])=>(1===o[a]&&(t[a]=e),t),{});function c(t){return t.replace(/_([a-z])/g,(t,e)=>e.toUpperCase())}function u(t){return t.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function p(t){return!(null===t||"object"!=typeof t||Array.isArray(t)||t instanceof Date)}function l(t,e){const a={...t};for(const t of e)delete a[t];return a}function m(t){if(!p(t))return Array.isArray(t)?t.map(t=>m(t)):t;const e={};for(const[a,i]of Object.entries(t)){let t=s[a];t||(t=c(a)),p(i)?e[t]=m(i):Array.isArray(i)?e[t]=i.map(t=>m(t)):e[t]=i}return e}function h(t){if(!p(t))return Array.isArray(t)?t.map(t=>h(t)):t;const e={};for(const[a,i]of Object.entries(t)){let t=d[a];t||(t=u(a)),p(i)?e[t]=h(i):Array.isArray(i)?e[t]=i.map(t=>h(t)):e[t]="string"==typeof i&&r.has(t)?n(i):i}return e}function y(t){const e=t;if(p(e?.data?.result)){const t=e.data.result,a=Object.keys(t);return 1===a.length&&p(t[a[0]])?m(t[a[0]]):m(t)}return m(t)}function g(t){if(!t)return{};if(!p(t))return{};const{general:e,shop:a,checkout:i,features:r,wallet:n,tajrobe:s,domain:o,enamad:d,google:c,logo:u,social:l,...m}=t,h={...p(e)?e:{},...p(a)?a:{}},{registerType:y,showProductStockNumber:g,...w}=h||{};return{...m,scripts:{enamad:d,google:c},shop:v({...w,domain:o,logo:u,social:l}),settings:{checkout:f(i),features:C(r),wallet:I(n),tajrobe:S(s),registerType:b(y),showProductStockNumber:_(g)}}}function f(t){if(!p(t))return{};const e=p(t.minBasket)?t.minBasket:{},a=e.minAmount??e.minBasket,i="number"==typeof a?a:Number(a),r={...t,addToCartAlert:_(t.addToCartAlert),dynamicForm:_(t.dynamicForm),emailOptional:_(t.emailOptional??t.email_optional),preventRedirect:_(t.preventRedirect??t.manual),minBasket:{enabled:_(e.enabled),minAmount:Number.isFinite(i)?i:0},miniCart:_(t.miniCart),postalCodeMandatory:_(t.postalCodeMandatory),quickAddToCart:_(t.quickAddToCart)};return delete r.manual,r}function b(t){return"string"==typeof t?t:""}function _(t){return"boolean"==typeof t?t:p(t)&&Object.prototype.hasOwnProperty.call(t,"enabled")?_(t.enabled):1===t||"1"===t||"true"===t}function v(t){if(!p(t))return{};const e={...t};if(p(e.city)){const t=l(e.city,["createdAt","updatedAt"]);let a=t.region;p(a)&&(a=l(a,["createdAt","updatedAt","cities"])),t.region=a,e.city=t}return e}const w={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"},A=new Set(["activateAlopeykAdvanced","activate_alopeyk_advanced"]),P=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 C(t){if(!p(t))return{};const e={},a=(t,a)=>{if(A.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)};p(t.flags)&&Object.entries(t.flags).forEach(([t,e])=>{a(t,e)}),p(t.configurations)&&Object.entries(t.configurations).forEach(([t,e])=>{a(t,e)}),Object.entries(t).forEach(([t,e])=>{"flags"!==t&&"premium"!==t&&"configurations"!==t&&(p(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("_")?c(t):t,a=w[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);P.has(a)||(i[a]=e)});const r={...i};return p(t.premium)&&(r.premium=t.premium),r}function I(t){if(!p(t))return{};const e=p(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 S(t){if(!p(t))return{};const e=p(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 z(t){const e=y(t);if(!p(e))return{};const a=Array.isArray(e.items)?e.items.map(t=>function(t){if(!p(t))return{};const e=q(t),a=j(t.productVariantId??e.variantId)??e.variantId;return{id:K(t.id??t.cartProductId)??"",createdAt:B(t.createdAt),updatedAt:B(t.updatedAt),productVariantId:a,quantity:j(t.quantity)??0,unitPrice:j(t.unitPrice)??0,lineTotal:j(t.lineTotal)??0,product:e,formAttributes:t.formAttributes,formFields:t.formFields,bookingAttributes:t.bookingAttributes}}(t)):[];return{...e,items:a,netTotal:j(e.netTotal)??0,grossTotal:j(e.grossTotal),needsShipping:Boolean(e.needsShipping),minBasketLimitViolated:Boolean(e.minBasketLimitViolated),deleteCoupon:void 0===e.deleteCoupon?void 0:Boolean(e.deleteCoupon)}}function T(t){const e=y(t);if(!p(e))return{};const a=l(e,["shippingMethod","user","userData"]),i=Array.isArray(e.items)?e.items.map(t=>function(t){if(!p(t))return{};const e=q(t),a=j(t.productVariantId??e.variantId)??e.variantId,i=Array.isArray(e.attributes)?e.attributes:[],r=U(e.hasMaxOrder??t.hasMaxOrder);return{id:K(t.id??t.invoiceItemId??t.cartProductId)??"",productVariantId:a,productId:j(e.productId??t.productId),name:B(t.name)??B(e.name)??"",url:B(e.url)??B(t.url),attributes:i,productType:B(e.productType)??B(t.productType),hasMaxOrder:r,maxOrderQuantity:j(e.maxOrderQuantity??t.maxOrderQuantity),minOrderQuantity:j(e.minOrderQuantity??t.minOrderQuantity),image:Y(t.image??e.image),quantity:j(t.quantity)??0,unitPrice:j(t.unitPrice)??0,lineTotal:j(t.lineTotal)??0,rawPrice:j(t.rawPrice??t.originalPrice)??0,customerProfit:j(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=p(n)&&p(n.discountCode)?B(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}}(G(e.shippingAddress)),shippingItems:Array.isArray(e.shippingItems)?e.shippingItems.map(t=>function(t){if(!p(t))return{};const e=p(t.rate)?t.rate:p(t.shippingRate)?t.shippingRate:p(t.shippingMethod)?t.shippingMethod:t;return{invoiceItemIds:M(t),rate:at(e)}}(t)):[],discountUsages:r,netTotal:j(e.netTotal)??0,finalTotal:j(e.finalTotal)??0,vat:j(e.vat)??0,vatPercent:j(e.vatPercent)??0,itemsDiscount:j(e.itemsDiscount)??0,discountTotal:j(e.discountTotal)??0,customerProfit:j(e.customerProfit)??0,customerProfitPercentage:j(e.customerProfitPercentage)??0,itemsTotalRawPrice:j(e.itemsTotalRawPrice)??0,couponTotal:j(e.couponTotal)??0,shippingTotal:j(e.shippingTotal)??0,creditTotal:j(e.creditTotal)??0,needsShipping:Boolean(e.needsShipping),userComment:"string"==typeof e.userComment?e.userComment:void 0,discountCode:s}}function E(t){const e=y(t);if(!p(e))return{};if(!p(e.invoice))return e;const a=T(e.invoice),{items:i,...r}=a;return{...e,invoice:{...r,invoiceItems:Array.isArray(i)?i:[]}}}function N(t){const e=y(t);if(!p(e))return{};const a=Array.isArray(e.orders)?e.orders.map(t=>E(t)):[],i=j(e.pageNumber??e.page),r=j(e.pageSize),n=j(e.totalCount??e.total)??a.length;return{...l(e,["page","total"]),orders:a,totalCount:n,...void 0!==i?{pageNumber:i}:{},...void 0!==r?{pageSize:r}:{}}}function k(t){const e=y(t);if(!p(e))return{};const a=Array.isArray(e.transactions)?e.transactions:Array.isArray(e.walletTransactions)?e.walletTransactions:[],i=j(e.pageNumber??e.page),r=j(e.pageSize),n=j(e.totalCount??e.total);return{...l(e,["page","total","walletTransactions"]),transactions:a,...void 0!==i?{pageNumber:i}:{},...void 0!==r?{pageSize:r}:{},...void 0!==n?{totalCount:n}:{}}}function O(t){return G(t)}function R(t){const e=y(t);if(p(e))return $(e)}function $(t){if(!t)return;const e=function(t){const e=F(t);if(!e)return;if(1===Object.keys(e).length&&p(e.user))return F(e.user)??e.user;return e}(t);if(!e)return;const a={},i=j(e.id);void 0!==i&&(a.id=i);const r=B(e.email);r&&(a.email=r);const n=B(e.mobilePhone)??B(e.phoneNumber);n&&(a.mobilePhone=n);const s=B(e.phoneNumber);s&&s!==n&&(a.phoneNumber=s);const o=B(e.firstName);o&&(a.firstName=o);const d=B(e.lastName);d&&(a.lastName=d);const c=B(e.birthDate);return c&&(a.birthDate=c),Object.keys(a).length>0?a:void 0}function G(t){if(!t||0===Object.keys(t).length)return;const e=$(t.user),a=F(t.region),i=F(t.city),r=F(i?.region),n=B(t.regionName)??x(t.region),s=D(a??t.region,{fallbackId:j(t.regionId),fallbackName:n})??D(r,{fallbackId:j(t.regionId),fallbackName:n}),o=j(t.regionId)??s?.id,d=B(t.cityName)??B(i?.name)??x(t.city),c=function(t,e={}){if(null==t)return;const a=F(t),i=j(a?.id)??j(t)??e.fallbackId,r=B(a?.name)??x(t)??e.fallbackName;if(void 0===i||!r)return;const n={id:i,name:r},s=j(a?.regionId)??e.fallbackRegionId;void 0!==s&&(n.regionId=s);const o=j(a?.latitude);void 0!==o&&(n.latitude=o);const d=j(a?.longitude);void 0!==d&&(n.longitude=d);return n}(i??t.city,{fallbackId:j(t.cityId),fallbackName:d,fallbackRegionId:o}),u=B(t.firstName)??e?.firstName??"",p=B(t.lastName)??e?.lastName??"",l={id:j(t.id)??0,identifier:B(t.identifier)??"",firstName:u,lastName:p,city:c??{id:j(t.cityId??t.city)??0,name:d??"",...void 0!==o?{regionId:o}:{}},address:B(t.address)??""},m=B(t.mobilePhone)??B(t.phoneNumber)??e?.mobilePhone??e?.phoneNumber,h=B(t.phoneNumber)??e?.phoneNumber;m&&(l.mobilePhone=m),h&&h!==m&&(l.phoneNumber=h);const y=B(t.email)??e?.email;y&&(l.email=y),s&&(l.region=s);const g=B(t.postalCode);g&&(l.postalCode=g);const f=B(t.description);f&&(l.description=f);const b=j(t.latitude);void 0!==b&&(l.latitude=b);const _=j(t.longitude);void 0!==_&&(l.longitude=_);const v=U(t.userSetCoordinatesBefore);return void 0!==v&&(l.userSetCoordinatesBefore=v),l}function D(t,e={}){if(null==t)return;const a=F(t),i=j(a?.id)??j(t)??e.fallbackId,r=B(a?.name)??x(t)??e.fallbackName;return void 0!==i&&r?{id:i,name:r}:void 0}function F(t){if(p(t))return p(t.data)?t.data:t}function x(t){const e=B(t);if(e)return void 0===j(e)?e:void 0}function M(t){return(Array.isArray(t.invoiceItemIds)?t.invoiceItemIds:void 0!==t.invoiceItemId?[t.invoiceItemId]:[]).map(t=>K(t)).filter(t=>void 0!==t)}function j(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 B(t){if("string"!=typeof t)return;const e=t.trim();return e.length>0?e:void 0}function U(t){return"boolean"==typeof t?t:1===t||"1"===t||"true"===t||0!==t&&"0"!==t&&"false"!==t&&void 0}function K(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 q(t){if(!p(t))return{variantId:0,name:"",attributes:[]};const e=p(t.variant)?t.variant:void 0,a=p(e?.product)?e.product:void 0,i=p(t.product)?t.product:void 0,r=j(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:j(i?.productId??t.productId??a?.id),name:B(i?.name)??B(t.name)??"",url:B(i?.url)??B(t.url)??B(a?.url),image:Y(i?.image??t.image),attributes:n,productType:B(i?.productType)??B(t.productType)??B(a?.productType),hasMaxOrder:i?.hasMaxOrder??t.hasMaxOrder??e?.hasMaxOrder,maxOrderQuantity:j(i?.maxOrderQuantity??t.maxOrderQuantity??e?.maxOrderQuantity),minOrderQuantity:j(i?.minOrderQuantity??t.minOrderQuantity??e?.minOrderQuantity)}}function L(t){if(!p(t))return{};const e=l(t,["staticUrl","summary","tags","slug"]);return e.variants&&Array.isArray(e.variants)&&(e.variants=e.variants.map(t=>p(t)?l(t,["name","title","product","status","soldCount"]):{})),e.categories&&Array.isArray(e.categories)&&(e.categories=e.categories.map(t=>p(t)?{id:t.id,name:t.name,url:t.url}:{})),e.images&&Array.isArray(e.images)&&(e.images=e.images.map(t=>Y(t)??{})),e}function Y(t){return p(t)?l(t,["widthRatio","heightRatio","thumb","order"]):t}function V(t){const e=L(t);return e?l(e,["themeConfig"]):e}function Q(t){const e=y(t);if(e.items&&Array.isArray(e.items)){const t=j(e.total)??e.items.length,a=j(e.pageSize)??e.items.length,i=j(e.page)??1,r=j(e.totalPages)??Math.ceil(t/a);return{items:e.items.map(t=>V(t)),total:t,page:i,pageSize:a,totalPages:r}}return e}function W(t){if(!p(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=>V(t)),a.products.total=j(e.productsCount)??0,a.products.page=j(e.productsPageNumber)??1,a.products.pageSize=j(e.productsPageSize)??20),Array.isArray(e.blogPages)&&(a.blogPages.items=e.blogPages.map(t=>st(t)),a.blogPages.total=j(e.blogPagesCount)??0,a.blogPages.page=j(e.blogPagesPageNumber)??1,a.blogPages.pageSize=j(e.blogPagesPageSize)??20),Array.isArray(e.cmsPages)&&(a.cmsPages.items=e.cmsPages.map(t=>st(t)),a.cmsPages.total=j(e.cmsPagesCount)??0,a.cmsPages.page=j(e.cmsPagesPageNumber)??1,a.cmsPages.pageSize=j(e.cmsPagesPageSize)??20),Array.isArray(e.categories)&&(a.productCategories.items=e.categories.map(t=>rt(t)),a.productCategories.total=j(e.productCategoriesCount)??0,a.productCategories.page=j(e.productCategoriesPageNumber)??1,a.productCategories.pageSize=j(e.productCategoriesPageSize)??20),a}function J(t){if(p(t)){const e={...t};return delete e.user,{shipping_address:h(e)}}return{shipping_address:h(t)}}function H(t,e,a){const i={product_variants:[{id:t,count:e}]};return a&&(i.form_attributes=h(a)),i}function Z(t){if(!p(t))return{product_variants:[]};const e=t.variants||t.productVariants||[],a={product_variants:Array.isArray(e)?e.map(t=>p(t)?{id:t.id||t.variantId,count:t.count||t.quantity,form_attributes:t.formAttributes?h(t.formAttributes):void 0}:{}):[]};return t.coupon&&(a.coupon=t.coupon),a}function X(t){const e=y(t);if(!p(e))return[];return(Array.isArray(e.paymentTypes)?e.paymentTypes:Array.isArray(e.methods)?e.methods:[]).map(t=>p(t)?{id:j(t.id)??0,code:t.code,title:"string"==typeof t.title?t.title:"",titleFa:"string"==typeof t.titleFa?t.titleFa:"",description:"string"==typeof t.description?t.description:null,paymentSubType:j(t.paymentSubType)??null,order:j(t.order)??0,isDefault:Boolean(t.isDefault)}:{id:0,code:"",title:"",titleFa:"",description:null,paymentSubType:null,order:0,isDefault:!1})}function tt(t){const e=y(t);return(Array.isArray(e)?e:p(e)&&Array.isArray(e.shippingMethods)?e.shippingMethods:[]).map(t=>function(t){if(!p(t))return{id:0,name:"",type:""};return{id:j(t.id)??0,name:B(t.name)??"",type:B(t.type)??""}}(t))}function et(t){const e=y(t);if(!p(e))return{shippingMethods:[],groupedShippingRates:{},itemsShippingRate:[]};const a={};if(Array.isArray(e.shippingMethods)&&e.shippingMethods.forEach((t,e)=>{if(!p(t))return;const i=Array.isArray(t.shippingRate)?t.shippingRate.map(t=>at(t)):[];if(0===i.length)return;const r=Array.isArray(t.invoiceItemIds)?t.invoiceItemIds:[],n=r.length>0?r.map(String).sort().join(","):String(e);a[n]=i}),0===Object.keys(a).length&&p(e.groupedShippingRates))for(const[t,i]of Object.entries(e.groupedShippingRates))a[t]=Array.isArray(i)?i.map(t=>at(t)):[];return{shippingMethods:[],groupedShippingRates:a,itemsShippingRate:Array.isArray(e.itemsShippingRate)?e.itemsShippingRate.map(t=>p(t)?{invoiceItemId:K(t.invoiceItemId)??M(t)[0]??"",shippingRate:at(t.shippingRate??t.rate??t)}:{invoiceItemId:"",shippingRate:at(void 0)}):[]}}function at(t){return p(t)?{id:j(t.id??t.rateId)??0,name:B(t.name)??"",price:j(t.price??t.amount)??0,description:B(t.description??t.deliveryDescription??t.details),icon:B(t.icon??t.iconUrl??t.logo),color:B(t.color??t.bgColor??t.backgroundColor??t.iconColor),type:B(t.type)}:{id:0,name:"",price:0}}function it(t){return p(t)?l(t,["staticUrl","products","items"]):{}}function rt(t){const e=it(t);return e?l(e,["themeConfig"]):{}}function nt(t){return p(t)?l(t,["staticUrl","urlKey"]):{}}function st(t){const e=nt(t);return e?l(e,["themeConfig"]):{}}function ot(t){const e=y(t);if(!e||!e.route)return e??{};const a=p(e.route)?e.route:{};if(a.entity){switch(a.entityType){case"product":a.entity=L(a.entity);break;case"product_category":a.entity=it(a.entity);break;case"cms_page":case"blog_page":a.entity=nt(a.entity)}p(a.entity)&&(a.entity=l(a.entity,["id"])),!a.url&&p(a.entity)&&a.entity.url&&(a.url=a.entity.url)}return a}function dt(t){if(!p(t))return{};const e={...t};return e.entity&&(e.entity=rt(e.entity),p(e.entity)&&(e.entity=l(e.entity,["id"]))),e.children&&Array.isArray(e.children)&&(e.children=e.children.map(dt)),e}function ct(t){const e=y(t);return e?e.cmsPages&&Array.isArray(e.cmsPages)?{items:e.cmsPages.map(st),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=>st(t)),total:e.total||e.items.length,page:e.page||1,pageSize:e.pageSize||e.items.length}:e:{}}function ut(t){if(!p(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 pt(t){if(!p(t))return{};const e={};if(t.entityType&&(e.entityType=t.entityType),void 0!==t.entityId&&(e.entityId=t.entityId),p(t.entity)){const a=l(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=>pt(t))),e}function lt(t){const e=y(t);if(!e||!e.tree)return e??{};const a=p(e.tree)?e.tree:{};return p(a.treeStructure)&&Array.isArray(a.treeStructure.nodes)&&(a.treeStructure.nodes=a.treeStructure.nodes.map(t=>pt(t))),e}class mt{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=e?.params?h(e.params):void 0,r=this.buildUrl(t,a),n=i.generateKey("GET",r,a);if(!1!==e?.cache){const e=this.getApiName(t),a=this.config.cache[e];if(a?.enabled&&a.ttl){const e=this.cache.get(n,a.ttl);if(e)return this.config.debug&&console.log("[Sazito SDK] Cache hit:",t),{data:e}}}const s=await this.request("GET",r,e);return s.data&&!1!==e?.cache&&this.cache.set(n,s.data),s}async post(t,e,a){const i=this.buildUrl(t),r=this.isMultipartBody(e),n=e?r?e:h(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:h(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;if(c=d?.includes("application/json")?await r.json():await r.text(),a?.skipTransform&&r.ok)return{data:c};const u=void 0!==c?.result?c.result:c;this.config.debug&&console.log(`[Sazito SDK] ${t} ${e}:`,{status:r.status,data:u});let p=u?m(u):u;const l=["cart","product","user","order","invoice","payment","shippingAddress"];if(p&&"object"==typeof p&&!Array.isArray(p)){const t=Object.keys(p);1===t.length&&l.includes(t[0])&&"object"==typeof p[t[0]]&&null!==p[t[0]]&&(p=p[t[0]])}return r.ok?{data:p}:{error:{status:r.status,message:p?.message||u?.message||r.statusText||"Request failed",type:"api",details:p}}}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 ht{constructor(){this.data=new Map}getItem(t){return this.data.get(t)??null}setItem(t,e){this.data.set(t,e)}removeItem(t){this.data.delete(t)}}class yt{constructor(t){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",this.storage=t??("undefined"!=typeof window&&"undefined"!=typeof localStorage&&"function"==typeof localStorage.getItem?localStorage:new ht)}getCartCredentials(){const t=this.getItem(this.CART_KEY),e=t?.identifier?.trim();return e?{identifier:e}:null}setCartCredentials(t){const e=t.identifier.trim();if(!e)throw new Error("Cart identifier is required.");this.setItem(this.CART_KEY,{identifier:e})}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){try{const e=this.storage.getItem(t);return e?JSON.parse(e):null}catch{return null}}setItem(t,e){try{this.storage.setItem(t,JSON.stringify(e))}catch{}}removeItem(t){try{this.storage.removeItem(t)}catch{}}}const gt="/api/v1/product_categories",ft="/api/v1/search",bt="/api/v2/carts",_t="/api/v2/invoices",vt="/api/v2/shipping_addresses",wt="/api/v2/payments",At="/api/v1/orders",Pt="/api/v1/users",Ct="/api/v1/sessions",It="/api/v1/feedbacks",St="/api/v1/cms_pages",zt="/api/v1/images",Tt="/api/v1/scheduler/events",Et="/api/v1/scheduler/bookings",Nt="/api/v1/entity_route/route",kt="/api/v1/feedbacks/comments/details";class Ot{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(Nt,{...e,params:{url_part:a}});if(i.data){const t=ot(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:Q(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(ft,{...a,params:i});if(r.data){return{data:W(r.data)}}return r}}class Rt{constructor(t){this.http=t}async get(t,e){const a=await this.http.get(`${gt}/${t}`,e);if(a.data){const t=function(t){const e=y(t);return e?it(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(gt,{...e,params:a});if(i.data){const t=function(t){const e=y(t);return e?(e.categories&&Array.isArray(e.categories)&&(e.categories=e.categories.map(rt)),p(e.tree)&&p(e.tree.treeStructure)&&Array.isArray(e.tree.treeStructure.nodes)&&(e.tree.treeStructure.nodes=e.tree.treeStructure.nodes.map(dt)),e):{}}(i.data);return{data:t}}return i}}class $t{constructor(t,e){this.http=t,this.credentials=e}persistCartCredentials(t){this.credentials.setCartCredentials({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(`${bt}/0`,{...t,params:{identifier:e.identifier}});return a.data?{data:z(a.data)}:(a.error&&this.clearCart(),a)}async create(t,e){const a=await this.http.post(bt,t,e);if(!a.data)return a;const i=z(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(`${bt}/0/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=z(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(`${bt}/0/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=z(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(`${bt}/0/remove_products_from_cart`,{identifier:i.identifier,cartProductId:String(t),variants:[{id:e}]},a);if(r.data){const t=z(r.data);return this.persistCartCredentials(t),{data:t}}return r}clearCart(){this.credentials.clearCartCredentials()}}class Gt{constructor(t){this.http=t}async list(t,e){const a={pageNumber:t?.pageNumber??1,pageSize:t?.pageSize??20};t?.filters&&t.filters.length>0&&(a.filters=JSON.stringify(t.filters));const i=await this.http.get(At,{...e,params:a});return i.data?{data:N(i.data)}:i}async get(t,e){const a=await this.http.get(`${At}/${t}`,e);return a.data?{data:E(a.data)}:a}}class Dt{constructor(t,e){this.http=t,this.credentials=e}normalizeInvoiceResponse(t){return t.data?{data:T(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(`${_t}/${a.id}/refresh`,{cart_id:String(0),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(_t,{cart_id:String(0),cart_identifier:e.identifier},t);if(a.data){const t=T(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(`${_t}/${a.id}/refresh`,{cart_id:String(0),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(`${_t}/${r.id}/add_shipping_address`,{identifier:r.identifier,shipping_address_identifier:e,cart_id:0,cart_identifier:i.identifier,...t>0?{shipping_address_id:t}:{}},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(`${_t}/${a.id}/add_discount_code`,{identifier:a.identifier,discount_code:t.toUpperCase()},e);return i.data?(this.credentials.setDiscountCode(t.toUpperCase()),{data:T(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(`${_t}/${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(`${_t}/${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(`${_t}/${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(`${_t}/${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(`${_t}/${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(`${_t}/${e.id}/applicable_shipping_methods`,{...t,cache:t?.cache??!1,params:{identifier:e.identifier}});return a.data?{data:et(a.data)}:a}clearInvoice(){this.credentials.clearInvoiceCredentials()}}class Ft{constructor(t,e){this.http=t,this.credentials=e}sanitizeAddressInput(t){const e={...t};return delete e.user,e}unwrapAddressPayload(t){let e=t;const a=new Set;for(;e&&"object"==typeof e&&!Array.isArray(e)&&!a.has(e);){a.add(e);const t=e,i=t.shippingAddress??t.shipping_address??t.data;if(void 0===i)break;e=i}return e}extractAddressList(t){if(Array.isArray(t))return t;if(!t||"object"!=typeof t)return[];const e=t,a=[e.shippingAddresses,e.addresses,e.items,e.data];for(const t of a)if(Array.isArray(t))return t;return[]}async createAddress(t,e){const a=this.sanitizeAddressInput(t),i=await this.http.post(vt,{shipping_address:a},e);if(i.data){const t=O(this.unwrapAddressPayload(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(vt,{identifier:a.identifier,shipping_address:i},e);if(r.data){const t=O(this.unwrapAddressPayload(r.data));return t?(this.credentials.setShippingCredentials({id:t.id,identifier:t.identifier}),{data:t}):r}return r}async listAddresses(t){const e=await this.http.get(vt,{...t,cache:t?.cache??!1});if(e.error)return{error:e.error};return{data:this.extractAddressList(e.data).map(t=>O(this.unwrapAddressPayload(t))).filter(t=>Boolean(t?.identifier)).sort((t,e)=>e.id-t.id)}}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(`${vt}/${e.id}`,{...t,params:{identifier:e.identifier}});if(a.data){const t=O(this.unwrapAddressPayload(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:tt(e.data)}:e.error?{error:e.error}:{data:[]}}clearAddress(){this.credentials.clearShippingCredentials()}}class xt{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(`${wt}/list`,{invoice_identifier:e.identifier},t);return a.data?{data:X(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(wt,{invoice_identifier:a.identifier,payment_type:t},{...e,skipTransform:!0});if(i.error)return{error:i.error};if(i.data){const t=i.data,e=t&&"object"==typeof t&&"result"in t?t.result?.payment:t.payment;if(e&&"object"==typeof e){const t=String(e.payment_identifier??""),a=Number(e.id??0),i=e.payment_type,r={id:a,identifier:t,amount:Number(e.payment_amount??0),paymentType:{id:null!=i?.id?Number(i.id):void 0,code:i?.reference_code??""}};return t&&this.credentials.setPaymentCredentials({id:a,identifier:t}),{data:r}}}return{data:i.data}}async initialize(t){return this.submitPaymentStep(void 0,t)}async verify(t,e){return this.submitPaymentStep(t,e)}async processStep(t,e){return this.submitPaymentStep(t,e)}async submitPaymentStep(t,e){const a=this.credentials.getPaymentCredentials();if(!a)return{error:{message:"No payment found. Please create a payment first.",type:"validation"}};const{paymentIdentifier:i,...r}=t??{},n=await this.http.post(`${wt}/${a.id}/process_payment_step`,{paymentIdentifier:i||a.identifier,...r},this.withExactJsonHeader(e));return this.finalizeStepResponse(n,a.id,e)}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(`${wt}/${a.id}/process_payment_step`,i,e);return this.finalizeStepResponse(r,a.id,e)}async pollUntilSettled(t,e=15e3){let a=!0;for(;a;){const i=await this.verify(void 0,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=h(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,""))}async finalizeStepResponse(t,e,a){if(!t.data)return t;const i=t=>!!t&&"object"==typeof t&&!Array.isArray(t);let r=t.data;if("string"==typeof r)try{r=JSON.parse(r)}catch{return{error:{message:"Invalid payment step response",type:"api"}}}const n=r;if(i(n)){const t="string"==typeof n.error?n.error:"",e=Number(n.error_code??0);if(t||e)return{error:{message:t||"Payment step failed",type:"api",status:Number(n.status)||void 0}}}const s=i(n)&&i(n.result)?n.result:n,o=this.normalizeAction(s);return await this.callPinchAfterSuccessfulPayment(o,e,a),{data:o}}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 Mt{constructor(t){this.http=t}normalizeUserResponse(t){if(!t.data)return t;const e=R(t.data);return e?{data:e}:t}normalizeLoginResponse(t){if(!t.data||!t.data.user)return t;const e=R(t.data.user);return e?{data:{...t.data,user:e}}:t}async login(t,e){const a=await this.http.post(`${Ct}/login`,t,e);return this.normalizeLoginResponse(a)}async requestMobileOTP(t,e){return this.http.post(`${Ct}/login_request`,t,e)}async verifyMobileOTP(t,e){const a=await this.http.post(`${Ct}/login_request_verification`,t,e);return this.normalizeLoginResponse(a)}async requestEmailLogin(t,e){return this.http.post(`${Pt}/email_login_request`,t,e)}async register(t,e){const a=await this.http.post(`${Pt}/register`,t,e);return this.normalizeUserResponse(a)}async getCurrentUser(t){const e=await this.http.get(`${Pt}/current`,t);return this.normalizeUserResponse(e)}async updateProfile(t,e,a){const i=await this.http.put(`${Pt}/${t}`,e,a);return this.normalizeUserResponse(i)}async requestMobilePhoneUpdate(t,e){return this.http.post(`${Pt}/update_mobile_phone_request`,t,e)}async verifyMobilePhoneUpdate(t,e){const a=await this.http.post(`${Pt}/update_mobile_phone_verification`,t,e);return this.normalizeUserResponse(a)}async forgotPassword(t,e){return this.http.post(`${Pt}/forgot_password`,t,e)}async revivePassword(t,e){const a=await this.http.post(`${Pt}/revive_password`,t,e);return this.normalizeLoginResponse(a)}async mergeUser(t){return this.http.post(`${Pt}/merge_user`,{},t)}}class jt{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(ft,{...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:W(r.data)}}return r}}class Bt{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(kt,t,e)}async getProductStatistics(t,e){const a=await this.http.get(`${kt}/${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(`${kt}/${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(It,{...e,params:this.transformLegacyFilters(t)})}async create(t,e){return this.http.post(It,t,e)}async get(t,e){return this.http.get(`${It}/${t}`,e)}}class Ut{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?.pageNumber??t?.page_number??1,i=t?.pageSize??t?.page_size??20,r=await this.http.get("/api/v1/wallet/transactions",{...e,params:{pageNumber:a,pageSize:i}});return r.data?{data:k(r.data)}:r}async applyCredit(t,e){const a=this.validateInvoiceId(t);if(a)return a;const i=await this.http.post(`${_t}/${t}/add_credit`,{},e);return i.data?{data:T(i.data)}:i}async removeCredit(t,e){const a=this.validateInvoiceId(t);if(a)return a;const i=await this.http.post(`${_t}/${t}/remove_credit`,{},e);return i.data?{data:T(i.data)}:i}}class Kt{constructor(t){this.http=t}async getPage(t,e){const a=await this.http.get(Nt,{...e,params:{url_part:t}}),i=ot(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=ut({...t,cmsPageTypes:"normal"}),i=await this.http.get(St,{...e,params:a});return{...i,data:ct(i.data)}}async getBlogPost(t,e){const a=await this.http.get(Nt,{...e,params:{url_part:t}}),i=ot(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=ut({...t,cmsPageTypes:"blog"}),i=await this.http.get(St,{...e,params:a});return{...i,data:ct(i.data)}}async listAll(t,e){const a=ut(t),i=await this.http.get(St,{...e,params:a});return{...i,data:ct(i.data)}}}class qt{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(zt,a,{...e,headers:i})}async delete(t,e){return this.http.delete(`${zt}/${t}`,e)}}class Lt{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 Yt{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(Tt,{...e,params:this.transformEventFilters(t)})}async getEvent(t,e){const a=await this.http.get(`${Tt}/${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(Et,t,e)}async listBookings(t){return this.http.get(Et,t)}async cancelBooking(t,e){return this.http.post(`${Et}/${t}/cancel`,{},e)}}class Vt{constructor(t){this.http=t}async resolve(t,e){const a=await this.http.get(Nt,{...e,params:{url_part:t}});if(a.data){return{data:ot(a.data)}}return a}}class Qt{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?lt(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{details:e,entity:a}=t,i=this.firstNonEmpty(e?.title,e?.name),r=this.firstNonEmpty(a?.title,a?.name);return!0===e?.isTitleDefault?r||i:i||r}firstNonEmpty(...t){return t.find(t=>"string"==typeof t&&t.trim().length>0)||""}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 Wt{constructor(t){this.http=t}async getInfo(t){const e=await this.http.get("/api/v2/general/info",t);return e.data?{data:g(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 Jt{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 Ht(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function Zt(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 Xt(t){return"string"==typeof t?t.trim():""}class te{constructor(t){this.http=t}normalizeCity(t){return Ht(t)?{id:Zt(t.id),name:Xt(t.name),latitude:Zt(t.latitude),longitude:Zt(t.longitude)}:{id:0,name:"",latitude:0,longitude:0}}normalizeRegion(t){if(!Ht(t))return{id:0,name:"",cities:[]};const e=Array.isArray(t.cities)?t.cities:[];return{id:Zt(t.id),name:Xt(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:Ht(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 ee{constructor(t,a){const i=e(t);this.http=new mt(i),this.tokenStorage=this.http.getTokenStorage(),this.credentialsManager=a??new yt,this.products=new Ot(this.http),this.categories=new Rt(this.http),this.cart=new $t(this.http,this.credentialsManager),this.invoices=new Dt(this.http,this.credentialsManager),this.shipping=new Ft(this.http,this.credentialsManager),this.payments=new xt(this.http,this.credentialsManager),this.orders=new Gt(this.http),this.users=new Mt(this.http),this.search=new jt(this.http),this.feedbacks=new Bt(this.http),this.wallet=new Ut(this.http),this.cms=new Kt(this.http),this.images=new qt(this.http),this.visits=new Lt(this.http),this.booking=new Yt(this.http),this.entityRoutes=new Vt(this.http),this.menu=new Qt(this.http),this.general=new Wt(this.http),this.dynamicForms=new Jt(this.http),this.regions=new te(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()}getCredentialsManager(){return this.credentialsManager}clearAll(){this.clearAuth(),this.clearCache(),this.clearCredentials()}async searchQuery(t,e,a){return this.search.query(t,e,a)}}function ae(t,e){return new ee(t,e)}function ie(t){return function(t){if(!t||"object"!=typeof t)return!1;const e=t;return e.http instanceof mt&&e.credentials instanceof yt}(t)?t:function(t){const a=e(t);return{http:new mt(a),credentials:new yt}}(t)}function re(t){const{http:e}=ie(t);return new Ot(e)}function ne(t){const{http:e}=ie(t);return new Rt(e)}function se(t){const{http:e,credentials:a}=ie(t);return new $t(e,a)}function oe(t){const{http:e}=ie(t);return new Gt(e)}function de(t){const{http:e,credentials:a}=ie(t);return new Dt(e,a)}function ce(t){const{http:e,credentials:a}=ie(t);return new Ft(e,a)}function ue(t){const{http:e,credentials:a}=ie(t);return new xt(e,a)}function pe(t){const{http:e}=ie(t);return new Mt(e)}function le(t){const{http:e}=ie(t);return new jt(e)}function me(t){const{http:e}=ie(t);return new Bt(e)}function he(t){const{http:e}=ie(t);return new Ut(e)}function ye(t){const{http:e}=ie(t);return new Kt(e)}function ge(t){const{http:e}=ie(t);return new qt(e)}function fe(t){const{http:e}=ie(t);return new Lt(e)}function be(t){const{http:e}=ie(t);return new Yt(e)}function _e(t){const{http:e}=ie(t);return new Vt(e)}function ve(t){const{http:e}=ie(t);return new Qt(e)}function we(t){const{http:e}=ie(t);return new Wt(e)}function Ae(t){const{http:e}=ie(t);return new Jt(e)}function Pe(t){const{http:e}=ie(t);return new te(e)}export{yt as CredentialsManager,mt as HttpClient,ht as MemoryStorage,ee as SazitoClient,a as TokenStorage,be as booking,se as cart,ne as categories,ye as cms,be as createBookingAPI,ye as createCMSAPI,se as createCartAPI,ne as createCategoriesAPI,Ae as createDynamicFormsAPI,_e as createEntityRoutesAPI,me as createFeedbacksAPI,we as createGeneralAPI,ge as createImagesAPI,de as createInvoicesAPI,ve as createMenuAPI,oe as createOrdersAPI,ue as createPaymentsAPI,re as createProductsAPI,Pe as createRegionsAPI,ae as createSazitoClient,le as createSearchAPI,ce as createShippingAPI,pe as createUsersAPI,fe as createVisitsAPI,he as createWalletAPI,Ae as dynamicForms,_e as entityRoutes,me as feedbacks,we as general,ge as images,de as invoices,ve as menu,oe as orders,ue as payments,re as products,Pe as regions,le as search,ce as shipping,n as toEnglishDigits,H as transformAddToCartInput,y as transformApiResponse,z as transformCartResponse,Z as transformCreateCartInput,T as transformInvoiceResponse,Q as transformProductListResponse,h as transformRequestKeys,m as transformResponseKeys,J as transformShippingAddressInput,pe as users,fe as visits,he as wallet};
package/dist/index.umd.js CHANGED
@@ -1 +1 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).SazitoSDK={})}(this,function(t){"use strict";const e={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 a(t){return{...e,...t,retry:{...e.retry,...t.retry},cache:{...e.cache,...t.cache},customFetchApi:t.customFetchApi||("undefined"!=typeof fetch?fetch:void 0)}}class i{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 r{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 n=new Set(["mobile_phone","phone_number"]);function s(t){return t.replace(/[۰-۹٠-٩]/g,t=>{const e=t.charCodeAt(0);return String(e>=1776?e-1776:e-1632)})}const o={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"},d=Object.values(o).reduce((t,e)=>(t[e]=(t[e]||0)+1,t),{}),c=Object.entries(o).reduce((t,[e,a])=>(1===d[a]&&(t[a]=e),t),{});function p(t){return t.replace(/_([a-z])/g,(t,e)=>e.toUpperCase())}function u(t){return t.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function l(t){return!(null===t||"object"!=typeof t||Array.isArray(t)||t instanceof Date)}function m(t,e){const a={...t};for(const t of e)delete a[t];return a}function h(t){if(!l(t))return Array.isArray(t)?t.map(t=>h(t)):t;const e={};for(const[a,i]of Object.entries(t)){let t=o[a];t||(t=p(a)),l(i)?e[t]=h(i):Array.isArray(i)?e[t]=i.map(t=>h(t)):e[t]=i}return e}function y(t){if(!l(t))return Array.isArray(t)?t.map(t=>y(t)):t;const e={};for(const[a,i]of Object.entries(t)){let t=c[a];t||(t=u(a)),l(i)?e[t]=y(i):Array.isArray(i)?e[t]=i.map(t=>y(t)):e[t]="string"==typeof i&&n.has(t)?s(i):i}return e}function g(t){const e=t;if(l(e?.data?.result)){const t=e.data.result,a=Object.keys(t);return 1===a.length&&l(t[a[0]])?h(t[a[0]]):h(t)}return h(t)}function f(t){if(!t)return{};if(!l(t))return{};const{general:e,shop:a,checkout:i,features:r,wallet:n,tajrobe:s,domain:o,enamad:d,google:c,logo:p,social:u,...m}=t,h={...l(e)?e:{},...l(a)?a:{}},{registerType:y,showProductStockNumber:g,...f}=h||{};return{...m,scripts:{enamad:d,google:c},shop:w({...f,domain:o,logo:p,social:u}),settings:{checkout:b(i),features:C(r),wallet:S(n),tajrobe:z(s),registerType:_(y),showProductStockNumber:v(g)}}}function b(t){if(!l(t))return{};const e=l(t.minBasket)?t.minBasket:{},a=e.minAmount??e.minBasket,i="number"==typeof a?a:Number(a),r={...t,addToCartAlert:v(t.addToCartAlert),dynamicForm:v(t.dynamicForm),emailOptional:v(t.emailOptional??t.email_optional),preventRedirect:v(t.preventRedirect??t.manual),minBasket:{enabled:v(e.enabled),minAmount:Number.isFinite(i)?i:0},miniCart:v(t.miniCart),postalCodeMandatory:v(t.postalCodeMandatory),quickAddToCart:v(t.quickAddToCart)};return delete r.manual,r}function _(t){return"string"==typeof t?t:""}function v(t){return"boolean"==typeof t?t:l(t)&&Object.prototype.hasOwnProperty.call(t,"enabled")?v(t.enabled):1===t||"1"===t||"true"===t}function w(t){if(!l(t))return{};const e={...t};if(l(e.city)){const t=m(e.city,["createdAt","updatedAt"]);let a=t.region;l(a)&&(a=m(a,["createdAt","updatedAt","cities"])),t.region=a,e.city=t}return e}const A={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"},P=new Set(["activateAlopeykAdvanced","activate_alopeyk_advanced"]),I=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 C(t){if(!l(t))return{};const e={},a=(t,a)=>{if(P.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)};l(t.flags)&&Object.entries(t.flags).forEach(([t,e])=>{a(t,e)}),l(t.configurations)&&Object.entries(t.configurations).forEach(([t,e])=>{a(t,e)}),Object.entries(t).forEach(([t,e])=>{"flags"!==t&&"premium"!==t&&"configurations"!==t&&(l(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("_")?p(t):t,a=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);I.has(a)||(i[a]=e)});const r={...i};return l(t.premium)&&(r.premium=t.premium),r}function S(t){if(!l(t))return{};const e=l(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 z(t){if(!l(t))return{};const e=l(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 T(t){const e=g(t);if(!l(e))return{};const a=Array.isArray(e.items)?e.items.map(t=>function(t){if(!l(t))return{};const e=U(t),a=x(t.productVariantId??e.variantId)??e.variantId;return{id:B(t.id??t.cartProductId)??"",productVariantId:a,quantity:x(t.quantity)??0,unitPrice:x(t.unitPrice)??0,lineTotal:x(t.lineTotal)??0,product:e,formAttributes:t.formAttributes,formFields:t.formFields,bookingAttributes:t.bookingAttributes}}(t)):[];return{...e,items:a,netTotal:x(e.netTotal)??0,grossTotal:x(e.grossTotal),needsShipping:Boolean(e.needsShipping),minBasketLimitViolated:Boolean(e.minBasketLimitViolated),deleteCoupon:void 0===e.deleteCoupon?void 0:Boolean(e.deleteCoupon)}}function E(t){const e=g(t);if(!l(e))return{};const a=m(e,["shippingMethod","user","userData"]),i=Array.isArray(e.items)?e.items.map(t=>function(t){if(!l(t))return{};const e=U(t),a=x(t.productVariantId??e.variantId)??e.variantId,i=Array.isArray(e.attributes)?e.attributes:[],r=j(e.hasMaxOrder??t.hasMaxOrder);return{id:B(t.id??t.invoiceItemId??t.cartProductId)??"",productVariantId:a,productId:x(e.productId??t.productId),name:M(t.name)??M(e.name)??"",url:M(e.url)??M(t.url),attributes:i,productType:M(e.productType)??M(t.productType),hasMaxOrder:r,maxOrderQuantity:x(e.maxOrderQuantity??t.maxOrderQuantity),minOrderQuantity:x(e.minOrderQuantity??t.minOrderQuantity),image:q(t.image??e.image),quantity:x(t.quantity)??0,unitPrice:x(t.unitPrice)??0,lineTotal:x(t.lineTotal)??0,rawPrice:x(t.rawPrice??t.originalPrice)??0,customerProfit:x(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=l(n)&&l(n.discountCode)?M(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}}(O(e.shippingAddress)),shippingItems:Array.isArray(e.shippingItems)?e.shippingItems.map(t=>function(t){if(!l(t))return{};const e=l(t.rate)?t.rate:l(t.shippingRate)?t.shippingRate:l(t.shippingMethod)?t.shippingMethod:t;return{invoiceItemIds:F(t),rate:J(e)}}(t)):[],discountUsages:r,netTotal:x(e.netTotal)??0,finalTotal:x(e.finalTotal)??0,vat:x(e.vat)??0,vatPercent:x(e.vatPercent)??0,itemsDiscount:x(e.itemsDiscount)??0,discountTotal:x(e.discountTotal)??0,customerProfit:x(e.customerProfit)??0,customerProfitPercentage:x(e.customerProfitPercentage)??0,itemsTotalRawPrice:x(e.itemsTotalRawPrice)??0,couponTotal:x(e.couponTotal)??0,shippingTotal:x(e.shippingTotal)??0,creditTotal:x(e.creditTotal)??0,needsShipping:Boolean(e.needsShipping),userComment:"string"==typeof e.userComment?e.userComment:void 0,discountCode:s}}function k(t){return O(t)}function N(t){const e=g(t);if(l(e))return R(e)}function R(t){if(!t)return;const e=function(t){const e=D(t);if(!e)return;if(1===Object.keys(e).length&&l(e.user))return D(e.user)??e.user;return e}(t);if(!e)return;const a={},i=x(e.id);void 0!==i&&(a.id=i);const r=M(e.email);r&&(a.email=r);const n=M(e.mobilePhone)??M(e.phoneNumber);n&&(a.mobilePhone=n);const s=M(e.phoneNumber);s&&s!==n&&(a.phoneNumber=s);const o=M(e.firstName);o&&(a.firstName=o);const d=M(e.lastName);d&&(a.lastName=d);const c=M(e.birthDate);return c&&(a.birthDate=c),Object.keys(a).length>0?a:void 0}function O(t){if(!t||0===Object.keys(t).length)return;const e=R(t.user),a=D(t.region),i=D(t.city),r=D(i?.region),n=M(t.regionName)??G(t.region),s=$(a??t.region,{fallbackId:x(t.regionId),fallbackName:n})??$(r,{fallbackId:x(t.regionId),fallbackName:n}),o=x(t.regionId)??s?.id,d=M(t.cityName)??M(i?.name)??G(t.city),c=function(t,e={}){if(null==t)return;const a=D(t),i=x(a?.id)??x(t)??e.fallbackId,r=M(a?.name)??G(t)??e.fallbackName;if(void 0===i||!r)return;const n={id:i,name:r},s=x(a?.regionId)??e.fallbackRegionId;void 0!==s&&(n.regionId=s);const o=x(a?.latitude);void 0!==o&&(n.latitude=o);const d=x(a?.longitude);void 0!==d&&(n.longitude=d);return n}(i??t.city,{fallbackId:x(t.cityId),fallbackName:d,fallbackRegionId:o}),p=M(t.firstName)??e?.firstName??"",u=M(t.lastName)??e?.lastName??"",l={id:x(t.id)??0,identifier:M(t.identifier)??"",firstName:p,lastName:u,city:c??{id:x(t.cityId??t.city)??0,name:d??"",...void 0!==o?{regionId:o}:{}},address:M(t.address)??""},m=M(t.mobilePhone)??M(t.phoneNumber)??e?.mobilePhone??e?.phoneNumber,h=M(t.phoneNumber)??e?.phoneNumber;m&&(l.mobilePhone=m),h&&h!==m&&(l.phoneNumber=h);const y=M(t.email)??e?.email;y&&(l.email=y),s&&(l.region=s);const g=M(t.postalCode);g&&(l.postalCode=g);const f=M(t.description);f&&(l.description=f);const b=x(t.latitude);void 0!==b&&(l.latitude=b);const _=x(t.longitude);void 0!==_&&(l.longitude=_);const v=j(t.userSetCoordinatesBefore);return void 0!==v&&(l.userSetCoordinatesBefore=v),l}function $(t,e={}){if(null==t)return;const a=D(t),i=x(a?.id)??x(t)??e.fallbackId,r=M(a?.name)??G(t)??e.fallbackName;return void 0!==i&&r?{id:i,name:r}:void 0}function D(t){if(l(t))return l(t.data)?t.data:t}function G(t){const e=M(t);if(e)return void 0===x(e)?e:void 0}function F(t){return(Array.isArray(t.invoiceItemIds)?t.invoiceItemIds:void 0!==t.invoiceItemId?[t.invoiceItemId]:[]).map(t=>B(t)).filter(t=>void 0!==t)}function x(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 M(t){if("string"!=typeof t)return;const e=t.trim();return e.length>0?e:void 0}function j(t){return"boolean"==typeof t?t:1===t||"1"===t||"true"===t||0!==t&&"0"!==t&&"false"!==t&&void 0}function B(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 U(t){if(!l(t))return{variantId:0,name:"",attributes:[]};const e=l(t.variant)?t.variant:void 0,a=l(e?.product)?e.product:void 0,i=l(t.product)?t.product:void 0,r=x(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:x(i?.productId??t.productId??a?.id),name:M(i?.name)??M(t.name)??"",url:M(i?.url)??M(t.url)??M(a?.url),image:q(i?.image??t.image),attributes:n,productType:M(i?.productType)??M(t.productType)??M(a?.productType),hasMaxOrder:i?.hasMaxOrder??t.hasMaxOrder??e?.hasMaxOrder,maxOrderQuantity:x(i?.maxOrderQuantity??t.maxOrderQuantity??e?.maxOrderQuantity),minOrderQuantity:x(i?.minOrderQuantity??t.minOrderQuantity??e?.minOrderQuantity)}}function K(t){if(!l(t))return{};const e=m(t,["staticUrl","summary","tags","slug"]);return e.variants&&Array.isArray(e.variants)&&(e.variants=e.variants.map(t=>l(t)?m(t,["name","title","product","status","soldCount"]):{})),e.categories&&Array.isArray(e.categories)&&(e.categories=e.categories.map(t=>l(t)?{id:t.id,name:t.name,url:t.url}:{})),e.images&&Array.isArray(e.images)&&(e.images=e.images.map(t=>q(t)??{})),e}function q(t){return l(t)?m(t,["widthRatio","heightRatio","thumb","order"]):t}function L(t){const e=K(t);return e?m(e,["themeConfig"]):e}function Y(t){const e=g(t);if(e.items&&Array.isArray(e.items)){const t=x(e.total)??e.items.length,a=x(e.pageSize)??e.items.length,i=x(e.page)??1,r=x(e.totalPages)??Math.ceil(t/a);return{items:e.items.map(t=>L(t)),total:t,page:i,pageSize:a,totalPages:r}}return e}function V(t){if(!l(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=>L(t)),a.products.total=x(e.productsCount)??0,a.products.page=x(e.productsPageNumber)??1,a.products.pageSize=x(e.productsPageSize)??20),Array.isArray(e.blogPages)&&(a.blogPages.items=e.blogPages.map(t=>et(t)),a.blogPages.total=x(e.blogPagesCount)??0,a.blogPages.page=x(e.blogPagesPageNumber)??1,a.blogPages.pageSize=x(e.blogPagesPageSize)??20),Array.isArray(e.cmsPages)&&(a.cmsPages.items=e.cmsPages.map(t=>et(t)),a.cmsPages.total=x(e.cmsPagesCount)??0,a.cmsPages.page=x(e.cmsPagesPageNumber)??1,a.cmsPages.pageSize=x(e.cmsPagesPageSize)??20),Array.isArray(e.categories)&&(a.productCategories.items=e.categories.map(t=>X(t)),a.productCategories.total=x(e.productCategoriesCount)??0,a.productCategories.page=x(e.productCategoriesPageNumber)??1,a.productCategories.pageSize=x(e.productCategoriesPageSize)??20),a}function Q(t){const e=g(t);if(!l(e))return[];return(Array.isArray(e.paymentTypes)?e.paymentTypes:Array.isArray(e.methods)?e.methods:[]).map(t=>l(t)?{id:x(t.id)??0,code:t.code,title:"string"==typeof t.title?t.title:"",titleFa:"string"==typeof t.titleFa?t.titleFa:"",description:"string"==typeof t.description?t.description:null,paymentSubType:x(t.paymentSubType)??null,order:x(t.order)??0,isDefault:Boolean(t.isDefault)}:{id:0,code:"",title:"",titleFa:"",description:null,paymentSubType:null,order:0,isDefault:!1})}function W(t){const e=g(t);return(Array.isArray(e)?e:l(e)&&Array.isArray(e.shippingMethods)?e.shippingMethods:[]).map(t=>function(t){if(!l(t))return{id:0,name:"",type:""};return{id:x(t.id)??0,name:M(t.name)??"",type:M(t.type)??""}}(t))}function H(t){const e=g(t);if(!l(e))return{shippingMethods:[],groupedShippingRates:{},itemsShippingRate:[]};const a={};if(Array.isArray(e.shippingMethods)&&e.shippingMethods.forEach((t,e)=>{if(!l(t))return;const i=Array.isArray(t.shippingRate)?t.shippingRate.map(t=>J(t)):[];if(0===i.length)return;const r=Array.isArray(t.invoiceItemIds)?t.invoiceItemIds:[],n=r.length>0?r.map(String).sort().join(","):String(e);a[n]=i}),0===Object.keys(a).length&&l(e.groupedShippingRates))for(const[t,i]of Object.entries(e.groupedShippingRates))a[t]=Array.isArray(i)?i.map(t=>J(t)):[];return{shippingMethods:[],groupedShippingRates:a,itemsShippingRate:Array.isArray(e.itemsShippingRate)?e.itemsShippingRate.map(t=>l(t)?{invoiceItemId:B(t.invoiceItemId)??F(t)[0]??"",shippingRate:J(t.shippingRate??t.rate??t)}:{invoiceItemId:"",shippingRate:J(void 0)}):[]}}function J(t){return l(t)?{id:x(t.id??t.rateId)??0,name:M(t.name)??"",price:x(t.price??t.amount)??0,description:M(t.description??t.deliveryDescription??t.details),icon:M(t.icon??t.iconUrl??t.logo),color:M(t.color??t.bgColor??t.backgroundColor??t.iconColor),type:M(t.type)}:{id:0,name:"",price:0}}function Z(t){return l(t)?m(t,["staticUrl","products","items"]):{}}function X(t){const e=Z(t);return e?m(e,["themeConfig"]):{}}function tt(t){return l(t)?m(t,["staticUrl","urlKey"]):{}}function et(t){const e=tt(t);return e?m(e,["themeConfig"]):{}}function at(t){const e=g(t);if(!e||!e.route)return e??{};const a=l(e.route)?e.route:{};if(a.entity){switch(a.entityType){case"product":a.entity=K(a.entity);break;case"product_category":a.entity=Z(a.entity);break;case"cms_page":case"blog_page":a.entity=tt(a.entity)}l(a.entity)&&(a.entity=m(a.entity,["id"])),!a.url&&l(a.entity)&&a.entity.url&&(a.url=a.entity.url)}return a}function it(t){if(!l(t))return{};const e={...t};return e.entity&&(e.entity=X(e.entity),l(e.entity)&&(e.entity=m(e.entity,["id"]))),e.children&&Array.isArray(e.children)&&(e.children=e.children.map(it)),e}function rt(t){const e=g(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(!l(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(!l(t))return{};const e={};if(t.entityType&&(e.entityType=t.entityType),void 0!==t.entityId&&(e.entityId=t.entityId),l(t.entity)){const a=m(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=g(t);if(!e||!e.tree)return e??{};const a=l(e.tree)?e.tree:{};return l(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 i,this.cache=new r,this.fetchApi=t.customFetchApi.bind(globalThis)}async get(t,e){const a=this.buildUrl(t,e?.params),i=r.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(i,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(i,n.data),n}async post(t,e,a){const i=this.buildUrl(t),r=this.isMultipartBody(e),n=e?r?e:y(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:y(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;if(c=d?.includes("application/json")?await r.json():await r.text(),a?.skipTransform&&r.ok)return{data:c};const p=void 0!==c?.result?c.result:c;this.config.debug&&console.log(`[Sazito SDK] ${t} ${e}:`,{status:r.status,data:p});let u=p?h(p):p;const l=["cart","product","user","order","invoice","payment","shippingAddress"];if(u&&"object"==typeof u&&!Array.isArray(u)){const t=Object.keys(u);1===t.length&&l.includes(t[0])&&"object"==typeof u[t[0]]&&null!==u[t[0]]&&(u=u[t[0]])}return r.ok?{data:u}:{error:{status:r.status,message:u?.message||p?.message||r.statusText||"Request failed",type:"api",details:u}}}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.data=new Map}getItem(t){return this.data.get(t)??null}setItem(t,e){this.data.set(t,e)}removeItem(t){this.data.delete(t)}}class pt{constructor(t){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",this.storage=t??("undefined"!=typeof window&&"undefined"!=typeof localStorage&&"function"==typeof localStorage.getItem?localStorage:new ct)}getCartCredentials(){const t=this.getItem(this.CART_KEY),e=t?.identifier?.trim();return e?{identifier:e}:null}setCartCredentials(t){const e=t.identifier.trim();if(!e)throw new Error("Cart identifier is required.");this.setItem(this.CART_KEY,{identifier:e})}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){try{const e=this.storage.getItem(t);return e?JSON.parse(e):null}catch{return null}}setItem(t,e){try{this.storage.setItem(t,JSON.stringify(e))}catch{}}removeItem(t){try{this.storage.removeItem(t)}catch{}}}const ut="/api/v1/product_categories",lt="/api/v1/search",mt="/api/v2/carts",ht="/api/v2/invoices",yt="/api/v2/shipping_addresses",gt="/api/v2/payments",ft="/api/v1/orders",bt="/api/v1/users",_t="/api/v1/sessions",vt="/api/v1/feedbacks",wt="/api/v1/cms_pages",At="/api/v1/images",Pt="/api/v1/scheduler/events",It="/api/v1/scheduler/bookings",Ct="/api/v1/entity_route/route",St="/api/v1/feedbacks/comments/details";class zt{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(Ct,{...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:Y(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(lt,{...a,params:i});if(r.data){return{data:V(r.data)}}return r}}class Tt{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=g(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=g(t);return e?(e.categories&&Array.isArray(e.categories)&&(e.categories=e.categories.map(X)),l(e.tree)&&l(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({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(`${mt}/0`,{...t,params:{identifier:e.identifier}});return a.data?{data:T(a.data)}:(a.error&&this.clearCart(),a)}async create(t,e){const a=await this.http.post(mt,t,e);if(!a.data)return a;const i=T(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(`${mt}/0/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=T(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(`${mt}/0/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=T(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(`${mt}/0/remove_products_from_cart`,{identifier:i.identifier,cartProductId:String(t),variants:[{id:e}]},a);if(r.data){const t=T(r.data);return this.persistCartCredentials(t),{data:t}}return r}clearCart(){this.credentials.clearCartCredentials()}}class kt{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(ft,{...e,params:a})}async get(t,e){return this.http.get(`${ft}/${t}`,e)}}class Nt{constructor(t,e){this.http=t,this.credentials=e}normalizeInvoiceResponse(t){return t.data?{data:E(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(`${ht}/${a.id}/refresh`,{cart_id:String(0),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(ht,{cart_id:String(0),cart_identifier:e.identifier},t);if(a.data){const t=E(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(`${ht}/${a.id}/refresh`,{cart_id:String(0),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(`${ht}/${r.id}/add_shipping_address`,{identifier:r.identifier,shipping_address_identifier:e,cart_id:0,cart_identifier:i.identifier,...t>0?{shipping_address_id:t}:{}},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(`${ht}/${a.id}/add_discount_code`,{identifier:a.identifier,discount_code:t.toUpperCase()},e);return i.data?(this.credentials.setDiscountCode(t.toUpperCase()),{data:E(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(`${ht}/${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(`${ht}/${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(`${ht}/${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(`${ht}/${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(`${ht}/${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(`${ht}/${e.id}/applicable_shipping_methods`,{...t,cache:t?.cache??!1,params:{identifier:e.identifier}});return a.data?{data:H(a.data)}:a}clearInvoice(){this.credentials.clearInvoiceCredentials()}}class Rt{constructor(t,e){this.http=t,this.credentials=e}sanitizeAddressInput(t){const e={...t};return delete e.user,e}unwrapAddressPayload(t){let e=t;const a=new Set;for(;e&&"object"==typeof e&&!Array.isArray(e)&&!a.has(e);){a.add(e);const t=e,i=t.shippingAddress??t.shipping_address??t.data;if(void 0===i)break;e=i}return e}extractAddressList(t){if(Array.isArray(t))return t;if(!t||"object"!=typeof t)return[];const e=t,a=[e.shippingAddresses,e.addresses,e.items,e.data];for(const t of a)if(Array.isArray(t))return t;return[]}async createAddress(t,e){const a=this.sanitizeAddressInput(t),i=await this.http.post(yt,{shipping_address:a},e);if(i.data){const t=k(this.unwrapAddressPayload(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(yt,{identifier:a.identifier,shipping_address:i},e);if(r.data){const t=k(this.unwrapAddressPayload(r.data));return t?(this.credentials.setShippingCredentials({id:t.id,identifier:t.identifier}),{data:t}):r}return r}async listAddresses(t){const e=await this.http.get(yt,{...t,cache:t?.cache??!1});if(e.error)return{error:e.error};return{data:this.extractAddressList(e.data).map(t=>k(this.unwrapAddressPayload(t))).filter(t=>Boolean(t?.identifier)).sort((t,e)=>e.id-t.id)}}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(`${yt}/${e.id}`,{...t,params:{identifier:e.identifier}});if(a.data){const t=k(this.unwrapAddressPayload(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:W(e.data)}:e.error?{error:e.error}:{data:[]}}clearAddress(){this.credentials.clearShippingCredentials()}}class Ot{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(`${gt}/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(gt,{invoice_identifier:a.identifier,payment_type:t},{...e,skipTransform:!0});if(i.error)return{error:i.error};if(i.data){const t=i.data,e=t&&"object"==typeof t&&"result"in t?t.result?.payment:t.payment;if(e&&"object"==typeof e){const t=String(e.payment_identifier??""),a=Number(e.id??0),i=e.payment_type,r={id:a,identifier:t,amount:Number(e.payment_amount??0),paymentType:{id:null!=i?.id?Number(i.id):void 0,code:i?.reference_code??""}};return t&&this.credentials.setPaymentCredentials({id:a,identifier:t}),{data:r}}}return{data:i.data}}async initialize(t){return this.submitPaymentStep(void 0,t)}async verify(t,e){return this.submitPaymentStep(t,e)}async processStep(t,e){return this.submitPaymentStep(t,e)}async submitPaymentStep(t,e){const a=this.credentials.getPaymentCredentials();if(!a)return{error:{message:"No payment found. Please create a payment first.",type:"validation"}};const{paymentIdentifier:i,...r}=t??{},n=await this.http.post(`${gt}/${a.id}/process_payment_step`,{paymentIdentifier:i||a.identifier,...r},this.withExactJsonHeader(e));return this.finalizeStepResponse(n,a.id,e)}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(`${gt}/${a.id}/process_payment_step`,i,e);return this.finalizeStepResponse(r,a.id,e)}async pollUntilSettled(t,e=15e3){let a=!0;for(;a;){const i=await this.verify(void 0,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=y(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,""))}async finalizeStepResponse(t,e,a){if(!t.data)return t;const i=t=>!!t&&"object"==typeof t&&!Array.isArray(t);let r=t.data;if("string"==typeof r)try{r=JSON.parse(r)}catch{return{error:{message:"Invalid payment step response",type:"api"}}}const n=r;if(i(n)){const t="string"==typeof n.error?n.error:"",e=Number(n.error_code??0);if(t||e)return{error:{message:t||"Payment step failed",type:"api",status:Number(n.status)||void 0}}}const s=i(n)&&i(n.result)?n.result:n,o=this.normalizeAction(s);return await this.callPinchAfterSuccessfulPayment(o,e,a),{data:o}}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 $t{constructor(t){this.http=t}normalizeUserResponse(t){if(!t.data)return t;const e=N(t.data);return e?{data:e}:t}normalizeLoginResponse(t){if(!t.data||!t.data.user)return t;const e=N(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(`${bt}/email_login_request`,t,e)}async register(t,e){const a=await this.http.post(`${bt}/register`,t,e);return this.normalizeUserResponse(a)}async getCurrentUser(t){const e=await this.http.get(`${bt}/current`,t);return this.normalizeUserResponse(e)}async updateProfile(t,e,a){const i=await this.http.put(`${bt}/${t}`,e,a);return this.normalizeUserResponse(i)}async requestMobilePhoneUpdate(t,e){return this.http.post(`${bt}/update_mobile_phone_request`,t,e)}async verifyMobilePhoneUpdate(t,e){const a=await this.http.post(`${bt}/update_mobile_phone_verification`,t,e);return this.normalizeUserResponse(a)}async forgotPassword(t,e){return this.http.post(`${bt}/forgot_password`,t,e)}async revivePassword(t,e){const a=await this.http.post(`${bt}/revive_password`,t,e);return this.normalizeLoginResponse(a)}async mergeUser(t){return this.http.post(`${bt}/merge_user`,{},t)}}class Dt{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(lt,{...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:V(r.data)}}return r}}class Gt{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(St,t,e)}async getProductStatistics(t,e){const a=await this.http.get(`${St}/${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(`${St}/${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(vt,{...e,params:this.transformLegacyFilters(t)})}async create(t,e){return this.http.post(vt,t,e)}async get(t,e){return this.http.get(`${vt}/${t}`,e)}}class Ft{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(`${ht}/${t}/add_credit`,{},e)}async removeCredit(t,e){const a=this.validateInvoiceId(t);return a||this.http.post(`${ht}/${t}/remove_credit`,{},e)}}class xt{constructor(t){this.http=t}async getPage(t,e){const a=await this.http.get(Ct,{...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(wt,{...e,params:a});return{...i,data:rt(i.data)}}async getBlogPost(t,e){const a=await this.http.get(Ct,{...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(wt,{...e,params:a});return{...i,data:rt(i.data)}}async listAll(t,e){const a=nt(t),i=await this.http.get(wt,{...e,params:a});return{...i,data:rt(i.data)}}}class Mt{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(At,a,{...e,headers:i})}async delete(t,e){return this.http.delete(`${At}/${t}`,e)}}class jt{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 Bt{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(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 Ut{constructor(t){this.http=t}async resolve(t,e){const a=await this.http.get(Ct,{...e,params:{url_part:t}});if(a.data){return{data:at(a.data)}}return a}}class Kt{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{details:e,entity:a}=t,i=this.firstNonEmpty(e?.title,e?.name),r=this.firstNonEmpty(a?.title,a?.name);return!0===e?.isTitleDefault?r||i:i||r}firstNonEmpty(...t){return t.find(t=>"string"==typeof t&&t.trim().length>0)||""}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 qt{constructor(t){this.http=t}async getInfo(t){const e=await this.http.get("/api/v2/general/info",t);return e.data?{data:f(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 Lt{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 Yt(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function Vt(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 Wt{constructor(t){this.http=t}normalizeCity(t){return Yt(t)?{id:Vt(t.id),name:Qt(t.name),latitude:Vt(t.latitude),longitude:Vt(t.longitude)}:{id:0,name:"",latitude:0,longitude:0}}normalizeRegion(t){if(!Yt(t))return{id:0,name:"",cities:[]};const e=Array.isArray(t.cities)?t.cities:[];return{id:Vt(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:Yt(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 Ht{constructor(t,e){const i=a(t);this.http=new dt(i),this.tokenStorage=this.http.getTokenStorage(),this.credentialsManager=e??new pt,this.products=new zt(this.http),this.categories=new Tt(this.http),this.cart=new Et(this.http,this.credentialsManager),this.invoices=new Nt(this.http,this.credentialsManager),this.shipping=new Rt(this.http,this.credentialsManager),this.payments=new Ot(this.http,this.credentialsManager),this.orders=new kt(this.http),this.users=new $t(this.http),this.search=new Dt(this.http),this.feedbacks=new Gt(this.http),this.wallet=new Ft(this.http),this.cms=new xt(this.http),this.images=new Mt(this.http),this.visits=new jt(this.http),this.booking=new Bt(this.http),this.entityRoutes=new Ut(this.http),this.menu=new Kt(this.http),this.general=new qt(this.http),this.dynamicForms=new Lt(this.http),this.regions=new Wt(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()}getCredentialsManager(){return this.credentialsManager}clearAll(){this.clearAuth(),this.clearCache(),this.clearCredentials()}async searchQuery(t,e,a){return this.search.query(t,e,a)}}function Jt(t){return function(t){if(!t||"object"!=typeof t)return!1;const e=t;return e.http instanceof dt&&e.credentials instanceof pt}(t)?t:function(t){const e=a(t);return{http:new dt(e),credentials:new pt}}(t)}function Zt(t){const{http:e}=Jt(t);return new zt(e)}function Xt(t){const{http:e}=Jt(t);return new Tt(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 kt(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 Rt(e,a)}function re(t){const{http:e,credentials:a}=Jt(t);return new Ot(e,a)}function ne(t){const{http:e}=Jt(t);return new $t(e)}function se(t){const{http:e}=Jt(t);return new Dt(e)}function oe(t){const{http:e}=Jt(t);return new Gt(e)}function de(t){const{http:e}=Jt(t);return new Ft(e)}function ce(t){const{http:e}=Jt(t);return new xt(e)}function pe(t){const{http:e}=Jt(t);return new Mt(e)}function ue(t){const{http:e}=Jt(t);return new jt(e)}function le(t){const{http:e}=Jt(t);return new Bt(e)}function me(t){const{http:e}=Jt(t);return new Ut(e)}function he(t){const{http:e}=Jt(t);return new Kt(e)}function ye(t){const{http:e}=Jt(t);return new qt(e)}function ge(t){const{http:e}=Jt(t);return new Lt(e)}function fe(t){const{http:e}=Jt(t);return new Wt(e)}t.CredentialsManager=pt,t.HttpClient=dt,t.MemoryStorage=ct,t.SazitoClient=Ht,t.TokenStorage=i,t.booking=le,t.cart=te,t.categories=Xt,t.cms=ce,t.createBookingAPI=le,t.createCMSAPI=ce,t.createCartAPI=te,t.createCategoriesAPI=Xt,t.createDynamicFormsAPI=ge,t.createEntityRoutesAPI=me,t.createFeedbacksAPI=oe,t.createGeneralAPI=ye,t.createImagesAPI=pe,t.createInvoicesAPI=ae,t.createMenuAPI=he,t.createOrdersAPI=ee,t.createPaymentsAPI=re,t.createProductsAPI=Zt,t.createRegionsAPI=fe,t.createSazitoClient=function(t,e){return new Ht(t,e)},t.createSearchAPI=se,t.createShippingAPI=ie,t.createUsersAPI=ne,t.createVisitsAPI=ue,t.createWalletAPI=de,t.dynamicForms=ge,t.entityRoutes=me,t.feedbacks=oe,t.general=ye,t.images=pe,t.invoices=ae,t.menu=he,t.orders=ee,t.payments=re,t.products=Zt,t.regions=fe,t.search=se,t.shipping=ie,t.toEnglishDigits=s,t.transformAddToCartInput=function(t,e,a){const i={product_variants:[{id:t,count:e}]};return a&&(i.form_attributes=y(a)),i},t.transformApiResponse=g,t.transformCartResponse=T,t.transformCreateCartInput=function(t){if(!l(t))return{product_variants:[]};const e=t.variants||t.productVariants||[],a={product_variants:Array.isArray(e)?e.map(t=>l(t)?{id:t.id||t.variantId,count:t.count||t.quantity,form_attributes:t.formAttributes?y(t.formAttributes):void 0}:{}):[]};return t.coupon&&(a.coupon=t.coupon),a},t.transformInvoiceResponse=E,t.transformProductListResponse=Y,t.transformRequestKeys=y,t.transformResponseKeys=h,t.transformShippingAddressInput=function(t){if(l(t)){const e={...t};return delete e.user,{shipping_address:y(e)}}return{shipping_address:y(t)}},t.users=ne,t.visits=ue,t.wallet=de});
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).SazitoSDK={})}(this,function(t){"use strict";const e={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 a(t){return{...e,...t,retry:{...e.retry,...t.retry},cache:{...e.cache,...t.cache},customFetchApi:t.customFetchApi||("undefined"!=typeof fetch?fetch:void 0)}}class i{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 r{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 n=new Set(["mobile_phone","phone_number"]);function s(t){return t.replace(/[۰-۹٠-٩]/g,t=>{const e=t.charCodeAt(0);return String(e>=1776?e-1776:e-1632)})}const o={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"},d=Object.values(o).reduce((t,e)=>(t[e]=(t[e]||0)+1,t),{}),c=Object.entries(o).reduce((t,[e,a])=>(1===d[a]&&(t[a]=e),t),{});function p(t){return t.replace(/_([a-z])/g,(t,e)=>e.toUpperCase())}function u(t){return t.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function l(t){return!(null===t||"object"!=typeof t||Array.isArray(t)||t instanceof Date)}function m(t,e){const a={...t};for(const t of e)delete a[t];return a}function h(t){if(!l(t))return Array.isArray(t)?t.map(t=>h(t)):t;const e={};for(const[a,i]of Object.entries(t)){let t=o[a];t||(t=p(a)),l(i)?e[t]=h(i):Array.isArray(i)?e[t]=i.map(t=>h(t)):e[t]=i}return e}function y(t){if(!l(t))return Array.isArray(t)?t.map(t=>y(t)):t;const e={};for(const[a,i]of Object.entries(t)){let t=c[a];t||(t=u(a)),l(i)?e[t]=y(i):Array.isArray(i)?e[t]=i.map(t=>y(t)):e[t]="string"==typeof i&&n.has(t)?s(i):i}return e}function g(t){const e=t;if(l(e?.data?.result)){const t=e.data.result,a=Object.keys(t);return 1===a.length&&l(t[a[0]])?h(t[a[0]]):h(t)}return h(t)}function f(t){if(!t)return{};if(!l(t))return{};const{general:e,shop:a,checkout:i,features:r,wallet:n,tajrobe:s,domain:o,enamad:d,google:c,logo:p,social:u,...m}=t,h={...l(e)?e:{},...l(a)?a:{}},{registerType:y,showProductStockNumber:g,...f}=h||{};return{...m,scripts:{enamad:d,google:c},shop:w({...f,domain:o,logo:p,social:u}),settings:{checkout:b(i),features:C(r),wallet:S(n),tajrobe:z(s),registerType:_(y),showProductStockNumber:v(g)}}}function b(t){if(!l(t))return{};const e=l(t.minBasket)?t.minBasket:{},a=e.minAmount??e.minBasket,i="number"==typeof a?a:Number(a),r={...t,addToCartAlert:v(t.addToCartAlert),dynamicForm:v(t.dynamicForm),emailOptional:v(t.emailOptional??t.email_optional),preventRedirect:v(t.preventRedirect??t.manual),minBasket:{enabled:v(e.enabled),minAmount:Number.isFinite(i)?i:0},miniCart:v(t.miniCart),postalCodeMandatory:v(t.postalCodeMandatory),quickAddToCart:v(t.quickAddToCart)};return delete r.manual,r}function _(t){return"string"==typeof t?t:""}function v(t){return"boolean"==typeof t?t:l(t)&&Object.prototype.hasOwnProperty.call(t,"enabled")?v(t.enabled):1===t||"1"===t||"true"===t}function w(t){if(!l(t))return{};const e={...t};if(l(e.city)){const t=m(e.city,["createdAt","updatedAt"]);let a=t.region;l(a)&&(a=m(a,["createdAt","updatedAt","cities"])),t.region=a,e.city=t}return e}const A={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"},P=new Set(["activateAlopeykAdvanced","activate_alopeyk_advanced"]),I=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 C(t){if(!l(t))return{};const e={},a=(t,a)=>{if(P.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)};l(t.flags)&&Object.entries(t.flags).forEach(([t,e])=>{a(t,e)}),l(t.configurations)&&Object.entries(t.configurations).forEach(([t,e])=>{a(t,e)}),Object.entries(t).forEach(([t,e])=>{"flags"!==t&&"premium"!==t&&"configurations"!==t&&(l(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("_")?p(t):t,a=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);I.has(a)||(i[a]=e)});const r={...i};return l(t.premium)&&(r.premium=t.premium),r}function S(t){if(!l(t))return{};const e=l(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 z(t){if(!l(t))return{};const e=l(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 T(t){const e=g(t);if(!l(e))return{};const a=Array.isArray(e.items)?e.items.map(t=>function(t){if(!l(t))return{};const e=L(t),a=B(t.productVariantId??e.variantId)??e.variantId;return{id:q(t.id??t.cartProductId)??"",createdAt:U(t.createdAt),updatedAt:U(t.updatedAt),productVariantId:a,quantity:B(t.quantity)??0,unitPrice:B(t.unitPrice)??0,lineTotal:B(t.lineTotal)??0,product:e,formAttributes:t.formAttributes,formFields:t.formFields,bookingAttributes:t.bookingAttributes}}(t)):[];return{...e,items:a,netTotal:B(e.netTotal)??0,grossTotal:B(e.grossTotal),needsShipping:Boolean(e.needsShipping),minBasketLimitViolated:Boolean(e.minBasketLimitViolated),deleteCoupon:void 0===e.deleteCoupon?void 0:Boolean(e.deleteCoupon)}}function E(t){const e=g(t);if(!l(e))return{};const a=m(e,["shippingMethod","user","userData"]),i=Array.isArray(e.items)?e.items.map(t=>function(t){if(!l(t))return{};const e=L(t),a=B(t.productVariantId??e.variantId)??e.variantId,i=Array.isArray(e.attributes)?e.attributes:[],r=K(e.hasMaxOrder??t.hasMaxOrder);return{id:q(t.id??t.invoiceItemId??t.cartProductId)??"",productVariantId:a,productId:B(e.productId??t.productId),name:U(t.name)??U(e.name)??"",url:U(e.url)??U(t.url),attributes:i,productType:U(e.productType)??U(t.productType),hasMaxOrder:r,maxOrderQuantity:B(e.maxOrderQuantity??t.maxOrderQuantity),minOrderQuantity:B(e.minOrderQuantity??t.minOrderQuantity),image:V(t.image??e.image),quantity:B(t.quantity)??0,unitPrice:B(t.unitPrice)??0,lineTotal:B(t.lineTotal)??0,rawPrice:B(t.rawPrice??t.originalPrice)??0,customerProfit:B(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=l(n)&&l(n.discountCode)?U(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}}(G(e.shippingAddress)),shippingItems:Array.isArray(e.shippingItems)?e.shippingItems.map(t=>function(t){if(!l(t))return{};const e=l(t.rate)?t.rate:l(t.shippingRate)?t.shippingRate:l(t.shippingMethod)?t.shippingMethod:t;return{invoiceItemIds:j(t),rate:tt(e)}}(t)):[],discountUsages:r,netTotal:B(e.netTotal)??0,finalTotal:B(e.finalTotal)??0,vat:B(e.vat)??0,vatPercent:B(e.vatPercent)??0,itemsDiscount:B(e.itemsDiscount)??0,discountTotal:B(e.discountTotal)??0,customerProfit:B(e.customerProfit)??0,customerProfitPercentage:B(e.customerProfitPercentage)??0,itemsTotalRawPrice:B(e.itemsTotalRawPrice)??0,couponTotal:B(e.couponTotal)??0,shippingTotal:B(e.shippingTotal)??0,creditTotal:B(e.creditTotal)??0,needsShipping:Boolean(e.needsShipping),userComment:"string"==typeof e.userComment?e.userComment:void 0,discountCode:s}}function N(t){const e=g(t);if(!l(e))return{};if(!l(e.invoice))return e;const a=E(e.invoice),{items:i,...r}=a;return{...e,invoice:{...r,invoiceItems:Array.isArray(i)?i:[]}}}function k(t){const e=g(t);if(!l(e))return{};const a=Array.isArray(e.orders)?e.orders.map(t=>N(t)):[],i=B(e.pageNumber??e.page),r=B(e.pageSize),n=B(e.totalCount??e.total)??a.length;return{...m(e,["page","total"]),orders:a,totalCount:n,...void 0!==i?{pageNumber:i}:{},...void 0!==r?{pageSize:r}:{}}}function R(t){const e=g(t);if(!l(e))return{};const a=Array.isArray(e.transactions)?e.transactions:Array.isArray(e.walletTransactions)?e.walletTransactions:[],i=B(e.pageNumber??e.page),r=B(e.pageSize),n=B(e.totalCount??e.total);return{...m(e,["page","total","walletTransactions"]),transactions:a,...void 0!==i?{pageNumber:i}:{},...void 0!==r?{pageSize:r}:{},...void 0!==n?{totalCount:n}:{}}}function O(t){return G(t)}function $(t){const e=g(t);if(l(e))return D(e)}function D(t){if(!t)return;const e=function(t){const e=x(t);if(!e)return;if(1===Object.keys(e).length&&l(e.user))return x(e.user)??e.user;return e}(t);if(!e)return;const a={},i=B(e.id);void 0!==i&&(a.id=i);const r=U(e.email);r&&(a.email=r);const n=U(e.mobilePhone)??U(e.phoneNumber);n&&(a.mobilePhone=n);const s=U(e.phoneNumber);s&&s!==n&&(a.phoneNumber=s);const o=U(e.firstName);o&&(a.firstName=o);const d=U(e.lastName);d&&(a.lastName=d);const c=U(e.birthDate);return c&&(a.birthDate=c),Object.keys(a).length>0?a:void 0}function G(t){if(!t||0===Object.keys(t).length)return;const e=D(t.user),a=x(t.region),i=x(t.city),r=x(i?.region),n=U(t.regionName)??M(t.region),s=F(a??t.region,{fallbackId:B(t.regionId),fallbackName:n})??F(r,{fallbackId:B(t.regionId),fallbackName:n}),o=B(t.regionId)??s?.id,d=U(t.cityName)??U(i?.name)??M(t.city),c=function(t,e={}){if(null==t)return;const a=x(t),i=B(a?.id)??B(t)??e.fallbackId,r=U(a?.name)??M(t)??e.fallbackName;if(void 0===i||!r)return;const n={id:i,name:r},s=B(a?.regionId)??e.fallbackRegionId;void 0!==s&&(n.regionId=s);const o=B(a?.latitude);void 0!==o&&(n.latitude=o);const d=B(a?.longitude);void 0!==d&&(n.longitude=d);return n}(i??t.city,{fallbackId:B(t.cityId),fallbackName:d,fallbackRegionId:o}),p=U(t.firstName)??e?.firstName??"",u=U(t.lastName)??e?.lastName??"",l={id:B(t.id)??0,identifier:U(t.identifier)??"",firstName:p,lastName:u,city:c??{id:B(t.cityId??t.city)??0,name:d??"",...void 0!==o?{regionId:o}:{}},address:U(t.address)??""},m=U(t.mobilePhone)??U(t.phoneNumber)??e?.mobilePhone??e?.phoneNumber,h=U(t.phoneNumber)??e?.phoneNumber;m&&(l.mobilePhone=m),h&&h!==m&&(l.phoneNumber=h);const y=U(t.email)??e?.email;y&&(l.email=y),s&&(l.region=s);const g=U(t.postalCode);g&&(l.postalCode=g);const f=U(t.description);f&&(l.description=f);const b=B(t.latitude);void 0!==b&&(l.latitude=b);const _=B(t.longitude);void 0!==_&&(l.longitude=_);const v=K(t.userSetCoordinatesBefore);return void 0!==v&&(l.userSetCoordinatesBefore=v),l}function F(t,e={}){if(null==t)return;const a=x(t),i=B(a?.id)??B(t)??e.fallbackId,r=U(a?.name)??M(t)??e.fallbackName;return void 0!==i&&r?{id:i,name:r}:void 0}function x(t){if(l(t))return l(t.data)?t.data:t}function M(t){const e=U(t);if(e)return void 0===B(e)?e:void 0}function j(t){return(Array.isArray(t.invoiceItemIds)?t.invoiceItemIds:void 0!==t.invoiceItemId?[t.invoiceItemId]:[]).map(t=>q(t)).filter(t=>void 0!==t)}function B(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 U(t){if("string"!=typeof t)return;const e=t.trim();return e.length>0?e:void 0}function K(t){return"boolean"==typeof t?t:1===t||"1"===t||"true"===t||0!==t&&"0"!==t&&"false"!==t&&void 0}function q(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 L(t){if(!l(t))return{variantId:0,name:"",attributes:[]};const e=l(t.variant)?t.variant:void 0,a=l(e?.product)?e.product:void 0,i=l(t.product)?t.product:void 0,r=B(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:B(i?.productId??t.productId??a?.id),name:U(i?.name)??U(t.name)??"",url:U(i?.url)??U(t.url)??U(a?.url),image:V(i?.image??t.image),attributes:n,productType:U(i?.productType)??U(t.productType)??U(a?.productType),hasMaxOrder:i?.hasMaxOrder??t.hasMaxOrder??e?.hasMaxOrder,maxOrderQuantity:B(i?.maxOrderQuantity??t.maxOrderQuantity??e?.maxOrderQuantity),minOrderQuantity:B(i?.minOrderQuantity??t.minOrderQuantity??e?.minOrderQuantity)}}function Y(t){if(!l(t))return{};const e=m(t,["staticUrl","summary","tags","slug"]);return e.variants&&Array.isArray(e.variants)&&(e.variants=e.variants.map(t=>l(t)?m(t,["name","title","product","status","soldCount"]):{})),e.categories&&Array.isArray(e.categories)&&(e.categories=e.categories.map(t=>l(t)?{id:t.id,name:t.name,url:t.url}:{})),e.images&&Array.isArray(e.images)&&(e.images=e.images.map(t=>V(t)??{})),e}function V(t){return l(t)?m(t,["widthRatio","heightRatio","thumb","order"]):t}function Q(t){const e=Y(t);return e?m(e,["themeConfig"]):e}function W(t){const e=g(t);if(e.items&&Array.isArray(e.items)){const t=B(e.total)??e.items.length,a=B(e.pageSize)??e.items.length,i=B(e.page)??1,r=B(e.totalPages)??Math.ceil(t/a);return{items:e.items.map(t=>Q(t)),total:t,page:i,pageSize:a,totalPages:r}}return e}function H(t){if(!l(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=>Q(t)),a.products.total=B(e.productsCount)??0,a.products.page=B(e.productsPageNumber)??1,a.products.pageSize=B(e.productsPageSize)??20),Array.isArray(e.blogPages)&&(a.blogPages.items=e.blogPages.map(t=>rt(t)),a.blogPages.total=B(e.blogPagesCount)??0,a.blogPages.page=B(e.blogPagesPageNumber)??1,a.blogPages.pageSize=B(e.blogPagesPageSize)??20),Array.isArray(e.cmsPages)&&(a.cmsPages.items=e.cmsPages.map(t=>rt(t)),a.cmsPages.total=B(e.cmsPagesCount)??0,a.cmsPages.page=B(e.cmsPagesPageNumber)??1,a.cmsPages.pageSize=B(e.cmsPagesPageSize)??20),Array.isArray(e.categories)&&(a.productCategories.items=e.categories.map(t=>at(t)),a.productCategories.total=B(e.productCategoriesCount)??0,a.productCategories.page=B(e.productCategoriesPageNumber)??1,a.productCategories.pageSize=B(e.productCategoriesPageSize)??20),a}function J(t){const e=g(t);if(!l(e))return[];return(Array.isArray(e.paymentTypes)?e.paymentTypes:Array.isArray(e.methods)?e.methods:[]).map(t=>l(t)?{id:B(t.id)??0,code:t.code,title:"string"==typeof t.title?t.title:"",titleFa:"string"==typeof t.titleFa?t.titleFa:"",description:"string"==typeof t.description?t.description:null,paymentSubType:B(t.paymentSubType)??null,order:B(t.order)??0,isDefault:Boolean(t.isDefault)}:{id:0,code:"",title:"",titleFa:"",description:null,paymentSubType:null,order:0,isDefault:!1})}function Z(t){const e=g(t);return(Array.isArray(e)?e:l(e)&&Array.isArray(e.shippingMethods)?e.shippingMethods:[]).map(t=>function(t){if(!l(t))return{id:0,name:"",type:""};return{id:B(t.id)??0,name:U(t.name)??"",type:U(t.type)??""}}(t))}function X(t){const e=g(t);if(!l(e))return{shippingMethods:[],groupedShippingRates:{},itemsShippingRate:[]};const a={};if(Array.isArray(e.shippingMethods)&&e.shippingMethods.forEach((t,e)=>{if(!l(t))return;const i=Array.isArray(t.shippingRate)?t.shippingRate.map(t=>tt(t)):[];if(0===i.length)return;const r=Array.isArray(t.invoiceItemIds)?t.invoiceItemIds:[],n=r.length>0?r.map(String).sort().join(","):String(e);a[n]=i}),0===Object.keys(a).length&&l(e.groupedShippingRates))for(const[t,i]of Object.entries(e.groupedShippingRates))a[t]=Array.isArray(i)?i.map(t=>tt(t)):[];return{shippingMethods:[],groupedShippingRates:a,itemsShippingRate:Array.isArray(e.itemsShippingRate)?e.itemsShippingRate.map(t=>l(t)?{invoiceItemId:q(t.invoiceItemId)??j(t)[0]??"",shippingRate:tt(t.shippingRate??t.rate??t)}:{invoiceItemId:"",shippingRate:tt(void 0)}):[]}}function tt(t){return l(t)?{id:B(t.id??t.rateId)??0,name:U(t.name)??"",price:B(t.price??t.amount)??0,description:U(t.description??t.deliveryDescription??t.details),icon:U(t.icon??t.iconUrl??t.logo),color:U(t.color??t.bgColor??t.backgroundColor??t.iconColor),type:U(t.type)}:{id:0,name:"",price:0}}function et(t){return l(t)?m(t,["staticUrl","products","items"]):{}}function at(t){const e=et(t);return e?m(e,["themeConfig"]):{}}function it(t){return l(t)?m(t,["staticUrl","urlKey"]):{}}function rt(t){const e=it(t);return e?m(e,["themeConfig"]):{}}function nt(t){const e=g(t);if(!e||!e.route)return e??{};const a=l(e.route)?e.route:{};if(a.entity){switch(a.entityType){case"product":a.entity=Y(a.entity);break;case"product_category":a.entity=et(a.entity);break;case"cms_page":case"blog_page":a.entity=it(a.entity)}l(a.entity)&&(a.entity=m(a.entity,["id"])),!a.url&&l(a.entity)&&a.entity.url&&(a.url=a.entity.url)}return a}function st(t){if(!l(t))return{};const e={...t};return e.entity&&(e.entity=at(e.entity),l(e.entity)&&(e.entity=m(e.entity,["id"]))),e.children&&Array.isArray(e.children)&&(e.children=e.children.map(st)),e}function ot(t){const e=g(t);return e?e.cmsPages&&Array.isArray(e.cmsPages)?{items:e.cmsPages.map(rt),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=>rt(t)),total:e.total||e.items.length,page:e.page||1,pageSize:e.pageSize||e.items.length}:e:{}}function dt(t){if(!l(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 ct(t){if(!l(t))return{};const e={};if(t.entityType&&(e.entityType=t.entityType),void 0!==t.entityId&&(e.entityId=t.entityId),l(t.entity)){const a=m(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=>ct(t))),e}function pt(t){const e=g(t);if(!e||!e.tree)return e??{};const a=l(e.tree)?e.tree:{};return l(a.treeStructure)&&Array.isArray(a.treeStructure.nodes)&&(a.treeStructure.nodes=a.treeStructure.nodes.map(t=>ct(t))),e}class ut{constructor(t){this.config=t,this.baseUrl="http://api.sazito.com:8080",this.domain=t.domain,this.tokenStorage=new i,this.cache=new r,this.fetchApi=t.customFetchApi.bind(globalThis)}async get(t,e){const a=e?.params?y(e.params):void 0,i=this.buildUrl(t,a),n=r.generateKey("GET",i,a);if(!1!==e?.cache){const e=this.getApiName(t),a=this.config.cache[e];if(a?.enabled&&a.ttl){const e=this.cache.get(n,a.ttl);if(e)return this.config.debug&&console.log("[Sazito SDK] Cache hit:",t),{data:e}}}const s=await this.request("GET",i,e);return s.data&&!1!==e?.cache&&this.cache.set(n,s.data),s}async post(t,e,a){const i=this.buildUrl(t),r=this.isMultipartBody(e),n=e?r?e:y(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:y(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;if(c=d?.includes("application/json")?await r.json():await r.text(),a?.skipTransform&&r.ok)return{data:c};const p=void 0!==c?.result?c.result:c;this.config.debug&&console.log(`[Sazito SDK] ${t} ${e}:`,{status:r.status,data:p});let u=p?h(p):p;const l=["cart","product","user","order","invoice","payment","shippingAddress"];if(u&&"object"==typeof u&&!Array.isArray(u)){const t=Object.keys(u);1===t.length&&l.includes(t[0])&&"object"==typeof u[t[0]]&&null!==u[t[0]]&&(u=u[t[0]])}return r.ok?{data:u}:{error:{status:r.status,message:u?.message||p?.message||r.statusText||"Request failed",type:"api",details:u}}}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 lt{constructor(){this.data=new Map}getItem(t){return this.data.get(t)??null}setItem(t,e){this.data.set(t,e)}removeItem(t){this.data.delete(t)}}class mt{constructor(t){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",this.storage=t??("undefined"!=typeof window&&"undefined"!=typeof localStorage&&"function"==typeof localStorage.getItem?localStorage:new lt)}getCartCredentials(){const t=this.getItem(this.CART_KEY),e=t?.identifier?.trim();return e?{identifier:e}:null}setCartCredentials(t){const e=t.identifier.trim();if(!e)throw new Error("Cart identifier is required.");this.setItem(this.CART_KEY,{identifier:e})}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){try{const e=this.storage.getItem(t);return e?JSON.parse(e):null}catch{return null}}setItem(t,e){try{this.storage.setItem(t,JSON.stringify(e))}catch{}}removeItem(t){try{this.storage.removeItem(t)}catch{}}}const ht="/api/v1/product_categories",yt="/api/v1/search",gt="/api/v2/carts",ft="/api/v2/invoices",bt="/api/v2/shipping_addresses",_t="/api/v2/payments",vt="/api/v1/orders",wt="/api/v1/users",At="/api/v1/sessions",Pt="/api/v1/feedbacks",It="/api/v1/cms_pages",Ct="/api/v1/images",St="/api/v1/scheduler/events",zt="/api/v1/scheduler/bookings",Tt="/api/v1/entity_route/route",Et="/api/v1/feedbacks/comments/details";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(Tt,{...e,params:{url_part:a}});if(i.data){const t=nt(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:W(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(yt,{...a,params:i});if(r.data){return{data:H(r.data)}}return r}}class kt{constructor(t){this.http=t}async get(t,e){const a=await this.http.get(`${ht}/${t}`,e);if(a.data){const t=function(t){const e=g(t);return e?et(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(ht,{...e,params:a});if(i.data){const t=function(t){const e=g(t);return e?(e.categories&&Array.isArray(e.categories)&&(e.categories=e.categories.map(at)),l(e.tree)&&l(e.tree.treeStructure)&&Array.isArray(e.tree.treeStructure.nodes)&&(e.tree.treeStructure.nodes=e.tree.treeStructure.nodes.map(st)),e):{}}(i.data);return{data:t}}return i}}class Rt{constructor(t,e){this.http=t,this.credentials=e}persistCartCredentials(t){this.credentials.setCartCredentials({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(`${gt}/0`,{...t,params:{identifier:e.identifier}});return a.data?{data:T(a.data)}:(a.error&&this.clearCart(),a)}async create(t,e){const a=await this.http.post(gt,t,e);if(!a.data)return a;const i=T(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(`${gt}/0/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=T(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(`${gt}/0/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=T(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(`${gt}/0/remove_products_from_cart`,{identifier:i.identifier,cartProductId:String(t),variants:[{id:e}]},a);if(r.data){const t=T(r.data);return this.persistCartCredentials(t),{data:t}}return r}clearCart(){this.credentials.clearCartCredentials()}}class Ot{constructor(t){this.http=t}async list(t,e){const a={pageNumber:t?.pageNumber??1,pageSize:t?.pageSize??20};t?.filters&&t.filters.length>0&&(a.filters=JSON.stringify(t.filters));const i=await this.http.get(vt,{...e,params:a});return i.data?{data:k(i.data)}:i}async get(t,e){const a=await this.http.get(`${vt}/${t}`,e);return a.data?{data:N(a.data)}:a}}class $t{constructor(t,e){this.http=t,this.credentials=e}normalizeInvoiceResponse(t){return t.data?{data:E(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(`${ft}/${a.id}/refresh`,{cart_id:String(0),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(ft,{cart_id:String(0),cart_identifier:e.identifier},t);if(a.data){const t=E(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(`${ft}/${a.id}/refresh`,{cart_id:String(0),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(`${ft}/${r.id}/add_shipping_address`,{identifier:r.identifier,shipping_address_identifier:e,cart_id:0,cart_identifier:i.identifier,...t>0?{shipping_address_id:t}:{}},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(`${ft}/${a.id}/add_discount_code`,{identifier:a.identifier,discount_code:t.toUpperCase()},e);return i.data?(this.credentials.setDiscountCode(t.toUpperCase()),{data:E(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(`${ft}/${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(`${ft}/${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(`${ft}/${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(`${ft}/${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(`${ft}/${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(`${ft}/${e.id}/applicable_shipping_methods`,{...t,cache:t?.cache??!1,params:{identifier:e.identifier}});return a.data?{data:X(a.data)}:a}clearInvoice(){this.credentials.clearInvoiceCredentials()}}class Dt{constructor(t,e){this.http=t,this.credentials=e}sanitizeAddressInput(t){const e={...t};return delete e.user,e}unwrapAddressPayload(t){let e=t;const a=new Set;for(;e&&"object"==typeof e&&!Array.isArray(e)&&!a.has(e);){a.add(e);const t=e,i=t.shippingAddress??t.shipping_address??t.data;if(void 0===i)break;e=i}return e}extractAddressList(t){if(Array.isArray(t))return t;if(!t||"object"!=typeof t)return[];const e=t,a=[e.shippingAddresses,e.addresses,e.items,e.data];for(const t of a)if(Array.isArray(t))return t;return[]}async createAddress(t,e){const a=this.sanitizeAddressInput(t),i=await this.http.post(bt,{shipping_address:a},e);if(i.data){const t=O(this.unwrapAddressPayload(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(bt,{identifier:a.identifier,shipping_address:i},e);if(r.data){const t=O(this.unwrapAddressPayload(r.data));return t?(this.credentials.setShippingCredentials({id:t.id,identifier:t.identifier}),{data:t}):r}return r}async listAddresses(t){const e=await this.http.get(bt,{...t,cache:t?.cache??!1});if(e.error)return{error:e.error};return{data:this.extractAddressList(e.data).map(t=>O(this.unwrapAddressPayload(t))).filter(t=>Boolean(t?.identifier)).sort((t,e)=>e.id-t.id)}}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(`${bt}/${e.id}`,{...t,params:{identifier:e.identifier}});if(a.data){const t=O(this.unwrapAddressPayload(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:Z(e.data)}:e.error?{error:e.error}:{data:[]}}clearAddress(){this.credentials.clearShippingCredentials()}}class Gt{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(`${_t}/list`,{invoice_identifier:e.identifier},t);return a.data?{data:J(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(_t,{invoice_identifier:a.identifier,payment_type:t},{...e,skipTransform:!0});if(i.error)return{error:i.error};if(i.data){const t=i.data,e=t&&"object"==typeof t&&"result"in t?t.result?.payment:t.payment;if(e&&"object"==typeof e){const t=String(e.payment_identifier??""),a=Number(e.id??0),i=e.payment_type,r={id:a,identifier:t,amount:Number(e.payment_amount??0),paymentType:{id:null!=i?.id?Number(i.id):void 0,code:i?.reference_code??""}};return t&&this.credentials.setPaymentCredentials({id:a,identifier:t}),{data:r}}}return{data:i.data}}async initialize(t){return this.submitPaymentStep(void 0,t)}async verify(t,e){return this.submitPaymentStep(t,e)}async processStep(t,e){return this.submitPaymentStep(t,e)}async submitPaymentStep(t,e){const a=this.credentials.getPaymentCredentials();if(!a)return{error:{message:"No payment found. Please create a payment first.",type:"validation"}};const{paymentIdentifier:i,...r}=t??{},n=await this.http.post(`${_t}/${a.id}/process_payment_step`,{paymentIdentifier:i||a.identifier,...r},this.withExactJsonHeader(e));return this.finalizeStepResponse(n,a.id,e)}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(`${_t}/${a.id}/process_payment_step`,i,e);return this.finalizeStepResponse(r,a.id,e)}async pollUntilSettled(t,e=15e3){let a=!0;for(;a;){const i=await this.verify(void 0,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=y(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,""))}async finalizeStepResponse(t,e,a){if(!t.data)return t;const i=t=>!!t&&"object"==typeof t&&!Array.isArray(t);let r=t.data;if("string"==typeof r)try{r=JSON.parse(r)}catch{return{error:{message:"Invalid payment step response",type:"api"}}}const n=r;if(i(n)){const t="string"==typeof n.error?n.error:"",e=Number(n.error_code??0);if(t||e)return{error:{message:t||"Payment step failed",type:"api",status:Number(n.status)||void 0}}}const s=i(n)&&i(n.result)?n.result:n,o=this.normalizeAction(s);return await this.callPinchAfterSuccessfulPayment(o,e,a),{data:o}}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 Ft{constructor(t){this.http=t}normalizeUserResponse(t){if(!t.data)return t;const e=$(t.data);return e?{data:e}:t}normalizeLoginResponse(t){if(!t.data||!t.data.user)return t;const e=$(t.data.user);return e?{data:{...t.data,user:e}}:t}async login(t,e){const a=await this.http.post(`${At}/login`,t,e);return this.normalizeLoginResponse(a)}async requestMobileOTP(t,e){return this.http.post(`${At}/login_request`,t,e)}async verifyMobileOTP(t,e){const a=await this.http.post(`${At}/login_request_verification`,t,e);return this.normalizeLoginResponse(a)}async requestEmailLogin(t,e){return this.http.post(`${wt}/email_login_request`,t,e)}async register(t,e){const a=await this.http.post(`${wt}/register`,t,e);return this.normalizeUserResponse(a)}async getCurrentUser(t){const e=await this.http.get(`${wt}/current`,t);return this.normalizeUserResponse(e)}async updateProfile(t,e,a){const i=await this.http.put(`${wt}/${t}`,e,a);return this.normalizeUserResponse(i)}async requestMobilePhoneUpdate(t,e){return this.http.post(`${wt}/update_mobile_phone_request`,t,e)}async verifyMobilePhoneUpdate(t,e){const a=await this.http.post(`${wt}/update_mobile_phone_verification`,t,e);return this.normalizeUserResponse(a)}async forgotPassword(t,e){return this.http.post(`${wt}/forgot_password`,t,e)}async revivePassword(t,e){const a=await this.http.post(`${wt}/revive_password`,t,e);return this.normalizeLoginResponse(a)}async mergeUser(t){return this.http.post(`${wt}/merge_user`,{},t)}}class xt{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(yt,{...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:H(r.data)}}return r}}class Mt{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(Et,t,e)}async getProductStatistics(t,e){const a=await this.http.get(`${Et}/${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(`${Et}/${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(Pt,{...e,params:this.transformLegacyFilters(t)})}async create(t,e){return this.http.post(Pt,t,e)}async get(t,e){return this.http.get(`${Pt}/${t}`,e)}}class jt{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?.pageNumber??t?.page_number??1,i=t?.pageSize??t?.page_size??20,r=await this.http.get("/api/v1/wallet/transactions",{...e,params:{pageNumber:a,pageSize:i}});return r.data?{data:R(r.data)}:r}async applyCredit(t,e){const a=this.validateInvoiceId(t);if(a)return a;const i=await this.http.post(`${ft}/${t}/add_credit`,{},e);return i.data?{data:E(i.data)}:i}async removeCredit(t,e){const a=this.validateInvoiceId(t);if(a)return a;const i=await this.http.post(`${ft}/${t}/remove_credit`,{},e);return i.data?{data:E(i.data)}:i}}class Bt{constructor(t){this.http=t}async getPage(t,e){const a=await this.http.get(Tt,{...e,params:{url_part:t}}),i=nt(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=dt({...t,cmsPageTypes:"normal"}),i=await this.http.get(It,{...e,params:a});return{...i,data:ot(i.data)}}async getBlogPost(t,e){const a=await this.http.get(Tt,{...e,params:{url_part:t}}),i=nt(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=dt({...t,cmsPageTypes:"blog"}),i=await this.http.get(It,{...e,params:a});return{...i,data:ot(i.data)}}async listAll(t,e){const a=dt(t),i=await this.http.get(It,{...e,params:a});return{...i,data:ot(i.data)}}}class Ut{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(Ct,a,{...e,headers:i})}async delete(t,e){return this.http.delete(`${Ct}/${t}`,e)}}class Kt{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 qt{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(St,{...e,params:this.transformEventFilters(t)})}async getEvent(t,e){const a=await this.http.get(`${St}/${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(zt,t,e)}async listBookings(t){return this.http.get(zt,t)}async cancelBooking(t,e){return this.http.post(`${zt}/${t}/cancel`,{},e)}}class Lt{constructor(t){this.http=t}async resolve(t,e){const a=await this.http.get(Tt,{...e,params:{url_part:t}});if(a.data){return{data:nt(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?pt(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{details:e,entity:a}=t,i=this.firstNonEmpty(e?.title,e?.name),r=this.firstNonEmpty(a?.title,a?.name);return!0===e?.isTitleDefault?r||i:i||r}firstNonEmpty(...t){return t.find(t=>"string"==typeof t&&t.trim().length>0)||""}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 Vt{constructor(t){this.http=t}async getInfo(t){const e=await this.http.get("/api/v2/general/info",t);return e.data?{data:f(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 Wt(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function Ht(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 Jt(t){return"string"==typeof t?t.trim():""}class Zt{constructor(t){this.http=t}normalizeCity(t){return Wt(t)?{id:Ht(t.id),name:Jt(t.name),latitude:Ht(t.latitude),longitude:Ht(t.longitude)}:{id:0,name:"",latitude:0,longitude:0}}normalizeRegion(t){if(!Wt(t))return{id:0,name:"",cities:[]};const e=Array.isArray(t.cities)?t.cities:[];return{id:Ht(t.id),name:Jt(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:Wt(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 Xt{constructor(t,e){const i=a(t);this.http=new ut(i),this.tokenStorage=this.http.getTokenStorage(),this.credentialsManager=e??new mt,this.products=new Nt(this.http),this.categories=new kt(this.http),this.cart=new Rt(this.http,this.credentialsManager),this.invoices=new $t(this.http,this.credentialsManager),this.shipping=new Dt(this.http,this.credentialsManager),this.payments=new Gt(this.http,this.credentialsManager),this.orders=new Ot(this.http),this.users=new Ft(this.http),this.search=new xt(this.http),this.feedbacks=new Mt(this.http),this.wallet=new jt(this.http),this.cms=new Bt(this.http),this.images=new Ut(this.http),this.visits=new Kt(this.http),this.booking=new qt(this.http),this.entityRoutes=new Lt(this.http),this.menu=new Yt(this.http),this.general=new Vt(this.http),this.dynamicForms=new Qt(this.http),this.regions=new Zt(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()}getCredentialsManager(){return this.credentialsManager}clearAll(){this.clearAuth(),this.clearCache(),this.clearCredentials()}async searchQuery(t,e,a){return this.search.query(t,e,a)}}function te(t){return function(t){if(!t||"object"!=typeof t)return!1;const e=t;return e.http instanceof ut&&e.credentials instanceof mt}(t)?t:function(t){const e=a(t);return{http:new ut(e),credentials:new mt}}(t)}function ee(t){const{http:e}=te(t);return new Nt(e)}function ae(t){const{http:e}=te(t);return new kt(e)}function ie(t){const{http:e,credentials:a}=te(t);return new Rt(e,a)}function re(t){const{http:e}=te(t);return new Ot(e)}function ne(t){const{http:e,credentials:a}=te(t);return new $t(e,a)}function se(t){const{http:e,credentials:a}=te(t);return new Dt(e,a)}function oe(t){const{http:e,credentials:a}=te(t);return new Gt(e,a)}function de(t){const{http:e}=te(t);return new Ft(e)}function ce(t){const{http:e}=te(t);return new xt(e)}function pe(t){const{http:e}=te(t);return new Mt(e)}function ue(t){const{http:e}=te(t);return new jt(e)}function le(t){const{http:e}=te(t);return new Bt(e)}function me(t){const{http:e}=te(t);return new Ut(e)}function he(t){const{http:e}=te(t);return new Kt(e)}function ye(t){const{http:e}=te(t);return new qt(e)}function ge(t){const{http:e}=te(t);return new Lt(e)}function fe(t){const{http:e}=te(t);return new Yt(e)}function be(t){const{http:e}=te(t);return new Vt(e)}function _e(t){const{http:e}=te(t);return new Qt(e)}function ve(t){const{http:e}=te(t);return new Zt(e)}t.CredentialsManager=mt,t.HttpClient=ut,t.MemoryStorage=lt,t.SazitoClient=Xt,t.TokenStorage=i,t.booking=ye,t.cart=ie,t.categories=ae,t.cms=le,t.createBookingAPI=ye,t.createCMSAPI=le,t.createCartAPI=ie,t.createCategoriesAPI=ae,t.createDynamicFormsAPI=_e,t.createEntityRoutesAPI=ge,t.createFeedbacksAPI=pe,t.createGeneralAPI=be,t.createImagesAPI=me,t.createInvoicesAPI=ne,t.createMenuAPI=fe,t.createOrdersAPI=re,t.createPaymentsAPI=oe,t.createProductsAPI=ee,t.createRegionsAPI=ve,t.createSazitoClient=function(t,e){return new Xt(t,e)},t.createSearchAPI=ce,t.createShippingAPI=se,t.createUsersAPI=de,t.createVisitsAPI=he,t.createWalletAPI=ue,t.dynamicForms=_e,t.entityRoutes=ge,t.feedbacks=pe,t.general=be,t.images=me,t.invoices=ne,t.menu=fe,t.orders=re,t.payments=oe,t.products=ee,t.regions=ve,t.search=ce,t.shipping=se,t.toEnglishDigits=s,t.transformAddToCartInput=function(t,e,a){const i={product_variants:[{id:t,count:e}]};return a&&(i.form_attributes=y(a)),i},t.transformApiResponse=g,t.transformCartResponse=T,t.transformCreateCartInput=function(t){if(!l(t))return{product_variants:[]};const e=t.variants||t.productVariants||[],a={product_variants:Array.isArray(e)?e.map(t=>l(t)?{id:t.id||t.variantId,count:t.count||t.quantity,form_attributes:t.formAttributes?y(t.formAttributes):void 0}:{}):[]};return t.coupon&&(a.coupon=t.coupon),a},t.transformInvoiceResponse=E,t.transformProductListResponse=W,t.transformRequestKeys=y,t.transformResponseKeys=h,t.transformShippingAddressInput=function(t){if(l(t)){const e={...t};return delete e.user,{shipping_address:y(e)}}return{shipping_address:y(t)}},t.users=de,t.visits=he,t.wallet=ue});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sazito/client-sdk",
3
- "version": "1.2.4",
3
+ "version": "1.2.5",
4
4
  "packageManager": "pnpm@10.28.2",
5
5
  "description": "Official JavaScript/TypeScript SDK for Sazito e-commerce platform - Client Edition",
6
6
  "main": "dist/index.js",
@@ -38,7 +38,10 @@
38
38
  "docs:typecheck": "pnpm --dir docs run types:check",
39
39
  "publish:patch": "npm version patch && npm publish",
40
40
  "publish:minor": "npm version minor && npm publish",
41
- "publish:major": "npm version major && npm publish"
41
+ "publish:major": "npm version major && npm publish",
42
+ "release:sdk": "node scripts/release.mjs sdk",
43
+ "release:checkout": "node scripts/release.mjs checkout",
44
+ "release:all": "node scripts/release.mjs all"
42
45
  },
43
46
  "keywords": [
44
47
  "sazito",