### XSearch Service JavaScript Usage Examples Source: https://docs.xgen.ai/v1/docs/xsearch-services Demonstrates basic usage of the XSearch Service methods in JavaScript, including examples for getting search results, property values, category pages, and trending searches. ```JavaScript // Returns a search response containing the results xg.search.getResults({query: 'coat', options: {collection: '', deploymentId:''}}); // Returns a list of property values for the given collection xg.search.getResultValues({collection: ''}); // Returns a search response for the given category and collection xg.search.getCategoryPage({category: 'coat', collection: ''}); // Returns a list of trending search terms for the given collection xg.search.getTrendingSearches({collection: ''}); ``` -------------------------------- ### Install XGen AI SDK in Browser (UMD) Source: https://docs.xgen.ai/v1/docs/installation Demonstrates how to include the XGen AI SDK in a web browser using a UMD (Universal Module Definition) script tag and initialize the XGenClient object for immediate use. ```HTML ``` -------------------------------- ### Install XGen AI SDK via npm for Node.js Source: https://docs.xgen.ai/v1/docs/installation Provides the command-line instruction to install the XGen AI SDK core package into a Node.js project using npm, saving it as a dependency in your package.json. ```Bash npm install @xgenai/sdk-core --save ``` -------------------------------- ### Install XGen AI SDK in Browser (ES Modules) Source: https://docs.xgen.ai/v1/docs/installation Illustrates how to import and initialize the XGen AI SDK in a web browser environment using native ES modules via a script tag, providing a modern approach to module loading. ```HTML ``` -------------------------------- ### Add Fetch Polyfill for Node.js < 17 Source: https://docs.xgen.ai/v1/docs/installation Recommends installing and importing a fetch() polyfill, specifically 'cross-fetch/polyfill', for Node.js environments older than version 17 to ensure the SDK's network operations function correctly. ```JavaScript // npm install cross-fetch --save import 'cross-fetch/polyfill'; ``` -------------------------------- ### Import XGenClient in Node.js Applications Source: https://docs.xgen.ai/v1/docs/installation Shows the syntax for importing the XGenClient class in Node.js, supporting both the modern ES modules (default) and the traditional CommonJS module systems to accommodate different project setups. ```JavaScript // Using ES modules (default) import XGenClient from '@xgenai/sdk-core'; // OR if you are using CommonJS modules const XGenClient = require('@xgenai/sdk-core') ``` -------------------------------- ### Initialize XGenClient SDK and Fetch Recommendations Source: https://docs.xgen.ai/v1/docs/usage This snippet demonstrates how to initialize the XGenClient SDK with your API key, secret, client ID, and tracker ID. It also shows a basic example of how to use the initialized client to fetch recommendations for a specific element by its ID. Optional configurations for environment and authentication store are also included. ```JavaScript import XGenClient from '@xgenai/sdk-core'; const xg = new XGenClient({ key: '', secret: '', clientId: '', trackerId: '', getEnv: () => 'stage', //optional: function that returns the environment (`stage` or `prod`) authStore: new LocalCookieAuthStore() //default - can pass in a custom auth store instance }); // get recommendations by element id const result = await xg.recommend.getResultsById({elementId: ''}); // and much more... ``` -------------------------------- ### JavaScript XRecommend Service Usage Examples Source: https://docs.xgen.ai/v1/docs/xrecommend-service Demonstrates how to call the `getResults` and `getResultsById` methods of the `xg.recommend` service to retrieve recommendations using element IDs. ```javascript // Returns a recommendation response mapped by element IDs. xg.recommend.getResults({ elementIds: ['', ''], { pathname: '/en-us/' } }); // Returns a recommendation response for the given element ID. xg.recommend.getResultsById({ elementId: '', { pathname: '/en-us/' } }); ``` -------------------------------- ### JavaScript Examples for XGen AI Tracking Methods Source: https://docs.xgen.ai/v1/docs/tracking Demonstrates how to use various `xg.track` methods to record user interactions such as page views, item views, category views, add-to-cart, purchases, DOM element interactions, search queries, and custom events. Includes an example of batch tracking. ```JavaScript // tracks a page view event xg.track.pageView(); // tracks the view of a item/product xg.track.itemView({item, context}); // tracks the view of a category xg.track.categoryView({category, items, context}); // tracks an add to cart event for an item/product xg.track.addToCart({item, context}); // tracks a purchase order event for item(s)/product(s) xg.track.purchaseOrder({items, orderId, tax, discount, context }); // tracks the view of a specific dom element xg.track.elementView({element, context}); // tracks the render of a specific dom element xg.track.elementRender({element, context}); // tracks the click of a specific dom element xg.track.elementClick({element, item, context }); // tracks a search query event (tracked by default when calling xg.search.getResults()) xg.track.searchQuery({query, queryId, deploymentId, page, context}); // tracks the results of a search query (tracked by default when calling xg.search.getResults()) xg.track.searchResult({query, queryId, deploymentId, page, context}); // tracks a click of a search item/product xg.track.searchClick({query, queryId, deploymentId, page, item, items, context}); // tracks a custom event xg.track.customEvent({category, action, name, value}); // batch tracking - this will batch tracking events until send() is called const batch = xg.track.createBatch(); batch.pageView(); batch.itemView({item, context}); batch.send(); ``` -------------------------------- ### XGen AI DOM Element Tracking API Methods Source: https://docs.xgen.ai/v1/docs/tracking API documentation for tracking interactions with specific DOM elements, including views, renders, and clicks. All tracking events return an object `{ message: string; success: boolean; }`. Parameters for `elementRender` and `elementClick` are inferred from code examples. ```APIDOC xg.track.elementView({element, context}) - Description: Tracks the view of a specific DOM node. - Parameters: - element: object (Required) - The DOM element to track (e.g., a CSS selector or DOM node reference). - context: object (Optional) - Dynamic information about the event. xg.track.elementRender({element, context}) - Description: Tracks the render of a specific DOM element. - Parameters: - element: object (Required) - The DOM element to track (e.g., a CSS selector or DOM node reference). - context: object (Optional) - Dynamic information about the event. xg.track.elementClick({element, item, context}) - Description: Tracks the click of a specific DOM element. - Parameters: - element: object (Required) - The DOM element that was clicked. - item: object (Optional) - Related item/product information, if the clicked element is associated with one. - context: object (Optional) - Dynamic information about the event. ``` -------------------------------- ### XGen AI Search Tracking API Methods Source: https://docs.xgen.ai/v1/docs/tracking API documentation for tracking search-related events, such as queries, results, and clicks on search items. These are often tracked by default when using `xg.search.getResults()`. All tracking events return an object `{ message: string; success: boolean; }`. Parameters are inferred from code examples. ```APIDOC xg.track.searchQuery({query, queryId, deploymentId, page, context}) - Description: Tracks a search query event. (Tracked by default when calling xg.search.getResults()). - Parameters: - query: string (Required) - The search query string. - queryId: string (Optional) - The unique ID of the search query. - deploymentId: string (Optional) - The ID of the search deployment. - page: number (Optional) - The current page number of search results. - context: object (Optional) - Dynamic information about the event. xg.track.searchResult({query, queryId, deploymentId, page, context}) - Description: Tracks the results of a search query. (Tracked by default when calling xg.search.getResults()). - Parameters: - query: string (Required) - The search query string. - queryId: string (Optional) - The unique ID of the search query. - deploymentId: string (Optional) - The ID of the search deployment. - page: number (Optional) - The current page number of search results. - context: object (Optional) - Dynamic information about the event. xg.track.searchClick({query, queryId, deploymentId, page, item, items, context}) - Description: Tracks a click of a search item/product. - Parameters: - query: string (Required) - The search query string. - queryId: string (Optional) - The unique ID of the search query. - deploymentId: string (Optional) - The ID of the search deployment. - page: number (Optional) - The current page number of search results. - item: object (Optional) - The clicked search item/product. - items: array (Optional) - An array of items/products related to the search results. - context: object (Optional) - Dynamic information about the event. ``` -------------------------------- ### CSS Selector for XGen Element Hook Source: https://docs.xgen.ai/v1/docs/search-experiences This example illustrates the use of a CSS selector to define an 'Element Hook' within the XGen search experience configuration. The specified selector targets a DOM element where the search experience content will be rendered, in this case, replacing the existing content of the matched element. ```CSS .searchSection ``` -------------------------------- ### Initialize XGen AI Client in JavaScript Source: https://docs.xgen.ai/v1/docs/definitions This snippet demonstrates how to create a new instance of the `XGenClient` in JavaScript. It requires API credentials such as `key`, `secret`, `clientId`, and `trackerId`. Optional parameters include `getEnv` for specifying the environment (`stage` or `prod`) and `authStore` for custom authentication handling, defaulting to `LocalCookieAuthStore`. ```javascript const xg = new XGenClient({ key: '', secret: '', clientId: '', trackerId: '', getEnv: () => 'stage', // optional: function that returns the environment (`stage` or `prod`) - defaults to 'prod' authStore: new LocalCookieAuthStore() // optional - can pass in a custom auth store instance - defaults to LocalCookieAuthStore }); ``` -------------------------------- ### Configure XRecommend Engine and Experiences in XGEN Platform Source: https://docs.xgen.ai/v1/docs/configure-xrecommend This section details the steps to set up and configure the XRecommend service within the XGEN AI platform, including creating an engine and defining recommendation experiences. It highlights the generation of an 'Experience ID' crucial for external integrations. ```APIDOC XGEN Platform - XRecommend Engine and Experience Configuration: 1. Configure XRecommend Engine: - Navigate to XRecommend Engines. - Create a New Engine. - Name the engine (click pencil edit icon). - Select "DeepRec" as the model type. - Select "Default" under Locale Training. - Deselect "Average Order Value" Goal for initial setup. - Click "Save and Train". 2. Configure XRecommend Experience (API Version): - Navigate to XRecommend Experiences. - Create a New Experience. - Select "API Version" in the modal. - Name the experience (e.g., "Homepage - Trending Now" or "Collection Page - Sustainable Products"). - Set the Experience Title (customer-facing, simple and clear). - Choose a Recommendation Type: - AI Model: for machine-learning powered recommendations - Best Sellers - Most Viewed - Recently Viewed - Purchased With Viewed With Random - No Recommendations: Best for items you want to explicitly dictate products for using the “Pin” - Choose a Product Filter (optional: saved Merchandising Rule to narrow recommendations). - Set Max Recommendations: Define how many products to return (e.g., 4–12 products). - Set Universal Pinned Products (Optional): Click Choose Products to select specific items that should always appear first. - Configure Product-Specific Pinning (Optional): Use Add Association to define specific pinning rules per product page. - Save the experience. - Copy the auto-generated Experience ID (important for Shopify integration). ``` -------------------------------- ### XGEN Platform Configuration for Product Listing Page (PLP) Source: https://docs.xgen.ai/v1/docs/configure-plp Details the essential configuration steps within the XGEN platform for enabling and customizing Product Listing Pages. This involves defining product constraints via XSearch Keywords, connecting search engines and merchandising rules through XSearch Experiences, and retrieving the Experience ID for Shopify integration. ```APIDOC 1. XSearch Keyword Configuration: Purpose: Restrict products shown on a PLP, define pinning, and sort order. Configurable Attributes: - Expiration date - Merchandising Rules (application) - Synonyms (addition) - Pin Specific Products - Exclude Specific Products - Control Sort Order Matching Requirement: Must match the Shopify collection URL Handle (with hyphens replaced by spaces). 2. XSearch Experience Configuration: Purpose: Connects an XSearch Engine and a Merchandising Rule to define the PLP behavior. Key Components: - XSearch Engine - Merchandising Rule (determines the filter menu/facets displayed on the PLP). 3. Experience ID Retrieval: Location: Displayed in the 'Experience Information' section after saving the XSearch Experience. Usage: This unique ID is critical for integrating the PLP service into the Shopify Admin Theme. ``` -------------------------------- ### Untitled Source: https://docs.xgen.ai/v1/docs/tracking No description -------------------------------- ### XSearch Service API Methods Reference Source: https://docs.xgen.ai/v1/docs/xsearch-services Comprehensive API documentation for the XSearch Service, detailing all available methods, their parameters (including types and required status), and their expected return values. ```APIDOC xg.search.getResults({query: string, options: object, queryId?: string}) - Description: Returns a search response containing the results. - Parameters: - query (string, required): The search query string. - options (object, required): Options object that allows you to control the search result response. - options.collection (string, required): Collection to get items from. - options.deploymentId (string, required): The deploymentId. - options.page (number, optional): The page of results. - options.facets (boolean, optional): If facets should be returned or not. - options.forceDeepSearch (boolean, optional): If deep search should be forced. - options.sortBy ('price' | 'update_date', optional): Sort by price or update date. - options.sortOrder ('asc' | 'desc', optional): Sort order. - options.context (object, optional): Dynamic contextual information. - queryId (string, optional): An optional queryId passed to cancel a request. - Returns: Promise<{ items: SearchProduct[]; facets: { [key: string]: unknown }; isFromCache: boolean; page: number; keyword: string; isUrlRedirect: boolean; isQueryTranslated: boolean; isCachedFilterApplied: boolean; isKeywordConfigApplied: boolean; behaviorId: string; responseEngine: string; totalResults: number; sortedBy: string; variantMapping?: { [key: string]: string }; searchTermMatches?: string[]; }> xg.search.getResultValues({collection: string}) - Description: Returns a list of property values for the given collection. - Parameters: - collection (string, required): Collection to get items from. - Returns: Promise<{ [key: string]: { name: string; count: number; } }> xg.search.getCategoryPage({category: string, collection: string, page?: number, queryId?: string}) - Description: Returns a search response for the given category and collection. - Parameters: - category (string, required): Category to get items from. - collection (string, required): Collection to get items from. - page (number, optional): Page number. - queryId (string, optional): Optional queryId passed to cancel a request. - Returns: Promise<{ items: SearchProduct[]; facets: { [key: string]: unknown }; isFromCache: boolean; page: number; keyword: string; isUrlRedirect: boolean; isQueryTranslated: boolean; isCachedFilterApplied: boolean; isKeywordConfigApplied: boolean; behaviorId: string; responseEngine: string; totalResults: number; sortedBy: string; variantMapping?: { [key: string]: string }; searchTermMatches?: string[]; }> xg.search.getTrendingSearches({collection: string}) - Description: Returns a list of trending search terms for the given collection. - Parameters: - collection (string, required): Collection to get items from. - Returns: Promise ``` -------------------------------- ### Implement a Custom Authentication Store with XGenClient Source: https://docs.xgen.ai/v1/docs/auth-store Demonstrates how to create a custom authentication store by extending `BaseAuthStore` and integrating it with the `XGenClient`. This allows for custom logic when saving authentication data, such as persisting it to a different storage mechanism. ```javascript import XGenClient, { BaseAuthStore } from '@xgenai/sdk-core'; class CustomAuthStore extends BaseAuthStore { save({tokenRecord, userRecord, sessionRecord}) { super.save({tokenRecord, userRecord, sessionRecord}); // your custom business logic... } } const xg = new XGenClient({ // ...other params authStore: new CustomAuthStore() }); ``` -------------------------------- ### XGen AI Custom Event and Batch Tracking API Methods Source: https://docs.xgen.ai/v1/docs/tracking API documentation for tracking custom events and utilizing batch tracking functionality. Batch tracking allows accumulating events before sending them in a single request. All tracking events return an object ` -------------------------------- ### SvelteKit SSR Integration with XGenClient Handle Hook Source: https://docs.xgen.ai/v1/docs/ssr-integration Illustrates how to initialize an `XGenClient` instance per request within a SvelteKit `handle` hook. It shows how to load authentication data from the request cookie and set updated authentication cookies in the response headers for SSR, ensuring state persistence. ```JavaScript // src/hooks.server.js import XGenClient from '@xgenai/sdk-core'; /** @type {import('@sveltejs/kit').Handle} */ export async function handle({ event, resolve }) {  event.locals.xg = new XGenClient({/*params*/});  // load the store data from the request cookie string  event.locals.xg.authStore.loadFromCookie(event.request.headers.get('cookie') || '');  const response = await resolve(event);  // send back the default 'xgen_token', 'xgen_user', 'xgen_session' cookies to the client with the latest store state  response.headers.append('set-cookie', event.locals.xg.authStore.exportToCookie());  return response; } ``` -------------------------------- ### Handle Service Responses with Promises and Async/Await in JavaScript Source: https://docs.xgen.ai/v1/docs/error-handling Demonstrates how to handle successful responses and errors from service calls using standard JavaScript Promise `.then().catch()` syntax. It also illustrates the modern `async/await` `try...catch` block for asynchronous operations, ensuring robust error management for `xg.recommend.getResultsById` calls. ```javascript xg.recommend.getResultsById({elementId: ''}).then((result) => { // success... console.log('Result:', result); }).catch((error) => { // error... console.log('Error:', error); }); // OR if you are using the async/await syntax: try { const result = xg.recommend.getResultsById({elementId: ''}); console.log('Result:', result); } catch (error) { console.log('Error:', error); } ``` -------------------------------- ### SvelteKit Server Endpoint Accessing XGenClient from Locals Source: https://docs.xgen.ai/v1/docs/ssr-integration Demonstrates how to access the `XGenClient` instance, previously initialized in the SvelteKit `handle` hook and stored in `event.locals`, within a server-side endpoint to perform actions like fetching recommendations using the authenticated client. ```JavaScript // src/routes/recommendations/+server.js /** * Creates a `POST /recommendations` server-side endpoint * * @type {import('./$types').RequestHandler} */ export async function POST({ request, locals }) {  const { email, password } = await request.json();  const results = await xg.recommend.getResultsById({elementId: ''})  return new Response(results); } ``` -------------------------------- ### XGen AI Core Tracking API Methods Source: https://docs.xgen.ai/v1/docs/tracking API documentation for fundamental XGen AI tracking methods, including page views, item/product views, category views, add-to-cart events, and purchase orders. All tracking events return an object `{ message: string; success: boolean; }`. ```APIDOC xg.track.pageView() - Description: Tracks a page view event. - Parameters: None xg.track.itemView({item, context}) - Description: Tracks an item/product view event. - Parameters: - item: object (Required) - The item/product to track - item.id: string (Required) - The ID of the item/product - item.name: string (Required) - The name of the item/product - item.price: string (Required) - The price of the item/product - item.currency: string (Required) - The currency of the item/product. Ex. USD - context: object (Optional) - Dynamic information about the event. xg.track.categoryView({category, items, context}) - Description: Tracks a category view event. - Parameters: - category: string (Required) - The category to track - items: string[] (Required) - The IDs of the first few category items/products - context: object (Optional) - Dynamic information about the event. xg.track.addToCart({item, context}) - Description: Tracks an add to cart event. - Parameters: - item: object (Required) - The item/product to track - item.id: string (Required) - The ID of the item/product - item.name: string (Required) - The name of the item/product - item.price: string (Required) - The price of the item/product - item.currency: string (Required) - The currency of the item/product. Ex. USD - item.quantity: number (Required) - The quantity of the item/product - context: object (Optional) - Dynamic information about the event. xg.track.purchaseOrder({items, orderId, tax, discount, context}) - Description: Tracks a purchase order event for item(s)/product(s). - Parameters: - items: item[] (Required) - The array of items/products to track - item.id: string (Required) - The ID of the item/product - item.name: string (Required) - The name of the item/product - item.price: string (Required) - The price of the item/product - item.currency: string (Required) - The currency of the item/product. Ex. USD - item.quantity: number (Required) - The quantity of the item/product - orderId: string (Required) - The unique identifier of the order - tax: number (Optional) - The tax amount of the order - discount: number (Optional) - The discount amount of the order - context: object (Optional) - Dynamic information about the event. ``` -------------------------------- ### XRecommend Service API Reference Source: https://docs.xgen.ai/v1/docs/xrecommend-service Comprehensive API documentation for the `xg.recommend` service, detailing the `getResults` and `getResultsById` methods, their parameters, and expected return types for retrieving recommendation data. ```APIDOC getResults: Description: Gets recommendation results by a list of elementIds. Parameters: - Name: elementIds Type: string[] Required: Yes Description: The IDs of the elements - Name: options Type: object Required: Yes Description: Options object that allows you to control the search result response Properties: - Name: options.pathname Type: string Required: No Description: The pathname that includes the locale (default to 'default' locale) - Name: context Type: object Required: No Description: Dynamic context object - Name: queryId Type: string Required: No Description: An optional queryId passed to cancel a request Returns: A Promise resolving to a Recommendations object: { [key: string]: { items: RecommendProduct[]; ruleEngine: string; ruleset: string; }; } getResultsById: Description: Gets recommendation results by a single elementId. Parameters: - Name: elementId Type: string Required: Yes Description: The ID of the element - Name: options Type: object Required: Yes Description: Options object that allows you to control the search result response Properties: - Name: options.pathname Type: string Required: No Description: The pathname that includes the locale (default to 'default' locale) - Name: context Type: object Required: No Description: Dynamic context object - Name: queryId Type: string Required: No Description: An optional queryId passed to cancel a request Returns: A Promise resolving to a Recommendations object: { items: RecommendProduct[]; ruleset: string; ruleEngine: string; } ``` -------------------------------- ### XGEN AI Event Tracking API Methods Source: https://docs.xgen.ai/v1/docs/tracking This section outlines the various event tracking methods available in the XGEN AI platform, including details on their parameters and usage. These methods allow for comprehensive monitoring of user behavior and system interactions. ```APIDOC elementRender Description: Tracks the render of a specific DOM node. Parameters: element (object, Required): Information about the DOM node to track element.id (string, Required): The ID of the DOM node element.items (string[], Optional): An array of the items/product IDs shown in the element context (object, Optional): Dynamic information about the event. elementClick Description: Tracks a click event on a specific DOM node. Parameters: element (object, Required): Information about the DOM node to track element.id (string, Required): The ID of the DOM node element.items (string[], Optional): An array of the items/product IDs shown in the element item (string, Required): The ID of the item/product clicked context (object, Optional): Dynamic information about the event. searchQuery Description: Tracks the search query. This is an event right before the search request is sent. Parameters: query (object, Required): Information about the search query queryId (string, Required): The ID of the search query deploymentId (string, Required): The ID of the deployment isTypeToSearch (boolean, Optional): Whether the query is a type-to-search query page (number, Optional): The page number of the search query context (object, Optional): Dynamic information about the event. searchResult Description: Tracks the results of the search request. Parameters: query (object, Required): Information about the search query queryId (string, Required): The ID of the search query deploymentId (string, Required): The ID of the deployment items (string[], Required): An array of the items/product IDs in the search results isTypeToSearch (boolean, Optional): Whether the query is a type-to-search query page (number, Optional): The page number of the search query context (object, Optional): Dynamic information about the event. searchClick Description: Tracks a click event on a search result. Parameters: query (object, Required): Information about the search query queryId (string, Required): The ID of the search query deploymentId (string, Required): The ID of the deployment item (string, Required): The ID of the item/product clicked items (string[], Optional): An array of the items/product IDs in the search results isTypeToSearch (boolean, Optional): Whether the query is a type-to-search query page (number, Optional): The page number of the search query context (object, Optional): Dynamic information about the event. customEvent Description: Tracks a custom event. Parameters: category (string, Required): The category of the event type action (string, Required): The action of the event name (string, Required): The name of the event value (string, Required): The value of the event context (object, Optional): Dynamic information about the event. ``` -------------------------------- ### Shopify Collection URL Handle to XSearch Keyword Mapping Source: https://docs.xgen.ai/v1/docs/configure-plp Defines the required mapping rule between a Shopify collection's URL handle and its corresponding XSearch Keyword in the XGEN platform. This ensures correct product filtering and display on the PLP. Hyphens in the URL handle must be replaced with spaces for the XSearch Keyword. ```APIDOC Mapping Rule: Shopify URL Handle Example: amazing-first-collection Corresponding XSearch Keyword: amazing first collection ``` -------------------------------- ### XGen SDK BaseAuthStore API Reference Source: https://docs.xgen.ai/v1/docs/auth-store Provides a comprehensive reference for the `BaseAuthStore` class, detailing its public fields (token, user, sessionId, isExpired) and core methods (`clear`, `save`, `loadFromCookie`, `exportToCookie`). It also lists overridable properties and methods for customizing cookie behavior and expiration logic. ```APIDOC BaseAuthStore { // base fields token: TokenRecord|null // the access_token and expiration user: UserRecord|null // the userId, userType, expiration, and alternateUserId (if applicable) sessionId: SessionRecord|null // the session id and expiration isExpired: boolean // checks if the record is expired // main methods clear() // "logout" the authenticated record - Returns: void save({tokenRecord, userRecord, sessionRecord}) // update the store with the new auth data - Parameters: - tokenRecord: TokenRecord - The token data to save. - userRecord: UserRecord - The user data to save. - sessionRecord: SessionRecord - The session data to save. - Returns: void // cookie parse and serialize helpers loadFromCookie(cookieHeader) - Parameters: - cookieHeader: string - The cookie header string to parse. - Returns: void exportToCookie(options = {}) - Parameters: - options: object - Options for exporting to cookie. - Returns: string // The serialized cookie string // overridable properties methods via constructor keyPrefix: string tokenSuffix: string userSuffix: string sessionSuffix: string generateUserId(): string // custom userId generation - Returns: string - A custom user ID. addAlternateuserId(): string // custom alternate userId generation - Returns: string - A custom alternate user ID. getUserExpiration(): number // custom function to generate a user expiration date - Defaults to 395 days from now - Returns: number - Timestamp for user expiration. getSessionExpiration(): number // custom function to generate a session expiration date - Defaults to 30 minutes from now - Returns: number - Timestamp for session expiration. } ``` -------------------------------- ### SvelteKit Global Type Definition for XGenClient in Locals Source: https://docs.xgen.ai/v1/docs/ssr-integration Provides the TypeScript declaration to ensure proper type detection for the `XGenClient` instance stored in `event.locals` within a SvelteKit application, enhancing developer experience with type checking and autocompletion. ```TypeScript // src/app.d.ts import XGenClient from '@xgenai/sdk-core'; declare global {  declare namespace App {    interface Locals {      xg: XGenClient    }  } } ``` -------------------------------- ### Configure XGen Type-to-Search General Settings Source: https://docs.xgen.ai/v1/docs/search-experiences Defines various general settings to control the behavior of the type-to-search functionality within XGen elements, optimizing search API calls and user experience. These settings are used to control the `getTypeToSearch` function. ```APIDOC No Type to Search (boolean) - Description: When this setting is enabled, there will be no search results as the user is typing. Enable Type to Search (boolean) - Description: This will enable the type-to-search functionality within experiences. This setting will also utilize XGen's type-to-search API which uses a faster version of DeepSearch. You can select a trigger to define exactly when this functionality kicks in. Switch to Primary Search (boolean) - Description: Instead of using the type-to-search API, type-to-search can be configured to use XGen's primary search API instead. You can utilize triggers to define when primary search will kick in, or you can configure it to always use primary search. Debounce Time (number) - Description: The debounce time is the amount of time required in between user actions in order for the search API to be called. For example, lets say the debounce is set to 150ms. When the user types a character, a 150ms timer will start. When that timer ends, the search API is called; however, if the user inputs another character before that 150ms timer is up, the timer will reset and wait another 150ms. Debounce is a way to optimize the API so that no unnecessary requests are sent thus decreasing the load on the network and the API which will result in a faster experience for the user. ``` -------------------------------- ### Integrate XRecommend Widget in Shopify Theme Editor Source: https://docs.xgen.ai/v1/docs/configure-xrecommend This section outlines the steps to integrate the XRecommend widget into a Shopify theme using the generated Experience ID from the XGEN Platform. ```APIDOC Shopify Theme Editor - XRecommend Widget Integration: 1. Open Theme Editor: - In your Shopify Admin dashboard, choose a theme to customize (public or archived). 2. Open Product Page: - In the top menu of your theme, select Products, and then a specific Product Page. 3. Insert App Block: - Click the “Add Section” button. - Select the "Apps" option. - Select “XRecommend” as an option. 4. Paste Experience ID: - In the field at the top of the page, paste the XRecommend Experience ID copied from the XGEN Platform. ``` -------------------------------- ### Update and Export XGen Auth Store with Cookie Data Source: https://docs.xgen.ai/v1/docs/ssr-integration Demonstrates how to load authentication data into the XGen client's auth store from a cookie string and how to export the store's current state back into a cookie string, with options to customize cookie attributes like `httpOnly`. ```JavaScript // update the store with the parsed data from the cookie string xg.authStore.loadFromCookie('xgen_token=...;xgen_user=...;xgen_session=...'); // exports the store data as cookie, with option to extend the default SameSite, Secure, HttpOnly, Path and Expires attributes xg.authStore.exportToCookie({ httpOnly: false }); // Output: 'xgen_token=...;xgen_user=...;xgen_session=...' ``` -------------------------------- ### Configure LocalCookieAuthStore with Custom Cookie Settings Source: https://docs.xgen.ai/v1/docs/auth-store Illustrates how to customize the `LocalCookieAuthStore` by providing custom functions for generating user IDs, alternate user IDs, and defining custom expiration durations for user and session cookies. This allows for fine-grained control over the cookie behavior. ```javascript import XGenClient, { LocalCookieAuthStore } from '@xgenai/sdk-core'; const authStore = new LocalCookieAuthStore({ generateUserId: () => 'custom_user_id', addAlternateUserId: () => 'custom_alternate_user_id', getUserExpiration: () => Date.now() + 1000 * 60 * 60 * 24 * 20, // 20 days from now sessionExpiration: () => Date.now() + 1000 * 60 * 60 // 1 hour from now }); ``` -------------------------------- ### XSearch Condition Operators Reference Source: https://docs.xgen.ai/v1/docs/merchandising-rules Defines the comprehensive list of operators available for configuring conditions within the XSearch experience. These operators are used to compare product property values against specified condition values, enabling precise filtering and merchandising rules. ```APIDOC Operator Types: - equals: Description: Checks if the product property value is equal to the condition value. - doesn't equal: Description: Checks if the product property value is not equal to the condition value. - contains: Description: Checks if the product property value contains the condition value. - doesn't contain: Description: Checks if the product property value does not contain the condition value. - greater than: Description: Checks if the product property value is greater than the condition number. - greater than or equal to: Description: Checks if the product property value is greater than or equal to the condition number. - less than: Description: Checks if the product property value is less than the condition number. - less than or equal to: Description: Checks if the product property value is less than or equal to the condition number. - matches regex: Description: Checks if the product property value matches the condition value regex string. - in: Description: Checks if a value of the property can be found in any of the given values. - not in: Description: Checks if a value of the property cannot be found in any of the given values. ``` -------------------------------- ### Product Catalog Field Mapping Schema Source: https://docs.xgen.ai/v1/docs/product-catalog-mapping Defines the comprehensive list of available fields and their corresponding data types for integrating product catalog data. This schema supports standard product attributes and includes a set of custom fields (string, array, integer) to accommodate bespoke attributes without altering the core structure, ensuring adaptability for future data requirements. ```APIDOC prod_name: 'string', prod_code: 'string', link: 'string', price: 'price_string', sale_price: 'price_string', is_on_sale: 'int_bool', category: 'string', categories: 'array_of_strings', sub_collection: 'string', sub_collections: 'array_of_strings', type: 'string', types: 'array_of_strings', tag: 'string', tags: 'array_of_strings', variants: 'array_of_objects', is_in_stock: 'int_bool', sku: 'string', image: 'string', image_alt: 'string', images: 'array_of_strings', quantity: 'integer', gender: 'string', color: 'string', size: 'string', currency: 'string', currency_symbol: 'string', custom_string_1: 'string', custom_string_2: 'string', custom_string_3: 'string', custom_string_4: 'string', custom_string_5: 'string', custom_string_6: 'string', custom_string_7: 'string', custom_string_8: 'string', custom_string_9: 'string', custom_string_10: 'string', custom_array_1: 'array', custom_array_2: 'array', custom_array_3: 'array', custom_array_4: 'array', custom_array_5: 'array', custom_array_6: 'array', custom_array_7: 'array', custom_array_8: 'array', custom_array_9: 'array', custom_array_10: 'array', custom_int_1: 'integer', custom_int_2: 'integer', custom_int_3: 'integer', custom_int_4: 'integer', custom_int_5: 'integer' ``` -------------------------------- ### Define XGen Type-to-Search Triggers Source: https://docs.xgen.ai/v1/docs/search-experiences Specifies conditions that determine when a specific piece of type-to-search functionality activates based on user input. These triggers allow for fine-grained control over when search results appear, with numerical values interpreted as 'greater than or equal to'. ```APIDOC No Trigger (boolean) - Description: The setting will be activated as soon as the user starts typing. Character Count (number) - Description: The setting will be activated as soon as the user types a query with that many characters. Word Count (number) - Description: The setting will be activated once the user types a query with that many words. Note: a word is counted by groups of characters separated by white space. “red p” and “red pants” are both considered two words, but “red “ with a space at the end is only considered one word. Key Input (boolean) - Description: The setting will be activated once the user types one of the designated keys while the search input is selected. ``` -------------------------------- ### XGEN AI Request Cancellation Methods Source: https://docs.xgen.ai/v1/docs/cancelation Provides methods to manage and cancel pending requests within the XGEN AI system, allowing for global cancellation or targeted cancellation via a unique key. ```APIDOC xg.cancelAll() - Description: Cancels all pending requests. - Parameters: None - Returns: No explicit return value mentioned. xg.cancel(cancelKey) - Description: Cancels a single request by its cancellation token key. - Parameters: - cancelKey (string): The cancellation token key for the request. - Returns: No explicit return value mentioned. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.