### Installation and Startup Commands (Bash) Source: https://context7.com/itswadesh/svelte-commerce/llms.txt Provides essential bash commands for setting up the Svelte Commerce project locally. This includes cloning the repository, installing npm dependencies, configuring environment variables by copying an example file, and starting the development server. ```bash # Clone repository git clone https://github.com/itswadesh/svelte-commerce.git cd svelte-commerce # Install dependencies npm install # Configure environment cp .env.example .env # Edit .env with your settings # Start development server npm run dev # Open browser open http://localhost:3000 ``` -------------------------------- ### Environment Variables Configuration (.env) Source: https://context7.com/itswadesh/svelte-commerce/llms.txt Shows an example of a `.env` file for configuring environment variables. These variables are used to set up connections to backend services like Litekart or MedusaJS, and define domain-specific settings. They are prefixed with `PUBLIC_` to be exposed to the browser. ```dotenv # .env file # Litekart Backend PUBLIC_LITEKART_API_URL='https://api.litekart.in' PUBLIC_LITEKART_DOMAIN="arialshop.com" PUBLIC_SITEMAP_URL='https://pub-3.r2.dev' # MedusaJS Backend (alternative) PUBLIC_MEDUSA_API_URL='https://next.medusajs.com' PUBLIC_MEDUSA_PUBLISHABLE_API_KEY='pk_your_publishable_key_here' PUBLIC_MEDUSA_REGION_ID='region_us' ``` -------------------------------- ### Route-based Data Loading (TypeScript) Source: https://context7.com/itswadesh/svelte-commerce/llms.txt Shows how to implement server-side data loading for routes in SvelteKit using load functions. The example demonstrates a `+page.server.ts` file that imports and uses a more detailed load function from a separate file to fetch product data based on the route's slug. ```typescript // src/routes/(www)/products/[slug]/+page.server.ts export { load } from '$lib/core/load-functions/(www)/products/[slug]/load.server' // Load function implementation // src/lib/core/load-functions/(www)/products/[slug]/load.server.ts import { productService } from '$lib/core/services' export async function load({ params }) { const product = await productService.getOne(params.slug) return { product, meta: { title: product.title, description: product.description, image: product.thumbnail } } } ``` -------------------------------- ### Server Hooks Configuration (TypeScript) Source: https://context7.com/itswadesh/svelte-commerce/llms.txt An example of `src/hooks.server.ts` configuring SvelteKit server hooks. This includes enforcing HTTPS for non-local traffic and retrieving or determining the `storeId` from cookies or domain lookup, setting it in `event.locals` for downstream use. ```typescript // src/hooks.server.ts import type { Handle } from '@sveltejs/kit' export const handle: Handle = async ({ event, resolve }) => { // Force HTTPS except for localhost const url = event.url if (url.protocol === 'http:' && !url.hostname.match(/^(localhost|127\.0\.0\.1|\d+\.\d+\.\d+\.\d+)$/)) { return Response.redirect(`https://${url.host}${url.pathname}${url.search}`, 301) } // Get store ID from cookie or domain lookup const storeId = event.cookies.get('store_id') || await getStoreByDomain(url.hostname) event.locals.storeId = storeId return resolve(event) } ``` -------------------------------- ### Get Single Product Details by Slug using TypeScript Source: https://context7.com/itswadesh/svelte-commerce/llms.txt Retrieve detailed product information by its handle (slug). This function requires the product slug and returns a comprehensive product object including its variants, options, and pricing. It's useful for displaying individual product pages. ```typescript // Get product by slug const product = await productService.getOne('wireless-headphones') console.log({ id: product.id, title: product.title, description: product.description, price: product.price, thumbnail: product.thumbnail, images: product.images, variants: product.variants, options: product.options }) // Handle variants product.variants.forEach(variant => { console.log(`${variant.title}: $${variant.prices[0].amount / 100}`) }) // Handle options (size, color, etc.) product.options.forEach(option => { console.log(`${option.title}: ${option.values.join(', ')}`) }) ``` -------------------------------- ### Get Featured, Trending, and Related Products with TypeScript Source: https://context7.com/itswadesh/svelte-commerce/llms.txt Retrieve curated product collections for homepage and marketing. This service allows fetching featured, trending, or related products based on category, with pagination support. It returns lists of products. ```typescript // List featured products const featured = await productService.listFeaturedProducts({ page: 1 }) // List trending products const trending = await productService.listTrendingProducts({ page: 1, search: 'summer' }) // List related products by category const related = await productService.listRelatedProducts({ page: 1, categoryId: 'cat_accessories' }) ``` -------------------------------- ### Build and Deployment Commands (Bash) Source: https://context7.com/itswadesh/svelte-commerce/llms.txt Lists common bash commands for building the project for production, previewing the build, running tests, performing type checking, linting, and formatting the code. These commands are crucial for maintaining code quality and preparing the application for deployment. ```bash # Build for production npm run build # Preview production build npm run preview # Run tests npm test # Run tests with UI npm run test:ui # Type checking npm run check # Lint code npm run lint # Format code npm run format ``` -------------------------------- ### Docker Deployment Commands (Bash) Source: https://context7.com/itswadesh/svelte-commerce/llms.txt Details the bash commands required for deploying the Svelte Commerce project using Docker. This involves pulling the latest Docker image and running a container, specifying port mappings and necessary environment variables for configuration. ```bash # Pull latest image docker pull ghcr.io/itswadesh/svelte-commerce:latest # Run container docker run -d -p 3000:3000 \ -e PUBLIC_LITEKART_API_URL=https://api.litekart.in \ -e PUBLIC_LITEKART_DOMAIN=arialshop.com \ ghcr.io/itswadesh/svelte-commerce:latest # Access at http://localhost:3000 ``` -------------------------------- ### Docker Deployment Command Source: https://github.com/itswadesh/svelte-commerce/blob/main/README.md This command provides instructions for deploying the Svelte Commerce application using a pre-built Docker image. It pulls the latest image from GHCR and runs it in detached mode, exposing the application on port 3000. ```bash docker run -d -p 3000:3000 ghcr.io/itswadesh/svelte-commerce:latest ``` -------------------------------- ### User Authentication: Registration and Login (TypeScript) Source: https://context7.com/itswadesh/svelte-commerce/llms.txt Handles user registration and login using email/password. It manages authentication state, including loading and error states. Dependencies include a global auth store. ```typescript // src/lib/core/stores/auth.svelte.ts import { getUserState } from '$lib/core/stores/auth.svelte' const authState = getUserState() // Sign up new user const success = await authState.signup({ email: 'user@example.com', password: 'securepass123', firstName: 'John', lastName: 'Doe', phone: '+1234567890', role: 'USER', cartId: 'cart_abc123', // Optional: merge cart after signup origin: 'web' }) if (success) { console.log('User registered:', authState.user) } // Login existing user const loginSuccess = await authState.login({ email: 'user@example.com', password: 'securepass123', cartId: 'cart_abc123' // Optional: merge cart after login }) if (loginSuccess) { console.log('Logged in:', authState.user) } // Check loading state if (authState.loading) { console.log('Authentication in progress...') } // Check for errors if (authState.lastError) { console.error('Auth error:', authState.lastError) } ``` -------------------------------- ### Vendor Registration Process (TypeScript) Source: https://context7.com/itswadesh/svelte-commerce/llms.txt Enables users to register as vendors, providing business-specific information along with their contact details. This function initiates the vendor onboarding flow. ```typescript // Join as vendor await authState.joinAsVendor({ email: 'vendor@example.com', password: 'securepass123', firstName: 'Business', lastName: 'Owner', businessName: 'My Store LLC', phone: '+1234567890', role: 'VENDOR', cartId: null }) // Redirects to vendor dashboard (/dash) on success ``` -------------------------------- ### Backend Service Selection (TypeScript) Source: https://context7.com/itswadesh/svelte-commerce/llms.txt Demonstrates how to select the backend service connector in `src/lib/core/services/index.ts`. The code allows switching between the Litekart connector and the MedusaJS connector by commenting and uncommenting export statements. ```typescript // src/lib/core/services/index.ts // Option 1: Use Litekart backend export * from '@misiki/litekart-connector' // Option 2: Use MedusaJS backend (comment above, uncomment below) // export * from '@misiki/medusa-connector' ``` -------------------------------- ### Debounce and Delay Utilities (TypeScript) Source: https://context7.com/itswadesh/svelte-commerce/llms.txt Demonstrates how to use `debounce` and `wait` utility functions from '$lib/core/utils' to control function execution timing. `debounce` limits the rate at which a function can be called, useful for search inputs, while `wait` introduces asynchronous delays, useful for sequential loading operations. ```typescript import { debounce, wait } from '$lib/core/utils' // Debounce search input const handleSearch = debounce((query: string) => { console.log('Searching for:', query) // API call here }, 300) // 300ms delay // Use in component function onInput(event: Event) { const query = (event.target as HTMLInputElement).value handleSearch(query) } // Wait utility for delays async function loadSequentially() { console.log('Loading step 1...') await wait(1000) // Wait 1 second console.log('Loading step 2...') await wait(500) // Wait 500ms console.log('Done!') } ``` -------------------------------- ### Mandatory Environment Variables Source: https://github.com/itswadesh/svelte-commerce/blob/main/README.md This code block lists the mandatory environment variables required for the Svelte Commerce deployment, specifically for the LiteKart integration. These variables define the store's domain and API endpoint. ```bash PUBLIC_LITEKART_DOMAIN=arialshop.com PUBLIC_LITEKART_API_URL=https://api.litekart.in ``` -------------------------------- ### Configure Service Integration (TypeScript) Source: https://github.com/itswadesh/svelte-commerce/blob/main/README.md This snippet demonstrates how to configure which service connector to use for Svelte Commerce. It involves exporting a module from either '@misiki/litekart-connector' or '@misiki/medusa-connector'. This is crucial for defining the application's backend integration. ```typescript export * from '@misiki/litekart-connector' // or // export * from '@misiki/medusa-connector' ``` -------------------------------- ### Date and Time Formatting Utilities (TypeScript) Source: https://context7.com/itswadesh/svelte-commerce/llms.txt Offers functions to format dates, times, and timestamps into human-readable formats, including relative time representations like 'X hours ago'. ```typescript import { date, dateOnly, time, timestampToAgo } from '$lib/core/utils' // Full date and time const orderDate = date('2024-01-15T14:30:00Z') console.log(orderDate) // "Jan 15, 2024, 02:30 PM" // Date only const deliveryDate = dateOnly('2024-01-20') console.log(deliveryDate) // "Jan 20, 2024" // Time only const orderTime = time('2024-01-15T14:30:00') console.log(orderTime) // "02:30 PM" // Relative time (ago) const lastSeen = timestampToAgo('2024-01-15T10:00:00Z') console.log(lastSeen) // "2 hours ago" ``` -------------------------------- ### Price Formatting Utility (TypeScript) Source: https://context7.com/itswadesh/svelte-commerce/llms.txt Formats numerical prices into human-readable currency strings, supporting various currency codes and regional formatting conventions. It takes a number and a currency code as input. ```typescript // src/lib/core/utils/index.ts import { formatPrice, formatSlug, truncate } from '$lib/core/utils' // Format price with currency const price = formatPrice(99.99, 'USD') console.log(price) // "$99.99" const euroPrice = formatPrice(149.99, 'EUR') console.log(euroPrice) // "€149.99" const inrPrice = formatPrice(9999, 'INR') console.log(inrPrice) // "₹9999.00" // Format for non-decimal currencies const yenPrice = formatPrice(5000, 'JPY') console.log(yenPrice) // "¥5000 JPY" ``` -------------------------------- ### Add Product Review with TypeScript Source: https://context7.com/itswadesh/svelte-commerce/llms.txt Submit product reviews and ratings. This function requires product and variant IDs, the review text, and a rating. It can also include uploaded image URLs. It returns the submitted review object. ```typescript // Add product review const review = await productService.addReview({ productId: 'prod_123abc', variantId: 'variant_456def', review: 'Great product! Highly recommend.', rating: 5, uploadedImages: [ 'https://example.com/review-img1.jpg', 'https://example.com/review-img2.jpg' ] }) console.log('Review submitted:', review) ``` -------------------------------- ### List Products with Filters using TypeScript Source: https://context7.com/itswadesh/svelte-commerce/llms.txt Retrieve paginated product listings with search and category filtering. This service requires pagination parameters and optionally search terms and category IDs. It returns a paginated list of products and their total count. ```typescript // src/lib/core/services/medusa/product-service.ts import { productService } from '$lib/core/services' // List all products with pagination const products = await productService.list({ page: 1, search: 'laptop', categories: 'cat_electronics' }) console.log('Products:', products.data) console.log('Total count:', products.count) console.log('Pagination:', { offset: products.offset, limit: products.limit }) // Product structure products.data.forEach(product => { console.log({ id: product.id, title: product.title, price: product.price, thumbnail: product.thumbnail, slug: product.slug, variants: product.variants, options: product.options }) }) ``` -------------------------------- ### User Profile Management: Update and Logout (TypeScript) Source: https://context7.com/itswadesh/svelte-commerce/llms.txt Allows users to update their profile information and log out of the system. It utilizes the global auth store to manage user data and session state. ```typescript // Update user profile await authState.updateMe({ id: authState.user.id, firstName: 'Jane', lastName: 'Smith', email: 'jane.smith@example.com', phone: '+1987654321' }) console.log('Updated user:', authState.user) // Logout user await authState.logout() // Automatically redirects to / and shows login modal ``` -------------------------------- ### Apply and Remove Coupons - SvelteKit Source: https://context7.com/itswadesh/svelte-commerce/llms.txt Applies discount coupons to the cart and removes them, with automatic price recalculation. Handles potential errors during coupon application and logs the discount amount and new total. ```typescript // Apply discount coupon try { const updatedCart = await cartState.applyCoupon('SUMMER2024') console.log('Discount applied:', updatedCart.discountAmount) console.log('New total:', updatedCart.total) } catch (error) { console.error('Coupon failed:', error) } // Remove coupon await cartState.removeCoupon() ``` -------------------------------- ### Toast Notification Utility (TypeScript) Source: https://context7.com/itswadesh/svelte-commerce/llms.txt A utility for displaying user feedback through toast messages. It supports different notification types (success, error, info, warning) and can automatically extract messages from error objects. ```typescript import { toast } from '$lib/core/utils' // Success notification toast('Order placed successfully!', 'success') // Error notification toast('Payment failed. Please try again.', 'error') // Info notification toast('Your cart has been saved.', 'info') // Warning notification toast('Low stock available.', 'warning') // Handle complex error objects try { await someApiCall() } catch (error) { toast(error, 'error') // Automatically extracts message } ``` -------------------------------- ### Add Items to Cart - SvelteKit Source: https://context7.com/itswadesh/svelte-commerce/llms.txt Adds products to the shopping cart, with options to manage quantity and create the cart if it doesn't exist. Cart state is persisted in localStorage and synchronized with the backend. Supports adding new items or updating existing ones. ```typescript // src/lib/core/stores/cart.svelte.ts import { getCartState } from '$lib/core/stores/cart.svelte' // In your component const cartState = getCartState() // Add item to cart await cartState.add({ qty: 2, productId: 'prod_123abc', variantId: 'variant_456def', lineId: undefined // Optional: provide if updating existing line item }) // Add or update item (checks if item exists) await cartState.addOrUpdate({ productId: 'prod_123abc', variantId: 'variant_456def', qty: 1 }) // Access cart data console.log(cartState.cart.lineItems) // Array of cart items console.log(cartState.cart.total) // Total price console.log(cartState.isUpdatingCart) // Loading state ``` -------------------------------- ### Set Shipping Method and Payment - SvelteKit Source: https://context7.com/itswadesh/svelte-commerce/llms.txt Allows the selection of shipping methods and payment providers within the cart. Updates the cart with the chosen shipping rate and sets the preferred payment method for checkout. ```typescript // Set shipping rate await cartState.setShippingRate({ shippingRateId: 'rate_standard_shipping' }) // Set payment method await cartState.setSelectedPaymentMethod('stripe') ``` -------------------------------- ### Manage Backend Cart Operations with TypeScript Source: https://context7.com/itswadesh/svelte-commerce/llms.txt Perform direct cart API calls for custom integrations. This service allows fetching, adding, updating, and applying coupons to carts, requiring cart and product IDs. It returns updated cart objects. ```typescript // src/lib/core/services/medusa/cart-service.ts import { cartService } from '$lib/core/services' // Fetch current cart const cart = await cartService.fetchCartData() // Get cart by ID const specificCart = await cartService.getCartByCartId('cart_abc123') // Add to cart (low-level) const updatedCart = await cartService.addToCart({ productId: 'prod_123', variantId: 'var_456', qty: 2, cartId: 'cart_abc123', // Optional lineId: null // Null for new item }) // Update cart item const updated = await cartService.updateCart({ qty: 5, cartId: 'cart_abc123', lineId: 'line_789', productId: 'prod_123', variantId: 'var_456', isSelectedForCheckout: true }) // Apply coupon code const discountedCart = await cartService.applyCoupon({ cartId: 'cart_abc123', couponCode: 'SAVE20' }) // Remove coupon const removedCoupon = await cartService.removeCoupon({ cartId: 'cart_abc123', promotionId: 'promo_xyz' }) ``` -------------------------------- ### Single Item Checkout (Buy Now) - SvelteKit Source: https://context7.com/itswadesh/svelte-commerce/llms.txt Facilitates immediate purchases of a single item without adding it to the main shopping cart. It manages the checkout session and provides functionality to restore the previous cart state after the transaction. ```typescript // Create single-item checkout (Buy Now functionality) await cartState.createSingleItemCheckoutSession({ productId: 'prod_123abc', variantId: 'variant_456def', qty: 1 }) // After payment or cancellation, restore previous cart await cartState.restorePrevCart() // Reset single-item session await cartState.resetSingleItemCheckoutSession() ``` -------------------------------- ### Deep Copy Object Utility (TypeScript) Source: https://context7.com/itswadesh/svelte-commerce/llms.txt Illustrates the usage of the `deepCopy` utility function from '$lib/core/utils' to create independent copies of objects. This ensures that modifications to the copied object do not affect the original, which is crucial for maintaining data integrity in complex object structures. ```typescript import { deepCopy } from '$lib/core/utils' const original = { user: { name: 'John', address: { city: 'NYC' } }, items: [1, 2, 3] } const copy = deepCopy(original) copy.user.address.city = 'LA' console.log(original.user.address.city) // "NYC" console.log(copy.user.address.city) // "LA" ``` -------------------------------- ### Checkout Address Management - SvelteKit Source: https://context7.com/itswadesh/svelte-commerce/llms.txt Updates shipping and billing addresses for the checkout process. It allows setting addresses independently or linking them and also supports updating the customer's email and phone number. ```typescript // Update shipping address await cartState.updateShippingAddress({ shippingAddress: { firstName: 'John', lastName: 'Doe', address_1: '123 Main St', address_2: 'Apt 4B', city: 'New York', state: 'NY', zip: '10001', countryCode: 'US', phone: '+1234567890' }, billingAddress: { firstName: 'John', lastName: 'Doe', address_1: '456 Business Ave', city: 'New York', state: 'NY', zip: '10002', countryCode: 'US' }, isBillingAddressSameAsShipping: false }) // Update customer email await cartState.updateEmail({ email: 'customer@example.com', phone: '+1234567890' }) ``` -------------------------------- ### Text Utility Functions: Slug, Truncate, Class Merging (TypeScript) Source: https://context7.com/itswadesh/svelte-commerce/llms.txt Provides essential text manipulation functions including formatting slugs into titles, truncating long strings, and merging CSS class names, often used with conditional logic. ```typescript // Format slug to readable text const title = formatSlug('wireless-gaming-headset') console.log(title) // "Wireless Gaming Headset" // Truncate long text const description = 'This is a very long product description that needs to be shortened...' const short = truncate(description, 50, '...') console.log(short) // "This is a very long product description that n..." // Class name merging (TailwindCSS) import { cn } from '$lib/core/utils' const classes = cn( 'bg-blue-500', 'text-white', condition && 'font-bold', { 'underline': isActive } ) ``` -------------------------------- ### Complete and Process Cart Payments with TypeScript Source: https://context7.com/itswadesh/svelte-commerce/llms.txt Finalize a cart and manage shipping and payment options. This involves updating shipping rates and payment methods before completing the cart to process the order. It requires cart and rate IDs and returns the completed order object. ```typescript // Update shipping rate const withShipping = await cartService.updateShippingRate({ cartId: 'cart_abc123', shippingRateId: 'rate_express' }) // Update payment method const withPayment = await cartService.updateCartPaymentMethod({ cartId: 'cart_abc123', paymentMethod: 'stripe' }) // Complete cart (finalize order) const completedOrder = await cartService.completeCart('cart_abc123') ``` -------------------------------- ### Update Cart Items and Clear Cart - SvelteKit Source: https://context7.com/itswadesh/svelte-commerce/llms.txt Modifies quantities of existing cart items, removes specific items, or clears the entire cart. It provides real-time updates and loading indicators for item modifications and supports updating item selection for checkout. ```typescript // Update quantity of cart item await cartState.update({ qty: 3, lineId: 'line_789ghi', productId: 'prod_123abc', variantId: 'variant_456def', isSelectedForCheckout: true }) // Check if specific item is updating if (cartState.updatingItem['line_789ghi']) { console.log('Item is being updated...') } // Remove item from cart await cartState.remove({ cartId: cartState.cart.id, lineId: 'line_789ghi' }) // Clear entire cart await cartState.clear() ``` -------------------------------- ### OTP Verification for Phone Numbers (TypeScript) Source: https://context7.com/itswadesh/svelte-commerce/llms.txt Verifies user phone numbers using a One-Time Password (OTP). This function is crucial for secure user verification. It requires the user's phone number and the OTP code. ```typescript // Verify OTP (phone verification) await authState.verifyOtp({ phone: '+1234567890', otp: '123456' }) // User is automatically redirected based on role // VENDOR/ADMIN -> /dash // USER -> / ``` -------------------------------- ### Update Customer Information in Cart with TypeScript Source: https://context7.com/itswadesh/svelte-commerce/llms.txt Update cart details with customer information and addresses. This function requires the cart ID and can include customer ID, email, phone, and detailed shipping/billing addresses. It returns the updated cart object. ```typescript // Update cart with customer info and addresses const cart = await cartService.updateCart2({ cartId: 'cart_abc123', email: 'customer@example.com', phone: '+1234567890', customer_id: 'cust_456def', shippingAddress: { firstName: 'Jane', lastName: 'Smith', address_1: '789 Oak Lane', address_2: '', city: 'Los Angeles', state: 'CA', zip: '90001', countryCode: 'US', phone: '+1987654321' }, billingAddress: { firstName: 'Jane', lastName: 'Smith', address_1: '789 Oak Lane', city: 'Los Angeles', state: 'CA', zip: '90001', countryCode: 'US', phone: '+1987654321' }, isBillingAddressSameAsShipping: true }) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.