/** * SDK Configuration */ interface CacheConfig { enabled: boolean; ttl?: number; } interface RetryConfig { enabled: boolean; retries: number; retryDelay: number; } interface SazitoConfig { domain: string; /** API key sent in the Sazito-API-Key header when provided. */ apiKey?: string; /** Payments collection path for deployments with a custom API version map. */ paymentsBasePath?: string; timeout?: number; retry?: RetryConfig; cache?: { products?: CacheConfig; categories?: CacheConfig; cart?: CacheConfig; orders?: CacheConfig; search?: CacheConfig; cms?: CacheConfig; tags?: CacheConfig; entityRoutes?: CacheConfig; }; customFetchApi?: typeof fetch; debug?: boolean; } /** * Common types used throughout the SDK */ type JsonPrimitive = string | number | boolean | null; type JsonValue = JsonPrimitive | JsonObject | JsonArray; interface JsonObject { [key: string]: JsonValue; } type JsonArray = JsonValue[]; /** Error returned by every SDK API method. */ interface SazitoError { status?: number; message: string; type: 'network' | 'api' | 'validation'; details?: JsonValue; } /** * Unified response pattern for all API calls. * API failures are returned in `error`; public API methods do not throw them. */ type SazitoResponse = { data: T; error?: never; } | { data?: never; error: SazitoError; }; /** * Paginated response wrapper */ interface PaginatedResponse { items: T[]; total: number; page: number; pageSize: number; } /** * Request options that can be passed to an API call */ interface RequestOptions { /** Override retry count (0-3); explicitly opts non-idempotent requests into retries. */ retries?: number; timeout?: number; cache?: boolean; headers?: Record; signal?: AbortSignal; skipTransform?: boolean; } /** * Cookie options for token storage */ interface CookieOptions { httpOnly?: boolean; secure?: boolean; sameSite?: 'Strict' | 'Lax' | 'None'; maxAge?: number; path?: string; domain?: string; } /** * Image type used in products, categories, etc. */ interface Image { id: number; name: string; url: string; alt?: string; width?: number; height?: number; createdAt: string; updatedAt: string; } /** * Product attribute (e.g., color, size) */ /** * Rich attribute value for typed fields like color swatches. * `value` is the human-readable label; `extra` carries the payload * (e.g. a hex color when `fieldType` is `'color'`). */ interface ProductAttributeValueObject { value: string; extra?: string; fieldType?: string; } interface ProductAttribute { name: string; /** Backend attribute category, such as `'differentiator'`, when present. */ attributeType?: string; /** Backend value type, such as `'string'`, when present. */ type?: string; value: string | ProductAttributeValueObject; } /** * Normalized product snapshot embedded in checkout entities * (cart items, invoice items, successful order items). */ interface CheckoutProductSnapshot { variantId: number; productId?: number; name: string; url?: string; image?: Image; attributes: ProductAttribute[]; productType?: string; hasMaxOrder?: boolean; maxOrderQuantity?: number; minOrderQuantity?: number; } /** * Region (استان) */ interface Region$1 { id: number; name: string; cities?: City$1[]; } /** * City (شهر) */ interface City$1 { id: number; name: string; regionId?: number; latitude?: number; longitude?: number; } /** * Product-related types */ /** Slim image returned by all storefront product reads. */ interface ProductImage { id: number; alt?: string; url: string; width?: number; height?: number; } /** Variant fields available on list and search cards. */ interface ProductListVariant { id: number; enabled: boolean; price: number; originalPrice?: number; stockQuantity: number; isStockManaged: boolean; attributes: ProductAttribute[]; hasMaxOrder: boolean; maxOrderQuantity: number; minOrderQuantity: number; dynamicFormId?: number; sortIndex: number; imageId?: number; } /** Details variants additionally expose their SKU. */ interface ProductVariant extends ProductListVariant { sku?: string; } /** Product card returned by storefront list and search. */ interface ProductListItem { id: number; name: string; url: string; enabled: boolean; /** Search may return an empty string on the SDP branch. */ productType: string; dynamicFormId?: number; eventEntityId?: number; attributes?: ProductAttribute[]; /** Total image count returned by the API. */ imageCount: number; images: ProductImage[] | null; variants: ProductListVariant[] | null; } interface ProductBreadcrumbCategory { id: number; name: string; url: string; } /** Storefront detail product; entity routes move id to entityId. */ interface Product { id?: number; name: string; url: string; enabled: boolean; productType: string; themeConfig?: JsonObject; dynamicFormId?: number; eventEntityId?: number; attributes?: ProductAttribute[]; images: ProductImage[] | null; variants: ProductVariant[] | null; categories: ProductBreadcrumbCategory[] | null; } interface ProductCategory { id?: number; name: string; url: string; enabled?: boolean; description?: string; productsCount?: number; themeConfig?: JsonObject; attributes?: ProductAttribute[]; createdAt?: string; updatedAt?: string; } interface Tag { id: number; name: string; slug: string; } type ProductSort = 'newest' | 'best-selling' | 'availability' | 'discount' | '!price' | 'price'; interface ProductFilters { page?: number; pageSize?: number; sort?: ProductSort; categories?: number | number[]; priceMin?: number; priceMax?: number; availableOnly?: boolean; discountedOnly?: boolean; pinnedIds?: number[]; similarTo?: number; } /** * Cart-related types */ interface SchedulerBookingAttributes { eventEntityId: string | number; eventTitle?: string; eventId?: string; startDateTimeLocal: string; endDateTimeLocal: string; timezone: string; } interface UploadedFormFileAttribute { serveKey: string; fileName: string; } type FormAttributeValue = string | number | boolean | null | UploadedFormFileAttribute; interface CartProduct { id: number | string; /** When this line was first added to the cart. */ createdAt?: string; updatedAt?: string; productVariantId: number; quantity: number; unitPrice: number; lineTotal: number; product: CheckoutProductSnapshot; formAttributes?: Record; formFields?: JsonObject; bookingAttributes?: SchedulerBookingAttributes; } interface Cart { id: number; identifier: string; items: CartProduct[]; netTotal: number; grossTotal?: number; needsShipping: boolean; minBasketLimitViolated: boolean; deleteCoupon?: boolean; } interface CartCredentials { identifier: string; } interface AddToCartInput { id: number; count: number; formAttributes?: Record; } interface CreateCartInput { coupon?: string; variants: AddToCartInput[]; formAttributes?: Record; schedulerBookingAttributes?: SchedulerBookingAttributes; } /** * Invoice and checkout-related types */ interface InvoiceItemFormAttributes { formId?: number; formData: Record; } interface InvoiceItem { id: number | string; productVariantId: number; productId?: number; name: string; url?: string; attributes: ProductAttribute[]; productType?: string; hasMaxOrder?: boolean; maxOrderQuantity?: number; minOrderQuantity?: number; image?: Image; quantity: number; unitPrice: number; lineTotal: number; rawPrice: number; customerProfit: number; commercialFiles?: JsonValue; formAttributes?: Record | InvoiceItemFormAttributes; bookingAttributes?: SchedulerBookingAttributes; formFields?: JsonObject; } interface ShippingItem { invoiceItemIds: Array; rate: { id: number; name: string; price: number; icon?: string; color?: string; type?: string; }; } interface ShippingAddressRegion { id: number; name: string; } interface ShippingAddressCity { id: number; name: string; regionId?: number; latitude?: number; longitude?: number; } interface ShippingAddress { id: number; identifier: string; firstName: string; lastName: string; mobilePhone?: string; phoneNumber?: string; email?: string; region?: ShippingAddressRegion; city: ShippingAddressCity; address: string; postalCode?: string; description?: string; latitude?: number; longitude?: number; userSetCoordinatesBefore?: boolean; } interface InvoiceShippingAddressRegion extends ShippingAddressRegion { city: ShippingAddressCity; } interface InvoiceShippingAddress { identifier: string; firstName: string; lastName: string; mobilePhone?: string; phoneNumber?: string; email?: string; region?: InvoiceShippingAddressRegion; address: string; postalCode?: string; description?: string; latitude?: number; longitude?: number; userSetCoordinatesBefore?: boolean; } interface User { id?: number; email?: string; mobilePhone?: string; phoneNumber?: string; firstName?: string; lastName?: string; birthDate?: string; } interface Invoice { id: number; identifier: string; items: InvoiceItem[]; shippingAddress?: InvoiceShippingAddress; shippingItems: ShippingItem[]; needsShipping: boolean; userComment?: string; netTotal: number; finalTotal: number; vat: number; vatPercent: number; itemsDiscount: number; discountTotal: number; customerProfit: number; customerProfitPercentage: number; itemsTotalRawPrice: number; couponTotal: number; shippingTotal: number; creditTotal: number; discountUsages: Array<{ discountCode: { code: string; userSegment?: string; }; }>; coupon?: { userSegment?: string; }; discountCode?: string; } interface InvoiceCredentials { id: number; identifier: string; } interface CreateInvoiceInput { cartIdentifier: string; } interface RefreshInvoiceInput { cartIdentifier: string; identifier: string; } /** * Shipping-related types */ interface ShippingMethod { id: number; name: string; type: string; } interface ShippingRate { id: number; name: string; price: number; description?: string; icon?: string; color?: string; type?: string; } interface ItemShippingRate { invoiceItemId: number | string; shippingRate: ShippingRate; } interface ApplicableShippingMethods { shippingMethods: ShippingMethod[]; groupedShippingRates: Record; itemsShippingRate: ItemShippingRate[]; } interface ShippingAddressInput { firstName: string; lastName: string; mobilePhone: string; phoneNumber?: string; email?: string; regionId?: number; cityId?: number; address: string; postalCode?: string; description?: string; latitude?: number; longitude?: number; showMap?: boolean; userSetCoordinatesBefore?: boolean; } interface ShippingAddressCredentials { id: number; identifier: string; } interface ShippingAssignment { rateId: number; invoiceItemIds: Array; } /** * Order-related types */ type OrderPublicId = number | string; /** Account order item; retained as an alias for existing imports. */ type OrderInvoiceItem = InvoiceItem; interface OrderShippingItem { id: OrderPublicId; invoiceItemIds: OrderPublicId[]; rate: { id?: OrderPublicId; name: string; price: number; type?: string; icon?: string; color?: string; }; } interface OrderInvoice { invoiceItems: InvoiceItem[]; shippingItems: JsonObject[]; netTotal?: number; finalTotal?: number; shippingTotal?: number; discountTotal?: number; creditTotal?: number; vat?: number; vatPercent?: number; itemsTotalRawPrice?: number; itemsDiscount?: number; customerProfit?: number; customerProfitPercentage?: number; discountUsages?: Array<{ discountCode?: { code?: string; }; }>; } interface Order { id: number; orderNumber: string; orderIdentifier: string; invoice: OrderInvoice; } interface OrdersListResponse { orders: Order[]; pageNumber?: number; pageSize?: number; totalCount: number; totalCountRaw: number; totalNotSeen: number; totalSeen: number; } interface OrderFilters { pageNumber?: number; pageSize?: number; filters?: Array<{ name: string; value: JsonValue; }>; } /** * Payment completion order from process_payment_step; independent of account Order. */ interface CheckoutInvoiceItem { /** Invoice-line identifier used to associate this item with a shipment. */ id?: OrderPublicId; productVariantId: OrderPublicId; name: string; image?: { url?: string; }; variantAttributes: ProductAttribute[]; singleItemPrice: number; noOfItems: number; totalItemsPrice: number; customerProfit?: number; formAttributes?: unknown; bookingAttributes?: unknown; productVariant: { commercialFiles?: Array<{ id: OrderPublicId; }>; product: { productType: string; }; }; } interface CheckoutShippingItem { id: OrderPublicId; invoiceItemIds: OrderPublicId[]; rate: { id?: OrderPublicId; name: string; description?: string; price: number; type?: string; icon?: string; color?: string; }; } interface CheckoutInvoice { invoiceItems: CheckoutInvoiceItem[]; shippingItems: CheckoutShippingItem[]; /** May be omitted by the payment verification response. */ netTotal?: number; /** May be omitted by the payment verification response. */ finalTotal?: number; shippingTotal?: number; discountTotal?: number; creditTotal?: number; vat?: number; vatPercent?: number; itemsTotalRawPrice?: number; itemsDiscount?: number; customerProfit?: number; customerProfitPercentage?: number; discountUsages?: Array<{ discountCode?: { code?: string; }; }>; } interface CheckoutOrder { id: OrderPublicId; orderNumber: OrderPublicId; orderIdentifier: string; invoice: CheckoutInvoice; } /** * Payment-related types */ type PaymentGateway = 'mellatpayment' | 'pecpayment' | 'sadadpayment' | 'zarinpalpayment' | 'paypingpayment' | 'podpayment' | 'uppayment' | 'seppayment' | 'vandarpayment' | 'yourgatepayment' | 'bazarpayment' | 'zifypayment' | 'zibalpayment' | 'snapppayment' | 'torobpaypayment' | 'azkipayment' | 'digipaypayment' | 'novapaypayment' | 'zarinpluspayment' | 'tomanpayment' | 'tarapayment' | 'ozonpayment' | 'millipaypayment' | 'ayriapayment' | 'sabinpayment' | 'paymentinplace' | 'cardtocardpayment' | 'freepayment'; type PaymentStatus = 'PENDING' | 'PROCESSING' | 'PAID' | 'FAILED' | 'CANCELLED' | 'REFUNDED'; interface PaymentMethod { id: number; code: PaymentGateway; /** Backend display title (English). */ title: string; /** Backend display title (Persian). */ titleFa: string; /** Backend description; often null. */ description: string | null; /** Backend payment sub-type id; null when not provided. */ paymentSubType: number | null; /** Display order from backend. */ order: number; isDefault: boolean; } interface Payment { /** Zero is valid for identifier-scoped routes before gateway return. */ id: number; identifier: string; paymentType: { id?: number; code: PaymentGateway; }; amount: number; } interface PaymentActionBase { message?: string; /** Complete backend result before SDK normalization. */ raw?: JsonObject; } type PaymentAction = PaymentActionBase & ({ action: 'POST'; address: string; payload: Record; } | { action: 'REDIRECT'; address: string; } | { action: 'UPLOAD'; time?: number; } | { action: 'show_otp_modal'; time?: number; } /** Successful payment; some deployments omit order details in the terminal response. */ | { action: 'show_order'; order?: CheckoutOrder; } | { action: 'pending'; order: CheckoutOrder; } | { action: 'payment_fail_error' | 'show_error' | 'FAIL'; } | { action: 'StockViolated'; } | { action: 'unknown'; backendAction: string; raw: JsonObject; }); interface PaymentCredentials { /** Zero is valid for identifier-scoped routes before gateway return. */ id: number; identifier: string; } interface CreatePaymentInput { invoiceId: number; invoiceIdentifier: string; paymentType: number; } interface PaymentStepInput { /** Payment ID supplied by Sazito's gateway-return path. */ id?: number; /** Payment identifier supplied by Sazito's gateway-return path. */ paymentIdentifier?: string; payload?: JsonObject; tatoken?: string; trackingData?: JsonObject; isFailed?: string; imageUrl?: string; code?: string; } type PaymentCallbackFieldValue = JsonValue | undefined; type PaymentCallbackFields = Record; /** Raw gateway callback accepted by the form-encoded verification request. */ interface VerifyPaymentCallbackInput { paymentId: string | number; paymentIdentifier: string; /** Form/body fields are added first. */ body?: PaymentCallbackFields; /** Query fields are added second and win when a name is duplicated. */ query?: PaymentCallbackFields; } /** Controls the repeated JSON status check after a `pending` callback result. */ interface PaymentPollingOptions extends RequestOptions { /** Delay before each request, including the first one. Defaults to 15 seconds. */ intervalMs?: number; /** Overall polling deadline. Defaults to five minutes. */ pollingTimeoutMs?: number; /** Optional maximum number of status requests. */ maxAttempts?: number; /** Skip the initial delay when an immediate status check is desired. */ immediate?: boolean; } type PaymentStepFormValue = string | number | boolean | null | undefined; type PaymentStepFormFields = Record; /** * Search-related types */ /** * CMS Page types */ type CMSPageType = 'normal' | 'blog'; /** * Blog page entity from search results */ interface BlogPage { id?: number; name: string; url: string; enabled?: boolean; cmsPageType?: CMSPageType; content?: string; summary?: string; image?: Image; themeConfig?: JsonObject; attributes?: ProductAttribute[]; createdAt: string; updatedAt: string; } /** * CMS page entity from search results */ interface CmsPage { id?: number; name: string; url: string; enabled?: boolean; cmsPageType?: CMSPageType; content?: string; summary?: string; image?: Image; themeConfig?: JsonObject; attributes?: ProductAttribute[]; createdAt: string; updatedAt: string; } /** * Search response containing multiple entity types * Each entity type has its own array and pagination info */ interface SearchResponse { products: { items: ProductListItem[]; total: number; page: number; pageSize: number; }; blogPages: { items: BlogPage[]; total: number; page: number; pageSize: number; }; cmsPages: { items: CmsPage[]; total: number; page: number; pageSize: number; }; productCategories: { items: ProductCategory[]; total: number; page: number; pageSize: number; }; } /** * Entity Route types * For resolving URL paths to entities (products, categories, CMS pages) */ /** * Entity type discriminator */ type EntityType = 'product' | 'product_category' | 'cms_page' | 'blog_page' | 'unknown'; /** * Entity route response - polymorphic based on entity type */ interface EntityRoute { entityType: EntityType; entityId: number; url: string; } /** * Product entity route */ interface ProductEntityRoute extends EntityRoute { entityType: 'product'; entity: Product; } /** * Product category entity route */ interface ProductCategoryEntityRoute extends EntityRoute { entityType: 'product_category'; entity: ProductCategory; } /** * CMS page entity route */ interface CMSPageEntityRoute extends EntityRoute { entityType: 'cms_page'; entity: CmsPage; } /** * Blog page entity route */ interface BlogPageEntityRoute extends EntityRoute { entityType: 'blog_page'; entity: BlogPage; } /** * Unknown entity route (404) */ interface UnknownEntityRoute extends EntityRoute { entityType: 'unknown'; entity?: never; } /** * Union type for all possible entity routes */ type EntityRouteResponse = ProductEntityRoute | ProductCategoryEntityRoute | CMSPageEntityRoute | BlogPageEntityRoute | UnknownEntityRoute; /** * Menu and Navigation Types */ /** * Clean navigation menu item returned by SDK */ interface MenuItem { name: string; url: string; children: MenuItem[]; } /** * Raw menu tree structure from API (camelCased by HTTP client) */ interface MenuTree { id: number; identifier: string; treeStructure: { nodes: MenuNode[]; }; } /** * Raw menu node from API (camelCased by HTTP client) */ interface MenuNode { entityType: 'product_category' | 'product' | 'cms_page' | 'blog_page' | 'url'; entityId: number | null; entity?: { id?: number; name?: string; title?: string; url?: string; enabled?: boolean; }; details?: { title?: string; isTitleDefault?: boolean; url?: string; name?: string; entityType?: string; includeChildren?: boolean; }; children: MenuNode[]; } /** * Credentials Manager for guest users * Manages cart, invoice, shipping, and payment credentials. * Accepts an optional StorageAdapter — defaults to localStorage in browsers, * in-memory otherwise (SSR / server actions). */ interface StorageAdapter { getItem(key: string): string | null; setItem(key: string, value: string): void; removeItem(key: string): void; } declare class MemoryStorage implements StorageAdapter { private data; getItem(key: string): string | null; setItem(key: string, value: string): void; removeItem(key: string): void; } declare class CredentialsManager { private readonly CART_KEY; private readonly INVOICE_KEY; private readonly SHIPPING_KEY; private readonly PAYMENT_KEY; private readonly DISCOUNT_KEY; private storage; constructor(storage?: StorageAdapter); /** * Cart Credentials */ getCartCredentials(): CartCredentials | null; setCartCredentials(credentials: CartCredentials & { id?: number; }): void; clearCartCredentials(): void; /** * Invoice Credentials */ getInvoiceCredentials(): InvoiceCredentials | null; setInvoiceCredentials(credentials: InvoiceCredentials): void; clearInvoiceCredentials(): void; /** * Shipping Address Credentials */ getShippingCredentials(): ShippingAddressCredentials | null; setShippingCredentials(credentials: ShippingAddressCredentials): void; clearShippingCredentials(): void; /** * Payment Credentials */ getPaymentCredentials(): PaymentCredentials | null; setPaymentCredentials(credentials: PaymentCredentials): void; clearPaymentCredentials(): void; /** * Discount Code */ getDiscountCode(): string | null; setDiscountCode(code: string): void; clearDiscountCode(): void; /** * Clear all credentials */ clearAll(): void; private getItem; private setItem; private removeItem; } /** * Token storage for auth token persistence * Primary storage: localStorage (user_id_token), with cookie fallback. */ declare class TokenStorage { private readonly tokenKey; /** * Get token from localStorage (fallback to cookie) */ get(): string | null; /** * Set token in localStorage and cookie fallback */ set(token: string, options?: CookieOptions): void; /** * Remove token from both localStorage and cookie */ remove(): void; private getFromLocalStorage; private setInLocalStorage; private removeFromLocalStorage; /** * Parse document.cookie into key-value pairs */ private parseCookies; /** * Set a cookie with options */ private setCookie; } /** * HTTP Client with native fetch * Provides unified response pattern, retry logic, caching, and automatic data transformation */ declare class HttpClient { private readonly baseUrl; private domain; private config; private tokenStorage; private cache; private fetchApi; constructor(config: Required); /** * GET request */ get(endpoint: string, options?: RequestOptions & { params?: Record; }): Promise>; /** * POST request */ post(endpoint: string, body?: any, options?: RequestOptions & { skipRequestTransform?: boolean; }): Promise>; /** * PUT request */ put(endpoint: string, body?: any, options?: RequestOptions): Promise>; /** * DELETE request */ delete(endpoint: string, options?: RequestOptions): Promise>; /** * Core request method */ private request; /** * Parse JSON responses from text so an invalid JSON error body can still be * returned using the standard API-error envelope. */ private parseResponseBody; /** Extract a useful message from the common backend error shapes. */ private extractErrorMessage; /** Keep network error details serializable, matching `SazitoError.details`. */ private serializeErrorDetails; /** Preserve debug structure without printing credentials or customer PII. */ private redactDebugValue; /** * Build full URL with query params */ private buildUrl; /** * Get request headers */ private getHeaders; private isMultipartBody; private isFormUrlEncodedBody; /** * Check if status code should trigger a retry */ private shouldRetry; /** HTTP methods that are safe to replay after a transport/proxy failure. */ private isIdempotentMethod; /** * Delay helper for retries */ private delay; /** * Extract API name from endpoint for cache management */ private getApiName; /** * Get token storage instance */ getTokenStorage(): TokenStorage; /** Whether verbose SDK diagnostics were enabled by the client config. */ isDebugEnabled(): boolean; /** * Clear all cache */ clearCache(): void; } /** * Products API */ declare class ProductsAPI { private http; constructor(http: HttpClient); /** * Map SDK sort values to API sort values */ private mapSortToApi; /** * Transform filters to API request params */ private transformFilters; /** * Get a single product by slug or URL path * Uses the storefront product details API */ get(slugOrPath: string, options?: RequestOptions): Promise>; /** * List products with filters */ list(filters?: ProductFilters, options?: RequestOptions): Promise>>; /** * Search across all entity types (products, blog pages, CMS pages, product categories) */ search(query: string, filters?: ProductFilters, options?: RequestOptions): Promise>; } /** * Categories API */ /** * Category tree node structure */ interface CategoryTreeNode { id: number; entityType: 'product_category'; entityId: number; entity: ProductCategory; details: JsonObject; children: CategoryTreeNode[]; createdAt: string; updatedAt: string; } /** * Category tree structure */ interface CategoryTree { id: number; treeType: 'product_categories'; treeStructure: { nodes: CategoryTreeNode[]; }; } /** * Category list response with hierarchical tree */ interface CategoryListResponse { categories: ProductCategory[]; tree: CategoryTree; } /** * Category list filters */ interface CategoryFilters { page?: number; pageSize?: number; } declare class CategoriesAPI { private http; constructor(http: HttpClient); /** * Get a single category by ID or slug */ get(idOrSlug: string | number, options?: RequestOptions): Promise>; /** * List all categories with hierarchical tree structure * @param filters Optional pagination filters * @param options Additional request options */ list(filters?: CategoryFilters, options?: RequestOptions): Promise>; } /** * Cart API * Supports both authenticated and guest users via credentials */ interface AddItemAttributesInput { formAttributes?: Record; schedulerBookingAttributes?: CreateCartInput['schedulerBookingAttributes']; coupon?: string; } interface UpdateItemAttributesInput { formAttributes?: Record; coupon?: string; deleteCoupon?: boolean; } declare class CartAPI { private http; private credentials; constructor(http: HttpClient, credentials: CredentialsManager); private persistCartCredentials; /** * Get current cart */ get(options?: RequestOptions): Promise>; /** * Create a new cart */ create(input: CreateCartInput, options?: RequestOptions): Promise>; /** * Add item to cart */ addItem(variantId: number, count: number, formAttributes?: Record, options?: RequestOptions): Promise>; /** * Add item to cart with standardized attributes payload. */ addItemWithAttributes(variantId: number, count: number, attributes?: AddItemAttributesInput, options?: RequestOptions): Promise>; /** * Update cart item quantity */ updateItem(cartProductId: number | string, variantId: number, count: number, formAttributes?: Record, options?: RequestOptions): Promise>; /** * Update cart item quantity and optional coupon mutations. */ updateItemWithAttributes(cartProductId: number | string, variantId: number, count: number, attributes?: UpdateItemAttributesInput, options?: RequestOptions): Promise>; /** * Remove item from cart */ removeItem(cartProductId: number | string, variantId: number, options?: RequestOptions): Promise>; /** * Clear current cart credentials */ clearCart(): void; } /** * Orders API * Authenticated order listing and public detail retrieval using ID and identifier */ declare class OrdersAPI { private http; constructor(http: HttpClient); /** * List orders (requires authentication) */ list(filters?: OrderFilters, options?: RequestOptions): Promise>; /** * Get a public order by ID and its secret order identifier. * The backend must validate that the identifier belongs to this order. * Sends `GET /api/v1/orders/{id}?order_identifier={orderIdentifier}`. */ get(orderId: OrderPublicId, orderIdentifier: string, options?: RequestOptions): Promise>; } /** * Invoices API (Checkout) */ interface AddInvoiceFormInput { formAttributes: JsonObject; invoiceIdentifier?: string; identifier?: string; } declare class InvoicesAPI { private http; private credentials; constructor(http: HttpClient, credentials: CredentialsManager); private normalizeInvoiceResponse; /** * Get current invoice */ get(options?: RequestOptions): Promise>; /** * Create a new invoice from cart */ create(options?: RequestOptions): Promise>; /** * Refresh invoice (sync with cart) */ refresh(options?: RequestOptions): Promise>; /** * Add shipping address to invoice */ addShippingAddress(shippingAddressId: number, shippingAddressIdentifier: string, options?: RequestOptions): Promise>; /** * Add discount code to invoice */ addDiscountCode(code: string, options?: RequestOptions): Promise>; /** * Assign shipping method to invoice */ assignShippingMethod(shippings: ShippingAssignment[], options?: RequestOptions): Promise>; /** * Add invoice details (user comment) */ addDetails(comment: string, options?: RequestOptions): Promise>; /** * Attach checkout dynamic form data to invoice. */ addForm(input: AddInvoiceFormInput, options?: RequestOptions): Promise>; /** * Apply wallet credit to invoice. */ addCredit(options?: RequestOptions): Promise>; /** * Remove wallet credit from invoice. */ removeCredit(options?: RequestOptions): Promise>; /** * Toggle wallet credit based on current invoice state. */ toggleCredit(options?: RequestOptions): Promise>; /** * Get applicable shipping methods for invoice */ getApplicableShippingMethods(options?: RequestOptions): Promise>; /** * Clear current invoice credentials */ clearInvoice(): void; } /** * Shipping API (Addresses and Methods) */ declare class ShippingAPI { private http; private credentials; constructor(http: HttpClient, credentials: CredentialsManager); private sanitizeAddressInput; private unwrapAddressPayload; private extractAddressList; /** * Create shipping address */ createAddress(address: ShippingAddressInput, options?: RequestOptions): Promise>; /** * Update the address referenced by the currently stored credentials. * @deprecated Do not use during checkout. Existing invoices can reference * this row, so mutation can rewrite address data shown on previous orders. * Create a new address snapshot with createAddress instead. */ updateAddress(address: ShippingAddressInput, options?: RequestOptions): Promise>; /** * Get the authenticated user's shipping addresses, newest first. * This endpoint is intentionally not cached: checkout must see an address * created by the user's most recent order immediately. */ listAddresses(options?: RequestOptions): Promise>; /** * Get shipping address */ getAddress(options?: RequestOptions): Promise>; /** * Get list of enabled shipping methods */ getMethods(options?: RequestOptions): Promise>; /** * Clear shipping address credentials */ clearAddress(): void; } /** * Payments API */ declare class PaymentsAPI { private http; private credentials; private paymentsBasePath; private readonly pinchedPayments; private verificationTraceSequence; constructor(http: HttpClient, credentials: CredentialsManager, paymentsBasePath?: string); /** * Get list of payment methods for invoice */ getMethods(options?: RequestOptions): Promise>; /** * Create payment */ create(paymentTypeId: number, options?: RequestOptions): Promise>; /** * Initialize payment: start the payment step before redirecting the user to * the gateway. Returns the next {@link PaymentAction} (typically REDIRECT or * POST for hosted gateways, or show_order for zero-amount/instant payments). */ initialize(options?: RequestOptions): Promise>; /** * Verify payment after the user returns from the gateway. Forwards the * gateway callback parameters (e.g. `tatoken`, `trackingData`, `isFailed`, * `code`) to the same payment-step endpoint and returns the settled * {@link PaymentAction} (show_order on success, FAIL/StockViolated otherwise, * or pending if the gateway has not reported back yet). */ verify(input?: PaymentStepInput, options?: RequestOptions): Promise>; /** * Verify a gateway callback using Sazito's SSR form contract. Body fields * are written first and query fields second, and every gateway value is * wrapped as `payload[name]`. The validated payment identifier is the sole * top-level credential and is always written last. */ verifyPaymentCallback(input: VerifyPaymentCallbackInput, options?: RequestOptions): Promise>; /** Send one JSON payment status request. Used by pending polling only. */ getPaymentStep(options?: RequestOptions): Promise>; /** * Process payment step (for card-to-card or multi-step payments). * * @deprecated Prefer {@link verify} for gateway-return verification. */ processStep(input: PaymentStepInput, options?: RequestOptions): Promise>; /** * Shared JSON core for initialization, status checks and multi-step payment * actions. Gateway callback verification intentionally uses form encoding. */ private submitJsonPaymentStep; /** * Process payment step in form mode (non-JSON content-type). */ processStepForm(input: FormData | PaymentStepFormFields, options?: RequestOptions): Promise>; /** * Poll payment state every 15 seconds until action changes from pending. */ pollUntilSettled(options?: PaymentPollingOptions, intervalMs?: number): Promise>; /** * Clear payment credentials */ clearPayment(): void; private withExactJsonHeader; private buildProcessStepFormData; private buildProcessStepBody; private appendFormValue; private resolvePaymentCredentials; /** * Payment creation has been returned in a few compatible envelope shapes * across deployments: `{ result: { payment: ... } }`, a direct payment * under `result`, and (for request-log proxies) under `response.result`. * Keep the shape handling here so the credential parser never silently * mistakes an invoice identifier for the payment identifier. A zero id is * valid for identifier-scoped payment routes. */ private extractPaymentPayload; private normalizePaymentId; private paymentStepInputToCallbackFields; private appendCallbackValue; private withContentType; private waitForPoll; /** * Post-process a `process_payment_step` response. The exact-JSON endpoint * returns an envelope `{ result: PaymentAction, error, error_code, status }`. * Some storefront proxies preserve their request log wrapper and return it * as `{ method, path, response: }`; accept both shapes. */ private finalizeStepResponse; private normalizeAction; private optionalNumber; private isPostPayload; private isCheckoutOrder; private callPinchAfterSuccessfulPayment; private nextVerificationTraceId; private logVerification; private redactVerificationLogValue; } /** * Users API (Authentication and user management) */ /** * Login input (SDK uses camelCase) */ interface LoginInput { email: string; password: string; } /** * Register input (SDK uses camelCase) */ interface RegisterInput { email: string; password: string; passwordConfirmation: string; firstName?: string; lastName?: string; mobilePhone?: string; } /** * Mobile login input */ interface MobileLoginInput { mobilePhone: string; } /** * Verify mobile OTP input (SDK uses camelCase) */ interface VerifyMobileInput { mobilePhone: string; token: string; } /** * Passwordless email login input */ interface EmailLoginRequestInput { email: string; } /** * Forgot password input */ interface ForgotPasswordInput { email: string; } /** * Reset password input (SDK uses camelCase) */ interface ResetPasswordInput { forgotPasswordToken: string; password: string; passwordConfirmation: string; } /** * Update user profile input */ interface UpdateProfileInput { firstName?: string; lastName?: string; email?: string; password?: string; passwordConfirmation?: string; birthDate?: string; } /** * Update user phone request input */ interface UpdateMobilePhoneRequestInput { mobilePhone: string; } /** * Verify user phone update input */ interface UpdateMobilePhoneVerificationInput { mobilePhone: string; token: string; } interface LoginResponse { jwt: string; user?: User; } declare class UsersAPI { private http; constructor(http: HttpClient); private normalizeUserResponse; private normalizeLoginResponse; /** * Login with email and password */ login(input: LoginInput, options?: RequestOptions): Promise>; /** * Request mobile OTP */ requestMobileOTP(input: MobileLoginInput, options?: RequestOptions): Promise>; /** * Verify mobile OTP */ verifyMobileOTP(input: VerifyMobileInput, options?: RequestOptions): Promise>; /** * Passwordless login request via email */ requestEmailLogin(input: EmailLoginRequestInput, options?: RequestOptions): Promise>; /** * Register new user */ register(input: RegisterInput, options?: RequestOptions): Promise>; /** * Get current user (requires authentication) */ getCurrentUser(options?: RequestOptions): Promise>; /** * Update user profile (requires authentication) */ updateProfile(userId: number, data: UpdateProfileInput, options?: RequestOptions): Promise>; /** * Request mobile phone update (requires authentication) */ requestMobilePhoneUpdate(input: UpdateMobilePhoneRequestInput, options?: RequestOptions): Promise>; /** * Verify mobile phone update (requires authentication) */ verifyMobilePhoneUpdate(input: UpdateMobilePhoneVerificationInput, options?: RequestOptions): Promise>; /** * Forgot password - send reset email */ forgotPassword(input: ForgotPasswordInput, options?: RequestOptions): Promise>; /** * Revive/Reset password with token */ revivePassword(input: ResetPasswordInput, options?: RequestOptions): Promise>; /** * Merge guest and current user accounts after login */ mergeUser(options?: RequestOptions): Promise>; } /** * Search API */ interface SearchFilters { page?: number; pageSize?: number; categoryId?: number; minPrice?: number; maxPrice?: number; } declare class SearchAPI { private http; constructor(http: HttpClient); private transformFilters; /** * Query across multiple entity types (products, blog pages, CMS pages, categories) */ query(term: string, filters?: SearchFilters, options?: RequestOptions): Promise>; } /** * Feedbacks API (Tajrobe reviews + legacy feedback methods) */ type RecommendationStatus = 'RECOMMENDED' | 'NEUTRAL' | 'NOT-RECOMMENDED' | 'NONE'; interface FeedbackProductAttribute { [key: string]: unknown; name: string; value: unknown; } interface FeedbackProductImage { [key: string]: unknown; url: string; alt?: string; } interface FeedbackSeedItem { /** Additional backend seed fields are retained for product submission. */ [key: string]: unknown; productId: string; productVariantId: string; productName: string; productAttributes: FeedbackProductAttribute[]; productImage: FeedbackProductImage; } interface FeedbackSeed { orderId: string; orderIdentifier: string; hasCommentAlready: boolean; items: FeedbackSeedItem[]; } interface CreateOrderRatingInput { orderId: string | number; orderIdentifier: string; orderRate: number; } interface CommentResponse { id: string; } interface ProductReviewRequest { /** Spread the selected FeedbackSeedItem to retain backend-specific fields. */ [key: string]: unknown; commentId: string | number; productId: string | number; productVariantId: string | number; productName?: string; productAttributes?: FeedbackProductAttribute[]; productImage?: FeedbackProductImage; productRate: number; text?: string; pros?: string[]; cons?: string[]; recommendationStatus?: RecommendationStatus; attachmentsServeKeys?: string[]; owner?: boolean; isAnonymous?: boolean; } /** * The editable part of a product review. Use `buildProductReviewInput` to * combine this draft with an item returned by `getSeed`. */ interface ProductReviewDraft { productRate: number; text?: string; pros?: string[]; cons?: string[]; recommendationStatus?: RecommendationStatus; attachmentsServeKeys?: string[]; owner?: boolean; isAnonymous?: boolean; } /** * Build the wire-ready product review input from a seed item. This keeps all * backend-specific fields returned by the seed while applying the user's * editable values in one place. */ declare function buildProductReviewInput(item: FeedbackSeedItem, commentId: string | number, draft: ProductReviewDraft): ProductReviewRequest; interface SubmitOrderFeedbackInput { /** Order identifier used to load and validate the feedback seed. */ orderIdentifier: string; orderRate: number; /** * Optional seed already loaded by the host. Supplying it avoids a second * seed request when the UI needs the items to render its form. */ seed?: FeedbackSeed; /** Product reviews to submit, in the desired order. */ reviews?: Array<{ item: FeedbackSeedItem; draft: ProductReviewDraft; }>; } interface SubmitOrderFeedbackResult { status: 'submitted' | 'already_submitted'; seed: FeedbackSeed; commentId?: string; submittedProductCount: number; requestedProductCount: number; } interface ProductStatistics { productStatistics: { averageRate: number; totalCount: number; recommendations: { recommendedPercentage: number; recommendedTotalCount: number; }; }; } interface ProductReview { productRate: number; userFirstName: string; userLastName: string; createdAt: string; owner: boolean; text: string; recommendationStatus: RecommendationStatus; pros: string[]; cons: string[]; isAnonymous: boolean; metadata: { variantOptions: any[]; productName: string; variantId: string; }; attachments: Array<{ serveUrl: string; }>; } interface ProductReviewsFilters { pageNumber?: number; pageSize?: number; } interface ProductReviewsResponse { entities: ProductReview[]; pageNumber: number; pageSize: number; totalCount: number; averageRate: number; recommendations: { recommendedPercentage: number; recommendedTotalCount: number; }; } interface ReviewAttachmentInput { file: File | Blob; name?: string; alt?: string; } interface ReviewUploadedImage { id: string; url: string; alt: string; serveUrl: string; serveKey: string; } interface ReviewImageUploadResponse { images: ReviewUploadedImage[]; } declare class FeedbacksAPI { private http; constructor(http: HttpClient); private validId; private validRating; private normalizeOrderId; private normalizeSeedItem; private normalizeSeed; private normalizeProductReview; private normalizeProductStatistics; private normalizeProductReviewsResponse; /** * Validate order and get products that can be reviewed. */ getSeed(orderIdentifier: string, options?: RequestOptions): Promise>; /** * Submit order/shop rating and get a comment identifier for product review steps. */ createOrderRating(input: CreateOrderRatingInput, options?: RequestOptions): Promise>; /** * Run the complete feedback flow in a safe, sequential order. * * The seed is always loaded first. An already-submitted seed returns a * successful completion result without creating another comment. Product * submissions stop at the first failure and the returned error includes the * comment ID and progress so the host can resume without recreating the * order rating. */ submitOrderFeedback(input: SubmitOrderFeedbackInput, options?: RequestOptions): Promise>; /** * Submit product-level review details. */ submitProductReview(input: ProductReviewRequest, options?: RequestOptions): Promise>; /** * Fetch product review statistics (without review list). */ getProductStatistics(productId: string | number, options?: RequestOptions): Promise>; /** * Fetch paginated product reviews. */ getProductReviews(productId: string | number, filters?: ProductReviewsFilters, options?: RequestOptions): Promise>; /** * Upload review images and get serve keys for attachments. */ uploadReviewImages(images: ReviewAttachmentInput[], options?: RequestOptions): Promise>; } /** * Wallet API (User wallet and transactions) */ type WalletTransactionReason = 'redeem' | 'NthPurchase' | 'merge-user' | 'SimpleCashbackRule' | 'BirthdateGift' | 'TajrobehAppreciation' | 'edit_order' | 'cancel_order' | 'edit_shipping_cost' | 'edit_cashback' | 'gift' | 'others' | 'Refund' | 'Charge' | 'Expired' | `${string}:activity`; interface WalletTransaction { id: string | number; reason: WalletTransactionReason; amount: number; createdAt: string; metaData?: Record; } interface WalletBalance { balance: number; enabled: boolean; } interface Wallet extends WalletBalance { currency?: string; transactions?: WalletTransaction[]; } interface TransactionFilters { pageNumber?: number; pageSize?: number; } interface WalletTransactionsResponse { transactions: WalletTransaction[]; pageNumber?: number; pageSize?: number; totalCount?: number; } declare class WalletAPI { private http; constructor(http: HttpClient); private validateInvoiceId; /** * Get wallet balance (requires authentication) */ getBalance(options?: RequestOptions): Promise>; /** * List wallet transactions (requires authentication) */ listTransactions(filters?: TransactionFilters, options?: RequestOptions): Promise>; /** * Apply wallet credit on an invoice (requires authentication) */ applyCredit(invoiceId: number, options?: RequestOptions): Promise>; /** * Remove wallet credit from an invoice (requires authentication) */ removeCredit(invoiceId: number, options?: RequestOptions): Promise>; } /** * CMS API (Content Management - Pages, Blogs, etc.) */ /** * CMS Page type (re-exported from search types for convenience) * Both regular pages and blog posts use this structure */ type CMSPage = CmsPage; /** * Filters for CMS pages list * Backend uses: page_number, page_size, filters[] */ interface CMSFilters { page?: number; pageSize?: number; cmsPageTypes?: CMSPageType | CMSPageType[]; } declare class CMSAPI { private http; constructor(http: HttpClient); private missingDataError; private unexpectedEntityError; /** * Get CMS page by URL path * Uses entity routes API (recommended approach) * @param urlPath - Page URL path (e.g., '/about-us') * @param options - Request options */ getPage(urlPath: string, options?: RequestOptions): Promise>; /** * List CMS pages (excludes blog posts) * @param filters - Filter options (will automatically exclude blog type) * @param options - Request options */ listPages(filters?: CMSFilters, options?: RequestOptions): Promise>>; /** * Get blog post by URL path * Uses entity routes API (recommended approach) * @param urlPath - Blog post URL path (e.g., '/blog/my-post') * @param options - Request options */ getBlogPost(urlPath: string, options?: RequestOptions): Promise>; /** * List blog posts * @param filters - Filter options (will automatically filter for blog type) * @param options - Request options */ listBlogPosts(filters?: CMSFilters, options?: RequestOptions): Promise>>; /** * List all CMS content (both pages and blog posts) * @param filters - Filter options * @param options - Request options */ listAll(filters?: CMSFilters, options?: RequestOptions): Promise>>; } /** * Images API (File upload) */ interface UploadImageResponse { id: number; url: string; filename: string; size: number; mime_type: string; } declare class ImagesAPI { private http; constructor(http: HttpClient); /** * Upload image file * @param file - File or Blob to upload */ upload(file: File | Blob, options?: RequestOptions): Promise>; /** * Delete image */ delete(imageId: number, options?: RequestOptions): Promise>; } /** * Visits API (Analytics and page views) */ /** * Visit tracking input (SDK uses camelCase) */ interface VisitInput { url: string; referrer?: string; userAgent?: string; entityType?: 'product' | 'category' | 'page'; entityId?: number; } /** * Visit tracking response (auto-transformed to camelCase by HTTP client) */ interface VisitResponse { id: number; createdAt: string; } declare class VisitsAPI { private http; constructor(http: HttpClient); /** * Track visit analytics event. * Backend endpoint `/api/v1/visits/add` does not accept a payload. */ track(inputOrOptions?: VisitInput | RequestOptions, options?: RequestOptions): Promise>; /** * Track product view */ trackProduct(productId: number, url: string, options?: RequestOptions): Promise>; /** * Track category view */ trackCategory(categoryId: number, url: string, options?: RequestOptions): Promise>; } /** * Booking API (Scheduler and appointments) */ /** * Legacy event shape returned by some scheduler list endpoints. */ interface Event { id: number; title: string; description?: string; startTime?: string; endTime?: string; capacity?: number; bookedCount?: number; availableSlots?: number; price?: number; location?: string; createdAt?: string; } /** * Event details used in product booking flow. */ interface SchedulerEvent { entityId: number; title: string; description: string; durationsMinute: number[]; } interface BookingTimeSlot { startTimeLocal: string; endTimeLocal: string; isAvailable: boolean; remainingCapacity: number; } interface BookingAvailableDay { date: string; timeSlots: BookingTimeSlot[]; } interface EventAvailabilitiesResponse { availableDays: BookingAvailableDay[]; } interface EventAvailabilityFilters { eventEntityId: number; duration: number; fromDate: string; toDate: string; timezone?: string; } interface CreateBookingInput { eventEntityId?: number; event_entity_id?: number; timezone: string; attendeeName?: string; attendee_name?: string; attendeeEmail?: string; attendee_email?: string; attendeePhone?: string; attendee_phone?: string; } interface Booking { id: number; eventId: number; event: Event; userId?: number; attendeeName: string; attendeeEmail?: string; attendeePhone?: string; status: 'pending' | 'confirmed' | 'cancelled'; bookingTime: string; createdAt: string; } interface EventFilters { startDate?: string; start_date?: string; endDate?: string; end_date?: string; availableOnly?: boolean; available_only?: boolean; page?: number; pageSize?: number; page_size?: number; } declare class BookingAPI { private http; constructor(http: HttpClient); private transformEventFilters; /** * List available events (legacy scheduler listing). */ listEvents(filters?: EventFilters, options?: RequestOptions): Promise>>; /** * Get event details used for booking (durations, title, description). */ getEvent(entityId: number, options?: RequestOptions): Promise>; /** * Get available days and time slots for an event. */ getEventAvailabilities(filters: EventAvailabilityFilters, options?: RequestOptions): Promise>; /** * Create booking (legacy endpoint kept for backward compatibility). */ createBooking(input: CreateBookingInput, options?: RequestOptions): Promise>; /** * List user bookings (requires authentication). */ listBookings(options?: RequestOptions): Promise>>; /** * Cancel booking. */ cancelBooking(bookingId: number, options?: RequestOptions): Promise>; } /** * Entity Routes API * Resolves URLs to entity data (products, categories, CMS pages) */ declare class EntityRoutesAPI { private http; constructor(http: HttpClient); /** * Resolve URL path to entity data * @param urlPart - URL pathname (e.g., '/product/laptop-abc' or '/category/electronics') * @returns Entity route with cleaned entity data based on type */ resolve(urlPart: string, options?: RequestOptions): Promise>; } /** * Menu API (Header Menu, Navigation Trees) */ declare class MenuAPI { private http; constructor(http: HttpClient); /** * Fetch header menu by identifier * @param identifier - Menu identifier (default: 'headermenu') * @param options - Request options */ getHeaderMenu(identifier?: string, options?: RequestOptions): Promise>; /** * Convert raw tree structure to clean navigation items * Filters out disabled items and processes nested children recursively */ private convertRawTreeToNavigation; /** * Extract the display title for a menu node */ private findNodeTitle; private firstNonEmpty; /** * Extract the URL for a menu node */ private findNodeUrl; /** * Determine if a node should be filtered out (disabled items) */ private shouldDropNode; } /** * General API (shop configuration and feature flags) */ interface Region { id: number; name: string; latitude: number; longitude: number; } interface City { id: number; name: string; latitude: number; longitude: number; region: Region; } interface PremiumInfo { enabled: boolean; nextRenewal: string; subscriptionSubtype: string; } interface GoogleAnalyticsCode { code: string; enabled: boolean; } interface GoogleInfo { analyticsCode: GoogleAnalyticsCode; analyticsId: GoogleAnalyticsCode; tagManager: GoogleAnalyticsCode; } interface LogoInfo { favicon: string; main: string; } interface SocialInfo { facebook: string; instagram: string; phone1: string; phone2: string; telegram: string; twitter: string; whatsapp: string; } interface DomainInfo { url: string; } interface EnamadInfo { code: string; } interface ShopInfo { name: string; description: string; city: City | null; domain: DomainInfo; logo: LogoInfo; social: SocialInfo; } interface CheckoutConfig { addToCartAlert: boolean; dynamicForm: boolean; emailOptional: boolean; preventRedirect: boolean; minBasket: { enabled: boolean; minAmount: number; }; miniCart: boolean; postalCodeMandatory: boolean; quickAddToCart: boolean; } interface TajrobeConfig { enabled: boolean; } interface WalletConfig { enabled: boolean; useWithDiscount: boolean; minAmount: number; minAmountRequired: boolean; } /** * Standardized feature shape: * - boolean feature switches as direct keys on the object * - premium details in `premium` */ interface ShopFeatures { [featureName: string]: boolean | PremiumInfo | undefined; premium?: PremiumInfo; } interface ScriptsInfo { enamad: EnamadInfo; google: GoogleInfo; } interface SettingsInfo { checkout: CheckoutConfig; features: ShopFeatures; wallet: WalletConfig; tajrobe: TajrobeConfig; registerType: string; showProductStockNumber: boolean; } /** * Standardized General API response */ interface GeneralInfo { shop: ShopInfo; settings: SettingsInfo; scripts: ScriptsInfo; } declare class GeneralAPI { private http; constructor(http: HttpClient); /** * Get normalized shop information including config and features. */ getInfo(options?: RequestOptions): Promise>; /** * Get standardized shop feature flags only. */ getFeatures(options?: RequestOptions): Promise>; /** * Get standardized checkout config only. */ getCheckoutConfig(options?: RequestOptions): Promise>; /** * Get standardized wallet config only. */ getWalletConfig(options?: RequestOptions): Promise>; /** * Get standardized Tajrobe config only. */ getTajrobeConfig(options?: RequestOptions): Promise>; } /** * Dynamic Forms API */ type DynamicFormFieldType = 'TextBox' | 'TextArea' | 'Select' | 'Checkbox' | 'StatusBox' | 'Number' | 'Password' | 'NationalId' | 'PhoneNumber' | 'IBAN' | 'Separator' | 'Uploader'; interface SelectOption { value: string; label: string; } interface DynamicFormField { key: string; name: string; type: DynamicFormFieldType; label: string; value: any; placeholder: string; required: boolean; inputOptions: SelectOption[]; allowedExtensions: string[]; } interface DynamicForm { id: number; title: string; description: string; fields: DynamicFormField[]; } interface UploadedDynamicFormFile { serveKey: string; } declare class DynamicFormsAPI { private http; constructor(http: HttpClient); private normalizeField; private normalizeForm; /** * Fetch dynamic form definition by ID. */ getForm(formId: number, options?: RequestOptions): Promise>; /** * Upload file for uploader fields in product dynamic forms. */ uploadProductFormFile(file: File | Blob, options?: RequestOptions): Promise>; } /** * Regions API */ interface RegionCity { id: number; name: string; latitude: number; longitude: number; } interface RegionWithCities { id: number; name: string; cities: RegionCity[]; } declare class RegionsAPI { private http; constructor(http: HttpClient); private normalizeCity; private normalizeRegion; private extractRegions; private sortAlphabetically; /** * Get all regions with nested cities (sorted by name). */ list(options?: RequestOptions): Promise>; } /** * Main Sazito SDK Client */ declare class SazitoClient { private http; private tokenStorage; private credentialsManager; readonly products: ProductsAPI; readonly categories: CategoriesAPI; readonly cart: CartAPI; readonly orders: OrdersAPI; readonly invoices: InvoicesAPI; readonly shipping: ShippingAPI; readonly payments: PaymentsAPI; readonly users: UsersAPI; readonly search: SearchAPI; readonly feedbacks: FeedbacksAPI; readonly wallet: WalletAPI; readonly cms: CMSAPI; readonly images: ImagesAPI; readonly visits: VisitsAPI; readonly booking: BookingAPI; readonly entityRoutes: EntityRoutesAPI; readonly menu: MenuAPI; readonly general: GeneralAPI; readonly dynamicForms: DynamicFormsAPI; readonly regions: RegionsAPI; constructor(config: SazitoConfig, credentialsManager?: CredentialsManager); /** * Set authentication token (stored in localStorage with cookie fallback) */ setAuthToken(token: string): void; /** * Get authentication token from storage */ getAuthToken(): string | null; /** * Clear authentication token */ clearAuth(): void; /** * Check if user is authenticated */ isAuthenticated(): boolean; /** * Clear all cache */ clearCache(): void; /** * Clear all guest credentials */ clearCredentials(): void; /** * Access the guest credential store used by checkout-related modules. * Useful for integrations that receive an SDK client from the host app and * need to restore cart/invoice/payment credentials on that same instance. */ getCredentialsManager(): CredentialsManager; /** * Clear everything (auth + cache + credentials) */ clearAll(): void; /** * Search helper for `client.search.query(...)`. */ searchQuery(query: string, filters?: SearchFilters, options?: RequestOptions): Promise>; } /** * Create a new Sazito SDK client instance */ declare function createSazitoClient(config: SazitoConfig, credentialsManager?: CredentialsManager): SazitoClient; interface ModuleContext { http: HttpClient; credentials: CredentialsManager; } declare function createProductsAPI(configOrContext: SazitoConfig | ModuleContext): ProductsAPI; declare function createCategoriesAPI(configOrContext: SazitoConfig | ModuleContext): CategoriesAPI; declare function createCartAPI(configOrContext: SazitoConfig | ModuleContext): CartAPI; declare function createOrdersAPI(configOrContext: SazitoConfig | ModuleContext): OrdersAPI; declare function createInvoicesAPI(configOrContext: SazitoConfig | ModuleContext): InvoicesAPI; declare function createShippingAPI(configOrContext: SazitoConfig | ModuleContext): ShippingAPI; declare function createPaymentsAPI(configOrContext: SazitoConfig | ModuleContext): PaymentsAPI; declare function createUsersAPI(configOrContext: SazitoConfig | ModuleContext): UsersAPI; declare function createSearchAPI(configOrContext: SazitoConfig | ModuleContext): SearchAPI; declare function createFeedbacksAPI(configOrContext: SazitoConfig | ModuleContext): FeedbacksAPI; declare function createWalletAPI(configOrContext: SazitoConfig | ModuleContext): WalletAPI; declare function createCMSAPI(configOrContext: SazitoConfig | ModuleContext): CMSAPI; declare function createImagesAPI(configOrContext: SazitoConfig | ModuleContext): ImagesAPI; declare function createVisitsAPI(configOrContext: SazitoConfig | ModuleContext): VisitsAPI; declare function createBookingAPI(configOrContext: SazitoConfig | ModuleContext): BookingAPI; declare function createEntityRoutesAPI(configOrContext: SazitoConfig | ModuleContext): EntityRoutesAPI; declare function createMenuAPI(configOrContext: SazitoConfig | ModuleContext): MenuAPI; declare function createGeneralAPI(configOrContext: SazitoConfig | ModuleContext): GeneralAPI; declare function createDynamicFormsAPI(configOrContext: SazitoConfig | ModuleContext): DynamicFormsAPI; declare function createRegionsAPI(configOrContext: SazitoConfig | ModuleContext): RegionsAPI; type TransformScalar = string | number | boolean | null | undefined; type TransformValue = TransformScalar | TransformObject | TransformValue[] | object; interface TransformObject { [key: string]: TransformValue; } interface ApiResponseEnvelope { data?: { result?: TransformObject; }; } /** Convert Persian and Arabic-Indic numerals to ASCII digits. */ declare function toEnglishDigits(input: string): string; /** * Transform object keys from snake_case to camelCase with field name beautification * @param obj - Object to transform * @returns Transformed object with camelCase keys and beautiful field names */ declare function transformResponseKeys(obj: TransformValue | object): TransformValue; /** * Transform object keys from camelCase to snake_case for API requests * @param obj - Object to transform * @returns Transformed object with snake_case keys */ declare function transformRequestKeys(obj: TransformValue | object): TransformValue; /** * Transform API response data structure * Unwraps the { data: { result: { ... } } } structure and transforms keys */ declare function transformApiResponse(response: TransformValue | ApiResponseEnvelope | object): T; /** * Specific transformer for cart responses * Handles the cart-specific data structure */ declare function transformCartResponse(response: TransformValue | ApiResponseEnvelope | object): T; declare function transformInvoiceResponse(response: TransformValue | ApiResponseEnvelope | object): T; /** * Specific transformer for product list responses * Handles paginated product lists */ declare function transformProductListResponse(response: TransformValue | ApiResponseEnvelope | object): T; /** * Transform shipping address input for API request */ declare function transformShippingAddressInput(input: TransformValue): TransformObject; /** * Transform add to cart input for API request */ declare function transformAddToCartInput(variantId: number, quantity: number, formAttributes?: TransformValue): TransformObject; /** * Transform create cart input for API request */ declare function transformCreateCartInput(input: TransformValue): TransformObject; export { BookingAPI, CMSAPI, CartAPI, CategoriesAPI, CredentialsManager, DynamicFormsAPI, EntityRoutesAPI, FeedbacksAPI, GeneralAPI, HttpClient, ImagesAPI, InvoicesAPI, MemoryStorage, MenuAPI, OrdersAPI, PaymentsAPI, ProductsAPI, RegionsAPI, SazitoClient, SearchAPI, ShippingAPI, TokenStorage, UsersAPI, VisitsAPI, WalletAPI, createBookingAPI as booking, buildProductReviewInput, createCartAPI as cart, createCategoriesAPI as categories, createCMSAPI as cms, createBookingAPI, createCMSAPI, createCartAPI, createCategoriesAPI, createDynamicFormsAPI, createEntityRoutesAPI, createFeedbacksAPI, createGeneralAPI, createImagesAPI, createInvoicesAPI, createMenuAPI, createOrdersAPI, createPaymentsAPI, createProductsAPI, createRegionsAPI, createSazitoClient, createSearchAPI, createShippingAPI, createUsersAPI, createVisitsAPI, createWalletAPI, createDynamicFormsAPI as dynamicForms, createEntityRoutesAPI as entityRoutes, createFeedbacksAPI as feedbacks, createGeneralAPI as general, createImagesAPI as images, createInvoicesAPI as invoices, createMenuAPI as menu, createOrdersAPI as orders, createPaymentsAPI as payments, createProductsAPI as products, createRegionsAPI as regions, createSearchAPI as search, createShippingAPI as shipping, toEnglishDigits, transformAddToCartInput, transformApiResponse, transformCartResponse, transformCreateCartInput, transformInvoiceResponse, transformProductListResponse, transformRequestKeys, transformResponseKeys, transformShippingAddressInput, createUsersAPI as users, createVisitsAPI as visits, createWalletAPI as wallet }; export type { AddInvoiceFormInput, AddItemAttributesInput, AddToCartInput, ApplicableShippingMethods, BlogPage, BlogPageEntityRoute, Booking, BookingAvailableDay, BookingTimeSlot, CMSFilters, CMSPage, CMSPageEntityRoute, CMSPageType, CacheConfig, Cart, CartCredentials, CartProduct, CategoryFilters, CategoryListResponse, CategoryTree, CategoryTreeNode, CheckoutConfig, CheckoutInvoice, CheckoutInvoiceItem, CheckoutOrder, CheckoutProductSnapshot, CheckoutShippingItem, City$1 as City, CmsPage, CommentResponse, CookieOptions, CreateBookingInput, CreateCartInput, CreateInvoiceInput, CreateOrderRatingInput, CreatePaymentInput, DomainInfo, DynamicForm, DynamicFormField, DynamicFormFieldType, EmailLoginRequestInput, EnamadInfo, EntityRoute, EntityRouteResponse, EntityType, Event, EventAvailabilitiesResponse, EventAvailabilityFilters, EventFilters, FeedbackProductAttribute, FeedbackProductImage, FeedbackSeed, FeedbackSeedItem, ForgotPasswordInput, FormAttributeValue, City as GeneralCity, GeneralInfo, Region as GeneralRegion, GoogleAnalyticsCode, GoogleInfo, Image, Invoice, InvoiceCredentials, InvoiceItem, InvoiceItemFormAttributes, InvoiceShippingAddress, InvoiceShippingAddressRegion, ItemShippingRate, JsonArray, JsonObject, JsonPrimitive, JsonValue, LoginInput, LoginResponse, LogoInfo, MenuItem, MenuNode, MenuTree, MobileLoginInput, ModuleContext, Order, OrderFilters, OrderInvoice, OrderInvoiceItem, OrderPublicId, OrderShippingItem, OrdersListResponse, PaginatedResponse, Payment, PaymentAction, PaymentCallbackFieldValue, PaymentCallbackFields, PaymentCredentials, PaymentGateway, PaymentMethod, PaymentPollingOptions, PaymentStatus, PaymentStepFormFields, PaymentStepFormValue, PaymentStepInput, PremiumInfo, Product, ProductAttribute, ProductAttributeValueObject, ProductBreadcrumbCategory, ProductCategory, ProductCategoryEntityRoute, ProductEntityRoute, ProductFilters, ProductImage, ProductListItem, ProductListVariant, ProductReview, ProductReviewDraft, ProductReviewRequest, ProductReviewsFilters, ProductReviewsResponse, ProductSort, ProductStatistics, ProductVariant, RecommendationStatus, RefreshInvoiceInput, Region$1 as Region, RegionCity, RegionWithCities, RegisterInput, RequestOptions, ResetPasswordInput, RetryConfig, ReviewAttachmentInput, ReviewImageUploadResponse, ReviewUploadedImage, SazitoConfig, SazitoError, SazitoResponse, SchedulerBookingAttributes, SchedulerEvent, ScriptsInfo, SearchFilters, SearchResponse, SelectOption, SettingsInfo, ShippingAddress, ShippingAddressCity, ShippingAddressCredentials, ShippingAddressInput, ShippingAddressRegion, ShippingAssignment, ShippingItem, ShippingMethod, ShippingRate, ShopFeatures, ShopInfo, SocialInfo, StorageAdapter, SubmitOrderFeedbackInput, SubmitOrderFeedbackResult, Tag, TajrobeConfig, TransactionFilters, UnknownEntityRoute, UpdateItemAttributesInput, UpdateMobilePhoneRequestInput, UpdateMobilePhoneVerificationInput, UpdateProfileInput, UploadImageResponse, UploadedDynamicFormFile, UploadedFormFileAttribute, User, VerifyMobileInput, VerifyPaymentCallbackInput, VisitInput, VisitResponse, Wallet, WalletBalance, WalletConfig, WalletTransaction, WalletTransactionReason, WalletTransactionsResponse };