@sazito/client-sdk 1.2.17 → 1.2.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +8 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.umd.js +1 -1
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -1413,6 +1413,14 @@ declare class PaymentsAPI {
|
|
|
1413
1413
|
private buildProcessStepBody;
|
|
1414
1414
|
private appendFormValue;
|
|
1415
1415
|
private resolvePaymentCredentials;
|
|
1416
|
+
/**
|
|
1417
|
+
* Payment creation has been returned in a few compatible envelope shapes
|
|
1418
|
+
* across v2 deployments: `{ result: { payment: ... } }`, a direct payment
|
|
1419
|
+
* under `result`, and (for request-log proxies) under `response.result`.
|
|
1420
|
+
* Keep the shape handling here so the credential parser never silently
|
|
1421
|
+
* stores an invoice identifier or a zero payment id.
|
|
1422
|
+
*/
|
|
1423
|
+
private extractPaymentPayload;
|
|
1416
1424
|
private normalizePaymentId;
|
|
1417
1425
|
private paymentStepInputToCallbackFields;
|
|
1418
1426
|
private appendCallbackValue;
|
package/dist/index.d.ts
CHANGED
|
@@ -1413,6 +1413,14 @@ declare class PaymentsAPI {
|
|
|
1413
1413
|
private buildProcessStepBody;
|
|
1414
1414
|
private appendFormValue;
|
|
1415
1415
|
private resolvePaymentCredentials;
|
|
1416
|
+
/**
|
|
1417
|
+
* Payment creation has been returned in a few compatible envelope shapes
|
|
1418
|
+
* across v2 deployments: `{ result: { payment: ... } }`, a direct payment
|
|
1419
|
+
* under `result`, and (for request-log proxies) under `response.result`.
|
|
1420
|
+
* Keep the shape handling here so the credential parser never silently
|
|
1421
|
+
* stores an invoice identifier or a zero payment id.
|
|
1422
|
+
*/
|
|
1423
|
+
private extractPaymentPayload;
|
|
1416
1424
|
private normalizePaymentId;
|
|
1417
1425
|
private paymentStepInputToCallbackFields;
|
|
1418
1426
|
private appendCallbackValue;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const t={apiBaseUrl:"http://api.sazito.com:8080",paymentsBasePath:"/api/v2/payments",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",variant_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 y(t){if(!u(t))return Array.isArray(t)?t.map(t=>y(t)):t;const e={};for(const[a,r]of Object.entries(t)){let t=d[a];t||(t=p(a)),u(r)?e[t]=y(r):Array.isArray(r)?e[t]=r.map(t=>y(t)):e[t]="string"==typeof r&&i.has(t)?n(r):r}return e}function h(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,y={...u(e)?e:{},...u(a)?a:{}},{registerType:h,showProductStockNumber:g,...A}=y||{};return{...m,scripts:{enamad:d,google:c},shop:v({...A,domain:o,logo:p,social:l}),settings:{checkout:f(r),features:I(i),wallet:C(n),tajrobe:S(s),registerType:b(h),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 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"},w=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(w.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=A[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 T(t){const e=h(t);if(!u(e))return{};const a=Array.isArray(e.items)?e.items.map(t=>function(t){if(!u(t))return{};const e=W(t),a=K(t.productVariantId??e.variantId)??e.variantId;return{id:Q(t.id??t.cartProductId)??"",createdAt:Y(t.createdAt),updatedAt:Y(t.updatedAt),productVariantId:a,quantity:K(t.quantity)??0,unitPrice:K(t.unitPrice)??0,lineTotal:K(t.lineTotal)??0,product:e,formAttributes:t.formAttributes,formFields:t.formFields,bookingAttributes:t.bookingAttributes}}(t)):[];return{...e,items:a,netTotal:K(e.netTotal)??0,grossTotal:K(e.grossTotal),needsShipping:Boolean(e.needsShipping),minBasketLimitViolated:Boolean(e.minBasketLimitViolated),deleteCoupon:void 0===e.deleteCoupon?void 0:Boolean(e.deleteCoupon)}}function k(t){const e=h(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=W(t),a=K(t.productVariantId??e.variantId)??e.variantId,r=Array.isArray(e.attributes)?e.attributes:[],i=J(e.hasMaxOrder??t.hasMaxOrder);return{id:Q(t.id??t.invoiceItemId??t.cartProductId)??"",productVariantId:a,productId:K(e.productId??t.productId),name:Y(t.name)??Y(e.name)??"",url:Y(e.url)??Y(t.url),attributes:r,productType:Y(e.productType)??Y(t.productType),hasMaxOrder:i,maxOrderQuantity:K(e.maxOrderQuantity??t.maxOrderQuantity),minOrderQuantity:K(e.minOrderQuantity??t.minOrderQuantity),image:Z(t.image??e.image),quantity:K(t.quantity)??0,unitPrice:K(t.unitPrice)??0,lineTotal:K(t.lineTotal)??0,rawPrice:K(t.rawPrice??t.originalPrice)??0,customerProfit:K(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)?Y(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}}(B(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:L(t),rate:nt(e)}}(t)):[],discountUsages:i,netTotal:K(e.netTotal)??0,finalTotal:K(e.finalTotal)??0,vat:K(e.vat)??0,vatPercent:K(e.vatPercent)??0,itemsDiscount:K(e.itemsDiscount)??0,discountTotal:K(e.discountTotal)??0,customerProfit:K(e.customerProfit)??0,customerProfitPercentage:K(e.customerProfitPercentage)??0,itemsTotalRawPrice:K(e.itemsTotalRawPrice)??0,couponTotal:K(e.couponTotal)??0,shippingTotal:K(e.shippingTotal)??0,creditTotal:K(e.creditTotal)??0,needsShipping:Boolean(e.needsShipping),userComment:"string"==typeof e.userComment?e.userComment:void 0,discountCode:s}}function E(t){const e=h(t);if(!u(e))return{};if(!u(e.invoice))return e;const a=k(e.invoice),{items:r,...i}=a;return{...e,invoice:{...i,invoiceItems:Array.isArray(r)?r:[]}}}function z(t){const e=h(t);if(!u(e))return{};const a=Array.isArray(e.orders)?e.orders.map(t=>E(t)):[],r=K(e.pageNumber??e.page),i=K(e.pageSize),n=K(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 N(t){const e=function(t){if(!u(t))return{};if(u(t.data)&&u(t.data.result))return t.data.result;return u(t.result)?t.result:t}(t),a=u(e.order)?e.order:e;if(!u(a))return{};const r=u(a.invoice)?a.invoice:{},i=Array.isArray(r.invoice_items)?r.invoice_items.map(x):[],n=Array.isArray(r.shipping_items)?r.shipping_items.map(R):[];return{id:Q(a.id),orderNumber:Q(a.order_number),orderIdentifier:Y(a.order_identifier),invoice:{invoiceItems:i,shippingItems:n,netTotal:K(r.net_total),finalTotal:K(r.final_total),shippingTotal:K(r.shipping_total),discountTotal:K(r.discount_total),creditTotal:K(r.credit_total),vat:K(r.vat),vatPercent:K(r.vat_percent),itemsDiscount:K(r.items_discount),itemsTotalRawPrice:K(r.items_total_raw_price),customerProfit:K(r.customer_profit),customerProfitPercentage:K(r.customer_profit_percentage),discountUsages:Array.isArray(r.discount_usages)?r.discount_usages.map($):void 0}}}function x(t){if(!u(t))return{};const e=u(t.product_variant)?t.product_variant:{},a=u(e.product)?e.product:{};return{productVariantId:Q(t.product_variant_id??e.id),name:Y(t.name),image:u(t.image)?{url:Y(t.image.url)}:void 0,variantAttributes:Array.isArray(t.variant_attributes)?t.variant_attributes.map(D):[],singleItemPrice:K(t.single_item_price),noOfItems:K(t.no_of_items),totalItemsPrice:K(t.total_items_price),customerProfit:K(t.customer_profit),formAttributes:t.form_attributes,bookingAttributes:t.booking_attributes,productVariant:{commercialFiles:Array.isArray(e.commercial_files)?e.commercial_files.map(O):void 0,product:{productType:Y(a.product_type)}}}}function R(t){return u(t)&&u(t.rate)?{id:Q(t.id),invoiceItemIds:Array.isArray(t.invoice_item_ids)?t.invoice_item_ids.map(Q).filter(t=>void 0!==t):[],rate:{id:Q(t.rate.id),name:Y(t.rate.name),price:K(t.rate.price),type:Y(t.rate.type),icon:Y(t.rate.icon),color:Y(t.rate.color)}}:{}}function D(t){return u(t)?{name:Y(t.name),value:Y(t.value)}:{}}function O(t){return u(t)?{id:Q(t.id)}:{}}function $(t){return u(t)&&u(t.discount_code)?{discountCode:{code:Y(t.discount_code.code)}}:{}}function F(t){const e=h(t);if(!u(e))return{};const a=Array.isArray(e.transactions)?e.transactions:Array.isArray(e.walletTransactions)?e.walletTransactions:[],r=K(e.pageNumber??e.page),i=K(e.pageSize),n=K(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 G(t){return B(t)}function M(t){const e=h(t);if(u(e))return V(e)}function V(t){if(!t)return;const e=function(t){const e=j(t);if(!e)return;if(1===Object.keys(e).length&&u(e.user))return j(e.user)??e.user;return e}(t);if(!e)return;const a={},r=K(e.id);void 0!==r&&(a.id=r);const i=Y(e.email);i&&(a.email=i);const n=Y(e.mobilePhone)??Y(e.phoneNumber);n&&(a.mobilePhone=n);const s=Y(e.phoneNumber);s&&s!==n&&(a.phoneNumber=s);const o=Y(e.firstName);o&&(a.firstName=o);const d=Y(e.lastName);d&&(a.lastName=d);const c=Y(e.birthDate);return c&&(a.birthDate=c),Object.keys(a).length>0?a:void 0}function B(t){if(!t||0===Object.keys(t).length)return;const e=V(t.user),a=j(t.region),r=j(t.city),i=j(r?.region),n=Y(t.regionName)??q(t.region),s=U(a??t.region,{fallbackId:K(t.regionId),fallbackName:n})??U(i,{fallbackId:K(t.regionId),fallbackName:n}),o=K(t.regionId)??s?.id,d=Y(t.cityName)??Y(r?.name)??q(t.city),c=function(t,e={}){if(null==t)return;const a=j(t),r=K(a?.id)??K(t)??e.fallbackId,i=Y(a?.name)??q(t)??e.fallbackName;if(void 0===r||!i)return;const n={id:r,name:i},s=K(a?.regionId)??e.fallbackRegionId;void 0!==s&&(n.regionId=s);const o=K(a?.latitude);void 0!==o&&(n.latitude=o);const d=K(a?.longitude);void 0!==d&&(n.longitude=d);return n}(r??t.city,{fallbackId:K(t.cityId),fallbackName:d,fallbackRegionId:o}),p=Y(t.firstName)??e?.firstName??"",u=Y(t.lastName)??e?.lastName??"",l={id:K(t.id)??0,identifier:Y(t.identifier)??"",firstName:p,lastName:u,city:c??{id:K(t.cityId??t.city)??0,name:d??"",...void 0!==o?{regionId:o}:{}},address:Y(t.address)??""},m=Y(t.mobilePhone)??Y(t.phoneNumber)??e?.mobilePhone??e?.phoneNumber,y=Y(t.phoneNumber)??e?.phoneNumber;m&&(l.mobilePhone=m),y&&y!==m&&(l.phoneNumber=y);const h=Y(t.email)??e?.email;h&&(l.email=h),s&&(l.region=s);const g=Y(t.postalCode);g&&(l.postalCode=g);const f=Y(t.description);f&&(l.description=f);const b=K(t.latitude);void 0!==b&&(l.latitude=b);const _=K(t.longitude);void 0!==_&&(l.longitude=_);const v=J(t.userSetCoordinatesBefore);return void 0!==v&&(l.userSetCoordinatesBefore=v),l}function U(t,e={}){if(null==t)return;const a=j(t),r=K(a?.id)??K(t)??e.fallbackId,i=Y(a?.name)??q(t)??e.fallbackName;return void 0!==r&&i?{id:r,name:i}:void 0}function j(t){if(u(t))return u(t.data)?t.data:t}function q(t){const e=Y(t);if(e)return void 0===K(e)?e:void 0}function L(t){return(Array.isArray(t.invoiceItemIds)?t.invoiceItemIds:void 0!==t.invoiceItemId?[t.invoiceItemId]:[]).map(t=>Q(t)).filter(t=>void 0!==t)}function K(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 Y(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 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 W(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=K(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:K(r?.productId??t.productId??a?.id),name:Y(r?.name)??Y(t.name)??"",url:Y(r?.url)??Y(t.url)??Y(a?.url),image:Z(r?.image??t.image),attributes:n,productType:Y(r?.productType)??Y(t.productType)??Y(a?.productType),hasMaxOrder:r?.hasMaxOrder??t.hasMaxOrder??e?.hasMaxOrder,maxOrderQuantity:K(r?.maxOrderQuantity??t.maxOrderQuantity??e?.maxOrderQuantity),minOrderQuantity:K(r?.minOrderQuantity??t.minOrderQuantity??e?.minOrderQuantity)}}function H(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=>Z(t)??{})),e}function Z(t){return u(t)?l(t,["widthRatio","heightRatio","thumb","order"]):t}function X(t){const e=H(t);return e?l(e,["themeConfig"]):e}function tt(t){const e=h(t);if(e.items&&Array.isArray(e.items)){const t=K(e.total)??e.items.length,a=K(e.pageSize)??e.items.length,r=K(e.page)??1,i=K(e.totalPages)??Math.ceil(t/a);return{items:e.items.map(t=>X(t)),total:t,page:r,pageSize:a,totalPages:i}}return e}function et(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=>X(t)),a.products.total=K(e.productsCount)??0,a.products.page=K(e.productsPageNumber)??1,a.products.pageSize=K(e.productsPageSize)??20),Array.isArray(e.blogPages)&&(a.blogPages.items=e.blogPages.map(t=>ct(t)),a.blogPages.total=K(e.blogPagesCount)??0,a.blogPages.page=K(e.blogPagesPageNumber)??1,a.blogPages.pageSize=K(e.blogPagesPageSize)??20),Array.isArray(e.cmsPages)&&(a.cmsPages.items=e.cmsPages.map(t=>ct(t)),a.cmsPages.total=K(e.cmsPagesCount)??0,a.cmsPages.page=K(e.cmsPagesPageNumber)??1,a.cmsPages.pageSize=K(e.cmsPagesPageSize)??20),Array.isArray(e.categories)&&(a.productCategories.items=e.categories.map(t=>ot(t)),a.productCategories.total=K(e.productCategoriesCount)??0,a.productCategories.page=K(e.productCategoriesPageNumber)??1,a.productCategories.pageSize=K(e.productCategoriesPageSize)??20),a}function at(t){const e=h(t);if(!u(e))return[];return(Array.isArray(e.paymentTypes)?e.paymentTypes:Array.isArray(e.methods)?e.methods:[]).map(t=>u(t)?{id:K(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:K(t.paymentSubType)??null,order:K(t.order)??0,isDefault:Boolean(t.isDefault)}:{id:0,code:"",title:"",titleFa:"",description:null,paymentSubType:null,order:0,isDefault:!1})}function rt(t){const e=h(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:K(t.id)??0,name:Y(t.name)??"",type:Y(t.type)??""}}(t))}function it(t){const e=h(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=>nt(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=>nt(t)):[];return{shippingMethods:[],groupedShippingRates:a,itemsShippingRate:Array.isArray(e.itemsShippingRate)?e.itemsShippingRate.map(t=>u(t)?{invoiceItemId:Q(t.invoiceItemId)??L(t)[0]??"",shippingRate:nt(t.shippingRate??t.rate??t)}:{invoiceItemId:"",shippingRate:nt(void 0)}):[]}}function nt(t){return u(t)?{id:K(t.id??t.rateId)??0,name:Y(t.name)??"",price:K(t.price??t.amount)??0,description:Y(t.description??t.deliveryDescription??t.details),icon:Y(t.icon??t.iconUrl??t.logo),color:Y(t.color??t.bgColor??t.backgroundColor??t.iconColor),type:Y(t.type)}:{id:0,name:"",price:0}}function st(t){return u(t)?l(t,["staticUrl","products","items"]):{}}function ot(t){const e=st(t);return e?l(e,["themeConfig"]):{}}function dt(t){return u(t)?l(t,["staticUrl","urlKey"]):{}}function ct(t){const e=dt(t);return e?l(e,["themeConfig"]):{}}function pt(t){const e=h(t);if(!e||!e.route)return e??{};const a=u(e.route)?e.route:{};if(a.entity){switch(a.entityType){case"product":a.entity=H(a.entity);break;case"product_category":a.entity=st(a.entity);break;case"cms_page":case"blog_page":a.entity=dt(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 ut(t){if(!u(t))return{};const e={...t};return e.entity&&(e.entity=ot(e.entity),u(e.entity)&&(e.entity=l(e.entity,["id"]))),e.children&&Array.isArray(e.children)&&(e.children=e.children.map(ut)),e}function lt(t){const e=h(t);return e?e.cmsPages&&Array.isArray(e.cmsPages)?{items:e.cmsPages.map(ct),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=>ct(t)),total:e.total||e.items.length,page:e.page||1,pageSize:e.pageSize||e.items.length}:e:{}}function mt(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 yt(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=>yt(t))),e}function ht(t){const e=h(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=>yt(t))),e}class gt{constructor(t){this.config=t,this.baseUrl=t.apiBaseUrl.replace(/\/$/,""),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?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 r=this.buildUrl(t),i=this.isMultipartBody(e),n=this.isFormUrlEncodedBody(e),s=i||n,o=e?s||a?.skipRequestTransform?e:y(e):void 0,d=this.getApiName(t);return this.cache.deletePattern(`GET:.*${d}`),this.request("POST",r,{...a,body:o,rawBody:s,omitJsonContentType:i})}async put(t,e,a){const r=this.buildUrl(t),i=this.isMultipartBody(e),n=e?i?e:y(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=await this.parseResponseBody(i);if(a?.skipTransform&&i.ok)return{data:d};const c=void 0!==d?.result?d.result:d;this.config.debug&&console.log(`[Sazito SDK] ${t} ${e}:`,this.redactDebugValue({status:i.status,data:c}));let p=c?m(c):c;const u=["cart","product","user","order","invoice","payment","shippingAddress"];if(p&&"object"==typeof p&&!Array.isArray(p)){const t=Object.keys(p);1===t.length&&u.includes(t[0])&&"object"==typeof p[t[0]]&&null!==p[t[0]]&&(p=p[t[0]])}return i.ok?{data:p}:{error:{status:i.status,message:this.extractErrorMessage(p,i.statusText),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:this.serializeErrorDetails(t)}}}}async parseResponseBody(t){const e=await t.text();if(!e)return;const a=t.headers.get("content-type");if(!a?.includes("application/json"))return e;try{return JSON.parse(e)}catch{return e}}extractErrorMessage(t,e){const a=t=>{if("string"==typeof t)return t.trim()||void 0;if(Array.isArray(t))for(const e of t){const t=a(e);if(t)return t}else if(t&&"object"==typeof t)for(const e of["message","error","errors","detail","title"]){const r=a(t[e]);if(r)return r}};return a(t)||e||"Request failed"}serializeErrorDetails(t){return{name:"string"==typeof t?.name?t.name:"Error",message:"string"==typeof t?.message?t.message:String(t)}}redactDebugValue(t,e=""){if(/authorization|cookie|password|secret|token|identifier|tracking|mobile|phone|email|postal|address|first.?name|last.?name|receipt.?ref|ref.?id/i.test(e)){if(null==t||""===t)return t;const e=String(t);return e.length<=4?"[REDACTED]":`[REDACTED:${e.slice(-4)}]`}return Array.isArray(t)?t.map(t=>this.redactDebugValue(t)):t&&"object"==typeof t?Object.fromEntries(Object.entries(t).map(([t,e])=>[t,this.redactDebugValue(e,t)])):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}isFormUrlEncodedBody(t){return"undefined"!=typeof URLSearchParams&&t instanceof URLSearchParams}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}isDebugEnabled(){return this.config.debug}clearCache(){this.cache.clear()}}class ft{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 bt{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 ft)}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 _t="/api/v1/product_categories",vt="/api/v1/search",At="/api/v2/carts",wt="/api/v2/invoices",Pt="/api/v2/shipping_addresses",It="/api/v1/pinch",Ct="/api/v1/orders",St="/api/v1/users",Tt="/api/v1/sessions",kt="/api/v1/feedbacks",Et="/api/v1/cms_pages",zt="/api/v1/images",Nt="/api/v1/scheduler/events",xt="/api/v1/scheduler/bookings",Rt="/api/v1/entity_route/route",Dt="/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}`,r=await this.http.get(Rt,{...e,params:{url_part:a}});if(r.data){const t=pt(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:tt(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(vt,{...a,params:r});if(i.data){return{data:et(i.data)}}return i}}class $t{constructor(t){this.http=t}async get(t,e){const a=await this.http.get(`${_t}/${t}`,e);if(a.data){const t=function(t){const e=h(t);return e?st(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(_t,{...e,params:a});if(r.data){const t=function(t){const e=h(t);return e?(e.categories&&Array.isArray(e.categories)&&(e.categories=e.categories.map(ot)),u(e.tree)&&u(e.tree.treeStructure)&&Array.isArray(e.tree.treeStructure.nodes)&&(e.tree.treeStructure.nodes=e.tree.treeStructure.nodes.map(ut)),e):{}}(r.data);return{data:t}}return r}}class Ft{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(`${At}/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(At,t,e);if(!a.data)return a;const r=T(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(`${At}/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=T(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(`${At}/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=T(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(`${At}/0/remove_products_from_cart`,{identifier:r.identifier,cartProductId:String(t),variants:[{id:e}]},a);if(i.data){const t=T(i.data);return this.persistCartCredentials(t),{data:t}}return i}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 r=await this.http.get(Ct,{...e,params:a});return r.data?{data:z(r.data)}:r}async get(t,e){const a=await this.http.get(`${Ct}/${t}`,e);return a.data?{data:E(a.data)}:a}}class Mt{constructor(t,e){this.http=t,this.credentials=e}normalizeInvoiceResponse(t){return t.data?{data:k(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(`${wt}/${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(wt,{cart_id:String(0),cart_identifier:e.identifier},t);if(a.data){const t=k(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(`${wt}/${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(`${wt}/${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(`${wt}/${a.id}/add_discount_code`,{identifier:a.identifier,discount_code:t.toUpperCase()},e);return r.data?(this.credentials.setDiscountCode(t.toUpperCase()),{data:k(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(`${wt}/${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(`${wt}/${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(`${wt}/${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(`${wt}/${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(`${wt}/${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(`${wt}/${e.id}/applicable_shipping_methods`,{...t,cache:t?.cache??!1,params:{identifier:e.identifier}});return a.data?{data:it(a.data)}:a}clearInvoice(){this.credentials.clearInvoiceCredentials()}}class Vt{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(Pt,{shipping_address:a},e);if(r.data){const t=G(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(Pt,{identifier:a.identifier,shipping_address:r},e);if(i.data){const t=G(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(Pt,{...t,cache:t?.cache??!1});if(e.error)return{error:e.error};return{data:this.extractAddressList(e.data).map(t=>G(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(`${Pt}/${e.id}`,{...t,params:{identifier:e.identifier}});if(a.data){const t=G(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:rt(e.data)}:e.error?{error:e.error}:{data:[]}}clearAddress(){this.credentials.clearShippingCredentials()}}class Bt{constructor(t,e,a="/api/v2/payments"){this.http=t,this.credentials=e,this.paymentsBasePath=a,this.pinchedPayments=new Set,this.verificationTraceSequence=0}async getMethods(t){const e=this.credentials.getInvoiceCredentials();if(!e)return{error:{message:"No invoice found",type:"validation"}};const a=await this.http.post(`${this.paymentsBasePath}/list`,{invoice_identifier:e.identifier},t);return a.data?{data:at(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(this.paymentsBasePath,{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;if(null===this.normalizePaymentId(a)||!t.trim())return{error:{message:"Payment creation response is missing a valid payment ID or identifier.",type:"api"}};const 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.submitJsonPaymentStep(void 0,t)}async verify(t,e){if(!t)return this.getPaymentStep(e);const a=this.resolvePaymentCredentials(t.id,t.paymentIdentifier);return"error"in a?{error:a.error}:this.verifyPaymentCallback({paymentId:a.data.id,paymentIdentifier:a.data.identifier,body:this.paymentStepInputToCallbackFields(t)},e)}async verifyPaymentCallback(t,e){const a=this.nextVerificationTraceId("callback"),r=this.normalizePaymentId(t.paymentId),i=t.paymentIdentifier?.trim();if(this.logVerification(a,"started",{paymentId:t.paymentId,paymentIdentifier:i,body:t.body,query:t.query,callbackFieldNames:Object.keys({...t.body??{},...t.query??{}})}),null===r||!i)return this.logVerification(a,"validation_failed",{reason:"Invalid payment callback credentials",normalizedPaymentId:r,hasPaymentIdentifier:Boolean(i)}),{error:{message:"Invalid payment callback credentials.",type:"validation"}};const n=new URLSearchParams,s={...t.body??{},...t.query??{}};for(const[t,e]of Object.entries(s))this.appendCallbackValue(n,`payload[${t}]`,e);n.set("payment_identifier",i);const o=`${this.paymentsBasePath}/${encodeURIComponent(String(r))}/process_payment_step`;this.logVerification(a,"request_prepared",{method:"POST",endpoint:o,contentType:"application/x-www-form-urlencoded;charset=UTF-8",form:Object.fromEntries(n.entries())});const d=await this.http.post(o,n,{...e,headers:this.withContentType(e?.headers,"application/x-www-form-urlencoded;charset=UTF-8"),skipTransform:!0});return this.logVerification(a,"response_received",d),this.finalizeStepResponse(d,r,e,a)}async getPaymentStep(t){return this.submitJsonPaymentStep(void 0,t)}async processStep(t,e){return this.submitJsonPaymentStep(t,e)}async submitJsonPaymentStep(t,e){const a=this.nextVerificationTraceId("status"),r=this.resolvePaymentCredentials(t?.id,t?.paymentIdentifier);if("error"in r)return this.logVerification(a,"validation_failed",r),{error:r.error};const i=r.data,n=`${this.paymentsBasePath}/${i.id}/process_payment_step`;this.logVerification(a,"request_prepared",{method:"POST",endpoint:n,contentType:"application/json",credentialSource:null!=t?.id||null!=t?.paymentIdentifier?"input":"storage",paymentId:i.id});const s=await this.http.post(n,this.buildProcessStepBody(t,i.identifier),{...this.withExactJsonHeader(e),skipRequestTransform:!0});return this.logVerification(a,"response_received",s),this.finalizeStepResponse(s,i.id,e,a)}async processStepForm(t,e){const a=this.resolvePaymentCredentials();if("error"in a)return{error:a.error};const r=a.data,i=this.buildProcessStepFormData(t,r.identifier);if(!i)return{error:{message:"FormData is not available in this runtime.",type:"validation"}};const n=await this.http.post(`${this.paymentsBasePath}/${r.id}/process_payment_step`,i,{...e,skipTransform:!0});return this.finalizeStepResponse(n,r.id,e)}async pollUntilSettled(t,e=15e3){const a=this.nextVerificationTraceId("poll"),r=t?.intervalMs??e,i=t?.pollingTimeoutMs??3e5,n=t?.maxAttempts,s=Date.now();let o,d=0;if(this.logVerification(a,"poll_started",{intervalMs:r,pollingTimeoutMs:i,maxAttempts:n,immediate:t?.immediate??!1,signalAborted:t?.signal?.aborted??!1}),!Number.isFinite(r)||r<0||!Number.isFinite(i)||i<=0||void 0!==n&&(!Number.isInteger(n)||n<=0)){const t={error:{message:"Invalid payment polling options.",type:"validation"}};return this.logVerification(a,"poll_validation_failed",t),t}for(;!o;){const e=Date.now()-s;if(e>=i||void 0!==n&&d>=n){const t={error:{message:"Payment verification timed out.",type:"network"}};return this.logVerification(a,"poll_timed_out",{attempt:d,elapsed:e,result:t}),t}if(!t?.immediate||d>0){const n=await this.waitForPoll(Math.min(r,i-e),t?.signal);if(n)return this.logVerification(a,"poll_cancelled",{attempt:d,result:n}),n}if(Date.now()-s>=i){const t={error:{message:"Payment verification timed out.",type:"network"}};return this.logVerification(a,"poll_timed_out",{attempt:d,elapsed:Date.now()-s,result:t}),t}d+=1,this.logVerification(a,"poll_request_started",{attempt:d});const c=await this.getPaymentStep(t);this.logVerification(a,"poll_response_received",{attempt:d,response:c}),c.data&&"pending"===c.data.action||(o=c)}return this.logVerification(a,"poll_settled",{attempts:d,elapsedMs:Date.now()-s,response:o}),o}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"},skipTransform:!0}}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=this.buildProcessStepBody(t,e),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}buildProcessStepBody(t,e){const a={payment_identifier:e};return t?("payload"in t&&void 0!==t.payload&&(a.payload=t.payload),"tatoken"in t&&void 0!==t.tatoken&&(a.tatoken=t.tatoken),"trackingData"in t&&void 0!==t.trackingData&&(a.tracking_data=t.trackingData),"isFailed"in t&&void 0!==t.isFailed&&(a.is_failed=t.isFailed),"imageUrl"in t&&void 0!==t.imageUrl&&(a.image_url=t.imageUrl),"code"in t&&void 0!==t.code&&(a.code=t.code),a):a}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,""))}resolvePaymentCredentials(t,e){const a=e?.trim();if(null!=t||null!=e){if(!Number.isSafeInteger(t)||Number(t)<=0||!a)return{error:{message:"Invalid payment callback credentials.",type:"validation"}};const e={id:Number(t),identifier:a};return this.credentials.setPaymentCredentials(e),{data:e}}const r=this.credentials.getPaymentCredentials();if(!r)return{error:{message:"No payment found. Please create a payment first.",type:"validation"}};const i=this.normalizePaymentId(r.id),n="string"==typeof r.identifier?r.identifier.trim():"";return null!==i&&n?{data:{id:i,identifier:n}}:{error:{message:"Stored payment credentials are invalid. Restore the payment ID and identifier from the original gateway return URL.",type:"validation"}}}normalizePaymentId(t){const e="string"==typeof t&&t.trim()?Number(t):t;return"number"==typeof e&&Number.isSafeInteger(e)&&e>0?e:null}paymentStepInputToCallbackFields(t){const e={...t.payload??{}};return void 0!==t.tatoken&&(e.tatoken=t.tatoken),void 0!==t.trackingData&&(e.trackingData=t.trackingData),void 0!==t.isFailed&&(e.isFailed=t.isFailed),void 0!==t.imageUrl&&(e.imageUrl=t.imageUrl),void 0!==t.code&&(e.code=t.code),e}appendCallbackValue(t,e,a){void 0!==a&&(Array.isArray(a)?a.forEach(a=>this.appendCallbackValue(t,e,a)):null!==a?t.append(e,"object"==typeof a?JSON.stringify(a):String(a)):t.append(e,""))}withContentType(t,e){const a={...t??{}};return delete a["Content-Type"],delete a["content-type"],{...a,"Content-Type":e}}waitForPoll(t,e){return e?.aborted?Promise.resolve({error:{message:"Payment verification cancelled.",type:"network"}}):new Promise(a=>{const r=()=>{clearTimeout(i),a({error:{message:"Payment verification cancelled.",type:"network"}})},i=setTimeout(()=>{e?.removeEventListener("abort",r),a(null)},t);e?.addEventListener("abort",r,{once:!0})})}async finalizeStepResponse(t,e,a,r){if(!t.data)return this.logVerification(r,"finished_without_data",t),t;const i=t=>!!t&&"object"==typeof t&&!Array.isArray(t);let n=t.data;if("string"==typeof n)try{n=JSON.parse(n)}catch{return this.logVerification(r,"response_parse_failed",{rawResponse:t.data}),{error:{message:"Invalid payment step response",type:"api"}}}const s=n,o=i(s)&&i(s.response)?s.response:s;if(this.logVerification(r,"envelope_unwrapped",{hadProxyResponseWrapper:o!==s,envelope:o}),i(o)){const t="string"==typeof o.error?o.error:"",e=Number(o.error_code??0);if(t||e)return this.logVerification(r,"envelope_error",{error:t,errorCode:e,status:o.status}),{error:{message:t||"Payment step failed",type:"api",status:Number(o.status)||void 0}}}const d=i(o)&&i(o.result)?o.result:o;this.logVerification(r,"action_extracted",d);const c=this.normalizeAction(d);return c?(this.logVerification(r,"action_normalized",c),await this.callPinchAfterSuccessfulPayment(c,e,a,r),this.logVerification(r,"finished",{paymentId:e,action:c.action}),{data:c}):(this.logVerification(r,"action_invalid",{reason:"Missing or malformed payment action fields",actionPayload:d}),{error:{message:"Invalid payment step result",type:"api"}})}normalizeAction(t){const e="string"==typeof t.action?t.action:"",a="string"==typeof t.message?t.message:void 0;switch(e){case"POST":return"string"==typeof t.address&&this.isPostPayload(t.payload)?{action:"POST",address:t.address,payload:t.payload,message:a,raw:t}:null;case"REDIRECT":return"string"==typeof t.address?{action:"REDIRECT",address:t.address,message:a,raw:t}:null;case"UPLOAD":return{action:"UPLOAD",time:this.optionalNumber(t.time),message:a,raw:t};case"show_otp_modal":return{action:"show_otp_modal",time:this.optionalNumber(t.time),message:a,raw:t};case"show_order":case"pending":{if(!t.order||"object"!=typeof t.order||Array.isArray(t.order))return null;const r=N(t.order);return this.isCheckoutOrder(r)?"show_order"===e?{action:"show_order",order:r,message:a,raw:t}:{action:"pending",order:r,message:a,raw:t}:null}case"payment_fail_error":return{action:"payment_fail_error",message:a,raw:t};case"show_error":return{action:"show_error",message:a,raw:t};case"FAIL":return{action:"FAIL",message:a,raw:t};case"StockViolated":return{action:"StockViolated",message:a,raw:t};default:return e?{action:"unknown",backendAction:e,raw:t,message:a}:null}}optionalNumber(t){return"number"==typeof t&&Number.isFinite(t)?t:void 0}isPostPayload(t){return!!t&&"object"==typeof t&&!Array.isArray(t)&&Object.values(t).every(t=>"string"==typeof t||"number"==typeof t)}isCheckoutOrder(t){const e=t=>"number"==typeof t&&Number.isFinite(t)||"string"==typeof t&&t.length>0,a=t.invoice;return e(t.id)&&e(t.orderNumber)&&"string"==typeof t.orderIdentifier&&t.orderIdentifier.length>0&&!!a&&Array.isArray(a.invoiceItems)&&Array.isArray(a.shippingItems)&&(void 0===a.netTotal||"number"==typeof a.netTotal&&Number.isFinite(a.netTotal))&&(void 0===a.finalTotal||"number"==typeof a.finalTotal&&Number.isFinite(a.finalTotal))&&a.invoiceItems.every(t=>e(t.productVariantId)&&"string"==typeof t.name&&Array.isArray(t.variantAttributes)&&t.variantAttributes.every(t=>"string"==typeof t.name&&"string"==typeof t.value)&&"number"==typeof t.singleItemPrice&&Number.isFinite(t.singleItemPrice)&&"number"==typeof t.noOfItems&&Number.isFinite(t.noOfItems)&&"number"==typeof t.totalItemsPrice&&Number.isFinite(t.totalItemsPrice)&&"string"==typeof t.productVariant?.product?.productType)&&a.shippingItems.every(t=>e(t.id)&&Array.isArray(t.invoiceItemIds)&&"string"==typeof t.rate?.name&&"number"==typeof t.rate?.price&&Number.isFinite(t.rate.price))}async callPinchAfterSuccessfulPayment(t,e,a,r){if("show_order"!==t.action)return void this.logVerification(r,"pinch_skipped",{reason:"Payment action is not show_order",action:t.action});if(this.pinchedPayments.has(e))return void this.logVerification(r,"pinch_skipped",{reason:"Payment was already pinched",paymentId:e});this.pinchedPayments.add(e),this.logVerification(r,"pinch_started",{method:"POST",endpoint:`${It}/order`,paymentId:e});const i=await this.http.post(`${It}/order`,{},a);if(i.error)return this.pinchedPayments.delete(e),void this.logVerification(r,"pinch_failed",i);this.logVerification(r,"pinch_succeeded",i)}nextVerificationTraceId(t){return this.verificationTraceSequence+=1,`${t}-${Date.now()}-${this.verificationTraceSequence}`}logVerification(t,e,a){this.http.isDebugEnabled()&&console.debug(`[Sazito SDK][Payment Verification][${t??"untracked"}] ${e}`,this.redactVerificationLogValue(a))}redactVerificationLogValue(t,e=""){if(/authorization|cookie|password|secret|token|identifier|tracking|mobile|phone|email|postal|address|first.?name|last.?name|receipt.?ref|ref.?id/i.test(e)){if(null==t||""===t)return t;const e=String(t);return e.length<=4?"[REDACTED]":`[REDACTED:${e.slice(-4)}]`}return Array.isArray(t)?t.map(t=>this.redactVerificationLogValue(t)):t&&"object"==typeof t?Object.fromEntries(Object.entries(t).map(([t,e])=>[t,this.redactVerificationLogValue(e,t)])):t}}class Ut{constructor(t){this.http=t}normalizeUserResponse(t){if(!t.data)return t;const e=M(t.data);return e?{data:e}:t}normalizeLoginResponse(t){if(!t.data||!t.data.user)return t;const e=M(t.data.user);return e?{data:{...t.data,user:e}}:t}async login(t,e){const a=await this.http.post(`${Tt}/login`,t,e);return this.normalizeLoginResponse(a)}async requestMobileOTP(t,e){return this.http.post(`${Tt}/login_request`,t,e)}async verifyMobileOTP(t,e){const a=await this.http.post(`${Tt}/login_request_verification`,t,e);return this.normalizeLoginResponse(a)}async requestEmailLogin(t,e){return this.http.post(`${St}/email_login_request`,t,e)}async register(t,e){const a=await this.http.post(`${St}/register`,t,e);return this.normalizeUserResponse(a)}async getCurrentUser(t){const e=await this.http.get(`${St}/current`,t);return this.normalizeUserResponse(e)}async updateProfile(t,e,a){const r=await this.http.put(`${St}/${t}`,e,a);return this.normalizeUserResponse(r)}async requestMobilePhoneUpdate(t,e){return this.http.post(`${St}/update_mobile_phone_request`,t,e)}async verifyMobilePhoneUpdate(t,e){const a=await this.http.post(`${St}/update_mobile_phone_verification`,t,e);return this.normalizeUserResponse(a)}async forgotPassword(t,e){return this.http.post(`${St}/forgot_password`,t,e)}async revivePassword(t,e){const a=await this.http.post(`${St}/revive_password`,t,e);return this.normalizeLoginResponse(a)}async mergeUser(t){return this.http.post(`${St}/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 r=this.transformFilters(e),i=await this.http.get(vt,{...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:et(i.data)}}return i}}class qt{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(Dt,t,e)}async getProductStatistics(t,e){const a=await this.http.get(`${Dt}/${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(`${Dt}/${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(kt,{...e,params:this.transformLegacyFilters(t)})}async create(t,e){return this.http.post(kt,t,e)}async get(t,e){return this.http.get(`${kt}/${t}`,e)}}class Lt{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:F(i.data)}:i}async applyCredit(t,e){const a=this.validateInvoiceId(t);if(a)return a;const r=await this.http.post(`${wt}/${t}/add_credit`,{},e);return r.data?{data:k(r.data)}:r}async removeCredit(t,e){const a=this.validateInvoiceId(t);if(a)return a;const r=await this.http.post(`${wt}/${t}/remove_credit`,{},e);return r.data?{data:k(r.data)}:r}}class Kt{constructor(t){this.http=t}missingDataError(t){return{error:{message:`No data returned from ${t} endpoint`,type:"api"}}}unexpectedEntityError(t,e,a,r=400){return{error:{message:`Expected ${t} at ${a}, but got ${e}`,type:"api",status:r,details:{expected:t,actual:e,urlPath:a}}}}async getPage(t,e){const a=await this.http.get(Rt,{...e,params:{url_part:t}});if(a.error)return{error:a.error};if(!a.data)return this.missingDataError("CMS page");const r=pt(a.data);return"cms_page"===r.entityType&&r.entity?"blog"===r.entity.cmsPageType?this.unexpectedEntityError("CMS page","blog page",t):{data:r.entity}:this.unexpectedEntityError("CMS page",r.entityType||"unknown entity",t,"unknown"===r.entityType?404:400)}async listPages(t,e){const a=mt({...t,cmsPageTypes:"normal"}),r=await this.http.get(Et,{...e,params:a});return r.error?{error:r.error}:r.data?{data:lt(r.data)}:this.missingDataError("CMS pages")}async getBlogPost(t,e){const a=await this.http.get(Rt,{...e,params:{url_part:t}});if(a.error)return{error:a.error};if(!a.data)return this.missingDataError("blog post");const r=pt(a.data);return"cms_page"===r.entityType&&r.entity?"blog"!==r.entity.cmsPageType?this.unexpectedEntityError("blog post","CMS page",t):{data:r.entity}:this.unexpectedEntityError("blog post",r.entityType||"unknown entity",t,"unknown"===r.entityType?404:400)}async listBlogPosts(t,e){const a=mt({...t,cmsPageTypes:"blog"}),r=await this.http.get(Et,{...e,params:a});return r.error?{error:r.error}:r.data?{data:lt(r.data)}:this.missingDataError("blog posts")}async listAll(t,e){const a=mt(t),r=await this.http.get(Et,{...e,params:a});return r.error?{error:r.error}:r.data?{data:lt(r.data)}:this.missingDataError("CMS content")}}class Yt{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(zt,a,{...e,headers:r})}async delete(t,e){return this.http.delete(`${zt}/${t}`,e)}}class Jt{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 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(Nt,{...e,params:this.transformEventFilters(t)})}async getEvent(t,e){const a=await this.http.get(`${Nt}/${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(xt,t,e)}async listBookings(t){return this.http.get(xt,t)}async cancelBooking(t,e){return this.http.post(`${xt}/${t}/cancel`,{},e)}}class Wt{constructor(t){this.http=t}async resolve(t,e){const a=await this.http.get(Rt,{...e,params:{url_part:t}});if(a.data){return{data:pt(a.data)}}return a}}class Ht{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}});if(a.error)return{error:a.error};const r=ht(a.data),i=r?.tree?.treeStructure?.nodes||[];return{data:this.convertRawTreeToNavigation(i)}}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 Zt{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 Xt{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 te(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function ee(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 ae(t){return"string"==typeof t?t.trim():""}class re{constructor(t){this.http=t}normalizeCity(t){return te(t)?{id:ee(t.id),name:ae(t.name),latitude:ee(t.latitude),longitude:ee(t.longitude)}:{id:0,name:"",latitude:0,longitude:0}}normalizeRegion(t){if(!te(t))return{id:0,name:"",cities:[]};const e=Array.isArray(t.cities)?t.cities:[];return{id:ee(t.id),name:ae(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:te(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 ie{constructor(t,a){const r=e(t);this.http=new gt(r),this.tokenStorage=this.http.getTokenStorage(),this.credentialsManager=a??new bt,this.products=new Ot(this.http),this.categories=new $t(this.http),this.cart=new Ft(this.http,this.credentialsManager),this.invoices=new Mt(this.http,this.credentialsManager),this.shipping=new Vt(this.http,this.credentialsManager),this.payments=new Bt(this.http,this.credentialsManager,r.paymentsBasePath),this.orders=new Gt(this.http),this.users=new Ut(this.http),this.search=new jt(this.http),this.feedbacks=new qt(this.http),this.wallet=new Lt(this.http),this.cms=new Kt(this.http),this.images=new Yt(this.http),this.visits=new Jt(this.http),this.booking=new Qt(this.http),this.entityRoutes=new Wt(this.http),this.menu=new Ht(this.http),this.general=new Zt(this.http),this.dynamicForms=new Xt(this.http),this.regions=new re(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 ne(t){if(!t||"object"!=typeof t)return!1;const e=t;return e.http instanceof gt&&e.credentials instanceof bt}function se(t){return ne(t)?t:function(t){const a=e(t);return{http:new gt(a),credentials:new bt}}(t)}function oe(t){const{http:e}=se(t);return new Ot(e)}function de(t){const{http:e}=se(t);return new $t(e)}function ce(t){const{http:e,credentials:a}=se(t);return new Ft(e,a)}function pe(t){const{http:e}=se(t);return new Gt(e)}function ue(t){const{http:e,credentials:a}=se(t);return new Mt(e,a)}function le(t){const{http:e,credentials:a}=se(t);return new Vt(e,a)}function me(t){const{http:a,credentials:r}=se(t),i=ne(t)?void 0:e(t).paymentsBasePath;return new Bt(a,r,i)}function ye(t){const{http:e}=se(t);return new Ut(e)}function he(t){const{http:e}=se(t);return new jt(e)}function ge(t){const{http:e}=se(t);return new qt(e)}function fe(t){const{http:e}=se(t);return new Lt(e)}function be(t){const{http:e}=se(t);return new Kt(e)}function _e(t){const{http:e}=se(t);return new Yt(e)}function ve(t){const{http:e}=se(t);return new Jt(e)}function Ae(t){const{http:e}=se(t);return new Qt(e)}function we(t){const{http:e}=se(t);return new Wt(e)}function Pe(t){const{http:e}=se(t);return new Ht(e)}function Ie(t){const{http:e}=se(t);return new Zt(e)}function Ce(t){const{http:e}=se(t);return new Xt(e)}function Se(t){const{http:e}=se(t);return new re(e)}exports.CredentialsManager=bt,exports.HttpClient=gt,exports.MemoryStorage=ft,exports.SazitoClient=ie,exports.TokenStorage=a,exports.booking=Ae,exports.cart=ce,exports.categories=de,exports.cms=be,exports.createBookingAPI=Ae,exports.createCMSAPI=be,exports.createCartAPI=ce,exports.createCategoriesAPI=de,exports.createDynamicFormsAPI=Ce,exports.createEntityRoutesAPI=we,exports.createFeedbacksAPI=ge,exports.createGeneralAPI=Ie,exports.createImagesAPI=_e,exports.createInvoicesAPI=ue,exports.createMenuAPI=Pe,exports.createOrdersAPI=pe,exports.createPaymentsAPI=me,exports.createProductsAPI=oe,exports.createRegionsAPI=Se,exports.createSazitoClient=function(t,e){return new ie(t,e)},exports.createSearchAPI=he,exports.createShippingAPI=le,exports.createUsersAPI=ye,exports.createVisitsAPI=ve,exports.createWalletAPI=fe,exports.dynamicForms=Ce,exports.entityRoutes=we,exports.feedbacks=ge,exports.general=Ie,exports.images=_e,exports.invoices=ue,exports.menu=Pe,exports.orders=pe,exports.payments=me,exports.products=oe,exports.regions=Se,exports.search=he,exports.shipping=le,exports.toEnglishDigits=n,exports.transformAddToCartInput=function(t,e,a){const r={product_variants:[{id:t,count:e}]};return a&&(r.form_attributes=y(a)),r},exports.transformApiResponse=h,exports.transformCartResponse=T,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?y(t.formAttributes):void 0}:{}):[]};return t.coupon&&(a.coupon=t.coupon),a},exports.transformInvoiceResponse=k,exports.transformProductListResponse=tt,exports.transformRequestKeys=y,exports.transformResponseKeys=m,exports.transformShippingAddressInput=function(t){if(u(t)){const e={...t};return delete e.user,{shipping_address:y(e)}}return{shipping_address:y(t)}},exports.users=ye,exports.visits=ve,exports.wallet=fe;
|
|
1
|
+
"use strict";const t={apiBaseUrl:"http://api.sazito.com:8080",paymentsBasePath:"/api/v2/payments",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",variant_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 y(t){if(!u(t))return Array.isArray(t)?t.map(t=>y(t)):t;const e={};for(const[a,r]of Object.entries(t)){let t=d[a];t||(t=p(a)),u(r)?e[t]=y(r):Array.isArray(r)?e[t]=r.map(t=>y(t)):e[t]="string"==typeof r&&i.has(t)?n(r):r}return e}function h(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,y={...u(e)?e:{},...u(a)?a:{}},{registerType:h,showProductStockNumber:g,...A}=y||{};return{...m,scripts:{enamad:d,google:c},shop:b({...A,domain:o,logo:p,social:l}),settings:{checkout:f(r),features:I(i),wallet:C(n),tajrobe:S(s),registerType:_(h),showProductStockNumber:v(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: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(r)?r:0},miniCart:v(t.miniCart),postalCodeMandatory:v(t.postalCodeMandatory),quickAddToCart:v(t.quickAddToCart)};return delete i.manual,i}function _(t){return"string"==typeof t?t:""}function v(t){return"boolean"==typeof t?t:u(t)&&Object.prototype.hasOwnProperty.call(t,"enabled")?v(t.enabled):1===t||"1"===t||"true"===t}function b(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 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"},w=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(w.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=A[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 T(t){const e=h(t);if(!u(e))return{};const a=Array.isArray(e.items)?e.items.map(t=>function(t){if(!u(t))return{};const e=W(t),a=K(t.productVariantId??e.variantId)??e.variantId;return{id:Q(t.id??t.cartProductId)??"",createdAt:Y(t.createdAt),updatedAt:Y(t.updatedAt),productVariantId:a,quantity:K(t.quantity)??0,unitPrice:K(t.unitPrice)??0,lineTotal:K(t.lineTotal)??0,product:e,formAttributes:t.formAttributes,formFields:t.formFields,bookingAttributes:t.bookingAttributes}}(t)):[];return{...e,items:a,netTotal:K(e.netTotal)??0,grossTotal:K(e.grossTotal),needsShipping:Boolean(e.needsShipping),minBasketLimitViolated:Boolean(e.minBasketLimitViolated),deleteCoupon:void 0===e.deleteCoupon?void 0:Boolean(e.deleteCoupon)}}function k(t){const e=h(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=W(t),a=K(t.productVariantId??e.variantId)??e.variantId,r=Array.isArray(e.attributes)?e.attributes:[],i=J(e.hasMaxOrder??t.hasMaxOrder);return{id:Q(t.id??t.invoiceItemId??t.cartProductId)??"",productVariantId:a,productId:K(e.productId??t.productId),name:Y(t.name)??Y(e.name)??"",url:Y(e.url)??Y(t.url),attributes:r,productType:Y(e.productType)??Y(t.productType),hasMaxOrder:i,maxOrderQuantity:K(e.maxOrderQuantity??t.maxOrderQuantity),minOrderQuantity:K(e.minOrderQuantity??t.minOrderQuantity),image:Z(t.image??e.image),quantity:K(t.quantity)??0,unitPrice:K(t.unitPrice)??0,lineTotal:K(t.lineTotal)??0,rawPrice:K(t.rawPrice??t.originalPrice)??0,customerProfit:K(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)?Y(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}}(B(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:L(t),rate:nt(e)}}(t)):[],discountUsages:i,netTotal:K(e.netTotal)??0,finalTotal:K(e.finalTotal)??0,vat:K(e.vat)??0,vatPercent:K(e.vatPercent)??0,itemsDiscount:K(e.itemsDiscount)??0,discountTotal:K(e.discountTotal)??0,customerProfit:K(e.customerProfit)??0,customerProfitPercentage:K(e.customerProfitPercentage)??0,itemsTotalRawPrice:K(e.itemsTotalRawPrice)??0,couponTotal:K(e.couponTotal)??0,shippingTotal:K(e.shippingTotal)??0,creditTotal:K(e.creditTotal)??0,needsShipping:Boolean(e.needsShipping),userComment:"string"==typeof e.userComment?e.userComment:void 0,discountCode:s}}function E(t){const e=h(t);if(!u(e))return{};if(!u(e.invoice))return e;const a=k(e.invoice),{items:r,...i}=a;return{...e,invoice:{...i,invoiceItems:Array.isArray(r)?r:[]}}}function z(t){const e=h(t);if(!u(e))return{};const a=Array.isArray(e.orders)?e.orders.map(t=>E(t)):[],r=K(e.pageNumber??e.page),i=K(e.pageSize),n=K(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 N(t){const e=function(t){if(!u(t))return{};if(u(t.data)&&u(t.data.result))return t.data.result;return u(t.result)?t.result:t}(t),a=u(e.order)?e.order:e;if(!u(a))return{};const r=u(a.invoice)?a.invoice:{},i=Array.isArray(r.invoice_items)?r.invoice_items.map(x):[],n=Array.isArray(r.shipping_items)?r.shipping_items.map(R):[];return{id:Q(a.id),orderNumber:Q(a.order_number),orderIdentifier:Y(a.order_identifier),invoice:{invoiceItems:i,shippingItems:n,netTotal:K(r.net_total),finalTotal:K(r.final_total),shippingTotal:K(r.shipping_total),discountTotal:K(r.discount_total),creditTotal:K(r.credit_total),vat:K(r.vat),vatPercent:K(r.vat_percent),itemsDiscount:K(r.items_discount),itemsTotalRawPrice:K(r.items_total_raw_price),customerProfit:K(r.customer_profit),customerProfitPercentage:K(r.customer_profit_percentage),discountUsages:Array.isArray(r.discount_usages)?r.discount_usages.map($):void 0}}}function x(t){if(!u(t))return{};const e=u(t.product_variant)?t.product_variant:{},a=u(e.product)?e.product:{};return{productVariantId:Q(t.product_variant_id??e.id),name:Y(t.name),image:u(t.image)?{url:Y(t.image.url)}:void 0,variantAttributes:Array.isArray(t.variant_attributes)?t.variant_attributes.map(D):[],singleItemPrice:K(t.single_item_price),noOfItems:K(t.no_of_items),totalItemsPrice:K(t.total_items_price),customerProfit:K(t.customer_profit),formAttributes:t.form_attributes,bookingAttributes:t.booking_attributes,productVariant:{commercialFiles:Array.isArray(e.commercial_files)?e.commercial_files.map(O):void 0,product:{productType:Y(a.product_type)}}}}function R(t){return u(t)&&u(t.rate)?{id:Q(t.id),invoiceItemIds:Array.isArray(t.invoice_item_ids)?t.invoice_item_ids.map(Q).filter(t=>void 0!==t):[],rate:{id:Q(t.rate.id),name:Y(t.rate.name),price:K(t.rate.price),type:Y(t.rate.type),icon:Y(t.rate.icon),color:Y(t.rate.color)}}:{}}function D(t){return u(t)?{name:Y(t.name),value:Y(t.value)}:{}}function O(t){return u(t)?{id:Q(t.id)}:{}}function $(t){return u(t)&&u(t.discount_code)?{discountCode:{code:Y(t.discount_code.code)}}:{}}function F(t){const e=h(t);if(!u(e))return{};const a=Array.isArray(e.transactions)?e.transactions:Array.isArray(e.walletTransactions)?e.walletTransactions:[],r=K(e.pageNumber??e.page),i=K(e.pageSize),n=K(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 G(t){return B(t)}function V(t){const e=h(t);if(u(e))return M(e)}function M(t){if(!t)return;const e=function(t){const e=U(t);if(!e)return;if(1===Object.keys(e).length&&u(e.user))return U(e.user)??e.user;return e}(t);if(!e)return;const a={},r=K(e.id);void 0!==r&&(a.id=r);const i=Y(e.email);i&&(a.email=i);const n=Y(e.mobilePhone)??Y(e.phoneNumber);n&&(a.mobilePhone=n);const s=Y(e.phoneNumber);s&&s!==n&&(a.phoneNumber=s);const o=Y(e.firstName);o&&(a.firstName=o);const d=Y(e.lastName);d&&(a.lastName=d);const c=Y(e.birthDate);return c&&(a.birthDate=c),Object.keys(a).length>0?a:void 0}function B(t){if(!t||0===Object.keys(t).length)return;const e=M(t.user),a=U(t.region),r=U(t.city),i=U(r?.region),n=Y(t.regionName)??q(t.region),s=j(a??t.region,{fallbackId:K(t.regionId),fallbackName:n})??j(i,{fallbackId:K(t.regionId),fallbackName:n}),o=K(t.regionId)??s?.id,d=Y(t.cityName)??Y(r?.name)??q(t.city),c=function(t,e={}){if(null==t)return;const a=U(t),r=K(a?.id)??K(t)??e.fallbackId,i=Y(a?.name)??q(t)??e.fallbackName;if(void 0===r||!i)return;const n={id:r,name:i},s=K(a?.regionId)??e.fallbackRegionId;void 0!==s&&(n.regionId=s);const o=K(a?.latitude);void 0!==o&&(n.latitude=o);const d=K(a?.longitude);void 0!==d&&(n.longitude=d);return n}(r??t.city,{fallbackId:K(t.cityId),fallbackName:d,fallbackRegionId:o}),p=Y(t.firstName)??e?.firstName??"",u=Y(t.lastName)??e?.lastName??"",l={id:K(t.id)??0,identifier:Y(t.identifier)??"",firstName:p,lastName:u,city:c??{id:K(t.cityId??t.city)??0,name:d??"",...void 0!==o?{regionId:o}:{}},address:Y(t.address)??""},m=Y(t.mobilePhone)??Y(t.phoneNumber)??e?.mobilePhone??e?.phoneNumber,y=Y(t.phoneNumber)??e?.phoneNumber;m&&(l.mobilePhone=m),y&&y!==m&&(l.phoneNumber=y);const h=Y(t.email)??e?.email;h&&(l.email=h),s&&(l.region=s);const g=Y(t.postalCode);g&&(l.postalCode=g);const f=Y(t.description);f&&(l.description=f);const _=K(t.latitude);void 0!==_&&(l.latitude=_);const v=K(t.longitude);void 0!==v&&(l.longitude=v);const b=J(t.userSetCoordinatesBefore);return void 0!==b&&(l.userSetCoordinatesBefore=b),l}function j(t,e={}){if(null==t)return;const a=U(t),r=K(a?.id)??K(t)??e.fallbackId,i=Y(a?.name)??q(t)??e.fallbackName;return void 0!==r&&i?{id:r,name:i}:void 0}function U(t){if(u(t))return u(t.data)?t.data:t}function q(t){const e=Y(t);if(e)return void 0===K(e)?e:void 0}function L(t){return(Array.isArray(t.invoiceItemIds)?t.invoiceItemIds:void 0!==t.invoiceItemId?[t.invoiceItemId]:[]).map(t=>Q(t)).filter(t=>void 0!==t)}function K(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 Y(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 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 W(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=K(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:K(r?.productId??t.productId??a?.id),name:Y(r?.name)??Y(t.name)??"",url:Y(r?.url)??Y(t.url)??Y(a?.url),image:Z(r?.image??t.image),attributes:n,productType:Y(r?.productType)??Y(t.productType)??Y(a?.productType),hasMaxOrder:r?.hasMaxOrder??t.hasMaxOrder??e?.hasMaxOrder,maxOrderQuantity:K(r?.maxOrderQuantity??t.maxOrderQuantity??e?.maxOrderQuantity),minOrderQuantity:K(r?.minOrderQuantity??t.minOrderQuantity??e?.minOrderQuantity)}}function H(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=>Z(t)??{})),e}function Z(t){return u(t)?l(t,["widthRatio","heightRatio","thumb","order"]):t}function X(t){const e=H(t);return e?l(e,["themeConfig"]):e}function tt(t){const e=h(t);if(e.items&&Array.isArray(e.items)){const t=K(e.total)??e.items.length,a=K(e.pageSize)??e.items.length,r=K(e.page)??1,i=K(e.totalPages)??Math.ceil(t/a);return{items:e.items.map(t=>X(t)),total:t,page:r,pageSize:a,totalPages:i}}return e}function et(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=>X(t)),a.products.total=K(e.productsCount)??0,a.products.page=K(e.productsPageNumber)??1,a.products.pageSize=K(e.productsPageSize)??20),Array.isArray(e.blogPages)&&(a.blogPages.items=e.blogPages.map(t=>ct(t)),a.blogPages.total=K(e.blogPagesCount)??0,a.blogPages.page=K(e.blogPagesPageNumber)??1,a.blogPages.pageSize=K(e.blogPagesPageSize)??20),Array.isArray(e.cmsPages)&&(a.cmsPages.items=e.cmsPages.map(t=>ct(t)),a.cmsPages.total=K(e.cmsPagesCount)??0,a.cmsPages.page=K(e.cmsPagesPageNumber)??1,a.cmsPages.pageSize=K(e.cmsPagesPageSize)??20),Array.isArray(e.categories)&&(a.productCategories.items=e.categories.map(t=>ot(t)),a.productCategories.total=K(e.productCategoriesCount)??0,a.productCategories.page=K(e.productCategoriesPageNumber)??1,a.productCategories.pageSize=K(e.productCategoriesPageSize)??20),a}function at(t){const e=h(t);if(!u(e))return[];return(Array.isArray(e.paymentTypes)?e.paymentTypes:Array.isArray(e.methods)?e.methods:[]).map(t=>u(t)?{id:K(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:K(t.paymentSubType)??null,order:K(t.order)??0,isDefault:Boolean(t.isDefault)}:{id:0,code:"",title:"",titleFa:"",description:null,paymentSubType:null,order:0,isDefault:!1})}function rt(t){const e=h(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:K(t.id)??0,name:Y(t.name)??"",type:Y(t.type)??""}}(t))}function it(t){const e=h(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=>nt(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=>nt(t)):[];return{shippingMethods:[],groupedShippingRates:a,itemsShippingRate:Array.isArray(e.itemsShippingRate)?e.itemsShippingRate.map(t=>u(t)?{invoiceItemId:Q(t.invoiceItemId)??L(t)[0]??"",shippingRate:nt(t.shippingRate??t.rate??t)}:{invoiceItemId:"",shippingRate:nt(void 0)}):[]}}function nt(t){return u(t)?{id:K(t.id??t.rateId)??0,name:Y(t.name)??"",price:K(t.price??t.amount)??0,description:Y(t.description??t.deliveryDescription??t.details),icon:Y(t.icon??t.iconUrl??t.logo),color:Y(t.color??t.bgColor??t.backgroundColor??t.iconColor),type:Y(t.type)}:{id:0,name:"",price:0}}function st(t){return u(t)?l(t,["staticUrl","products","items"]):{}}function ot(t){const e=st(t);return e?l(e,["themeConfig"]):{}}function dt(t){return u(t)?l(t,["staticUrl","urlKey"]):{}}function ct(t){const e=dt(t);return e?l(e,["themeConfig"]):{}}function pt(t){const e=h(t);if(!e||!e.route)return e??{};const a=u(e.route)?e.route:{};if(a.entity){switch(a.entityType){case"product":a.entity=H(a.entity);break;case"product_category":a.entity=st(a.entity);break;case"cms_page":case"blog_page":a.entity=dt(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 ut(t){if(!u(t))return{};const e={...t};return e.entity&&(e.entity=ot(e.entity),u(e.entity)&&(e.entity=l(e.entity,["id"]))),e.children&&Array.isArray(e.children)&&(e.children=e.children.map(ut)),e}function lt(t){const e=h(t);return e?e.cmsPages&&Array.isArray(e.cmsPages)?{items:e.cmsPages.map(ct),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=>ct(t)),total:e.total||e.items.length,page:e.page||1,pageSize:e.pageSize||e.items.length}:e:{}}function mt(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 yt(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=>yt(t))),e}function ht(t){const e=h(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=>yt(t))),e}class gt{constructor(t){this.config=t,this.baseUrl=t.apiBaseUrl.replace(/\/$/,""),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?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 r=this.buildUrl(t),i=this.isMultipartBody(e),n=this.isFormUrlEncodedBody(e),s=i||n,o=e?s||a?.skipRequestTransform?e:y(e):void 0,d=this.getApiName(t);return this.cache.deletePattern(`GET:.*${d}`),this.request("POST",r,{...a,body:o,rawBody:s,omitJsonContentType:i})}async put(t,e,a){const r=this.buildUrl(t),i=this.isMultipartBody(e),n=e?i?e:y(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=await this.parseResponseBody(i);if(a?.skipTransform&&i.ok)return{data:d};const c=void 0!==d?.result?d.result:d;this.config.debug&&console.log(`[Sazito SDK] ${t} ${e}:`,this.redactDebugValue({status:i.status,data:c}));let p=c?m(c):c;const u=["cart","product","user","order","invoice","payment","shippingAddress"];if(p&&"object"==typeof p&&!Array.isArray(p)){const t=Object.keys(p);1===t.length&&u.includes(t[0])&&"object"==typeof p[t[0]]&&null!==p[t[0]]&&(p=p[t[0]])}return i.ok?{data:p}:{error:{status:i.status,message:this.extractErrorMessage(p,i.statusText),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:this.serializeErrorDetails(t)}}}}async parseResponseBody(t){const e=await t.text();if(!e)return;const a=t.headers.get("content-type");if(!a?.includes("application/json"))return e;try{return JSON.parse(e)}catch{return e}}extractErrorMessage(t,e){const a=t=>{if("string"==typeof t)return t.trim()||void 0;if(Array.isArray(t))for(const e of t){const t=a(e);if(t)return t}else if(t&&"object"==typeof t)for(const e of["message","error","errors","detail","title"]){const r=a(t[e]);if(r)return r}};return a(t)||e||"Request failed"}serializeErrorDetails(t){return{name:"string"==typeof t?.name?t.name:"Error",message:"string"==typeof t?.message?t.message:String(t)}}redactDebugValue(t,e=""){if(/authorization|cookie|password|secret|token|identifier|tracking|mobile|phone|email|postal|address|first.?name|last.?name|receipt.?ref|ref.?id/i.test(e)){if(null==t||""===t)return t;const e=String(t);return e.length<=4?"[REDACTED]":`[REDACTED:${e.slice(-4)}]`}return Array.isArray(t)?t.map(t=>this.redactDebugValue(t)):t&&"object"==typeof t?Object.fromEntries(Object.entries(t).map(([t,e])=>[t,this.redactDebugValue(e,t)])):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}isFormUrlEncodedBody(t){return"undefined"!=typeof URLSearchParams&&t instanceof URLSearchParams}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}isDebugEnabled(){return this.config.debug}clearCache(){this.cache.clear()}}class ft{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 _t{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 ft)}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 vt="/api/v1/product_categories",bt="/api/v1/search",At="/api/v2/carts",wt="/api/v2/invoices",Pt="/api/v2/shipping_addresses",It="/api/v1/pinch",Ct="/api/v1/orders",St="/api/v1/users",Tt="/api/v1/sessions",kt="/api/v1/feedbacks",Et="/api/v1/cms_pages",zt="/api/v1/images",Nt="/api/v1/scheduler/events",xt="/api/v1/scheduler/bookings",Rt="/api/v1/entity_route/route",Dt="/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}`,r=await this.http.get(Rt,{...e,params:{url_part:a}});if(r.data){const t=pt(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:tt(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(bt,{...a,params:r});if(i.data){return{data:et(i.data)}}return i}}class $t{constructor(t){this.http=t}async get(t,e){const a=await this.http.get(`${vt}/${t}`,e);if(a.data){const t=function(t){const e=h(t);return e?st(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(vt,{...e,params:a});if(r.data){const t=function(t){const e=h(t);return e?(e.categories&&Array.isArray(e.categories)&&(e.categories=e.categories.map(ot)),u(e.tree)&&u(e.tree.treeStructure)&&Array.isArray(e.tree.treeStructure.nodes)&&(e.tree.treeStructure.nodes=e.tree.treeStructure.nodes.map(ut)),e):{}}(r.data);return{data:t}}return r}}class Ft{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(`${At}/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(At,t,e);if(!a.data)return a;const r=T(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(`${At}/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=T(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(`${At}/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=T(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(`${At}/0/remove_products_from_cart`,{identifier:r.identifier,cartProductId:String(t),variants:[{id:e}]},a);if(i.data){const t=T(i.data);return this.persistCartCredentials(t),{data:t}}return i}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 r=await this.http.get(Ct,{...e,params:a});return r.data?{data:z(r.data)}:r}async get(t,e){const a=await this.http.get(`${Ct}/${t}`,e);return a.data?{data:E(a.data)}:a}}class Vt{constructor(t,e){this.http=t,this.credentials=e}normalizeInvoiceResponse(t){return t.data?{data:k(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(`${wt}/${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(wt,{cart_id:String(0),cart_identifier:e.identifier},t);if(a.data){const t=k(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(`${wt}/${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(`${wt}/${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(`${wt}/${a.id}/add_discount_code`,{identifier:a.identifier,discount_code:t.toUpperCase()},e);return r.data?(this.credentials.setDiscountCode(t.toUpperCase()),{data:k(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(`${wt}/${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(`${wt}/${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(`${wt}/${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(`${wt}/${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(`${wt}/${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(`${wt}/${e.id}/applicable_shipping_methods`,{...t,cache:t?.cache??!1,params:{identifier:e.identifier}});return a.data?{data:it(a.data)}:a}clearInvoice(){this.credentials.clearInvoiceCredentials()}}class Mt{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(Pt,{shipping_address:a},e);if(r.data){const t=G(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(Pt,{identifier:a.identifier,shipping_address:r},e);if(i.data){const t=G(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(Pt,{...t,cache:t?.cache??!1});if(e.error)return{error:e.error};return{data:this.extractAddressList(e.data).map(t=>G(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(`${Pt}/${e.id}`,{...t,params:{identifier:e.identifier}});if(a.data){const t=G(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:rt(e.data)}:e.error?{error:e.error}:{data:[]}}clearAddress(){this.credentials.clearShippingCredentials()}}class Bt{constructor(t,e,a="/api/v2/payments"){this.http=t,this.credentials=e,this.paymentsBasePath=a,this.pinchedPayments=new Set,this.verificationTraceSequence=0}async getMethods(t){const e=this.credentials.getInvoiceCredentials();if(!e)return{error:{message:"No invoice found",type:"validation"}};const a=await this.http.post(`${this.paymentsBasePath}/list`,{invoice_identifier:e.identifier},t);return a.data?{data:at(a.data)}:a.error?{error:a.error}:{data:[]}}async create(t,e){const a=this.nextVerificationTraceId("create");if(!Number.isInteger(t)||t<=0)return{error:{message:"Invalid paymentTypeId. Provide a positive integer from payments.getMethods().",type:"validation"}};const r=this.credentials.getInvoiceCredentials();if(!r)return this.logVerification(a,"validation_failed",{reason:"No invoice found"}),{error:{message:"No invoice found",type:"validation"}};const i=await this.http.post(this.paymentsBasePath,{invoice_id:r.id,invoice_identifier:r.identifier,payment_type:t},{...e,skipTransform:!0});if(this.logVerification(a,"create_response_received",i),i.error)return{error:i.error};if(i.data){const t=i.data,e=this.extractPaymentPayload(t);if(e&&"object"==typeof e){const t=String(e.payment_identifier??e.paymentIdentifier??e.identifier??"").trim(),r=Number(e.id??0),i=e.payment_type??e.paymentType;if(null===this.normalizePaymentId(r)||!t.trim())return this.logVerification(a,"create_response_invalid",{candidateKeys:Object.keys(e),paymentId:r,hasPaymentIdentifier:Boolean(t.trim())}),{error:{message:"Payment creation response is missing a valid payment ID or identifier.",type:"api"}};const n={id:r,identifier:t,amount:Number(e.payment_amount??e.paymentAmount??e.amount??0),paymentType:{id:null!=i?.id?Number(i.id):void 0,code:i?.reference_code??i?.referenceCode??i?.code??""}};return t&&this.credentials.setPaymentCredentials({id:r,identifier:t}),{data:n}}}return this.logVerification(a,"create_response_invalid",{reason:"No payment object found",responseData:i.data}),{error:{message:"Payment creation response is missing a valid payment ID or identifier.",type:"api"}}}async initialize(t){return this.submitJsonPaymentStep(void 0,t)}async verify(t,e){if(!t)return this.getPaymentStep(e);const a=this.resolvePaymentCredentials(t.id,t.paymentIdentifier);return"error"in a?{error:a.error}:this.verifyPaymentCallback({paymentId:a.data.id,paymentIdentifier:a.data.identifier,body:this.paymentStepInputToCallbackFields(t)},e)}async verifyPaymentCallback(t,e){const a=this.nextVerificationTraceId("callback"),r=this.normalizePaymentId(t.paymentId),i=t.paymentIdentifier?.trim();if(this.logVerification(a,"started",{paymentId:t.paymentId,paymentIdentifier:i,body:t.body,query:t.query,callbackFieldNames:Object.keys({...t.body??{},...t.query??{}})}),null===r||!i)return this.logVerification(a,"validation_failed",{reason:"Invalid payment callback credentials",normalizedPaymentId:r,hasPaymentIdentifier:Boolean(i)}),{error:{message:"Invalid payment callback credentials.",type:"validation"}};const n=new URLSearchParams,s={...t.body??{},...t.query??{}};for(const[t,e]of Object.entries(s))this.appendCallbackValue(n,`payload[${t}]`,e);n.set("payment_identifier",i);const o=`${this.paymentsBasePath}/${encodeURIComponent(String(r))}/process_payment_step`;this.logVerification(a,"request_prepared",{method:"POST",endpoint:o,contentType:"application/x-www-form-urlencoded;charset=UTF-8",form:Object.fromEntries(n.entries())});const d=await this.http.post(o,n,{...e,headers:this.withContentType(e?.headers,"application/x-www-form-urlencoded;charset=UTF-8"),skipTransform:!0});return this.logVerification(a,"response_received",d),this.finalizeStepResponse(d,r,e,a)}async getPaymentStep(t){return this.submitJsonPaymentStep(void 0,t)}async processStep(t,e){return this.submitJsonPaymentStep(t,e)}async submitJsonPaymentStep(t,e){const a=this.nextVerificationTraceId("status"),r=this.resolvePaymentCredentials(t?.id,t?.paymentIdentifier);if("error"in r)return this.logVerification(a,"validation_failed",r),{error:r.error};const i=r.data,n=`${this.paymentsBasePath}/${i.id}/process_payment_step`;this.logVerification(a,"request_prepared",{method:"POST",endpoint:n,contentType:"application/json",credentialSource:null!=t?.id||null!=t?.paymentIdentifier?"input":"storage",paymentId:i.id});const s=await this.http.post(n,this.buildProcessStepBody(t,i.identifier),{...this.withExactJsonHeader(e),skipRequestTransform:!0});return this.logVerification(a,"response_received",s),this.finalizeStepResponse(s,i.id,e,a)}async processStepForm(t,e){const a=this.resolvePaymentCredentials();if("error"in a)return{error:a.error};const r=a.data,i=this.buildProcessStepFormData(t,r.identifier);if(!i)return{error:{message:"FormData is not available in this runtime.",type:"validation"}};const n=await this.http.post(`${this.paymentsBasePath}/${r.id}/process_payment_step`,i,{...e,skipTransform:!0});return this.finalizeStepResponse(n,r.id,e)}async pollUntilSettled(t,e=15e3){const a=this.nextVerificationTraceId("poll"),r=t?.intervalMs??e,i=t?.pollingTimeoutMs??3e5,n=t?.maxAttempts,s=Date.now();let o,d=0;if(this.logVerification(a,"poll_started",{intervalMs:r,pollingTimeoutMs:i,maxAttempts:n,immediate:t?.immediate??!1,signalAborted:t?.signal?.aborted??!1}),!Number.isFinite(r)||r<0||!Number.isFinite(i)||i<=0||void 0!==n&&(!Number.isInteger(n)||n<=0)){const t={error:{message:"Invalid payment polling options.",type:"validation"}};return this.logVerification(a,"poll_validation_failed",t),t}for(;!o;){const e=Date.now()-s;if(e>=i||void 0!==n&&d>=n){const t={error:{message:"Payment verification timed out.",type:"network"}};return this.logVerification(a,"poll_timed_out",{attempt:d,elapsed:e,result:t}),t}if(!t?.immediate||d>0){const n=await this.waitForPoll(Math.min(r,i-e),t?.signal);if(n)return this.logVerification(a,"poll_cancelled",{attempt:d,result:n}),n}if(Date.now()-s>=i){const t={error:{message:"Payment verification timed out.",type:"network"}};return this.logVerification(a,"poll_timed_out",{attempt:d,elapsed:Date.now()-s,result:t}),t}d+=1,this.logVerification(a,"poll_request_started",{attempt:d});const c=await this.getPaymentStep(t);this.logVerification(a,"poll_response_received",{attempt:d,response:c}),c.data&&"pending"===c.data.action||(o=c)}return this.logVerification(a,"poll_settled",{attempts:d,elapsedMs:Date.now()-s,response:o}),o}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"},skipTransform:!0}}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=this.buildProcessStepBody(t,e),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}buildProcessStepBody(t,e){const a={payment_identifier:e};return t?("payload"in t&&void 0!==t.payload&&(a.payload=t.payload),"tatoken"in t&&void 0!==t.tatoken&&(a.tatoken=t.tatoken),"trackingData"in t&&void 0!==t.trackingData&&(a.tracking_data=t.trackingData),"isFailed"in t&&void 0!==t.isFailed&&(a.is_failed=t.isFailed),"imageUrl"in t&&void 0!==t.imageUrl&&(a.image_url=t.imageUrl),"code"in t&&void 0!==t.code&&(a.code=t.code),a):a}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,""))}resolvePaymentCredentials(t,e){const a=e?.trim();if(null!=t||null!=e){if(!Number.isSafeInteger(t)||Number(t)<=0||!a)return{error:{message:"Invalid payment callback credentials.",type:"validation"}};const e={id:Number(t),identifier:a};return this.credentials.setPaymentCredentials(e),{data:e}}const r=this.credentials.getPaymentCredentials();if(!r)return{error:{message:"No payment found. Please create a payment first.",type:"validation"}};const i=this.normalizePaymentId(r.id),n="string"==typeof r.identifier?r.identifier.trim():"";return null!==i&&n?{data:{id:i,identifier:n}}:{error:{message:"Stored payment credentials are invalid. Restore the payment ID and identifier from the original gateway return URL.",type:"validation"}}}extractPaymentPayload(t){const e=t=>Boolean(t&&"object"==typeof t&&!Array.isArray(t)),a=[],r=t=>{e(t)&&!a.includes(t)&&(a.push(t),e(t.response)&&r(t.response),e(t.result)&&r(t.result),e(t.payment)&&r(t.payment))};return r(t),a.find(t=>e(t.payment)||void 0!==t.id||void 0!==t.payment_identifier||void 0!==t.paymentIdentifier)?.payment??a.find(t=>void 0!==t.id||void 0!==t.payment_identifier||void 0!==t.paymentIdentifier)}normalizePaymentId(t){const e="string"==typeof t&&t.trim()?Number(t):t;return"number"==typeof e&&Number.isSafeInteger(e)&&e>0?e:null}paymentStepInputToCallbackFields(t){const e={...t.payload??{}};return void 0!==t.tatoken&&(e.tatoken=t.tatoken),void 0!==t.trackingData&&(e.trackingData=t.trackingData),void 0!==t.isFailed&&(e.isFailed=t.isFailed),void 0!==t.imageUrl&&(e.imageUrl=t.imageUrl),void 0!==t.code&&(e.code=t.code),e}appendCallbackValue(t,e,a){void 0!==a&&(Array.isArray(a)?a.forEach(a=>this.appendCallbackValue(t,e,a)):null!==a?t.append(e,"object"==typeof a?JSON.stringify(a):String(a)):t.append(e,""))}withContentType(t,e){const a={...t??{}};return delete a["Content-Type"],delete a["content-type"],{...a,"Content-Type":e}}waitForPoll(t,e){return e?.aborted?Promise.resolve({error:{message:"Payment verification cancelled.",type:"network"}}):new Promise(a=>{const r=()=>{clearTimeout(i),a({error:{message:"Payment verification cancelled.",type:"network"}})},i=setTimeout(()=>{e?.removeEventListener("abort",r),a(null)},t);e?.addEventListener("abort",r,{once:!0})})}async finalizeStepResponse(t,e,a,r){if(!t.data)return this.logVerification(r,"finished_without_data",t),t;const i=t=>!!t&&"object"==typeof t&&!Array.isArray(t);let n=t.data;if("string"==typeof n)try{n=JSON.parse(n)}catch{return this.logVerification(r,"response_parse_failed",{rawResponse:t.data}),{error:{message:"Invalid payment step response",type:"api"}}}const s=n,o=i(s)&&i(s.response)?s.response:s;if(this.logVerification(r,"envelope_unwrapped",{hadProxyResponseWrapper:o!==s,envelope:o}),i(o)){const t="string"==typeof o.error?o.error:"",e=Number(o.error_code??0);if(t||e)return this.logVerification(r,"envelope_error",{error:t,errorCode:e,status:o.status}),{error:{message:t||"Payment step failed",type:"api",status:Number(o.status)||void 0}}}const d=i(o)&&i(o.result)?o.result:o;this.logVerification(r,"action_extracted",d);const c=this.normalizeAction(d);return c?(this.logVerification(r,"action_normalized",c),await this.callPinchAfterSuccessfulPayment(c,e,a,r),this.logVerification(r,"finished",{paymentId:e,action:c.action}),{data:c}):(this.logVerification(r,"action_invalid",{reason:"Missing or malformed payment action fields",actionPayload:d}),{error:{message:"Invalid payment step result",type:"api"}})}normalizeAction(t){const e="string"==typeof t.action?t.action:"",a="string"==typeof t.message?t.message:void 0;switch(e){case"POST":return"string"==typeof t.address&&this.isPostPayload(t.payload)?{action:"POST",address:t.address,payload:t.payload,message:a,raw:t}:null;case"REDIRECT":return"string"==typeof t.address?{action:"REDIRECT",address:t.address,message:a,raw:t}:null;case"UPLOAD":return{action:"UPLOAD",time:this.optionalNumber(t.time),message:a,raw:t};case"show_otp_modal":return{action:"show_otp_modal",time:this.optionalNumber(t.time),message:a,raw:t};case"show_order":case"pending":{if(!t.order||"object"!=typeof t.order||Array.isArray(t.order))return null;const r=N(t.order);return this.isCheckoutOrder(r)?"show_order"===e?{action:"show_order",order:r,message:a,raw:t}:{action:"pending",order:r,message:a,raw:t}:null}case"payment_fail_error":return{action:"payment_fail_error",message:a,raw:t};case"show_error":return{action:"show_error",message:a,raw:t};case"FAIL":return{action:"FAIL",message:a,raw:t};case"StockViolated":return{action:"StockViolated",message:a,raw:t};default:return e?{action:"unknown",backendAction:e,raw:t,message:a}:null}}optionalNumber(t){return"number"==typeof t&&Number.isFinite(t)?t:void 0}isPostPayload(t){return!!t&&"object"==typeof t&&!Array.isArray(t)&&Object.values(t).every(t=>"string"==typeof t||"number"==typeof t)}isCheckoutOrder(t){const e=t=>"number"==typeof t&&Number.isFinite(t)||"string"==typeof t&&t.length>0,a=t.invoice;return e(t.id)&&e(t.orderNumber)&&"string"==typeof t.orderIdentifier&&t.orderIdentifier.length>0&&!!a&&Array.isArray(a.invoiceItems)&&Array.isArray(a.shippingItems)&&(void 0===a.netTotal||"number"==typeof a.netTotal&&Number.isFinite(a.netTotal))&&(void 0===a.finalTotal||"number"==typeof a.finalTotal&&Number.isFinite(a.finalTotal))&&a.invoiceItems.every(t=>e(t.productVariantId)&&"string"==typeof t.name&&Array.isArray(t.variantAttributes)&&t.variantAttributes.every(t=>"string"==typeof t.name&&"string"==typeof t.value)&&"number"==typeof t.singleItemPrice&&Number.isFinite(t.singleItemPrice)&&"number"==typeof t.noOfItems&&Number.isFinite(t.noOfItems)&&"number"==typeof t.totalItemsPrice&&Number.isFinite(t.totalItemsPrice)&&"string"==typeof t.productVariant?.product?.productType)&&a.shippingItems.every(t=>e(t.id)&&Array.isArray(t.invoiceItemIds)&&"string"==typeof t.rate?.name&&"number"==typeof t.rate?.price&&Number.isFinite(t.rate.price))}async callPinchAfterSuccessfulPayment(t,e,a,r){if("show_order"!==t.action)return void this.logVerification(r,"pinch_skipped",{reason:"Payment action is not show_order",action:t.action});if(this.pinchedPayments.has(e))return void this.logVerification(r,"pinch_skipped",{reason:"Payment was already pinched",paymentId:e});this.pinchedPayments.add(e),this.logVerification(r,"pinch_started",{method:"POST",endpoint:`${It}/order`,paymentId:e});const i=await this.http.post(`${It}/order`,{},a);if(i.error)return this.pinchedPayments.delete(e),void this.logVerification(r,"pinch_failed",i);this.logVerification(r,"pinch_succeeded",i)}nextVerificationTraceId(t){return this.verificationTraceSequence+=1,`${t}-${Date.now()}-${this.verificationTraceSequence}`}logVerification(t,e,a){this.http.isDebugEnabled()&&console.debug(`[Sazito SDK][Payment Verification][${t??"untracked"}] ${e}`,this.redactVerificationLogValue(a))}redactVerificationLogValue(t,e=""){if(/authorization|cookie|password|secret|token|identifier|tracking|mobile|phone|email|postal|address|first.?name|last.?name|receipt.?ref|ref.?id/i.test(e)){if(null==t||""===t)return t;const e=String(t);return e.length<=4?"[REDACTED]":`[REDACTED:${e.slice(-4)}]`}return Array.isArray(t)?t.map(t=>this.redactVerificationLogValue(t)):t&&"object"==typeof t?Object.fromEntries(Object.entries(t).map(([t,e])=>[t,this.redactVerificationLogValue(e,t)])):t}}class jt{constructor(t){this.http=t}normalizeUserResponse(t){if(!t.data)return t;const e=V(t.data);return e?{data:e}:t}normalizeLoginResponse(t){if(!t.data||!t.data.user)return t;const e=V(t.data.user);return e?{data:{...t.data,user:e}}:t}async login(t,e){const a=await this.http.post(`${Tt}/login`,t,e);return this.normalizeLoginResponse(a)}async requestMobileOTP(t,e){return this.http.post(`${Tt}/login_request`,t,e)}async verifyMobileOTP(t,e){const a=await this.http.post(`${Tt}/login_request_verification`,t,e);return this.normalizeLoginResponse(a)}async requestEmailLogin(t,e){return this.http.post(`${St}/email_login_request`,t,e)}async register(t,e){const a=await this.http.post(`${St}/register`,t,e);return this.normalizeUserResponse(a)}async getCurrentUser(t){const e=await this.http.get(`${St}/current`,t);return this.normalizeUserResponse(e)}async updateProfile(t,e,a){const r=await this.http.put(`${St}/${t}`,e,a);return this.normalizeUserResponse(r)}async requestMobilePhoneUpdate(t,e){return this.http.post(`${St}/update_mobile_phone_request`,t,e)}async verifyMobilePhoneUpdate(t,e){const a=await this.http.post(`${St}/update_mobile_phone_verification`,t,e);return this.normalizeUserResponse(a)}async forgotPassword(t,e){return this.http.post(`${St}/forgot_password`,t,e)}async revivePassword(t,e){const a=await this.http.post(`${St}/revive_password`,t,e);return this.normalizeLoginResponse(a)}async mergeUser(t){return this.http.post(`${St}/merge_user`,{},t)}}class Ut{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(bt,{...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:et(i.data)}}return i}}class qt{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(Dt,t,e)}async getProductStatistics(t,e){const a=await this.http.get(`${Dt}/${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(`${Dt}/${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(kt,{...e,params:this.transformLegacyFilters(t)})}async create(t,e){return this.http.post(kt,t,e)}async get(t,e){return this.http.get(`${kt}/${t}`,e)}}class Lt{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:F(i.data)}:i}async applyCredit(t,e){const a=this.validateInvoiceId(t);if(a)return a;const r=await this.http.post(`${wt}/${t}/add_credit`,{},e);return r.data?{data:k(r.data)}:r}async removeCredit(t,e){const a=this.validateInvoiceId(t);if(a)return a;const r=await this.http.post(`${wt}/${t}/remove_credit`,{},e);return r.data?{data:k(r.data)}:r}}class Kt{constructor(t){this.http=t}missingDataError(t){return{error:{message:`No data returned from ${t} endpoint`,type:"api"}}}unexpectedEntityError(t,e,a,r=400){return{error:{message:`Expected ${t} at ${a}, but got ${e}`,type:"api",status:r,details:{expected:t,actual:e,urlPath:a}}}}async getPage(t,e){const a=await this.http.get(Rt,{...e,params:{url_part:t}});if(a.error)return{error:a.error};if(!a.data)return this.missingDataError("CMS page");const r=pt(a.data);return"cms_page"===r.entityType&&r.entity?"blog"===r.entity.cmsPageType?this.unexpectedEntityError("CMS page","blog page",t):{data:r.entity}:this.unexpectedEntityError("CMS page",r.entityType||"unknown entity",t,"unknown"===r.entityType?404:400)}async listPages(t,e){const a=mt({...t,cmsPageTypes:"normal"}),r=await this.http.get(Et,{...e,params:a});return r.error?{error:r.error}:r.data?{data:lt(r.data)}:this.missingDataError("CMS pages")}async getBlogPost(t,e){const a=await this.http.get(Rt,{...e,params:{url_part:t}});if(a.error)return{error:a.error};if(!a.data)return this.missingDataError("blog post");const r=pt(a.data);return"cms_page"===r.entityType&&r.entity?"blog"!==r.entity.cmsPageType?this.unexpectedEntityError("blog post","CMS page",t):{data:r.entity}:this.unexpectedEntityError("blog post",r.entityType||"unknown entity",t,"unknown"===r.entityType?404:400)}async listBlogPosts(t,e){const a=mt({...t,cmsPageTypes:"blog"}),r=await this.http.get(Et,{...e,params:a});return r.error?{error:r.error}:r.data?{data:lt(r.data)}:this.missingDataError("blog posts")}async listAll(t,e){const a=mt(t),r=await this.http.get(Et,{...e,params:a});return r.error?{error:r.error}:r.data?{data:lt(r.data)}:this.missingDataError("CMS content")}}class Yt{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(zt,a,{...e,headers:r})}async delete(t,e){return this.http.delete(`${zt}/${t}`,e)}}class Jt{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 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(Nt,{...e,params:this.transformEventFilters(t)})}async getEvent(t,e){const a=await this.http.get(`${Nt}/${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(xt,t,e)}async listBookings(t){return this.http.get(xt,t)}async cancelBooking(t,e){return this.http.post(`${xt}/${t}/cancel`,{},e)}}class Wt{constructor(t){this.http=t}async resolve(t,e){const a=await this.http.get(Rt,{...e,params:{url_part:t}});if(a.data){return{data:pt(a.data)}}return a}}class Ht{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}});if(a.error)return{error:a.error};const r=ht(a.data),i=r?.tree?.treeStructure?.nodes||[];return{data:this.convertRawTreeToNavigation(i)}}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 Zt{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 Xt{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 te(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function ee(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 ae(t){return"string"==typeof t?t.trim():""}class re{constructor(t){this.http=t}normalizeCity(t){return te(t)?{id:ee(t.id),name:ae(t.name),latitude:ee(t.latitude),longitude:ee(t.longitude)}:{id:0,name:"",latitude:0,longitude:0}}normalizeRegion(t){if(!te(t))return{id:0,name:"",cities:[]};const e=Array.isArray(t.cities)?t.cities:[];return{id:ee(t.id),name:ae(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:te(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 ie{constructor(t,a){const r=e(t);this.http=new gt(r),this.tokenStorage=this.http.getTokenStorage(),this.credentialsManager=a??new _t,this.products=new Ot(this.http),this.categories=new $t(this.http),this.cart=new Ft(this.http,this.credentialsManager),this.invoices=new Vt(this.http,this.credentialsManager),this.shipping=new Mt(this.http,this.credentialsManager),this.payments=new Bt(this.http,this.credentialsManager,r.paymentsBasePath),this.orders=new Gt(this.http),this.users=new jt(this.http),this.search=new Ut(this.http),this.feedbacks=new qt(this.http),this.wallet=new Lt(this.http),this.cms=new Kt(this.http),this.images=new Yt(this.http),this.visits=new Jt(this.http),this.booking=new Qt(this.http),this.entityRoutes=new Wt(this.http),this.menu=new Ht(this.http),this.general=new Zt(this.http),this.dynamicForms=new Xt(this.http),this.regions=new re(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 ne(t){if(!t||"object"!=typeof t)return!1;const e=t;return e.http instanceof gt&&e.credentials instanceof _t}function se(t){return ne(t)?t:function(t){const a=e(t);return{http:new gt(a),credentials:new _t}}(t)}function oe(t){const{http:e}=se(t);return new Ot(e)}function de(t){const{http:e}=se(t);return new $t(e)}function ce(t){const{http:e,credentials:a}=se(t);return new Ft(e,a)}function pe(t){const{http:e}=se(t);return new Gt(e)}function ue(t){const{http:e,credentials:a}=se(t);return new Vt(e,a)}function le(t){const{http:e,credentials:a}=se(t);return new Mt(e,a)}function me(t){const{http:a,credentials:r}=se(t),i=ne(t)?void 0:e(t).paymentsBasePath;return new Bt(a,r,i)}function ye(t){const{http:e}=se(t);return new jt(e)}function he(t){const{http:e}=se(t);return new Ut(e)}function ge(t){const{http:e}=se(t);return new qt(e)}function fe(t){const{http:e}=se(t);return new Lt(e)}function _e(t){const{http:e}=se(t);return new Kt(e)}function ve(t){const{http:e}=se(t);return new Yt(e)}function be(t){const{http:e}=se(t);return new Jt(e)}function Ae(t){const{http:e}=se(t);return new Qt(e)}function we(t){const{http:e}=se(t);return new Wt(e)}function Pe(t){const{http:e}=se(t);return new Ht(e)}function Ie(t){const{http:e}=se(t);return new Zt(e)}function Ce(t){const{http:e}=se(t);return new Xt(e)}function Se(t){const{http:e}=se(t);return new re(e)}exports.CredentialsManager=_t,exports.HttpClient=gt,exports.MemoryStorage=ft,exports.SazitoClient=ie,exports.TokenStorage=a,exports.booking=Ae,exports.cart=ce,exports.categories=de,exports.cms=_e,exports.createBookingAPI=Ae,exports.createCMSAPI=_e,exports.createCartAPI=ce,exports.createCategoriesAPI=de,exports.createDynamicFormsAPI=Ce,exports.createEntityRoutesAPI=we,exports.createFeedbacksAPI=ge,exports.createGeneralAPI=Ie,exports.createImagesAPI=ve,exports.createInvoicesAPI=ue,exports.createMenuAPI=Pe,exports.createOrdersAPI=pe,exports.createPaymentsAPI=me,exports.createProductsAPI=oe,exports.createRegionsAPI=Se,exports.createSazitoClient=function(t,e){return new ie(t,e)},exports.createSearchAPI=he,exports.createShippingAPI=le,exports.createUsersAPI=ye,exports.createVisitsAPI=be,exports.createWalletAPI=fe,exports.dynamicForms=Ce,exports.entityRoutes=we,exports.feedbacks=ge,exports.general=Ie,exports.images=ve,exports.invoices=ue,exports.menu=Pe,exports.orders=pe,exports.payments=me,exports.products=oe,exports.regions=Se,exports.search=he,exports.shipping=le,exports.toEnglishDigits=n,exports.transformAddToCartInput=function(t,e,a){const r={product_variants:[{id:t,count:e}]};return a&&(r.form_attributes=y(a)),r},exports.transformApiResponse=h,exports.transformCartResponse=T,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?y(t.formAttributes):void 0}:{}):[]};return t.coupon&&(a.coupon=t.coupon),a},exports.transformInvoiceResponse=k,exports.transformProductListResponse=tt,exports.transformRequestKeys=y,exports.transformResponseKeys=m,exports.transformShippingAddressInput=function(t){if(u(t)){const e={...t};return delete e.user,{shipping_address:y(e)}}return{shipping_address:y(t)}},exports.users=ye,exports.visits=be,exports.wallet=fe;
|