### Install Relewise SDK Packages Source: https://context7.com/relewise/relewise-sdk-javascript/llms.txt Install the core client and integrations packages for the Relewise SDK using npm. ```bash npm install @relewise/client npm install @relewise/integrations ``` -------------------------------- ### Install Relewise JS SDK Source: https://github.com/relewise/relewise-sdk-javascript/blob/main/README.md Install the official Relewise JavaScript SDK using npm or your preferred package manager. ```bash npm install @relewise/client ``` -------------------------------- ### Get Personal Product Recommendations Source: https://context7.com/relewise/relewise-sdk-javascript/llms.txt Use this to get personalized product recommendations based on user behavior and preferences. Ensure you have set up the Recommender with your dataset ID and API key. ```typescript import { Recommender, PersonalProductRecommendationBuilder, UserFactory } from '@relewise/client'; const recommender = new Recommender(DATASET_ID, API_KEY); const settings = { language: 'en-US', currency: 'USD', displayedAtLocation: 'homepage', user: UserFactory.byAuthenticatedId('user-abc-123') }; const builder = new PersonalProductRecommendationBuilder(settings) .setSelectedProductProperties({ displayName: true, pricing: true, dataKeys: ['ImageUrl', 'Url'] }) .setNumberOfRecommendations(8) .filters(f => f .addProductAssortmentFilter(1) .addProductDataFilter('InStock', b => b.addEqualsCondition(true))); const response = await recommender.recommendPersonalProducts(builder.build()); response?.recommendations?.forEach(product => { console.log(`Recommended: ${product.displayName}`); }); ``` -------------------------------- ### Start Development Watch Mode Source: https://github.com/relewise/relewise-sdk-javascript/blob/main/packages/client/dev.guide.md Run Rollup in watch mode to automatically detect and apply file changes during development. ```bash npm run dev ``` -------------------------------- ### Get Purchased With Product Recommendations Source: https://context7.com/relewise/relewise-sdk-javascript/llms.txt Generate "customers also bought" recommendations for a specific product to facilitate cross-selling. This requires specifying the product ID for which to find related purchases. ```typescript import { Recommender, PurchasedWithProductBuilder, UserFactory } from '@relewise/client'; const recommender = new Recommender(DATASET_ID, API_KEY); const settings = { language: 'en-US', currency: 'USD', displayedAtLocation: 'product page - bought together', user: UserFactory.byTemporaryId('user-session-id') }; const builder = new PurchasedWithProductBuilder(settings) .product({ productId: 'SKU-12345' }) .setSelectedProductProperties({ displayName: true, pricing: true, dataKeys: ['ImageUrl', 'Url'] }) .setNumberOfRecommendations(4) .filters(f => f .addProductIdFilter('SKU-12345', true)); // Exclude current product const response = await recommender.recommendPurchasedWithProduct(builder.build()); ``` -------------------------------- ### Get Purchased With Current Cart Recommendations Source: https://context7.com/relewise/relewise-sdk-javascript/llms.txt Generate recommendations based on the user's current shopping cart contents, suggesting items that are frequently purchased together with items in the cart. This helps in upselling or cross-selling. ```typescript import { Recommender, PurchasedWithCurrentCartBuilder, UserFactory } from '@relewise/client'; const recommender = new Recommender(DATASET_ID, API_KEY); const settings = { language: 'en-US', currency: 'USD', displayedAtLocation: 'cart page', user: UserFactory.byTemporaryId('user-session-id') }; const builder = new PurchasedWithCurrentCartBuilder(settings) .setSelectedProductProperties({ displayName: true, pricing: true, dataKeys: ['ImageUrl', 'Url'] }) .setNumberOfRecommendations(4) .filters(f => f .addProductInCartFilter(true)); // Exclude items already in cart const response = await recommender.recommendPurchasedWithCurrentCart(builder.build()); ``` -------------------------------- ### Get Products Viewed After Viewing Product Recommendations Source: https://context7.com/relewise/relewise-sdk-javascript/llms.txt Obtain "customers also viewed" recommendations based on browsing patterns. This is useful for suggesting related products a user might be interested in after viewing a specific item. ```typescript import { Recommender, ProductsViewedAfterViewingProductBuilder, UserFactory } from '@relewise/client'; const recommender = new Recommender(DATASET_ID, API_KEY); const settings = { language: 'en-US', currency: 'USD', displayedAtLocation: 'product page - also viewed', user: UserFactory.byTemporaryId('user-session-id') }; const builder = new ProductsViewedAfterViewingProductBuilder(settings) .product({ productId: 'SKU-12345', variantId: 'SKU-12345-BLUE' }) .setSelectedProductProperties({ displayName: true, pricing: true, dataKeys: ['ImageUrl', 'Url'] }) .setNumberOfRecommendations(6) .filters(f => f .addProductIdFilter('SKU-12345', true)); const response = await recommender.recommendProductsViewedAfterViewingProduct(builder.build()); ``` -------------------------------- ### Get Popular Products Recommendations Source: https://context7.com/relewise/relewise-sdk-javascript/llms.txt Retrieve trending or popular products based on recent purchase or view activity. You can specify the basis for popularity (e.g., 'MostPurchased', 'MostViewed') and the time frame. ```typescript import { Recommender, PopularProductsBuilder, UserFactory } from '@relewise/client'; const recommender = new Recommender(DATASET_ID, API_KEY); const settings = { language: 'en-US', currency: 'USD', displayedAtLocation: 'trending section', user: UserFactory.anonymous() }; const builder = new PopularProductsBuilder(settings) .basedOn('MostPurchased') // or 'MostViewed' .sinceMinutesAgo(10080) // Last 7 days .setSelectedProductProperties({ displayName: true, pricing: true, dataKeys: ['ImageUrl', 'Url'] }) .setNumberOfRecommendations(12) .filters(f => f .addProductAssortmentFilter(1)); const response = await recommender.recommendPopularProducts(builder.build()); ``` -------------------------------- ### Search Term Prediction Source: https://context7.com/relewise/relewise-sdk-javascript/llms.txt Get search term autocomplete suggestions as the user types. Requires a Searcher instance and user settings. ```typescript import { Searcher, SearchTermPredictionBuilder, UserFactory } from '@relewise/client'; const searcher = new Searcher(DATASET_ID, API_KEY); const settings = { language: 'en-US', currency: 'USD', displayedAtLocation: 'search autocomplete', user: UserFactory.byTemporaryId('user-session-id') }; const builder = new SearchTermPredictionBuilder(settings) .setTerm('run') // Partial search term .take(10); const response = await searcher.searchTermPrediction(builder.build()); // Display suggestions response?.predictions?.forEach(prediction => { console.log(`Suggestion: ${prediction.term} (${prediction.rank})`); }); ``` -------------------------------- ### Bootstrap Relewise Clients Source: https://github.com/relewise/relewise-sdk-javascript/blob/main/README.md Initialize Tracker, Searcher, or Recommender clients with your dataset ID, API key, and optional server URL. Ensure these credentials are replaced with your actual values from My.Relewise. ```typescript const tracker = new Tracker(RELEWISE_DATASET_ID, RELEWISE_API_KEY, { serverUrl: RELEWISE_SERVER_URL, }); const searcher = new Searcher(RELEWISE_DATASET_ID, RELEWISE_API_KEY, { serverUrl: RELEWISE_SERVER_URL, }); const recommender = new Recommender(RELEWISE_DATASET_ID, RELEWISE_API_KEY, { serverUrl: RELEWISE_SERVER_URL, }); ``` -------------------------------- ### Build and Test Client Package Source: https://github.com/relewise/relewise-sdk-javascript/blob/main/AGENTS.md Commands to build the client package, generate types, and run unit tests. These are standard steps after making changes or regenerating models. ```powershell npm run build npm run build:types npm test ``` -------------------------------- ### Link Library to App Project Source: https://github.com/relewise/relewise-sdk-javascript/blob/main/packages/integrations/dev.guide.md From the app project, link the local library using this command. Replace '@relewise/integrations' if your package name differs. ```bash npm link @relewise/integrations ``` -------------------------------- ### Link Local Library Project Source: https://github.com/relewise/relewise-sdk-javascript/blob/main/packages/client/dev.guide.md Use this command from the lib project to link it locally for development. ```bash npm link ``` -------------------------------- ### Initialize Relewise Clients Source: https://context7.com/relewise/relewise-sdk-javascript/llms.txt Initialize the Tracker, Searcher, and Recommender clients with your dataset credentials. The server URL is optional and defaults to the Relewise API endpoint. For service workers, specify 'default' for the cache option. ```typescript import { Tracker, Searcher, Recommender, UserFactory } from '@relewise/client'; // Initialize clients with your credentials const DATASET_ID = 'your-dataset-id'; const API_KEY = 'your-api-key'; const SERVER_URL = 'https://api.relewise.com'; // Optional, defaults to this const tracker = new Tracker(DATASET_ID, API_KEY, { serverUrl: SERVER_URL, }); const searcher = new Searcher(DATASET_ID, API_KEY, { serverUrl: SERVER_URL, }); const recommender = new Recommender(DATASET_ID, API_KEY, { serverUrl: SERVER_URL, }); // For service workers that don't support 'no-cache' const trackerWithCache = new Tracker(DATASET_ID, API_KEY, { serverUrl: SERVER_URL, cache: 'default' }); ``` -------------------------------- ### Link Library to App Project Source: https://github.com/relewise/relewise-sdk-javascript/blob/main/packages/client/dev.guide.md From the app project, link the local library using this command to use it in your application during development. ```bash npm link @relewise/client ``` -------------------------------- ### Build Production Release Source: https://github.com/relewise/relewise-sdk-javascript/blob/main/packages/client/dev.guide.md Run Rollup to create a production-ready distributable version of the package. ```bash npm run build ``` -------------------------------- ### Build and Test Integrations Package Source: https://github.com/relewise/relewise-sdk-javascript/blob/main/AGENTS.md Commands to build the integrations package, generate types, and run unit tests. Similar to the client package, these are essential validation steps. ```powershell cd packages/integrations npm ci npm run build npm run build:types npm test ``` -------------------------------- ### Basic Product Search with Filters and Facets Source: https://github.com/relewise/relewise-sdk-javascript/blob/main/README.md Use this snippet to perform a product search with specific product property selections, pagination, facets, and filters. Ensure the Searcher class is bootstrapped before use. ```typescript const searcher = new Searcher(RELEWISE_DATASET_ID, RELEWISE_API_KEY, { serverUrl: RELEWISE_SERVER_URL, }); const settings = { language: 'da-DK', currency: 'DKK', displayedAtLocation: 'search page', user: UserFactory.anonymous() }; const builder = new ProductSearchBuilder(settings) .setSelectedProductProperties({ displayName: true, pricing: true, dataKeys: ['Url', 'ShortDescription', 'ImageUrls', 'DK_*'] }) .setTerm('shoe') .pagination(p => p .setPageSize(30) .setPage(1)) .facets(f => f .addBrandFacet(['HP', 'Lenovo']) .addSalesPriceRangeFacet('Product', 100, 500) .addVariantSpecificationFacet('Size', ['XL'])) .filters(f => f .addProductAssortmentFilter(1) .addVariantAssortmentFilter(1)); searcher.searchProducts(builder.build()); ``` -------------------------------- ### Run Integration Tests Source: https://github.com/relewise/relewise-sdk-javascript/blob/main/packages/client/dev.guide.md Execute integration tests. Requires DATASET_ID and API_KEY. Optionally, SERVER_URL can be provided to change the API endpoint. ```bash npm run integration-test --DATASET_ID=... --API_KEY=... --SERVER_URL=https://api.relewise.com ``` -------------------------------- ### Batch Product Recommendations in TypeScript Source: https://context7.com/relewise/relewise-sdk-javascript/llms.txt Combine multiple recommendation requests into a single API call using the Recommender class and builders. ```typescript import { Recommender, ProductsRecommendationCollectionBuilder, PersonalProductRecommendationBuilder, PopularProductsBuilder, UserFactory } from '@relewise/client'; const recommender = new Recommender(DATASET_ID, API_KEY); const settings = { language: 'en-US', currency: 'USD', displayedAtLocation: 'homepage', user: UserFactory.byAuthenticatedId('user-123') }; const personalRecs = new PersonalProductRecommendationBuilder(settings) .setSelectedProductProperties({ displayName: true, pricing: true }) .setNumberOfRecommendations(6); const popularRecs = new PopularProductsBuilder(settings) .basedOn('MostPurchased') .setSelectedProductProperties({ displayName: true, pricing: true }) .setNumberOfRecommendations(6); const collectionBuilder = new ProductsRecommendationCollectionBuilder(settings) .addRequest(personalRecs.build()) .addRequest(popularRecs.build()); const response = await recommender.batchProductRecommendations(collectionBuilder.build()); const personalResults = response?.responses?.[0]?.recommendations; const popularResults = response?.responses?.[1]?.recommendations; ``` -------------------------------- ### Fetch Content Recommendations in TypeScript Source: https://context7.com/relewise/relewise-sdk-javascript/llms.txt Retrieve personalized or popular content recommendations for articles and blog posts. ```typescript import { Recommender, PersonalContentRecommendationBuilder, PopularContentsBuilder, UserFactory } from '@relewise/client'; const recommender = new Recommender(DATASET_ID, API_KEY); const settings = { language: 'en-US', currency: 'USD', displayedAtLocation: 'blog sidebar', user: UserFactory.byTemporaryId('user-session-id') }; // Personal content recommendations const personalBuilder = new PersonalContentRecommendationBuilder(settings) .setSelectedContentProperties({ displayName: true, dataKeys: ['ImageUrl', 'Summary', 'Author'] }) .setNumberOfRecommendations(5); const personalResponse = await recommender.recommendPersonalContents(personalBuilder.build()); // Popular content recommendations const popularBuilder = new PopularContentsBuilder(settings) .basedOn('MostViewed') .sinceMinutesAgo(10080) .setSelectedContentProperties({ displayName: true, dataKeys: ['ImageUrl', 'Summary'] }) .setNumberOfRecommendations(5); const popularResponse = await recommender.recommendPopularContents(popularBuilder.build()); ``` -------------------------------- ### Login to NPM Registry Source: https://github.com/relewise/relewise-sdk-javascript/blob/main/packages/client/dev.guide.md Assure you are properly logged into the NPM registry before publishing your package. ```bash npm login ``` -------------------------------- ### Execute SDK Update Skill Source: https://github.com/relewise/relewise-sdk-javascript/blob/main/AGENTS.md Initiates the \`update-sdk\` agent skill. This skill is used for regenerating client SDK models and types from the main Swagger source URL. It includes checks for Swagger generation, file validation, and PR descriptions. ```text $update-sdk ``` -------------------------------- ### Batch Entity Updates with Relewise SDK Source: https://context7.com/relewise/relewise-sdk-javascript/llms.txt Efficiently update multiple entities in batches for catalog synchronization. Configure the batch size and create updates for products and brands. ```typescript import { Integrator } from '@relewise/integrations'; import { ProductUpdateBuilder, BrandUpdateBuilder, ContentUpdateBuilder } from '@relewise/integrations'; const integrator = new Integrator(DATASET_ID, API_KEY); integrator.batchSize = 1000; // Configure batch size // Create multiple product updates const productUpdates = products.map(product => new ProductUpdateBuilder({ id: product.sku, productUpdateKind: 'UpdateAndAppend' }) .displayName([{ value: product.name, language: 'en-US' }]) .salesPrice([{ amount: product.price, currency: 'USD' }]) .build() ); // Create brand updates const brandUpdates = brands.map(brand => ({ $type: 'Relewise.Client.DataTypes.BrandUpdate, Relewise.Client', brand: { id: brand.id, displayName: brand.name }, brandUpdateKind: 'UpdateAndAppend' })); // Batch all trackable updates together const allUpdates = [...productUpdates, ...brandUpdates]; await integrator.batch(allUpdates); ``` -------------------------------- ### Generate API Client Models Source: https://github.com/relewise/relewise-sdk-javascript/blob/main/AGENTS.md Use this command to regenerate client models from Swagger definitions within the \`packages/client\` directory. Ensure you are in the \`packages/client\` directory before running. ```powershell cd packages/client npm ci npm run gen-api ``` -------------------------------- ### Track Product View Source: https://github.com/relewise/relewise-sdk-javascript/blob/main/README.md Use the tracker to record a product view event. Replace 'p-1' with the actual product ID. ```typescript await tracker.trackProductView({ productId: 'p-1', user: UserFactory.anonymous() }); ``` -------------------------------- ### Execute Dependency Upgrade Skill Source: https://github.com/relewise/relewise-sdk-javascript/blob/main/AGENTS.md Initiates the \`upgrade-dependencies\` agent skill. This skill automates refreshing npm package versions, performing preflight checks, creating chore branches, upgrading dependencies, running smoke checks, validating packages, and preparing PR descriptions. ```text $upgrade-dependencies ``` -------------------------------- ### Clean Build Artifacts Source: https://github.com/relewise/relewise-sdk-javascript/blob/main/packages/client/dev.guide.md Assure a clean build environment by removing all previous build artifacts before proceeding with a new build or release. ```bash npm run clean ``` -------------------------------- ### Track Orders with Relewise Source: https://context7.com/relewise/relewise-sdk-javascript/llms.txt Records completed orders to enhance recommendation accuracy. Requires a configured Tracker instance and order details including line items and user identification. ```typescript import { Tracker, UserFactory, DataValueFactory } from '@relewise/client'; const tracker = new Tracker(DATASET_ID, API_KEY); await tracker.trackOrder({ user: UserFactory.byAuthenticatedId('customer-12345'), orderNumber: 'ORD-2024-001234', subtotal: { currency: 'USD', amount: 299.98 }, lineItems: [ { productId: 'SKU-12345', variantId: 'SKU-12345-BLUE-L', quantity: 2, lineTotal: 199.98, data: { 'discountApplied': DataValueFactory.double(20.00) } }, { productId: 'SKU-67890', quantity: 1, lineTotal: 100.00 } ], cartName: 'default', data: { 'paymentMethod': DataValueFactory.string('credit_card'), 'shippingMethod': DataValueFactory.string('express') } }); ``` -------------------------------- ### Build TypeScript Declaration File Source: https://github.com/relewise/relewise-sdk-javascript/blob/main/packages/client/dev.guide.md Use Microsoft API Extractor to create a rolled-up TypeScript declaration (`.d.ts`) file for the project. ```bash npm run build:types ``` -------------------------------- ### Execute Product Search Source: https://context7.com/relewise/relewise-sdk-javascript/llms.txt Performs personalized product searches using the ProductSearchBuilder. Supports facets, filters, pagination, and sorting configurations. ```typescript import { Searcher, ProductSearchBuilder, UserFactory } from '@relewise/client'; const searcher = new Searcher(DATASET_ID, API_KEY); const settings = { language: 'en-US', currency: 'USD', displayedAtLocation: 'search results page', user: UserFactory.byTemporaryId('user-session-id') }; const builder = new ProductSearchBuilder(settings) .setTerm('running shoes') .setSelectedProductProperties({ displayName: true, pricing: true, brand: true, dataKeys: ['ImageUrl', 'ShortDescription', 'Url', 'Rating'] }) .setSelectedVariantProperties({ displayName: true, pricing: true, dataKeys: ['Color', 'Size', 'StockLevel'] }) .pagination(p => p .setPageSize(24) .setPage(1)) .facets(f => f .addBrandFacet(['Nike', 'Adidas']) .addSalesPriceRangeFacet('Product', 50, 200) .addVariantSpecificationFacet('Size', ['10', '11', '12']) .addProductDataStringValueFacet('Color', 'Variant', ['Black', 'White'])) .filters(f => f .addProductAssortmentFilter(1) .addVariantAssortmentFilter(1) .addProductDataFilter('InStock', b => b.addEqualsCondition(true))) .sorting(s => s .sortByProductRelevance()); const response = await searcher.searchProducts(builder.build()); // Handle response console.log(`Found ${response?.hits} products`); response?.results?.forEach(product => { console.log(`${product.displayName} - $${product.salesPrice}`); }); ``` -------------------------------- ### Track Product View Event Source: https://context7.com/relewise/relewise-sdk-javascript/llms.txt Track a product view event using the Tracker client. This can be a simple product view or include a specific variant. Ensure the user object is correctly created using UserFactory. ```typescript import { Tracker, UserFactory } from '@relewise/client'; const tracker = new Tracker(DATASET_ID, API_KEY); // Track a simple product view await tracker.trackProductView({ productId: 'SKU-12345', user: UserFactory.byTemporaryId('user-session-id') }); // Track product view with variant await tracker.trackProductView({ productId: 'SKU-12345', variantId: 'SKU-12345-BLUE-L', user: UserFactory.byAuthenticatedId('user-abc-123') }); ``` -------------------------------- ### Advanced Filtering with Relewise Client Source: https://context7.com/relewise/relewise-sdk-javascript/llms.txt Build complex filter combinations using AND/OR logic and various filter types for product searches. Includes basic, category, data, variant, and recency filters. ```typescript import { Searcher, ProductSearchBuilder, UserFactory, DataValueFactory } from '@relewise/client'; const searcher = new Searcher(DATASET_ID, API_KEY); const settings = { language: 'en-US', currency: 'USD', displayedAtLocation: 'filtered search', user: UserFactory.byTemporaryId('user-session-id') }; const builder = new ProductSearchBuilder(settings) .setTerm('shoes') .filters(f => f // Basic filters .addProductAssortmentFilter([1, 2]) .addBrandIdFilter(['nike', 'adidas']) .addProductSalesPriceFilter(50, 200) // Category filter .addProductCategoryIdFilter('Ancestor', ['footwear']) // Data filters with conditions .addProductDataFilter('InStock', b => b.addEqualsCondition(true)) .addProductDataFilter('Rating', b => b.addGreaterThanCondition(4.0)) .addVariantDataFilter('StockLevel', b => b.addGreaterThanCondition(0)) // Variant specification filter .addVariantSpecificationFilter('Color', 'Blue') // Recently viewed/purchased filters .addProductRecentlyViewedByUserFilter('2024-01-01T00:00:00Z', true) // Exclude recently viewed // Complex OR filter .or(orBuilder => orBuilder .addBrandIdFilter('nike') .addBrandIdFilter('adidas') .addBrandIdFilter('puma')) // Complex AND filter .and(andBuilder => andBuilder .addProductDataFilter('OnSale', b => b.addEqualsCondition(true)) .addProductDataFilter('NewArrival', b => b.addEqualsCondition(true)))); const response = await searcher.searchProducts(builder.build()); ``` -------------------------------- ### Publish Package to NPM Registry Source: https://github.com/relewise/relewise-sdk-javascript/blob/main/packages/client/dev.guide.md Submit your package to the NPM Registry. Ensure your package.json is updated to the next version number and a release is tagged. ```bash npm publish --access public ``` -------------------------------- ### Batched Search Requests Source: https://context7.com/relewise/relewise-sdk-javascript/llms.txt Combine multiple search requests (products, content, predictions) into a single HTTP request to reduce latency. Requires initializing Searcher and builders for each request type. ```typescript import { Searcher, SearchCollectionBuilder, ProductSearchBuilder, ContentSearchBuilder, SearchTermPredictionBuilder, UserFactory } from '@relewise/client'; const searcher = new Searcher(DATASET_ID, API_KEY); const settings = { language: 'en-US', currency: 'USD', displayedAtLocation: 'search page', user: UserFactory.byTemporaryId('user-session-id') }; const productSearch = new ProductSearchBuilder(settings) .setTerm('laptop') .setSelectedProductProperties({ displayName: true, pricing: true }) .pagination(p => p.setPageSize(10)); const contentSearch = new ContentSearchBuilder(settings) .setTerm('laptop buying guide') .setSelectedContentProperties({ displayName: true }); const predictions = new SearchTermPredictionBuilder(settings) .setTerm('lap') .take(5); const batchBuilder = new SearchCollectionBuilder(settings) .addRequest(productSearch.build()) .addRequest(contentSearch.build()) .addRequest(predictions.build()); const response = await searcher.batch(batchBuilder.build()); // Access individual responses const productResults = response?.responses?.[0]; const contentResults = response?.responses?.[1]; const searchPredictions = response?.responses?.[2]; ``` -------------------------------- ### Batching Multiple Search Requests Source: https://github.com/relewise/relewise-sdk-javascript/blob/main/README.md This snippet shows how to batch multiple search requests (product, content, term prediction) into a single HTTP request to reduce latency. Ensure all necessary builders are initialized. ```typescript const searcher = new Searcher(RELEWISE_DATASET_ID, RELEWISE_API_KEY, { serverUrl: RELEWISE_SERVER_URL, }); const searchCollectionBuilder = new SearchCollectionBuilder(settings) .addRequest(productSearchBuilder.build()) .addRequest(contentSearchBuilder.build()) .addRequest(searchTermPredictionBuilder.build()); searcher.batch(searchCollectionBuilder.build()); ``` -------------------------------- ### Update Product Catalog with Integrator Source: https://context7.com/relewise/relewise-sdk-javascript/llms.txt Manage product catalog data, including variants and categories, using the Integrator class. ```typescript import { Integrator } from '@relewise/integrations'; import { ProductUpdateBuilder } from '@relewise/integrations'; const integrator = new Integrator(DATASET_ID, API_KEY, { serverUrl: 'https://api.relewise.com' }); // Build a product update const productUpdate = new ProductUpdateBuilder({ id: 'SKU-12345', productUpdateKind: 'UpdateAndAppend', variantUpdateKind: 'UpdateAndAppend', replaceExistingVariants: false }) .displayName([ { value: 'Premium Running Shoes', language: 'en-US' }, { value: 'Premium Løbesko', language: 'da-DK' } ]) .listPrice([ { amount: 149.99, currency: 'USD' }, { amount: 999.00, currency: 'DKK' } ]) .salesPrice([ { amount: 129.99, currency: 'USD' }, { amount: 899.00, currency: 'DKK' } ]) .brand({ id: 'nike', displayName: 'Nike' }) .categoryPaths(b => b .path(p => p .category({ id: 'apparel', displayName: [{ language: 'en-US', value: 'Apparel' }] }) .category({ id: 'shoes', displayName: [{ language: 'en-US', value: 'Shoes' }] }) .category({ id: 'running', displayName: [{ language: 'en-US', value: 'Running' }] }))) .assortments([1, 2]) .data({ 'ImageUrl': { type: 'String', value: 'https://example.com/shoe.jpg' }, 'InStock': { type: 'Boolean', value: true }, 'StockCount': { type: 'Double', value: 150 } }) .variants([ { id: 'SKU-12345-BLUE-10', displayName: { values: [{ text: 'Blue - Size 10', language: { value: 'en-US' } }] }, specification: { 'Color': 'Blue', 'Size': '10' }, listPrice: { values: [{ amount: 149.99, currency: { value: 'USD' } }] }, salesPrice: { values: [{ amount: 129.99, currency: { value: 'USD' } }] }, assortments: [1], data: { 'StockCount': { type: 'Double', value: 25 } } } ]) .build(); await integrator.updateProduct(productUpdate); ``` -------------------------------- ### Unlink Local Library Project Source: https://github.com/relewise/relewise-sdk-javascript/blob/main/packages/client/dev.guide.md From the lib project, issue this command to unlink it after development is complete. ```bash npm unlink ``` -------------------------------- ### Generate TypeScript API Interfaces Source: https://github.com/relewise/relewise-sdk-javascript/blob/main/packages/client/dev.guide.md Generate all project-specific TypeScript interfaces from the swagger.json definitions. This should be run before building types. ```bash npm run gen-api ``` -------------------------------- ### Category Page Product Search Source: https://context7.com/relewise/relewise-sdk-javascript/llms.txt Use this for category/listing pages without a search term, enabling filtering and sorting. Ensure you have the necessary imports and dataset/API keys configured. ```typescript import { Searcher, ProductSearchBuilder, UserFactory } from '@relewise/client'; const searcher = new Searcher(DATASET_ID, API_KEY); const settings = { language: 'en-US', currency: 'USD', displayedAtLocation: 'category page', user: UserFactory.byTemporaryId('user-session-id') }; const builder = new ProductSearchBuilder(settings) // No search term - this is a category page .setSelectedProductProperties({ displayName: true, pricing: true, dataKeys: ['ImageUrl', 'Url'] }) .pagination(p => p .setPageSize(30) .setPage(1)) .facets(f => f .addBrandFacet() .addSalesPriceRangesFacet('Product', [ { lowerBound: 0, upperBound: 50 }, { lowerBound: 50, upperBound: 100 }, { lowerBound: 100, upperBound: 200 }, { lowerBound: 200 } ]) .addVariantSpecificationFacet('Size')) .filters(f => f .addProductAssortmentFilter(1) .addProductCategoryIdFilter('ImmediateParent', ['shoes', 'running'])) .sorting(s => s .sortByProductData('InStock', 'Descending', n => n .sortByProductData('NewArrival', 'Descending', n2 => n2 .sortByProductRelevance()))); const response = await searcher.searchProducts(builder.build()); ``` -------------------------------- ### Analyze Code for Client Package Source: https://github.com/relewise/relewise-sdk-javascript/blob/main/AGENTS.md Use the code analyzer tool to generate MCP ingestion payload for the client package. This command requires specifying the path to the client's tsconfig.json and the package name. ```powershell cd packages/code-analyzer npm ci npm run codeAnalyzer -- '..\client\tsconfig.json' '@relewise/client' ``` -------------------------------- ### Content Search Source: https://context7.com/relewise/relewise-sdk-javascript/llms.txt Search for content items like articles or blog posts using powerful filtering. Ensure the Searcher is initialized with dataset and API keys. ```typescript import { Searcher, ContentSearchBuilder, UserFactory } from '@relewise/client'; const searcher = new Searcher(DATASET_ID, API_KEY); const settings = { language: 'en-US', currency: 'USD', displayedAtLocation: 'content search', user: UserFactory.byTemporaryId('user-session-id') }; const builder = new ContentSearchBuilder(settings) .setTerm('running tips') .setSelectedContentProperties({ displayName: true, dataKeys: ['ImageUrl', 'Summary', 'Author', 'PublishedDate'] }) .pagination(p => p .setPageSize(10) .setPage(1)) .filters(f => f .addContentCategoryIdFilter('ImmediateParent', ['blog', 'fitness'])); const response = await searcher.searchContents(builder.build()); ``` -------------------------------- ### Analyze Code for Integrations Package Source: https://github.com/relewise/relewise-sdk-javascript/blob/main/AGENTS.md Use the code analyzer tool to generate MCP ingestion payload for the integrations package. This command requires specifying the path to the integrations' tsconfig.json and the package name. ```powershell npm run codeAnalyzer -- '..\integrations\tsconfig.json' '@relewise/integrations' ``` -------------------------------- ### Track User Behaviors Source: https://context7.com/relewise/relewise-sdk-javascript/llms.txt Records various user interactions such as category views, search terms, and profile updates. Uses the Tracker class to send event data to the Relewise platform. ```typescript import { Tracker, UserFactory } from '@relewise/client'; const tracker = new Tracker(DATASET_ID, API_KEY); const user = UserFactory.byTemporaryId('user-session-id'); // Track product category view (with category hierarchy path) await tracker.trackProductCategoryView({ idPath: ['electronics', 'computers', 'laptops'], user: user }); // Track brand view await tracker.trackBrandView({ brandId: 'apple', user: user }); // Track content view await tracker.trackContentView({ contentId: 'blog-post-123', user: user }); // Track content category view await tracker.trackContentCategoryView({ idPath: ['blog', 'technology'], user: user }); // Track search term (useful when not using Relewise search) await tracker.trackSearchTerm({ term: 'wireless headphones', language: 'en-US', user: user }); // Track user profile update await tracker.trackUserUpdate({ user: UserFactory.byAuthenticatedId('user-123', 'temp-456', { email: 'user@example.com', identifiers: { 'loyalty-tier': 'gold' } }), updateKind: 'UpdateAndAppend' }); // Track product engagement (like/dislike/favorite) await tracker.trackProductEngagement({ user: UserFactory.byAuthenticatedId('user-123'), product: { productId: 'SKU-12345' }, engagement: { sentiment: 'Like', isFavorite: true } }); ``` -------------------------------- ### Category Page Search without Term Source: https://github.com/relewise/relewise-sdk-javascript/blob/main/README.md This snippet demonstrates how to use the Searcher for category pages without specifying a search term. It includes product property selection, pagination, facets, filters, and sorting by relevance after stock. ```typescript const searcher = new Searcher(RELEWISE_DATASET_ID, RELEWISE_API_KEY, { serverUrl: RELEWISE_SERVER_URL, }); const settings = { language: 'da-DK', currency: 'DKK', displayedAtLocation: 'search page', user: UserFactory.anonymous() }; const builder = new ProductSearchBuilder(settings) .setSelectedProductProperties({ displayName: true, pricing: true, dataKeys: ['Url', 'ShortDescription', 'ImageUrls', 'DK_*'] }) .pagination(p => p .setPageSize(30) .setPage(1)) .facets(f => f .addBrandFacet(['HP', 'Lenovo']) .addSalesPriceRangeFacet('Product', 100, 500) .addVariantSpecificationFacet('Size', ['XL'])) .filters(f => f .addProductAssortmentFilter(1) .addVariantAssortmentFilter(1) .addProductCategoryIdFilter('ImmediateParent', ["category_id"])) .sorting(s => s .sortByProductData('InStock', 'Descending', (n) => n .sortByProductRelevance())); searcher.searchProducts(builder.build()); ``` -------------------------------- ### Unlink Local Library from App Source: https://github.com/relewise/relewise-sdk-javascript/blob/main/packages/client/dev.guide.md After development, unlink the library from the app project to remove the local link. ```bash npm unlink @relewise/client ``` -------------------------------- ### Create Authenticated User Source: https://github.com/relewise/relewise-sdk-javascript/blob/main/README.md Define an authenticated user with a persistent ID. Optionally, map a temporary ID to the authenticated user. ```typescript UserFactory.byAuthenticatedId('authenticatedId') UserFactory.byAuthenticatedId('authenticatedId', 'temporaryId') ``` -------------------------------- ### Create Temporary User Source: https://github.com/relewise/relewise-sdk-javascript/blob/main/README.md Generate a temporary user identifier using UserFactory.byTemporaryId. It's recommended to use a persistent 1st-party ID like one from localStorage. ```typescript UserFactory.byTemporaryId('') ``` -------------------------------- ### Create Typed Data Values with DataValueFactory Source: https://context7.com/relewise/relewise-sdk-javascript/llms.txt Use the DataValueFactory to generate typed values for product data, filters, and tracking. This utility supports primitives, collections, multilingual, and multi-currency formats. ```typescript import { DataValueFactory } from '@relewise/client'; // String value const stringValue = DataValueFactory.string('example'); // Boolean value const boolValue = DataValueFactory.boolean(true); // Double (number) value const numberValue = DataValueFactory.double(99.99); // String collection const stringCollection = DataValueFactory.stringCollection(['red', 'blue', 'green']); // Boolean collection const boolCollection = DataValueFactory.booleanCollection([true, false]); // Double collection const numberCollection = DataValueFactory.doubleCollection([1.0, 2.5, 3.75]); // Multilingual value const multilingualValue = DataValueFactory.multilingual([ { language: 'en-US', value: 'Running Shoes' }, { language: 'da-DK', value: 'Løbesko' } ]); // Multi-currency value const multiCurrencyValue = DataValueFactory.multiCurrency([ { currency: 'USD', amount: 99.99 }, { currency: 'EUR', amount: 89.99 }, { currency: 'DKK', amount: 699.00 } ]); // Use in tracking await tracker.trackCart({ user: UserFactory.anonymous(), subtotal: { currency: 'USD', amount: 99.99 }, lineItems: [{ productId: 'SKU-123', quantity: 1, lineTotal: 99.99, data: { 'customNote': DataValueFactory.string('Gift wrap please'), 'isGift': DataValueFactory.boolean(true) } }], data: { 'promoCode': DataValueFactory.string('SAVE10'), 'deliveryPreference': DataValueFactory.string('express') } }); ``` -------------------------------- ### Create User Objects with User Factory Source: https://context7.com/relewise/relewise-sdk-javascript/llms.txt Utilize the UserFactory to create different user types, including anonymous, temporary, authenticated, and users identified by email or custom identifiers. This is essential for tracking and personalization requests. You can also check if a user is anonymous at runtime. ```typescript import { UserFactory, userIsAnonymous } from '@relewise/client'; // Anonymous user - for users who did not consent to tracking (GDPR) const anonymousUser = UserFactory.anonymous(); // Temporary user - for non-logged-in users with a temporary ID (e.g., from localStorage) const temporaryUser = UserFactory.byTemporaryId('temp-user-12345'); // Authenticated user - for logged-in users with a persistent ID const authenticatedUser = UserFactory.byAuthenticatedId('user-abc-123'); // Authenticated user with temporary ID mapping (for user journey continuity) const mappedUser = UserFactory.byAuthenticatedId('user-abc-123', 'temp-user-12345'); // User identified by email const emailUser = UserFactory.byEmail('user@example.com'); // User identified by custom identifiers const customUser = UserFactory.byIdentifiers({ 'crm-id': 'CRM12345', 'loyalty-id': 'LOYALTY-9876' }); // User with additional data const userWithData = UserFactory.byTemporaryId('temp-123', { email: 'user@example.com', identifiers: { 'custom-key': 'custom-value' } }); // Check if user is anonymous at runtime if (userIsAnonymous(anonymousUser)) { console.log('User is anonymous - show consent prompt'); } ``` -------------------------------- ### Configure Cache Mode for Integrator Source: https://github.com/relewise/relewise-sdk-javascript/blob/main/README.md When using the Integrator client with service workers that do not support 'no-cache' mode, set the cache option to 'default'. ```typescript const integrator = new Integrator(RELEWISE_DATASET_ID, RELEWISE_API_KEY, { serverUrl: RELEWISE_SERVER_URL, cache: 'default' }); ``` -------------------------------- ### Create Anonymous User Source: https://github.com/relewise/relewise-sdk-javascript/blob/main/README.md Create an anonymous user when the user has not consented to tracking or is not logged in. ```typescript UserFactory.anonymous() ``` -------------------------------- ### Error Handling with ProblemDetailsError Source: https://context7.com/relewise/relewise-sdk-javascript/llms.txt Handle API errors gracefully using the ProblemDetailsError class for detailed error information. Includes handling for network errors and request cancellation. ```typescript import { Tracker, Searcher, ProblemDetailsError, UserFactory } from '@relewise/client'; const tracker = new Tracker(DATASET_ID, API_KEY); try { await tracker.trackProductView({ productId: 'SKU-12345', user: UserFactory.anonymous() }); } catch (error) { if (error instanceof ProblemDetailsError) { console.error('API Error:', error.details?.title); console.error('Status:', error.details?.status); console.error('Detail:', error.details?.detail); console.error('Trace ID:', error.details?.traceId); // Handle specific error types if (error.details?.status === 401) { console.error('Invalid API key'); } else if (error.details?.status === 404) { console.error('Dataset not found'); } } else if (error instanceof DOMException && error.name === 'AbortError') { console.log('Request was cancelled'); } else { console.error('Network or unexpected error:', error); } } // Using abort signal for request cancellation const controller = new AbortController(); setTimeout(() => controller.abort(), 5000); // Timeout after 5 seconds const searcher = new Searcher(DATASET_ID, API_KEY); try { await searcher.searchProducts(builder.build(), { abortSignal: controller.signal }); } catch (error) { if (error instanceof DOMException && error.name === 'AbortError') { console.log('Search request timed out'); } } ``` -------------------------------- ### Track Cart Update Event Source: https://context7.com/relewise/relewise-sdk-javascript/llms.txt Track updates to the shopping cart, including line items and associated data. Use DataValueFactory for custom data fields. The cartName and data fields are optional. ```typescript import { Tracker, UserFactory, DataValueFactory } from '@relewise/client'; const tracker = new Tracker(DATASET_ID, API_KEY); await tracker.trackCart({ user: UserFactory.byTemporaryId('user-session-id'), subtotal: { currency: 'USD', amount: 299.98 }, lineItems: [ { productId: 'SKU-12345', variantId: 'SKU-12345-BLUE-L', quantity: 2, lineTotal: 199.98 }, { productId: 'SKU-67890', quantity: 1, lineTotal: 100.00, data: { 'giftWrap': DataValueFactory.boolean(true) } } ], cartName: 'default', data: { 'basketId': DataValueFactory.string('cart-abc-123'), 'promoCode': DataValueFactory.string('SUMMER20') } }); ``` -------------------------------- ### Check if User is Anonymous Source: https://github.com/relewise/relewise-sdk-javascript/blob/main/README.md Utilize the userIsAnonymous helper function to determine if a user object should be treated as anonymous according to Relewise's rules. ```typescript import { userIsAnonymous, UserFactory } from '@relewise/client'; const user = UserFactory.anonymous(); if (userIsAnonymous(user)) { // render consent prompt or do alternate rendering for anonymous users } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.