id
stringlengths
12
53
messages
listlengths
3
3
code_search-resolver_f6aa54c7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/utils/with-fallback.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/**\n * Helper function to execute intsch as primary with intelligentSearchApi as fallback\n */\nexport async function withFallback<T>(\n primaryFn: () => Promise<T>,\n fallbackFn: () => Promise<T>,\n logger: any,\n operationName: string,\n args?: Record<string, unknown>\n ): Promise<T> {\n try {\n return await primaryFn()\n } catch (error) {\n logger.warn({\n message: `${operationName}: Primary call failed, using fallback`,\n error: error.message,\n args,\n })\n \n return fallbackFn()\n }\n }\n```" } ]
code_search-resolver_05941330
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/utils/string.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const toTitleCase = (str: string) => {\n return str\n .toLowerCase()\n .split(' ')\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ')\n}\n\nexport const removeDiacriticsFromURL = (url: string) =>\n encodeURIComponent(\n decodeURIComponent(url)\n .normalize('NFD')\n .replace(/[\\u0300-\\u036f]/g, '')\n )\n\n```" } ]
code_search-resolver_077bd55d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/utils/searchState.test.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { parseState } from './searchState'\n\ndescribe('parseState', () => {\n it('should correctly parse empty state', () => {\n expect(parseState('')).toEqual({})\n expect(parseState(undefined)).toEqual({})\n })\n\n it('should return empty on invalid state', () => {\n expect(parseState('adsasd')).toEqual({})\n expect(parseState('4')).toEqual({})\n })\n\n it('should correctly parse state', () => {\n expect(parseState(JSON.stringify({ property: 'value' }))).toEqual({\n property: 'value',\n })\n })\n})\n\n```" } ]
code_search-resolver_24cebaab
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/utils/i18n.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/no-use-before-define */\nimport {\n createMessagesLoader,\n formatTranslatableStringV2,\n parseTranslatableStringV2,\n} from '@vtex/api'\n\nimport { logDegradedSearchError } from '../resolvers/search/utils'\n\nexport const formatTranslatableProp =\n <R, P extends keyof R, I extends keyof R>(prop: P, idProp: I) =>\n (root: R, _: unknown, ctx: Context) =>\n addContextToTranslatableString(\n {\n content: root[prop] as unknown as string,\n context: root[idProp] as unknown as string,\n },\n ctx\n )\n\ninterface BaseMessage {\n content: string\n from?: string\n}\n\ninterface MessageWithContext extends BaseMessage {\n context: string | number\n}\n\nexport interface Message extends BaseMessage {\n context?: string\n}\n\nexport const addContextToTranslatableString = (\n message: Message,\n ctx: Context\n) => {\n const {\n vtex: { tenant },\n translated,\n } = ctx\n\n const { locale } = tenant!\n\n if (!message.content) {\n return message.content\n }\n\n const state = translated ? 'translated' : 'original'\n\n try {\n const {\n content,\n context: originalContext,\n from: originalFrom,\n } = parseTranslatableStringV2(message.content)\n\n const context = (originalContext || message.context)?.toString()\n const from = originalFrom || message.from || locale\n\n return formatTranslatableStringV2({ content, context, from, state })\n } catch (e) {\n logDegradedSearchError(ctx.vtex.logger, {\n service: 'node-vtex-api translation',\n error: 'Error when trying to add context to translatable string',\n errorStack: e,\n })\n\n return message.content\n }\n}\n\nexport const translateToCurrentLanguage = (\n message: MessageWithContext,\n ctx: Context\n) => {\n const {\n state,\n clients,\n vtex: { binding, tenant, locale },\n } = ctx\n\n if (!state.messagesBindingLanguage) {\n state.messagesBindingLanguage = createMessagesLoader(\n clients,\n locale ?? binding!.locale\n )\n }\n\n return state.messagesBindingLanguage!.load({\n content: message.content,\n context: message.context?.toString(),\n from: message.from ?? tenant!.locale,\n })\n}\n\nexport const translateManyToCurrentLanguage = (\n messages: Message[],\n ctx: Context\n) => {\n const {\n state,\n clients,\n vtex: { binding, tenant, locale },\n } = ctx\n\n if (!state.messagesBindingLanguage) {\n state.messagesBindingLanguage = createMessagesLoader(\n clients,\n locale ?? binding!.locale\n )\n }\n\n return state.messagesBindingLanguage!.loadMany(\n messages.map((message) => ({\n content: message.content,\n context: message.context,\n from: message.from ?? tenant!.locale,\n }))\n )\n}\n\nexport const shouldTranslateToUserLocale = ({\n vtex: { tenant, locale },\n}: Context) => tenant?.locale !== locale\n\nexport const shouldTranslateToBinding = (\n { translated, vtex: { binding, tenant } }: Context,\n ignoreIndexedTranslation?: boolean\n) =>\n binding &&\n binding?.locale !== tenant?.locale &&\n (!translated || ignoreIndexedTranslation)\n\nexport const shouldTranslateToTenantLocale = ({\n vtex: { locale, tenant },\n}: Context) => Boolean(tenant?.locale && locale && tenant.locale !== locale)\n\n```" } ]
code_search-resolver_84d10301
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/utils/vbase.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { VBase } from '@vtex/api'\nimport { createHash } from 'crypto'\n\nexport const staleFromVBaseWhileRevalidate = async <T>(\n vbase: VBase,\n bucket: string,\n filePath: string,\n validateFunction: (params?: any) => Promise<T>,\n params?: any,\n options?: { expirationInMinutes?: number}\n): Promise<T> => {\n const normalizedFilePath = normalizedJSONFile(filePath)\n const cachedData = await vbase.getJSON<StaleRevalidateData<T>>(bucket, normalizedFilePath, true).catch() as StaleRevalidateData<T>\n if(!cachedData){\n const endDate = getTTL(options?.expirationInMinutes)\n return await revalidate<T>(vbase, bucket, normalizedFilePath, endDate, validateFunction, params)\n }\n\n const { data, ttl} = cachedData as StaleRevalidateData<T>\n \n const today = new Date()\n const ttlDate = new Date(ttl)\n if(today < ttlDate){\n return data\n }\n const endDate = getTTL(options?.expirationInMinutes)\n revalidate<T>(vbase, bucket, normalizedFilePath, endDate, validateFunction, params)\n return data\n}\n\nconst getTTL = (expirationInMinutes?: number) => {\n const ttl = new Date()\n ttl.setMinutes(ttl.getMinutes() + (expirationInMinutes || 30 ))\n return ttl\n}\n\nconst revalidate = async<T> (\n vbase: VBase, bucket: string, filePath: string,\n endDate: Date, validateFunction: (params?: any) => Promise<T>, params?: any) => {\n const data = await validateFunction(params)\n const revalidatedData = { data, ttl: endDate }\n vbase.saveJSON<StaleRevalidateData<T>>(bucket, filePath, revalidatedData).catch()\n return data\n}\n\nconst normalizedJSONFile = (filePath: string) => createHash('md5').update(filePath).digest('hex') + '.json'\n```" } ]
code_search-resolver_a34c61a7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/utils/attachments.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { all, propEq } from 'ramda'\n\nexport const CHOICE_TYPES = {\n MULTIPLE: 'MULTIPLE',\n SINGLE: 'SINGLE',\n TOGGLE: 'TOGGLE',\n}\n\nconst isParentOptionSingleChoice = ({ composition }: AssemblyOption) => {\n if (!composition) {\n return false\n }\n\n const { minQuantity, maxQuantity } = composition\n\n return minQuantity === 1 && maxQuantity === 1\n}\n\nconst isParentOptionToggleChoice = ({ composition }: AssemblyOption) => {\n if (!composition) {\n return false\n }\n\n const { items } = composition\n\n return all(propEq('maxQuantity', 1))(items)\n}\n\nexport const getItemChoiceType = (childAssemblyData?: AssemblyOption) => {\n if (!childAssemblyData) {\n return CHOICE_TYPES.MULTIPLE\n }\n\n const isSingle = isParentOptionSingleChoice(childAssemblyData!)\n\n if (isSingle) {\n return CHOICE_TYPES.SINGLE\n }\n\n const isToggle = isParentOptionToggleChoice(childAssemblyData)\n\n if (isToggle) {\n return CHOICE_TYPES.TOGGLE\n }\n\n return CHOICE_TYPES.MULTIPLE\n}\n\n```" } ]
code_search-resolver_5cff4bdd
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/utils/cookie.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { parse } from 'cookie'\nimport { keys } from 'ramda'\n\nconst isUserLoggedIn = (ctx: Context) => {\n const {\n vtex: { account },\n } = ctx\n\n return !!ctx.cookies.get(`VtexIdclientAutCookie_${account}`)\n}\n\nconst parseCookie = (cookie: string) => {\n const parsed = parse(cookie)\n const cookieName = keys(parsed)[0]\n const cookieValue = parsed[cookieName]\n\n const extraOptions = {\n path: parsed.path,\n domain: parsed.domain,\n expires: parsed.expires ? new Date(parsed.expires) : undefined,\n }\n\n return {\n name: cookieName,\n value: cookieValue,\n options: extraOptions,\n }\n}\n\n/** Checkout cookie methods */\nconst CHECKOUT_COOKIE = 'checkout.vtex.com'\n\nconst checkoutCookieFormat = (orderFormId: string) =>\n `${CHECKOUT_COOKIE}=__ofid=${orderFormId};`\n\nconst getOrderFormIdFromCookie = (cookies: Context['cookies']) => {\n const cookie = cookies.get(CHECKOUT_COOKIE)\n\n return cookie && cookie.split('=')[1]\n}\n\nexport {\n isUserLoggedIn,\n CHECKOUT_COOKIE,\n checkoutCookieFormat,\n getOrderFormIdFromCookie,\n parseCookie,\n}\n\n```" } ]
code_search-resolver_61e437bd
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/utils/CategoryTreeSegmentsFinder.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { searchSlugify } from './slug'\nimport { VBase } from '@vtex/api'\nimport { Search } from '../clients/search'\nimport { CATEGORY_TREE_CHILDREN_BUCKET, CATEGORY_TREE_ROOT_BUCKET, CATEGORY_TREE_ROOT_PATH } from '../resolvers/search/constants'\nimport { staleFromVBaseWhileRevalidate } from './vbase'\ninterface Clients{\n vbase: VBase\n search: Search\n}\n\ninterface LazyCategoryTreeNode{\n id: number\n name: string\n hasChildren: boolean\n}\n\nexport interface CategoryIdNamePair{\n id: string\n name: string\n}\n\nexport class CategoryTreeSegmentsFinder {\n \n private clients: Clients\n private segments: string[]\n protected categoryTreeRoot: Record<string, LazyCategoryTreeNode>\n\n public constructor(clients: Clients, segments: string[]){\n this.clients = clients\n this.segments = segments\n this.categoryTreeRoot = {}\n }\n\n public find = async () => {\n const { segments } = this\n const result: (CategoryIdNamePair|null)[] = []\n await this.initCategoryTreeRoot()\n\n const rootCategorySegment = this.findRootCategorySegment()\n if(!rootCategorySegment){\n return []\n }\n \n const {category, index} = rootCategorySegment\n \n result[index] = {id: category.id.toString(), name: category.name}\n const segmentsTail = segments.slice(index+1)\n const categorySegmentsFromChildren = await this.findCategoriesFromChildren(category.id, segmentsTail)\n return result.concat(categorySegmentsFromChildren)\n }\n\n /**\n * Fetches a category children from vbase or search\n * clients: {vbase: VBase, search: Search}\n */\n protected lazyFetchChildren = async (id: number) => {\n const { search } = this.clients\n return await this.staleWhileRevalidate<Record<string, string>>(CATEGORY_TREE_CHILDREN_BUCKET, id.toString(), this.fetchChildrenFromSearch, { search, id })\n }\n\n protected staleWhileRevalidate = async <T>(bucket: string, path: string,validateFunction: (params?: any) => Promise<T>, params?: any) => {\n return await staleFromVBaseWhileRevalidate<T>(this.clients.vbase, bucket, path, validateFunction, params)\n }\n\n protected getCategoryTreeRoot = async () => {\n const categoryTree = await this.clients.search.categories(0)\n return categoryTree.reduce((acc, categoryTreeNode) => {\n const categorySlug = searchSlugify(categoryTreeNode.name)\n const lazyCategoryTreeNode = {\n id: categoryTreeNode.id,\n name: categoryTreeNode.name,\n hasChildren: categoryTreeNode.hasChildren,\n }\n acc[categorySlug] = lazyCategoryTreeNode\n return acc\n }, {} as Record<string, LazyCategoryTreeNode>)\n }\n\n private initCategoryTreeRoot = async () => {\n this.categoryTreeRoot = await this.staleWhileRevalidate<Record<string, LazyCategoryTreeNode>>(\n CATEGORY_TREE_ROOT_BUCKET, CATEGORY_TREE_ROOT_PATH, this.getCategoryTreeRoot)\n }\n \n // Returns {id: categoryId, name: categorySlug }\n private findCategoriesFromChildren = async (categoryId: number, segments: string[]) => {\n const result: (CategoryIdNamePair|null)[] = []\n for(const segment of segments){\n const children = await this.getChildren(categoryId)\n const childCategoryId = children[segment]\n if(childCategoryId){\n categoryId = Number(childCategoryId)\n result.push({ id: childCategoryId, name: segment })\n }else{\n result.push(null)\n }\n }\n return result\n }\n \n private findRootCategorySegment = () => {\n const { segments, categoryTreeRoot } = this\n const segmentIndex = segments.findIndex(segment => !!categoryTreeRoot[segment])\n return segmentIndex !== -1? {index: segmentIndex, category: categoryTreeRoot[segments[segmentIndex]]}: null\n }\n\n private getChildren = async (id: number) => {\n return await this.lazyFetchChildren(id)\n }\n \n // Returns { categorySlug: categoryId }\n private fetchChildrenFromSearch = async (params: { search: Search, id: number }): Promise<Record<string, string>> => {\n const {search, id} = params\n const categoryChildren = await search.getCategoryChildren(id)\n const categoryChildrenBySlug = Object.keys(categoryChildren).reduce((acc, categoryChildId: string) => {\n const categoryChildName = categoryChildren[categoryChildId]\n const categoryChildSlug = searchSlugify(categoryChildName)\n acc[categoryChildSlug] = categoryChildId\n return acc\n }, {} as Record<string, string>)\n return categoryChildrenBySlug\n }\n}\n```" } ]
code_search-resolver_8727a567
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/utils/compareResults.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { Logger } from '@vtex/api'\n\n/**\n * Utility to compare the results of two functions in parallel\n * Used primarily for comparing the results of two API implementations\n * during the migration from intelligent-search-api to intsch\n */\n\n/**\n * Represents a difference found between two values\n */\nexport interface ObjectDifference {\n path: string\n type:\n | 'missing_key'\n | 'extra_key'\n | 'different_value'\n | 'different_type'\n | 'array_length_mismatch'\n expected?: unknown\n actual?: unknown\n details?: string\n}\n\n/**\n * Result of deep comparison with differences\n */\nexport interface DeepComparisonResult {\n isEqual: boolean\n differences: ObjectDifference[]\n}\n\n/**\n * Finds differences between two values recursively\n * @param a First value to compare\n * @param b Second value to compare\n * @param path Current path in the object (for tracking location of differences)\n * @param maxDepth Maximum recursion depth (default: 20)\n * @param currentDepth Current recursion depth (internal use)\n * @returns Array of differences found\n */\nexport function findDifferences(\n a: unknown,\n b: unknown,\n path = '',\n maxDepth = 50,\n currentDepth = 0\n): ObjectDifference[] {\n const differences: ObjectDifference[] = []\n\n // If both values are exactly the same, no differences\n if (a === b) return differences\n\n // Check for null values or different types\n if (a === null || b === null || typeof a !== typeof b) {\n differences.push({\n path,\n type: 'different_type',\n expected: a === null ? 'null' : typeof a,\n actual: b === null ? 'null' : typeof b,\n })\n\n return differences\n }\n\n // If neither is an object, they are different primitive values\n if (typeof a !== 'object' || typeof b !== 'object') {\n differences.push({\n path,\n type: 'different_value',\n expected: a,\n actual: b,\n })\n\n return differences\n }\n\n // Check if maximum recursion depth has been reached (only for objects)\n if (currentDepth > maxDepth) {\n // When max depth is reached, consider values equal (original behavior)\n return differences\n }\n\n // Handle arrays specially\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) {\n differences.push({\n path,\n type: 'array_length_mismatch',\n expected: a.length,\n actual: b.length,\n })\n }\n\n const maxLength = Math.max(a.length, b.length)\n\n for (let i = 0; i < maxLength; i++) {\n const currentPath = path ? `${path}[${i}]` : `[${i}]`\n\n if (i >= a.length) {\n differences.push({\n path: currentPath,\n type: 'missing_key',\n actual: b[i],\n })\n } else if (i >= b.length) {\n differences.push({\n path: currentPath,\n type: 'extra_key',\n expected: a[i],\n })\n } else {\n differences.push(\n ...findDifferences(\n a[i],\n b[i],\n currentPath,\n maxDepth,\n currentDepth + 1\n )\n )\n }\n }\n\n return differences\n }\n\n // If one is an array but the other isn't\n if (Array.isArray(a) !== Array.isArray(b)) {\n differences.push({\n path,\n type: 'different_type',\n expected: Array.isArray(a) ? 'array' : 'object',\n actual: Array.isArray(b) ? 'array' : 'object',\n })\n\n return differences\n }\n\n // Cast to Record<string, unknown> for type safety\n const objA = a as Record<string, unknown>\n const objB = b as Record<string, unknown>\n\n // Compare object keys\n const keysA = Object.keys(objA)\n const keysB = Object.keys(objB)\n const allKeys = new Set([...keysA, ...keysB])\n\n for (const key of allKeys) {\n const currentPath = path ? `${path}.${key}` : key\n const hasKeyA = Object.prototype.hasOwnProperty.call(objA, key)\n const hasKeyB = Object.prototype.hasOwnProperty.call(objB, key)\n\n if (hasKeyA && !hasKeyB) {\n differences.push({\n path: currentPath,\n type: 'extra_key',\n expected: objA[key],\n })\n } else if (!hasKeyA && hasKeyB) {\n differences.push({\n path: currentPath,\n type: 'missing_key',\n actual: objB[key],\n })\n } else if (hasKeyA && hasKeyB) {\n differences.push(\n ...findDifferences(\n objA[key],\n objB[key],\n currentPath,\n maxDepth,\n currentDepth + 1\n )\n )\n }\n }\n\n return differences\n}\n\n/**\n * Performs a deep equality comparison between two values\n * @param a First value to compare\n * @param b Second value to compare\n * @param maxDepth Maximum recursion depth (default: 20)\n * @returns DeepComparisonResult with isEqual boolean and differences array\n */\nexport function isDeepEqual(\n a: unknown,\n b: unknown,\n maxDepth = 20\n): DeepComparisonResult {\n const differences = findDifferences(a, b, '', maxDepth, 0)\n\n return {\n isEqual: differences.length === 0,\n differences,\n }\n}\n\n/**\n * Filters out differences that should be ignored based on path and type\n * @param differences Array of differences to filter\n * @param ignoredDifferences Array of ignored difference configurations\n * @returns Filtered array of differences\n */\nexport function filterIgnoredDifferences(\n differences: ObjectDifference[],\n ignoredDifferences: IgnoredDifference[] = []\n): ObjectDifference[] {\n if (ignoredDifferences.length === 0) {\n return differences\n }\n\n return differences.filter((difference) => {\n // Check if this difference should be ignored\n return !ignoredDifferences.some(\n (ignored) =>\n ignored.path === difference.path && ignored.type === difference.type\n )\n })\n}\n\n/**\n * Configuration for ignoring expected differences\n */\nexport interface IgnoredDifference {\n path: string\n type:\n | 'missing_key'\n | 'extra_key'\n | 'different_value'\n | 'different_type'\n | 'array_length_mismatch'\n}\n\n/**\n * Options for the compareApiResults function\n */\nexport interface CompareApiResultsOptions {\n args?: unknown\n logPrefix?: string\n ignoredDifferences?: IgnoredDifference[]\n}\n\n/**\n * Executes two functions in parallel and compares their results\n * @param func1 First function to execute\n * @param func2 Second function to execute\n * @param sample Percentage of traffic that should execute the comparison (0-100)\n * @param logger Logger instance to use for logging\n * @param options Configuration options\n * @returns Promise with a result object containing the results and comparison details\n */\nexport async function compareApiResults<T>(\n func1: () => Promise<T>,\n func2: () => Promise<T>,\n sample: number,\n logger: Logger,\n options: CompareApiResultsOptions = {}\n): Promise<T> {\n const { logPrefix = 'API Comparison', ignoredDifferences = [] } = options\n\n // Check if we should perform comparison based on sample percentage\n const shouldCompare = Math.random() * 100 < sample\n\n if (!shouldCompare) {\n // If not in sample, just execute func1 and return its result\n return func1()\n }\n\n // Execute both functions in parallel\n const [result1, result2] = await Promise.all([\n func1().catch((error) => ({ __error: error })),\n func2().catch((error) => ({ __error: error })),\n ])\n\n // Check if either function resulted in an error\n const hasError1 =\n result1 && typeof result1 === 'object' && '__error' in result1\n\n const hasError2 =\n result2 && typeof result2 === 'object' && '__error' in result2\n\n let areEqual = false\n let differences: ObjectDifference[] = []\n let filteredDifferences: ObjectDifference[] = []\n\n try {\n if (!hasError1 && !hasError2) {\n const comparisonResult = isDeepEqual(result1, result2)\n\n differences = comparisonResult.differences\n filteredDifferences = filterIgnoredDifferences(\n differences,\n ignoredDifferences\n )\n areEqual = filteredDifferences.length === 0\n }\n } catch (error) {\n logger.error({\n message: `${logPrefix}: Error during deep comparison`,\n error,\n })\n }\n\n if (!areEqual && !hasError1 && !hasError2) {\n logger.error({\n message: `${logPrefix}: Results differ`,\n params: JSON.stringify(options.args),\n differences: filteredDifferences.slice(0, 10), // Limit to first 10 differences to avoid log overflow\n differenceCount: filteredDifferences.length,\n totalDifferences: differences.length,\n ignoredDifferences: differences.length - filteredDifferences.length,\n })\n } else if (areEqual) {\n logger.info({\n // Since the log level is indexed we are using it to get a sense of the % of results that are equal.\n message: `${logPrefix}: Results are equal`,\n params: JSON.stringify(options.args),\n totalDifferences: differences.length,\n ignoredDifferences: differences.length - filteredDifferences.length,\n })\n }\n\n if (!hasError1) {\n return result1 as T\n }\n\n if (hasError1 && !hasError2) {\n return result2 as T\n }\n\n throw Error('Both calls resulted in errors')\n}\n\n```" } ]
code_search-resolver_5845e6c4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/utils/object.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n adjust,\n curry,\n fromPairs,\n map,\n mergeAll,\n pipe,\n toPairs,\n zipObj,\n} from 'ramda'\n\n/**\n * Creates a new object with the own properties of the provided object, but the\n * keys renamed according to logic of renaming function.\n *\n * Keep in mind that in the case of keys conflict is behaviour undefined and\n * the result may vary between various JS engines!\n *\n * @func renameKeysWith\n * @category Object\n * @param {Function} func Function that renames the keys\n * @param {!Object} object Provided object\n * @return {!Object} New object with renamed keys\n * @see {@link https://github.com/ramda/ramda/wiki/Cookbook#rename-keys-of-an-object-by-a-function|Ramda Cookbook}\n * @example\n *\n * renameKeysWith(concat('a'), { A: 1, B: 2, C: 3 }) //=> { aA: 1, aB: 2, aC: 3 }\n */\ntype Tuple = [string, any]\nconst renameKeysWith = curry((func: any, object: any) =>\n pipe<any, Tuple[], any, any>(toPairs, map(adjust(0, func)), fromPairs)(object)\n)\n\n/*\n * Convert a list of fields like [ {key: 'propertyName', value: 'String'}, ... ]\n * to a JSON format.\n */\nconst parseFieldsToJson = (fields: any) =>\n mergeAll(fields.map((field: any) => zipObj([field.key], [field.value])))\n\n/**\n * Pass this to a filter to get distinct values from an array.\n * .filter(dinstinct)\n */\nfunction distinct<T>(value: T, index: number, self: T[]) {\n return self.indexOf(value) === index\n}\n\nexport { renameKeysWith, parseFieldsToJson, distinct }\n\n```" } ]
code_search-resolver_eb1fc46d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/utils/index.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { AxiosError } from 'axios'\nimport { AuthenticationError, ForbiddenError, UserInputError } from '@vtex/api'\n\nexport * from './object'\nexport * from './cookie'\n\nexport function generateRandomName() {\n return (1 + Math.random()).toString(36).substring(2)\n}\n\nexport function getFileExtension(fileName: string) {\n return fileName.match(/\\.[0-9a-z]+$/i)\n ? (fileName.match(/\\.[0-9a-z]+$/i) as any[])[0]\n : undefined\n}\n\nexport function statusToError(e: any) {\n if (!e.response) {\n throw e\n }\n\n const { response } = e as AxiosError\n const { status } = response!\n\n if (status === 401) {\n throw new AuthenticationError(e)\n }\n if (status === 403) {\n throw new ForbiddenError(e)\n }\n if (status === 400) {\n throw new UserInputError(e)\n }\n\n throw e\n}\n\n```" } ]
code_search-resolver_70e9da25
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/utils/compareResults.test.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { Logger } from '@vtex/api'\n\nimport {\n isDeepEqual,\n compareApiResults,\n findDifferences,\n filterIgnoredDifferences,\n type IgnoredDifference,\n type ObjectDifference,\n} from './compareResults'\n\ndescribe('isDeepEqual', () => {\n // Basic equality tests\n describe('basic equality', () => {\n it('should return true for identical primitive values', () => {\n expect(isDeepEqual(1, 1).isEqual).toBe(true)\n expect(isDeepEqual('hello', 'hello').isEqual).toBe(true)\n expect(isDeepEqual(true, true).isEqual).toBe(true)\n expect(isDeepEqual(null, null).isEqual).toBe(true)\n expect(isDeepEqual(undefined, undefined).isEqual).toBe(true)\n })\n\n it('should return false for different primitive values', () => {\n expect(isDeepEqual(1, 2).isEqual).toBe(false)\n expect(isDeepEqual('hello', 'world').isEqual).toBe(false)\n expect(isDeepEqual(true, false).isEqual).toBe(false)\n expect(isDeepEqual(null, undefined).isEqual).toBe(false)\n expect(isDeepEqual(0, null).isEqual).toBe(false)\n expect(isDeepEqual('', null).isEqual).toBe(false)\n })\n\n it('should handle empty arrays and objects', () => {\n expect(isDeepEqual([], []).isEqual).toBe(true)\n expect(isDeepEqual({}, {}).isEqual).toBe(true)\n expect(isDeepEqual([], {}).isEqual).toBe(false)\n })\n })\n\n // Simple objects and arrays tests\n describe('simple objects and arrays', () => {\n it('should compare simple arrays correctly', () => {\n expect(isDeepEqual([1, 2, 3], [1, 2, 3]).isEqual).toBe(true)\n expect(isDeepEqual([1, 2, 3], [1, 2, 4]).isEqual).toBe(false)\n expect(isDeepEqual([1, 2], [1, 2, 3]).isEqual).toBe(false)\n })\n\n it('should compare simple objects correctly', () => {\n expect(isDeepEqual({ a: 1, b: 2 }, { a: 1, b: 2 }).isEqual).toBe(true)\n expect(isDeepEqual({ a: 1, b: 2 }, { a: 1, b: 3 }).isEqual).toBe(false)\n expect(isDeepEqual({ a: 1 }, { a: 1, b: 2 }).isEqual).toBe(false)\n expect(isDeepEqual({ a: 1, b: 2 }, { b: 2, a: 1 }).isEqual).toBe(true) // order doesn't matter\n })\n\n it('should handle arrays with objects', () => {\n expect(isDeepEqual([{ a: 1 }], [{ a: 1 }]).isEqual).toBe(true)\n expect(isDeepEqual([{ a: 1 }], [{ a: 2 }]).isEqual).toBe(false)\n })\n\n it('should handle objects with arrays', () => {\n expect(isDeepEqual({ a: [1, 2] }, { a: [1, 2] }).isEqual).toBe(true)\n expect(isDeepEqual({ a: [1, 2] }, { a: [1, 3] }).isEqual).toBe(false)\n })\n })\n\n // Complex objects tests\n describe('complex nested objects', () => {\n it('should handle deeply nested objects', () => {\n const obj1 = {\n a: 1,\n b: {\n c: [1, 2, 3],\n d: {\n e: 'hello',\n f: {\n g: true,\n },\n },\n },\n }\n\n const obj2 = {\n a: 1,\n b: {\n c: [1, 2, 3],\n d: {\n e: 'hello',\n f: {\n g: true,\n },\n },\n },\n }\n\n const obj3 = {\n a: 1,\n b: {\n c: [1, 2, 3],\n d: {\n e: 'hello',\n f: {\n g: false, // Different value here\n },\n },\n },\n }\n\n expect(isDeepEqual(obj1, obj2).isEqual).toBe(true)\n expect(isDeepEqual(obj1, obj3).isEqual).toBe(false)\n })\n\n it('should handle circular references', () => {\n const obj1: Record<string, unknown> = { a: 1 }\n const obj2: Record<string, unknown> = { a: 1 }\n\n // Create circular references\n obj1.self = obj1\n obj2.self = obj2\n\n // These should fail as we're not specifically handling circular references\n // But we want to make sure it doesn't cause an infinite loop\n expect(() => isDeepEqual(obj1, obj2)).not.toThrow()\n })\n\n it('should handle arrays with mixed types', () => {\n const arr1 = [1, 'string', true, { a: 1 }, [1, 2]]\n const arr2 = [1, 'string', true, { a: 1 }, [1, 2]]\n const arr3 = [1, 'string', true, { a: 2 }, [1, 2]]\n\n expect(isDeepEqual(arr1, arr2).isEqual).toBe(true)\n expect(isDeepEqual(arr1, arr3).isEqual).toBe(false)\n })\n\n it('should handle objects with same content but different property order in nested arrays', () => {\n const obj1 = {\n searches: [\n {\n term: 'areia',\n count: 217,\n attributes: [\n {\n key: 'departamento',\n labelKey: 'Departamento',\n labelValue: 'Material de Construção',\n value: 'material-de-construcao',\n },\n {\n key: 'categoria',\n labelKey: 'Categoria',\n labelValue: 'Materiais básicos para obra',\n value: 'materiais-basicos-para-obra',\n },\n {\n key: 'subcategoria',\n labelKey: 'Subcategoria',\n labelValue: 'Areias',\n value: 'areias',\n },\n ],\n },\n {\n term: 'vaso caixa acoplada',\n count: 239,\n },\n {\n term: 'caixa acoplada',\n count: 86,\n },\n {\n term: 'vasos caixa acopladas',\n count: 66,\n },\n {\n term: 'kit vaso caixa acoplada',\n count: 117,\n },\n ],\n }\n\n const obj2 = {\n searches: [\n {\n term: 'areia',\n count: 217,\n attributes: [\n {\n key: 'departamento',\n value: 'material-de-construcao',\n labelKey: 'Departamento',\n labelValue: 'Material de Construção',\n },\n {\n key: 'categoria',\n value: 'materiais-basicos-para-obra',\n labelKey: 'Categoria',\n labelValue: 'Materiais básicos para obra',\n },\n {\n key: 'subcategoria',\n value: 'areias',\n labelKey: 'Subcategoria',\n labelValue: 'Areias',\n },\n ],\n },\n {\n term: 'vaso caixa acoplada',\n count: 239,\n },\n {\n term: 'caixa acoplada',\n count: 86,\n },\n {\n term: 'vasos caixa acopladas',\n count: 66,\n },\n {\n term: 'kit vaso caixa acoplada',\n count: 117,\n },\n ],\n }\n\n // These objects should be considered equal since they have the same content\n // but different property order in the attributes objects\n expect(isDeepEqual(obj1, obj2).isEqual).toBe(true)\n })\n })\n\n // maxDepth parameter tests\n describe('maxDepth parameter', () => {\n it('should respect the maxDepth parameter for nested objects', () => {\n const deepObj1 = {\n level1: {\n level2: {\n level3: {\n level4: {\n value: 'deep',\n },\n },\n },\n },\n }\n\n const deepObj2 = {\n level1: {\n level2: {\n level3: {\n level4: {\n value: 'different',\n },\n },\n },\n },\n }\n\n // With default depth (20), the difference should be detected\n expect(isDeepEqual(deepObj1, deepObj2).isEqual).toBe(false)\n\n // With depth of 3, the difference at level4 should not be detected\n expect(isDeepEqual(deepObj1, deepObj2, 3).isEqual).toBe(true)\n\n // With depth of 4, the difference should be detected\n expect(isDeepEqual(deepObj1, deepObj2, 4).isEqual).toBe(false)\n })\n\n it('should respect the maxDepth parameter for nested arrays', () => {\n const nestedArray1 = [1, [2, [3, [4, [5, 6]]]]]\n const nestedArray2 = [1, [2, [3, [4, [5, 7]]]]]\n\n // With default depth, the difference should be detected\n expect(isDeepEqual(nestedArray1, nestedArray2).isEqual).toBe(false)\n\n // With depth of 4, the difference at the deepest level should not be detected\n expect(isDeepEqual(nestedArray1, nestedArray2, 3).isEqual).toBe(true)\n\n // With depth of 5, the difference should be detected\n expect(isDeepEqual(nestedArray1, nestedArray2, 4).isEqual).toBe(false)\n })\n })\n\n describe('difference detection', () => {\n it('should return differences when using returnDifferences option', () => {\n const obj1 = { name: 'John', age: 25 }\n const obj2 = { name: 'Jane', age: 30 }\n\n const result = isDeepEqual(obj1, obj2)\n\n expect(result.isEqual).toBe(false)\n expect(result.differences).toHaveLength(2)\n expect(result.differences).toEqual([\n {\n path: 'name',\n type: 'different_value',\n expected: 'John',\n actual: 'Jane',\n },\n {\n path: 'age',\n type: 'different_value',\n expected: 25,\n actual: 30,\n },\n ])\n })\n\n it('should return no differences when objects are equal', () => {\n const obj1 = { name: 'John', age: 25 }\n const obj2 = { name: 'John', age: 25 }\n\n const result = isDeepEqual(obj1, obj2)\n\n expect(result.isEqual).toBe(true)\n expect(result.differences).toHaveLength(0)\n })\n\n it('should detect missing and extra keys', () => {\n const obj1 = { name: 'John', age: 25 }\n const obj2 = { name: 'John', email: 'john@example.com' }\n\n const result = isDeepEqual(obj1, obj2)\n\n expect(result.isEqual).toBe(false)\n expect(result.differences).toHaveLength(2)\n expect(result.differences).toEqual(\n expect.arrayContaining([\n {\n path: 'age',\n type: 'extra_key',\n expected: 25,\n },\n {\n path: 'email',\n type: 'missing_key',\n actual: 'john@example.com',\n },\n ])\n )\n })\n\n it('should detect nested differences with correct paths', () => {\n const obj1 = {\n user: {\n profile: {\n name: 'John',\n preferences: { theme: 'dark' },\n },\n },\n }\n\n const obj2 = {\n user: {\n profile: {\n name: 'Jane',\n preferences: { theme: 'light' },\n },\n },\n }\n\n const result = isDeepEqual(obj1, obj2)\n\n expect(result.isEqual).toBe(false)\n expect(result.differences).toHaveLength(2)\n expect(result.differences).toEqual([\n {\n path: 'user.profile.name',\n type: 'different_value',\n expected: 'John',\n actual: 'Jane',\n },\n {\n path: 'user.profile.preferences.theme',\n type: 'different_value',\n expected: 'dark',\n actual: 'light',\n },\n ])\n })\n\n it('should detect array differences', () => {\n const arr1 = [1, 2, { value: 'a' }]\n const arr2 = [1, 3, { value: 'b' }]\n\n const result = isDeepEqual(arr1, arr2)\n\n expect(result.isEqual).toBe(false)\n expect(result.differences).toHaveLength(2)\n expect(result.differences).toEqual([\n {\n path: '[1]',\n type: 'different_value',\n expected: 2,\n actual: 3,\n },\n {\n path: '[2].value',\n type: 'different_value',\n expected: 'a',\n actual: 'b',\n },\n ])\n })\n\n it('should detect type differences', () => {\n const obj1 = { value: 'string' }\n const obj2 = { value: 42 }\n\n const result = isDeepEqual(obj1, obj2)\n\n expect(result.isEqual).toBe(false)\n expect(result.differences).toHaveLength(1)\n expect(result.differences[0]).toEqual({\n path: 'value',\n type: 'different_type',\n expected: 'string',\n actual: 'number',\n })\n })\n })\n})\n\ndescribe('findDifferences', () => {\n it('should find differences between simple objects', () => {\n const obj1 = { a: 1, b: 2 }\n const obj2 = { a: 1, b: 3, c: 4 }\n\n const differences = findDifferences(obj1, obj2)\n\n expect(differences).toHaveLength(2)\n expect(differences).toEqual(\n expect.arrayContaining([\n {\n path: 'b',\n type: 'different_value',\n expected: 2,\n actual: 3,\n },\n {\n path: 'c',\n type: 'missing_key',\n actual: 4,\n },\n ])\n )\n })\n\n it('should respect maxDepth parameter', () => {\n const deep1 = { level1: { level2: { level3: { value: 'a' } } } }\n const deep2 = { level1: { level2: { level3: { value: 'b' } } } }\n\n const differences = findDifferences(deep1, deep2, '', 2)\n\n expect(differences).toHaveLength(0) // Should not find differences beyond maxDepth\n })\n})\n\ndescribe('filterIgnoredDifferences', () => {\n describe('basic filtering', () => {\n it('should return all differences when no ignored differences are provided', () => {\n const differences: ObjectDifference[] = [\n {\n path: 'name',\n type: 'different_value',\n expected: 'John',\n actual: 'Jane',\n },\n { path: 'age', type: 'extra_key', expected: 25 },\n ]\n\n const result = filterIgnoredDifferences(differences, [])\n\n expect(result).toEqual(differences)\n })\n\n it('should return all differences when ignoredDifferences is undefined', () => {\n const differences: ObjectDifference[] = [\n {\n path: 'name',\n type: 'different_value',\n expected: 'John',\n actual: 'Jane',\n },\n { path: 'age', type: 'extra_key', expected: 25 },\n ]\n\n const result = filterIgnoredDifferences(differences)\n\n expect(result).toEqual(differences)\n })\n\n it('should filter out exact path and type matches', () => {\n const differences: ObjectDifference[] = [\n {\n path: 'name',\n type: 'different_value',\n expected: 'John',\n actual: 'Jane',\n },\n { path: 'age', type: 'extra_key', expected: 25 },\n { path: 'email', type: 'missing_key', actual: 'john@example.com' },\n ]\n\n const ignoredDifferences: IgnoredDifference[] = [\n { path: 'age', type: 'extra_key' },\n { path: 'email', type: 'missing_key' },\n ]\n\n const result = filterIgnoredDifferences(differences, ignoredDifferences)\n\n expect(result).toEqual([\n {\n path: 'name',\n type: 'different_value',\n expected: 'John',\n actual: 'Jane',\n },\n ])\n })\n\n it('should not filter out differences with same path but different type', () => {\n const differences: ObjectDifference[] = [\n {\n path: 'value',\n type: 'different_value',\n expected: 'John',\n actual: 'Jane',\n },\n {\n path: 'value',\n type: 'different_type',\n expected: 'string',\n actual: 'number',\n },\n ]\n\n const ignoredDifferences: IgnoredDifference[] = [\n { path: 'value', type: 'different_value' },\n ]\n\n const result = filterIgnoredDifferences(differences, ignoredDifferences)\n\n expect(result).toEqual([\n {\n path: 'value',\n type: 'different_type',\n expected: 'string',\n actual: 'number',\n },\n ])\n })\n\n it('should not filter out differences with same type but different path', () => {\n const differences: ObjectDifference[] = [\n { path: 'name', type: 'extra_key', expected: 'John' },\n { path: 'age', type: 'extra_key', expected: 25 },\n ]\n\n const ignoredDifferences: IgnoredDifference[] = [\n { path: 'name', type: 'extra_key' },\n ]\n\n const result = filterIgnoredDifferences(differences, ignoredDifferences)\n\n expect(result).toEqual([{ path: 'age', type: 'extra_key', expected: 25 }])\n })\n })\n\n describe('array path filtering', () => {\n it('should filter array index paths correctly', () => {\n const differences: ObjectDifference[] = [\n { path: '[0].productReferenceCode', type: 'extra_key', expected: null },\n { path: '[0].brandImageUrl', type: 'extra_key', expected: null },\n {\n path: '[1].productReference',\n type: 'different_value',\n expected: 'ABC',\n actual: 'DEF',\n },\n ]\n\n const ignoredDifferences: IgnoredDifference[] = [\n { path: '[0].productReferenceCode', type: 'extra_key' },\n { path: '[0].brandImageUrl', type: 'extra_key' },\n ]\n\n const result = filterIgnoredDifferences(differences, ignoredDifferences)\n\n expect(result).toEqual([\n {\n path: '[1].productReference',\n type: 'different_value',\n expected: 'ABC',\n actual: 'DEF',\n },\n ])\n })\n\n it('should handle nested array paths', () => {\n const differences: ObjectDifference[] = [\n { path: 'data[0].items[2].specs', type: 'missing_key', actual: {} },\n {\n path: 'data[1].categories[0]',\n type: 'different_value',\n expected: 'A',\n actual: 'B',\n },\n ]\n\n const ignoredDifferences: IgnoredDifference[] = [\n { path: 'data[0].items[2].specs', type: 'missing_key' },\n ]\n\n const result = filterIgnoredDifferences(differences, ignoredDifferences)\n\n expect(result).toEqual([\n {\n path: 'data[1].categories[0]',\n type: 'different_value',\n expected: 'A',\n actual: 'B',\n },\n ])\n })\n })\n\n describe('complex nested paths', () => {\n it('should filter deeply nested object paths', () => {\n const differences: ObjectDifference[] = [\n {\n path: 'user.profile.preferences.theme',\n type: 'different_value',\n expected: 'dark',\n actual: 'light',\n },\n {\n path: 'user.profile.avatar',\n type: 'extra_key',\n expected: 'avatar.jpg',\n },\n {\n path: 'user.settings.notifications',\n type: 'missing_key',\n actual: true,\n },\n ]\n\n const ignoredDifferences: IgnoredDifference[] = [\n { path: 'user.profile.avatar', type: 'extra_key' },\n { path: 'user.settings.notifications', type: 'missing_key' },\n ]\n\n const result = filterIgnoredDifferences(differences, ignoredDifferences)\n\n expect(result).toEqual([\n {\n path: 'user.profile.preferences.theme',\n type: 'different_value',\n expected: 'dark',\n actual: 'light',\n },\n ])\n })\n })\n\n describe('all difference types', () => {\n it('should handle all supported difference types', () => {\n const differences: ObjectDifference[] = [\n { path: 'missing', type: 'missing_key', actual: 'value' },\n { path: 'extra', type: 'extra_key', expected: 'value' },\n {\n path: 'different',\n type: 'different_value',\n expected: 'old',\n actual: 'new',\n },\n {\n path: 'type',\n type: 'different_type',\n expected: 'string',\n actual: 'number',\n },\n {\n path: 'array',\n type: 'array_length_mismatch',\n expected: 3,\n actual: 5,\n },\n ]\n\n const ignoredDifferences: IgnoredDifference[] = [\n { path: 'missing', type: 'missing_key' },\n { path: 'extra', type: 'extra_key' },\n { path: 'type', type: 'different_type' },\n { path: 'array', type: 'array_length_mismatch' },\n ]\n\n const result = filterIgnoredDifferences(differences, ignoredDifferences)\n\n expect(result).toEqual([\n {\n path: 'different',\n type: 'different_value',\n expected: 'old',\n actual: 'new',\n },\n ])\n })\n })\n\n describe('edge cases', () => {\n it('should handle empty differences array', () => {\n const differences: any[] = []\n const ignoredDifferences: IgnoredDifference[] = [\n { path: 'any', type: 'extra_key' },\n ]\n\n const result = filterIgnoredDifferences(differences, ignoredDifferences)\n\n expect(result).toEqual([])\n })\n\n it('should handle empty ignored differences array', () => {\n const differences: ObjectDifference[] = [\n {\n path: 'name',\n type: 'different_value',\n expected: 'John',\n actual: 'Jane',\n },\n ]\n\n const result = filterIgnoredDifferences(differences, [])\n\n expect(result).toEqual(differences)\n })\n\n it('should filter all differences when all are ignored', () => {\n const differences: ObjectDifference[] = [\n {\n path: 'name',\n type: 'different_value',\n expected: 'John',\n actual: 'Jane',\n },\n { path: 'age', type: 'extra_key', expected: 25 },\n ]\n\n const ignoredDifferences: IgnoredDifference[] = [\n { path: 'name', type: 'different_value' },\n { path: 'age', type: 'extra_key' },\n ]\n\n const result = filterIgnoredDifferences(differences, ignoredDifferences)\n\n expect(result).toEqual([])\n })\n })\n})\n\ndescribe('compareApiResults', () => {\n const mockLogger = {\n error: jest.fn(),\n warn: jest.fn(),\n info: jest.fn(),\n debug: jest.fn(),\n account: '',\n workspace: '',\n operationId: '',\n requestId: '',\n traceId: '',\n transactionId: '',\n config: {},\n child: jest.fn(),\n addTags: jest.fn(),\n } as unknown as Logger\n\n let originalMathRandom: () => number\n\n beforeAll(() => {\n // Store original Math.random\n originalMathRandom = Math.random\n })\n\n afterAll(() => {\n // Restore original Math.random\n Math.random = originalMathRandom\n })\n\n beforeEach(() => {\n jest.clearAllMocks()\n // Reset Math.random to original implementation\n Math.random = originalMathRandom\n })\n\n describe('sampling functionality', () => {\n it('should only call func1 when sample is 0', async () => {\n const func1 = jest.fn().mockResolvedValue('result1')\n const func2 = jest.fn().mockResolvedValue('result2')\n\n const result = await compareApiResults(func1, func2, 0, mockLogger)\n\n expect(func1).toHaveBeenCalledTimes(1)\n expect(func2).not.toHaveBeenCalled()\n expect(result).toBe('result1')\n expect(mockLogger.error).not.toHaveBeenCalled()\n })\n\n it('should call both functions when sample is 100', async () => {\n const func1 = jest.fn().mockResolvedValue('result1')\n const func2 = jest.fn().mockResolvedValue('result1')\n\n const result = await compareApiResults(func1, func2, 100, mockLogger)\n\n expect(func1).toHaveBeenCalledTimes(1)\n expect(func2).toHaveBeenCalledTimes(1)\n expect(result).toBe('result1')\n })\n\n it('should only call func1 when Math.random indicates not in sample', async () => {\n // Mock Math.random to return 0.6 (60%), which should be >= 50% sample\n jest.spyOn(Math, 'random').mockImplementation().mockReturnValue(0.6)\n\n const func1 = jest.fn().mockResolvedValue('result1')\n const func2 = jest.fn().mockResolvedValue('result2')\n\n // 50% sample rate, but random returns 60%, so should not be in sample\n const result = await compareApiResults(func1, func2, 50, mockLogger)\n\n expect(func1).toHaveBeenCalledTimes(1)\n expect(func2).not.toHaveBeenCalled()\n expect(result).toBe('result1')\n })\n\n it('should call both functions when Math.random indicates in sample', async () => {\n // Mock Math.random to return 0.3 (30%), which should be < 50% sample\n jest.spyOn(Math, 'random').mockImplementation().mockReturnValue(0.3)\n\n const func1 = jest.fn().mockResolvedValue('result1')\n const func2 = jest.fn().mockResolvedValue('result1')\n\n // 50% sample rate, and random returns 30%, so should be in sample\n const result = await compareApiResults(func1, func2, 50, mockLogger)\n\n expect(func1).toHaveBeenCalledTimes(1)\n expect(func2).toHaveBeenCalledTimes(1)\n expect(result).toBe('result1')\n })\n })\n\n describe('comparison logic when in sample', () => {\n beforeEach(() => {\n // Always be in sample for these tests\n jest.spyOn(Math, 'random').mockImplementation().mockReturnValue(0.1)\n })\n\n it('should return result1 when both functions succeed and results are equal', async () => {\n const func1 = jest.fn().mockResolvedValue({ data: 'test' })\n const func2 = jest.fn().mockResolvedValue({ data: 'test' })\n\n const result = await compareApiResults(func1, func2, 100, mockLogger)\n\n expect(result).toEqual({ data: 'test' })\n expect(mockLogger.error).not.toHaveBeenCalled()\n })\n\n it('should log error when results differ', async () => {\n const func1 = jest.fn().mockResolvedValue({ data: 'test1' })\n const func2 = jest.fn().mockResolvedValue({ data: 'test2' })\n\n const result = await compareApiResults(func1, func2, 100, mockLogger, {\n args: { query: 'test' },\n logPrefix: 'Test API',\n })\n\n expect(result).toEqual({ data: 'test1' })\n expect(mockLogger.error).toHaveBeenCalledWith({\n message: 'Test API: Results differ',\n params: JSON.stringify({ query: 'test' }),\n differences: [\n {\n path: 'data',\n type: 'different_value',\n expected: 'test1',\n actual: 'test2',\n },\n ],\n differenceCount: 1,\n totalDifferences: 1,\n ignoredDifferences: 0,\n })\n })\n\n it('should return result2 when func1 errors but func2 succeeds', async () => {\n const func1 = jest.fn().mockRejectedValue(new Error('func1 error'))\n const func2 = jest.fn().mockResolvedValue({ data: 'test2' })\n\n const result = await compareApiResults(func1, func2, 100, mockLogger)\n\n expect(result).toEqual({ data: 'test2' })\n })\n\n it('should throw error when both functions fail', async () => {\n const func1 = jest.fn().mockRejectedValue(new Error('func1 error'))\n const func2 = jest.fn().mockRejectedValue(new Error('func2 error'))\n\n await expect(\n compareApiResults(func1, func2, 100, mockLogger)\n ).rejects.toThrow('Both calls resulted in errors')\n })\n })\n\n describe('ignored differences functionality', () => {\n beforeEach(() => {\n // Always be in sample for these tests\n jest.spyOn(Math, 'random').mockImplementation().mockReturnValue(0.1)\n })\n\n it('should consider results equal when all differences are ignored', async () => {\n const func1 = jest.fn().mockResolvedValue({\n name: 'John',\n age: 25,\n extra: 'field',\n })\n\n const func2 = jest.fn().mockResolvedValue({\n name: 'Jane',\n age: 30,\n })\n\n const ignoredDifferences: IgnoredDifference[] = [\n { path: 'name', type: 'different_value' },\n { path: 'age', type: 'different_value' },\n { path: 'extra', type: 'extra_key' },\n ]\n\n const result = await compareApiResults(func1, func2, 100, mockLogger, {\n ignoredDifferences,\n logPrefix: 'Test API',\n })\n\n expect(result).toEqual({ name: 'John', age: 25, extra: 'field' })\n expect(mockLogger.error).not.toHaveBeenCalled()\n expect(mockLogger.info).toHaveBeenCalledWith({\n message: 'Test API: Results are equal',\n params: undefined,\n totalDifferences: 3,\n ignoredDifferences: 3,\n })\n })\n\n it('should log differences after filtering out ignored ones', async () => {\n const func1 = jest.fn().mockResolvedValue([\n {\n productReferenceCode: null,\n brandImageUrl: null,\n name: 'Product A',\n price: 100,\n },\n ])\n\n const func2 = jest.fn().mockResolvedValue([\n {\n name: 'Product B',\n price: 150,\n },\n ])\n\n const ignoredDifferences: IgnoredDifference[] = [\n { path: '[0].productReferenceCode', type: 'extra_key' },\n { path: '[0].brandImageUrl', type: 'extra_key' },\n ]\n\n const result = await compareApiResults(func1, func2, 100, mockLogger, {\n ignoredDifferences,\n args: { query: 'test product' },\n logPrefix: 'Product API',\n })\n\n expect(result).toEqual([\n {\n productReferenceCode: null,\n brandImageUrl: null,\n name: 'Product A',\n price: 100,\n },\n ])\n\n expect(mockLogger.error).toHaveBeenCalledWith({\n message: 'Product API: Results differ',\n params: JSON.stringify({ query: 'test product' }),\n differences: [\n {\n path: '[0].name',\n type: 'different_value',\n expected: 'Product A',\n actual: 'Product B',\n },\n {\n path: '[0].price',\n type: 'different_value',\n expected: 100,\n actual: 150,\n },\n ],\n differenceCount: 2,\n totalDifferences: 4,\n ignoredDifferences: 2,\n })\n })\n\n it('should work with complex nested paths as in the example', async () => {\n const func1 = jest.fn().mockResolvedValue([\n {\n productReferenceCode: null,\n brandImageUrl: null,\n releaseDate: '2023-12-01',\n clusterHighlights: { '259': 'Solução Completa' },\n productClusters: { '260': 'Campanha' },\n searchableClusters: {\n '259': 'Solução Completa',\n '260': 'Campanha Pais Colaborador',\n },\n categories: [\n '/Segurança eletrônica/Câmeras de segurança/Câmeras Wi-fi/',\n ],\n categoriesIds: ['/2/33/101/'],\n },\n ])\n\n const func2 = jest.fn().mockResolvedValue([\n {\n releaseDate: 1702857600,\n clusterHighlights: ['Solução Completa'],\n productClusters: ['Campanha'],\n categories: ['/Segurança eletrônica/'],\n categoriesIds: ['2'],\n },\n ])\n\n const ignoredDifferences: IgnoredDifference[] = [\n { path: '[0].productReferenceCode', type: 'extra_key' },\n { path: '[0].brandImageUrl', type: 'extra_key' },\n { path: '[0].searchableClusters', type: 'extra_key' },\n { path: '[0].releaseDate', type: 'different_type' },\n { path: '[0].clusterHighlights', type: 'different_type' },\n { path: '[0].productClusters', type: 'different_type' },\n ]\n\n const result = await compareApiResults(func1, func2, 100, mockLogger, {\n ignoredDifferences,\n logPrefix: 'Complex Product API',\n })\n\n expect(result).toBeDefined()\n // Should still log errors for categories and categoriesIds differences\n expect(mockLogger.error).toHaveBeenCalledWith(\n expect.objectContaining({\n message: 'Complex Product API: Results differ',\n differenceCount: 2, // Only categories and categoriesIds differences remain\n totalDifferences: 8, // Total before filtering\n ignoredDifferences: 6, // Number filtered out\n })\n )\n })\n\n it('should handle empty ignored differences array', async () => {\n const func1 = jest.fn().mockResolvedValue({ name: 'John' })\n const func2 = jest.fn().mockResolvedValue({ name: 'Jane' })\n\n const result = await compareApiResults(func1, func2, 100, mockLogger, {\n ignoredDifferences: [],\n })\n\n expect(result).toEqual({ name: 'John' })\n expect(mockLogger.error).toHaveBeenCalled()\n })\n\n it('should handle undefined ignored differences', async () => {\n const func1 = jest.fn().mockResolvedValue({ name: 'John' })\n const func2 = jest.fn().mockResolvedValue({ name: 'Jane' })\n\n const result = await compareApiResults(func1, func2, 100, mockLogger, {\n // No ignoredDifferences property\n })\n\n expect(result).toEqual({ name: 'John' })\n expect(mockLogger.error).toHaveBeenCalled()\n })\n\n it('should handle mixed difference types in ignored differences', async () => {\n const func1 = jest.fn().mockResolvedValue({\n user: {\n name: 'John',\n avatar: 'avatar.jpg',\n settings: { theme: 'dark' },\n },\n items: [1, 2, 3],\n })\n\n const func2 = jest.fn().mockResolvedValue({\n user: {\n name: 'John',\n settings: { theme: 'light', notifications: true },\n },\n items: [1, 2],\n })\n\n const ignoredDifferences: IgnoredDifference[] = [\n { path: 'user.avatar', type: 'extra_key' },\n { path: 'user.settings.notifications', type: 'missing_key' },\n { path: 'items', type: 'array_length_mismatch' },\n { path: 'items[2]', type: 'extra_key' },\n ]\n\n const result = await compareApiResults(func1, func2, 100, mockLogger, {\n ignoredDifferences,\n logPrefix: 'Mixed Types API',\n })\n\n expect(result).toBeDefined()\n // Should still have one difference for theme\n expect(mockLogger.error).toHaveBeenCalledWith(\n expect.objectContaining({\n message: 'Mixed Types API: Results differ',\n differenceCount: 1, // Only theme difference remains\n totalDifferences: 5, // Total before filtering\n ignoredDifferences: 4, // Number filtered out\n })\n )\n })\n })\n})\n\n```" } ]
code_search-resolver_a3a9611d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/utils/categoryTreeSearch.test.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport * as TypeMoq from 'typemoq'\nimport { CategoryTreeSegmentsFinder } from \"./CategoryTreeSegmentsFinder\"\nimport { VBase, IOContext } from \"@vtex/api\"\nimport { Search } from \"../clients/search\"\n\n/* CategoryTree \n * c0 \n * / \\ \n * c1 c2 \n * / \\ \n * c3 c4\n * \\\n * c5\n */\n\nconst context = TypeMoq.Mock.ofType<IOContext>()\nconst vbaseMock = TypeMoq.Mock.ofInstance(VBase)\nconst searchMock = TypeMoq.Mock.ofInstance(Search)\n\nconst c5 = {'c5': '5'}\nconst c4 = {'c4': '4'}\nconst c3 = {'c3': '3'}\nconst c2 = {'c2': '2'}\nconst c1 = { 'c1': '1'}\nconst c0 = { 'c0': '0' }\nconst root = {'c0': {id: 0, name: 'c0', hasChildren: true}}\n\nconst childrenTree = {\n \"0\": {...c1, ...c2},\n \"1\": {...c3, ...c4},\n \"2\": {},\n \"3\": {},\n \"4\": {...c5},\n \"5\": {}\n} as any\n\nconst clients = {vbase: new vbaseMock.object(context.object), search: new searchMock.object(context.object) }\n\nconst toPair = (categories: any[]) => \n categories.map(c => {\n const [key, value] = c && Object.entries(c)[0] || []\n return key? { id: value, name: key }: null\n })\n\ndescribe('Category Tree Search tests', () => {\n const finder = class CategoryTreeSegmentsFinderMock extends CategoryTreeSegmentsFinder {\n public constructor(segments: string[]){\n super(clients, segments)\n this.categoryTreeRoot = root\n }\n\n protected lazyFetchChildren = async (id: number) => {\n const children = childrenTree[id.toString()]\n return children\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n protected staleWhileRevalidate = async <T>(_: string, __: string, func: (params?: any) => Promise<T>, params?: any) => {\n return func(params)\n }\n\n protected getCategoryTreeRoot = () => {\n return this.categoryTreeRoot as any\n }\n }\n test('It should find a complete tree of categories', async () => {\n const segments = 'c0/c1/c4'.split('/')\n const treeFinder = new finder(segments)\n const result = await treeFinder.find()\n expect(result).toStrictEqual(toPair([c0, c1, c4]))\n })\n\n test('It should find the maximum categories possible ', async () => {\n const segments = 'c0/c1/c2'.split('/')\n const treeFinder = new finder(segments)\n const result = await treeFinder.find()\n expect(result).toStrictEqual(toPair([c0, c1, null]))\n })\n\n test('It should not find when doesnt exist', async () => {\n const segments = 'x/c1/c4'.split('/')\n const treeFinder = new finder(segments)\n const result = await treeFinder.find()\n expect(result).toStrictEqual([])\n })\n})\n```" } ]
code_search-resolver_ebb449ca
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/index.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { fieldResolvers as benefitsFieldResolvers } from './benefits'\nimport {\n fieldResolvers as searchFieldResolvers,\n queries as searchQueries,\n} from './search'\nimport { queries as statsQueries } from './stats'\n\nexport const resolvers = {\n ...searchFieldResolvers,\n ...benefitsFieldResolvers,\n Query: {\n ...searchQueries,\n ...statsQueries,\n },\n}\n\n```" } ]
code_search-resolver_7bb833a5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/routes/workspaceSearchParams.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nconst BUCKET = 'workspace-search-params'\nconst MASTER = 'master'\n\nfunction disableCache(ctx: Context) {\n ctx.set('Cache-control', 'no-cache,no-store')\n}\n\nexport async function getWorkspaceSearchParamsFromStorage(ctx: Context) { \n const masterParams = await ctx.clients.vbase.getJSON<object>(BUCKET, MASTER, true)\n if (ctx.vtex.workspace == MASTER) return masterParams\n const filePath = ctx.vtex.workspace\n const params = await ctx.clients.vbase.getJSON<object>(BUCKET, filePath, true)\n // Logic: workspaces inherit params from master, and can override as desired\n return {\n ...masterParams,\n ...params\n }\n}\n\nexport async function getWorkspaceSearchParams(ctx: Context, next: () => Promise<object>) {\n const data = await getWorkspaceSearchParamsFromStorage(ctx)\n disableCache(ctx)\n ctx.body = data\n ctx.status = 200\n await next()\n}\n\nexport async function setWorkspaceSearchParams(ctx: Context, next: () => Promise<object>) {\n const filePath = ctx.vtex.workspace\n await ctx.clients.vbase.saveJSON<object>(BUCKET, filePath, ctx.query)\n disableCache(ctx)\n ctx.body = ctx.query\n ctx.status = 200\n await next()\n}\n\n```" } ]
code_search-resolver_8f45618d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/services/facets.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { buildAttributePath } from '../commons/compatibility-layer'\nimport { compareApiResults } from '../utils/compareResults'\nimport { fetchAppSettings } from './settings'\nimport type { FacetsInput } from '../typings/Search'\nimport { decodeQuery } from '../clients/intelligent-search-api'\nimport { parseState } from '../utils/searchState'\n\n/**\n * Builds a query string from an object of params, filtering out undefined/null values\n */\nfunction buildQueryString(params: Record<string, any>): string {\n const searchParams = new URLSearchParams()\n\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined && value !== null && value !== '') {\n searchParams.append(key, String(value))\n }\n }\n\n return searchParams.toString()\n}\n\n/**\n * Builds curl commands for debugging API requests\n */\nfunction buildCurlCommands(\n ctx: Context,\n path: string,\n params: Record<string, any>,\n shippingOptions?: string[]\n): { biggyCurl: string; intschCurl: string } {\n const { workspace, account } = ctx.vtex\n const queryString = buildQueryString(params)\n const shippingHeader = shippingOptions?.length\n ? ` -H \"x-vtex-shipping-options: ${shippingOptions.join(',')}\"`\n : ''\n\n const biggyCurl = `curl \"https://${workspace}--${account}.myvtex.com/_v/api/intelligent-search/facets/${path}?${queryString}\"${shippingHeader}`\n const intschCurl = `curl \"https://${account}.myvtex.com/api/intelligent-search/v0/facets/${path}?${queryString}\"${shippingHeader}`\n\n return { biggyCurl, intschCurl }\n}\n\ntype FetchFacetsOptions = {\n args: FacetsInput\n selectedFacets: SelectedFacet[]\n shippingOptions?: string[]\n}\n\n/**\n * Fetches facets using the intelligentSearchApi client (Biggy)\n */\nasync function fetchFacetsFromBiggy(ctx: Context, options: FetchFacetsOptions) {\n const { args, selectedFacets, shippingOptions } = options\n const {\n clients: { intelligentSearchApi },\n } = ctx\n\n const biggyArgs: { [key: string]: any } = {\n ...args,\n }\n\n // unnecessary field. It's is an object and breaks the @vtex/api cache\n delete biggyArgs.selectedFacets\n\n const result: any = await intelligentSearchApi.facets(\n { ...biggyArgs, query: args.fullText },\n buildAttributePath(selectedFacets),\n shippingOptions\n )\n\n if (ctx.vtex.tenant) {\n ctx.translated = result.translated\n }\n\n return result\n}\n\n/**\n * Fetches facets using the intsch client (Intelligent Search)\n */\nasync function fetchFacetsFromIntsch(\n ctx: Context,\n options: FetchFacetsOptions\n) {\n const { args, selectedFacets, shippingOptions } = options\n const {\n clients: { intsch },\n } = ctx\n\n const intschArgs: { [key: string]: any } = {\n ...args,\n }\n\n // unnecessary field. It's is an object and breaks the @vtex/api cache\n delete intschArgs.selectedFacets\n\n const result: any = await intsch.facets(\n { ...intschArgs, query: args.fullText },\n buildAttributePath(selectedFacets),\n shippingOptions\n )\n\n if (ctx.vtex.tenant) {\n ctx.translated = result.translated\n }\n\n return result\n}\n\n/**\n * Facets service that extracts facets fetching logic and implements comparison or flag-based routing\n */\nexport async function fetchFacets(ctx: Context, options: FetchFacetsOptions) {\n const { args, selectedFacets, shippingOptions } = options\n const { shouldUseNewPLPEndpoint } = await fetchAppSettings(ctx)\n\n // If flag is explicitly true, use intsch\n if (shouldUseNewPLPEndpoint) {\n return fetchFacetsFromIntsch(ctx, options)\n }\n\n // Build the exact request params as the clients do for debugging\n const path = buildAttributePath(selectedFacets)\n const clientArgs: { [key: string]: any } = { ...args }\n\n delete clientArgs.selectedFacets\n\n const query = args.fullText\n const { leap, searchState } = args as { leap?: boolean; searchState?: string }\n\n const requestParams = {\n ...clientArgs,\n query: query && decodeQuery(query),\n locale: ctx.vtex.locale ?? ctx.vtex.tenant?.locale,\n bgy_leap: leap ? true : undefined,\n ...parseState(searchState),\n }\n\n const { biggyCurl, intschCurl } = buildCurlCommands(\n ctx,\n path,\n requestParams,\n shippingOptions\n )\n\n // If flag is undefined, compare both APIs\n return compareApiResults(\n () => fetchFacetsFromBiggy(ctx, options),\n () => fetchFacetsFromIntsch(ctx, options),\n ctx.vtex.production ? 1 : 100,\n ctx.vtex.logger,\n {\n logPrefix: 'Facets',\n args: {\n biggyCurl,\n intschCurl,\n },\n }\n )\n}\n\n```" } ]
code_search-resolver_c9f5f21f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/services/autocomplete.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport function fetchAutocompleteSuggestions(ctx: Context, query: string) {\n const { intsch } = ctx.clients\n\n const args = { query }\n\n const locale = (ctx.vtex.segment?.cultureInfo ??\n ctx.vtex.tenant?.locale ??\n ctx.vtex.locale) as string\n\n return intsch.fetchAutocompleteSuggestionsV1({ ...args, locale })\n}\n\nexport function fetchTopSearches(ctx: Context) {\n const { intsch } = ctx.clients\n\n const locale = (ctx.vtex.segment?.cultureInfo ??\n ctx.vtex.tenant?.locale ??\n ctx.vtex.locale) as string\n\n return intsch.fetchTopSearchesV1(locale)\n}\n\nexport function fetchSearchSuggestions(ctx: Context, query: string) {\n const { intsch } = ctx.clients\n\n const args = { query }\n\n const locale = (ctx.vtex.segment?.cultureInfo ??\n ctx.vtex.tenant?.locale ??\n ctx.vtex.locale) as string\n\n return intsch.fetchSearchSuggestionsV1({ ...args, locale })\n}\n\nexport function fetchCorrection(ctx: Context, query: string) {\n const { intsch } = ctx.clients\n\n const args = { query }\n\n const locale = (ctx.vtex.segment?.cultureInfo ??\n ctx.vtex.tenant?.locale ??\n ctx.vtex.locale) as string\n\n return intsch.fetchCorrectionV1({ ...args, locale })\n}\n\n```" } ]
code_search-resolver_1732d944
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/services/productSearch.test.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { fetchProductSearch } from './productSearch'\nimport { createContext } from '../mocks/contextFactory'\nimport type { ProductSearchInput } from '../typings/Search'\nimport * as compareResultsModule from '../utils/compareResults'\n\ndescribe('fetchProductSearch service', () => {\n const mockProductSearchResponse = {\n products: [] as any,\n recordsFiltered: 2,\n }\n\n const mockArgs: ProductSearchInput = {\n fullText: 'test query',\n query: 'test',\n map: 'ft',\n selectedFacets: [],\n orderBy: 'OrderByTopSaleDESC',\n from: 0,\n to: 10,\n fuzzy: '0',\n operator: 'and',\n productOriginVtex: false,\n simulationBehavior: 'default',\n hideUnavailableItems: false,\n }\n\n const mockSelectedFacets: SelectedFacet[] = []\n\n beforeEach(() => {\n jest.clearAllMocks()\n })\n\n it('should use intsch when shouldUseNewPLPEndpoint is true', async () => {\n const ctx = createContext({\n accountName: 'testaccount',\n appSettings: {\n shouldUseNewPLPEndpoint: true,\n },\n intschSettings: {\n productSearch: mockProductSearchResponse,\n },\n })\n\n const result = await fetchProductSearch(ctx, mockArgs, mockSelectedFacets)\n\n expect(ctx.clients.intsch.productSearch).toHaveBeenCalled()\n expect(\n ctx.clients.intelligentSearchApi.productSearch\n ).not.toHaveBeenCalled()\n expect(result).toEqual({\n searchState: undefined,\n ...mockProductSearchResponse,\n })\n })\n\n it('should compare both APIs when shouldUseNewPLPEndpoint is undefined', async () => {\n const ctx = createContext({\n accountName: 'testaccount',\n appSettings: {\n shouldUseNewPLPEndpoint: undefined,\n },\n intelligentSearchApiSettings: {\n productSearch: mockProductSearchResponse,\n },\n intschSettings: {\n productSearch: mockProductSearchResponse,\n },\n })\n\n const mockResult = {\n searchState: undefined,\n ...mockProductSearchResponse,\n }\n\n const compareApiResultsSpy = jest\n .spyOn(compareResultsModule, 'compareApiResults')\n .mockResolvedValue(mockResult)\n\n const result = await fetchProductSearch(ctx, mockArgs, mockSelectedFacets)\n\n expect(compareApiResultsSpy).toHaveBeenCalled()\n expect(result).toEqual(mockResult)\n\n compareApiResultsSpy.mockRestore()\n })\n\n it('should handle shipping options correctly', async () => {\n const ctx = createContext({\n accountName: 'testaccount',\n appSettings: {\n shouldUseNewPLPEndpoint: false,\n },\n intelligentSearchApiSettings: {\n productSearch: mockProductSearchResponse,\n },\n })\n\n const shippingOptions = ['delivery', 'pickup']\n\n await fetchProductSearch(ctx, mockArgs, mockSelectedFacets, shippingOptions)\n\n expect(ctx.clients.intelligentSearchApi.productSearch).toHaveBeenCalledWith(\n expect.objectContaining({ query: 'test query' }),\n expect.any(String),\n shippingOptions\n )\n })\n\n it('should preserve searchState in response', async () => {\n const ctx = createContext({\n accountName: 'testaccount',\n appSettings: {\n shouldUseNewPLPEndpoint: false,\n },\n intelligentSearchApiSettings: {\n productSearch: mockProductSearchResponse,\n },\n })\n\n const argsWithSearchState = {\n ...mockArgs,\n searchState: 'test-search-state',\n }\n\n const result = await fetchProductSearch(\n ctx,\n argsWithSearchState,\n mockSelectedFacets\n )\n\n expect(result.searchState).toBe('test-search-state')\n })\n\n it('should set translated flag in context when tenant is present and productOriginVtex is false', async () => {\n const mockResponseWithTranslated = {\n ...mockProductSearchResponse,\n translated: true,\n } as any\n\n const ctx = createContext({\n accountName: 'testaccount',\n appSettings: {\n shouldUseNewPLPEndpoint: false,\n },\n intelligentSearchApiSettings: {\n productSearch: mockResponseWithTranslated,\n },\n tenantLocale: 'en-US',\n })\n\n await fetchProductSearch(ctx, mockArgs, mockSelectedFacets)\n\n expect(ctx.translated).toBe(true)\n })\n\n it('should not set translated flag when productOriginVtex is true', async () => {\n const mockResponseWithTranslated = {\n ...mockProductSearchResponse,\n translated: true,\n } as any\n\n const ctx = createContext({\n accountName: 'testaccount',\n appSettings: {\n shouldUseNewPLPEndpoint: false,\n },\n intelligentSearchApiSettings: {\n productSearch: mockResponseWithTranslated,\n },\n tenantLocale: 'en-US',\n })\n\n const argsWithProductOriginVtex = {\n ...mockArgs,\n productOriginVtex: true,\n }\n\n await fetchProductSearch(ctx, argsWithProductOriginVtex, mockSelectedFacets)\n\n expect(ctx.translated).toBeUndefined()\n })\n\n it('should include advertisement options in the request', async () => {\n const ctx = createContext({\n accountName: 'testaccount',\n appSettings: {\n shouldUseNewPLPEndpoint: false,\n },\n intelligentSearchApiSettings: {\n productSearch: mockProductSearchResponse,\n },\n })\n\n const argsWithAdOptions = {\n ...mockArgs,\n advertisementOptions: {\n showSponsored: true,\n sponsoredCount: 5,\n repeatSponsoredProducts: false,\n },\n }\n\n await fetchProductSearch(ctx, argsWithAdOptions, mockSelectedFacets)\n\n expect(ctx.clients.intelligentSearchApi.productSearch).toHaveBeenCalledWith(\n expect.objectContaining({\n showSponsored: true,\n sponsoredCount: 5,\n repeatSponsoredProducts: false,\n }),\n expect.any(String),\n undefined\n )\n })\n})\n\n```" } ]
code_search-resolver_e96824b0
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/services/product.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { SegmentData } from '../typings/Search'\nimport { fetchAppSettings } from './settings'\n\nexport type ProductIdentifier = {\n field: 'id' | 'slug' | 'ean' | 'reference' | 'sku'\n value: string\n}\n\nexport type ProductArgs = {\n slug?: string\n identifier?: ProductIdentifier\n regionId?: string\n salesChannel?: number\n}\n\ninterface FetchProductArgs {\n identifier: ProductIdentifier\n salesChannel?: number | null\n regionId?: string\n vtexSegment?: string\n}\n\n/**\n * Product service that extracts product fetching logic and implements compareApiResults\n * using search client as primary and intsch.fetchProduct as secondary\n */\n\n/**\n * Fetches a product using the search client with different identifier types\n */\nasync function fetchProductFromSearch(\n ctx: Context,\n args: FetchProductArgs\n): Promise<SearchProduct[]> {\n const { search } = ctx.clients\n const { identifier, salesChannel, vtexSegment } = args\n const { field, value } = identifier\n\n switch (field) {\n case 'id':\n return search.productById(value, vtexSegment, salesChannel)\n\n case 'slug':\n return search.product(value, vtexSegment, salesChannel)\n\n case 'ean':\n return search.productByEan(value, vtexSegment, salesChannel)\n\n case 'reference':\n return search.productByReference(value, vtexSegment, salesChannel)\n\n case 'sku':\n return search.productBySku(value, vtexSegment, salesChannel)\n\n default:\n throw new Error(`Unsupported product identifier field: ${field}`)\n }\n}\n\n/**\n * Fetches a product using the intsch client\n */\nasync function fetchProductFromIntsch(\n ctx: Context,\n args: FetchProductArgs\n): Promise<SearchProduct[]> {\n const { intsch } = ctx.clients\n const { identifier, salesChannel, regionId, vtexSegment } = args\n const { field, value } = identifier\n\n // Get locale from context (fallback)\n const defaultLocale = ctx.vtex.tenant?.locale ?? ctx.vtex.locale\n\n // Default salesChannel from args\n let finalSalesChannel = salesChannel ? `${salesChannel}` : undefined\n let finalLocale = defaultLocale\n\n // Parse vtexSegment if available to extract locale and salesChannel\n if (vtexSegment) {\n try {\n const segmentData: SegmentData = JSON.parse(\n Buffer.from(vtexSegment, 'base64').toString()\n )\n\n // Use segment's salesChannel if available, otherwise use the provided one\n if (segmentData.channel) {\n finalSalesChannel = segmentData.channel\n }\n\n // Use segment's locale (cultureInfo) if available, otherwise use default\n if (segmentData.cultureInfo) {\n finalLocale = segmentData.cultureInfo\n }\n } catch (error) {\n // If parsing fails, continue with defaults\n ctx.vtex.logger.warn({\n message: 'Failed to parse vtexSegment token, using defaults',\n error: error.message,\n vtexSegment,\n })\n }\n }\n\n const product = await intsch.fetchProduct({\n field,\n value,\n salesChannel: finalSalesChannel?.toString(),\n regionId,\n locale: finalLocale,\n })\n\n // intsch.fetchProduct returns a single SearchProduct, but we need to return an array\n // to match the search client interface\n return product ? [product] : []\n}\n\n/**\n * Builds vtex segment token for product fetching\n */\n\nexport function buildVtexSegment({\n vtexSegment,\n salesChannel,\n regionId,\n}: {\n vtexSegment?: SegmentData\n salesChannel?: string\n regionId?: string\n}): string {\n const cookie = {\n ...vtexSegment,\n regionId: regionId ?? vtexSegment?.regionId,\n channel: salesChannel ?? vtexSegment?.channel,\n }\n\n return Buffer.from(JSON.stringify(cookie)).toString('base64')\n}\n\nexport async function fetchProduct(\n ctx: Context,\n args: FetchProductArgs\n): Promise<SearchProduct[]> {\n const { shouldUseNewPDPEndpoint } = await fetchAppSettings(ctx)\n\n // Check if current account should skip comparison and use intsch directly\n if (shouldUseNewPDPEndpoint) {\n ctx.translated = true\n return fetchProductFromIntsch(ctx, args)\n }\n\n return fetchProductFromSearch(ctx, args)\n}\n\n/**\n * Helper function to validate product identifier\n */\nexport function isValidProductIdentifier(\n identifier: ProductIdentifier | undefined\n): identifier is ProductIdentifier {\n return (\n identifier?.field !== undefined &&\n identifier.value !== undefined &&\n ['id', 'slug', 'ean', 'reference', 'sku'].includes(identifier.field)\n )\n}\n\nexport async function resolveProduct(\n ctx: Context,\n rawArgs: ProductArgs\n): Promise<SearchProduct | null> {\n const args =\n rawArgs && isValidProductIdentifier(rawArgs.identifier)\n ? rawArgs\n : { identifier: { field: 'slug', value: rawArgs.slug ?? '' } }\n\n if (!args.identifier?.value) {\n throw new Error('No product identifier provided')\n }\n\n const cookie: SegmentData | undefined = ctx.vtex.segment as\n | SegmentData\n | undefined\n\n const { salesChannel } = rawArgs\n\n const vtexSegment =\n !cookie || (!cookie?.regionId && rawArgs.regionId)\n ? buildVtexSegment({\n vtexSegment: ctx.vtex.segment as SegmentData | undefined,\n salesChannel: rawArgs.salesChannel?.toString(),\n regionId: rawArgs.regionId,\n })\n : ctx.vtex.segmentToken\n\n const fetchArgs: FetchProductArgs = {\n identifier: args.identifier as ProductIdentifier,\n salesChannel,\n regionId: rawArgs.regionId,\n vtexSegment,\n }\n\n try {\n const products = await fetchProduct(ctx, fetchArgs)\n\n if (!products || products.length === 0) {\n return null\n }\n\n const [product] = products\n\n return product\n } catch (error) {\n ctx.vtex.logger.error({\n message: 'Error fetching product',\n error: error.message,\n args: fetchArgs,\n })\n throw error\n }\n}\n\nexport type ProductsByIdentifierArgs = {\n field: 'id' | 'ean' | 'reference' | 'sku'\n values: string[]\n salesChannel?: string | null\n regionId?: string | null\n}\n\n/**\n * Fetches multiple products by identifier using the search client\n */\nasync function fetchProductsByIdentifierFromSearch(\n ctx: Context,\n args: ProductsByIdentifierArgs,\n vtexSegment?: string\n): Promise<SearchProduct[]> {\n const { search } = ctx.clients\n const { field, values, salesChannel } = args\n\n switch (field) {\n case 'id':\n return search.productsById(values, vtexSegment, salesChannel)\n\n case 'ean':\n return search.productsByEan(values, vtexSegment, salesChannel)\n\n case 'reference':\n return search.productsByReference(values, vtexSegment, salesChannel)\n\n case 'sku':\n return search.productsBySku(values, vtexSegment, salesChannel)\n\n default:\n throw new Error(`Unsupported product identifier field: ${field}`)\n }\n}\n\n/**\n * Fetches multiple products by identifier using the intsch client\n */\nasync function fetchProductsByIdentifierFromIntsch(\n ctx: Context,\n args: ProductsByIdentifierArgs,\n vtexSegment?: string\n): Promise<SearchProduct[]> {\n const { intsch } = ctx.clients\n const { field, values, salesChannel, regionId } = args\n\n // Get locale from context (fallback)\n const defaultLocale = ctx.vtex.tenant?.locale ?? ctx.vtex.locale\n\n // Default salesChannel from args\n let finalSalesChannel = salesChannel ? `${salesChannel}` : undefined\n let finalLocale = defaultLocale\n\n // Parse vtexSegment if available to extract locale and salesChannel\n if (vtexSegment) {\n try {\n const segmentData: SegmentData = JSON.parse(\n Buffer.from(vtexSegment, 'base64').toString()\n )\n\n // Use segment's salesChannel if available, otherwise use the provided one\n if (segmentData.channel) {\n finalSalesChannel = segmentData.channel\n }\n\n // Use segment's locale (cultureInfo) if available, otherwise use default\n if (segmentData.cultureInfo) {\n finalLocale = segmentData.cultureInfo\n }\n } catch (error) {\n // If parsing fails, continue with defaults\n ctx.vtex.logger.warn({\n message: 'Failed to parse vtexSegment token, using defaults',\n error: error.message,\n vtexSegment,\n })\n }\n }\n\n // Fetch all products in parallel\n const productPromises = values.map((value) =>\n intsch.fetchProduct({\n field,\n value,\n salesChannel: finalSalesChannel?.toString(),\n regionId: regionId ?? undefined,\n locale: finalLocale,\n })\n )\n\n const products = await Promise.all(productPromises)\n\n return products as SearchProduct[]\n}\n\nexport async function resolveProductsByIdentifier(\n ctx: Context,\n args: ProductsByIdentifierArgs\n): Promise<SearchProduct[]> {\n const vtexSegment =\n !ctx.vtex.segment || (!ctx.vtex.segment?.regionId && args.regionId)\n ? buildVtexSegment({\n vtexSegment: ctx.vtex.segment as SegmentData | undefined,\n salesChannel: args.salesChannel?.toString(),\n regionId: args.regionId ?? undefined,\n })\n : ctx.vtex.segmentToken\n\n const { shouldUseNewPDPEndpoint } = await fetchAppSettings(ctx)\n\n try {\n let products: SearchProduct[]\n\n // Check if current account should use intsch directly\n if (shouldUseNewPDPEndpoint) {\n products = await fetchProductsByIdentifierFromIntsch(\n ctx,\n args,\n vtexSegment\n )\n } else {\n products = await fetchProductsByIdentifierFromSearch(\n ctx,\n args,\n vtexSegment\n )\n }\n\n return products\n } catch (error) {\n ctx.vtex.logger.error({\n message: 'Error fetching products by identifier',\n error: error.message,\n args,\n })\n throw error\n }\n}\n\n```" } ]
code_search-resolver_1bfe2178
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/services/settings.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ntype AppSettings = {\n shouldUseNewPDPEndpoint: boolean\n shouldUseNewPLPEndpoint: boolean\n}\n\nexport async function fetchAppSettings(ctx: Context): Promise<AppSettings> {\n const {\n clients: { apps },\n } = ctx\n\n try {\n const { shouldUseNewPDPEndpoint, shouldUseNewPLPEndpoint }: AppSettings =\n await apps.getAppSettings('vtex.search-resolver@1.x')\n\n return {\n shouldUseNewPDPEndpoint,\n shouldUseNewPLPEndpoint,\n }\n } catch (error) {\n ctx.vtex.logger.error({\n message: 'Error fetching app settings',\n error: error.message,\n })\n\n return {\n shouldUseNewPDPEndpoint: false,\n shouldUseNewPLPEndpoint: false,\n }\n }\n}\n\n```" } ]
code_search-resolver_5732305d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/services/autocomplete.test.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n fetchAutocompleteSuggestions,\n fetchTopSearches,\n fetchSearchSuggestions,\n fetchCorrection,\n} from './autocomplete'\nimport { createContext } from '../mocks/contextFactory'\n\ndescribe('fetchAutocompleteSuggestions', () => {\n beforeEach(() => {\n jest.clearAllMocks()\n })\n\n it('should call intsch and return its result when successful', async () => {\n const intschResult = {\n searches: [{ term: 'test', count: 1 }],\n }\n\n const ctx = createContext({\n intschSettings: {\n fetchAutocompleteSuggestionsV1: intschResult,\n },\n })\n\n const result = await fetchAutocompleteSuggestions(ctx, 'test')\n\n expect(\n ctx.clients.intsch.fetchAutocompleteSuggestionsV1\n ).toHaveBeenCalledWith({\n query: 'test',\n locale: undefined,\n })\n\n expect(result).toEqual(intschResult)\n })\n\n it('should throw error when intsch fails', async () => {\n const ctx = createContext({\n intschSettings: {\n fetchAutocompleteSuggestionsV1: new Error('Service unavailable'),\n },\n })\n\n await expect(fetchAutocompleteSuggestions(ctx, 'test')).rejects.toThrow(\n 'Service unavailable'\n )\n\n expect(\n ctx.clients.intsch.fetchAutocompleteSuggestionsV1\n ).toHaveBeenCalledWith({\n query: 'test',\n locale: undefined,\n })\n })\n\n it('should use locale from segment cultureInfo when available', async () => {\n const intschResult = {\n searches: [{ term: 'test-result', count: 1 }],\n }\n\n const ctx = createContext({\n intschSettings: {\n fetchAutocompleteSuggestionsV1: intschResult,\n },\n segment: {\n campaigns: null,\n channel: '1',\n priceTables: null,\n utm_campaign: null,\n utm_source: null,\n utmi_campaign: null,\n currencyCode: 'BRL',\n currencySymbol: 'R$',\n countryCode: 'BRA',\n cultureInfo: 'pt-BR',\n },\n tenantLocale: 'en-US',\n vtexLocale: 'es-ES',\n })\n\n await fetchAutocompleteSuggestions(ctx, 'test')\n\n expect(\n ctx.clients.intsch.fetchAutocompleteSuggestionsV1\n ).toHaveBeenCalledWith({\n query: 'test',\n locale: 'pt-BR',\n })\n })\n\n it('should fallback to tenant locale when segment cultureInfo is not available', async () => {\n const fallbackResult = {\n searches: [{ term: 'test-result', count: 1 }],\n }\n\n const ctx = createContext({\n intschSettings: {\n fetchAutocompleteSuggestionsV1: fallbackResult,\n },\n tenantLocale: 'en-US',\n vtexLocale: 'es-ES',\n })\n\n await fetchAutocompleteSuggestions(ctx, 'test')\n\n expect(\n ctx.clients.intsch.fetchAutocompleteSuggestionsV1\n ).toHaveBeenCalledWith({\n query: 'test',\n locale: 'en-US',\n })\n })\n\n it('should fallback to vtex locale when both segment cultureInfo and tenant locale are not available', async () => {\n const intschResult = {\n searches: [{ term: 'test-result', count: 1 }],\n }\n\n const ctx = createContext({\n intschSettings: {\n fetchAutocompleteSuggestionsV1: intschResult,\n },\n vtexLocale: 'es-ES',\n })\n\n await fetchAutocompleteSuggestions(ctx, 'test')\n\n expect(\n ctx.clients.intsch.fetchAutocompleteSuggestionsV1\n ).toHaveBeenCalledWith({\n query: 'test',\n locale: 'es-ES',\n })\n })\n})\n\ndescribe('fetchTopSearches', () => {\n beforeEach(() => {\n jest.clearAllMocks()\n })\n\n it('should call intsch and return its result when successful', async () => {\n const intschResult = {\n searches: [{ term: 'popular', count: 10 }],\n }\n\n const ctx = createContext({\n intschSettings: {\n fetchTopSearchesV1: intschResult,\n },\n })\n\n const result = await fetchTopSearches(ctx)\n\n expect(ctx.clients.intsch.fetchTopSearchesV1).toHaveBeenCalledWith(\n undefined\n )\n\n expect(result).toEqual(intschResult)\n })\n\n it('should throw error when intsch fails', async () => {\n const ctx = createContext({\n intschSettings: {\n fetchTopSearchesV1: new Error('Service unavailable'),\n },\n })\n\n await expect(fetchTopSearches(ctx)).rejects.toThrow('Service unavailable')\n\n expect(ctx.clients.intsch.fetchTopSearchesV1).toHaveBeenCalledWith(\n undefined\n )\n })\n})\n\ndescribe('fetchSearchSuggestions', () => {\n beforeEach(() => {\n jest.clearAllMocks()\n })\n\n it('should call intsch and return its result when successful', async () => {\n const intschResult = {\n searches: [{ term: 'suggestion', count: 5 }],\n }\n\n const ctx = createContext({\n intschSettings: {\n fetchSearchSuggestionsV1: intschResult,\n },\n })\n\n const result = await fetchSearchSuggestions(ctx, 'search')\n\n expect(ctx.clients.intsch.fetchSearchSuggestionsV1).toHaveBeenCalledWith({\n query: 'search',\n locale: undefined,\n })\n\n expect(result).toEqual(intschResult)\n })\n\n it('should throw error when intsch fails', async () => {\n const ctx = createContext({\n intschSettings: {\n fetchSearchSuggestionsV1: new Error('Service unavailable'),\n },\n })\n\n await expect(fetchSearchSuggestions(ctx, 'search')).rejects.toThrow(\n 'Service unavailable'\n )\n\n expect(ctx.clients.intsch.fetchSearchSuggestionsV1).toHaveBeenCalledWith({\n query: 'search',\n locale: undefined,\n })\n })\n})\n\ndescribe('fetchCorrection', () => {\n beforeEach(() => {\n jest.clearAllMocks()\n })\n\n it('should call intsch and return its result when successful', async () => {\n const intschResult = {\n correction: {\n text: 'text',\n highlighted: '<b>text</b>',\n misspelled: true,\n correction: true,\n },\n }\n\n const ctx = createContext({\n intschSettings: {\n fetchCorrectionV1: intschResult,\n },\n })\n\n const result = await fetchCorrection(ctx, 'test')\n\n expect(ctx.clients.intsch.fetchCorrectionV1).toHaveBeenCalledWith({\n query: 'test',\n locale: undefined,\n })\n\n expect(result).toEqual(intschResult)\n })\n\n it('should throw error when intsch fails', async () => {\n const ctx = createContext({\n intschSettings: {\n fetchCorrectionV1: new Error('Service unavailable'),\n },\n })\n\n await expect(fetchCorrection(ctx, 'test')).rejects.toThrow(\n 'Service unavailable'\n )\n\n expect(ctx.clients.intsch.fetchCorrectionV1).toHaveBeenCalledWith({\n query: 'test',\n locale: undefined,\n })\n })\n})\n\n```" } ]
code_search-resolver_bca5b027
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/services/banners.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { buildAttributePath } from '../commons/compatibility-layer'\n\nexport async function fetchBanners(\n ctx: Context,\n args: { fullText: string; selectedFacets: SelectedFacet[] }\n) {\n const { intsch } = ctx.clients\n\n const argumentsToFetchBanners = {\n query: args.fullText,\n path: buildAttributePath(args.selectedFacets),\n }\n\n const locale = (ctx.vtex.segment?.cultureInfo ||\n ctx.vtex.tenant?.locale ||\n ctx.vtex.locale) as string\n\n return intsch.fetchBannersV1({ ...argumentsToFetchBanners, locale })\n}\n\n```" } ]
code_search-resolver_07d66ed5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/services/facets.test.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { fetchFacets } from './facets'\nimport { createContext } from '../mocks/contextFactory'\nimport type { FacetsInput } from '../typings/Search'\nimport * as compareResultsModule from '../utils/compareResults'\n\ndescribe('fetchFacets service', () => {\n const mockFacetsResponse = {\n facets: [\n {\n name: 'Category',\n values: [\n { name: 'Electronics', quantity: 10 },\n { name: 'Clothing', quantity: 5 },\n ],\n },\n ],\n translated: false,\n }\n\n const mockArgs: FacetsInput = {\n fullText: 'test query',\n query: 'test',\n map: 'ft',\n selectedFacets: [],\n removeHiddenFacets: false,\n hideUnavailableItems: false,\n categoryTreeBehavior: 'default',\n }\n\n const mockSelectedFacets: SelectedFacet[] = []\n\n beforeEach(() => {\n jest.clearAllMocks()\n })\n\n it('should use intsch when shouldUseNewPLPEndpoint is true', async () => {\n const ctx = createContext({\n accountName: 'testaccount',\n appSettings: {\n shouldUseNewPLPEndpoint: true,\n },\n intschSettings: {\n facets: mockFacetsResponse,\n },\n })\n\n const result = await fetchFacets(ctx, {\n args: mockArgs,\n selectedFacets: mockSelectedFacets,\n })\n\n expect(ctx.clients.intsch.facets).toHaveBeenCalled()\n expect(ctx.clients.intelligentSearchApi.facets).not.toHaveBeenCalled()\n expect(result).toEqual(mockFacetsResponse)\n })\n\n it('should compare both APIs when shouldUseNewPLPEndpoint is undefined', async () => {\n const ctx = createContext({\n accountName: 'testaccount',\n appSettings: {\n shouldUseNewPLPEndpoint: undefined,\n },\n intelligentSearchApiSettings: {\n facets: mockFacetsResponse,\n },\n intschSettings: {\n facets: mockFacetsResponse,\n },\n })\n\n const compareApiResultsSpy = jest\n .spyOn(compareResultsModule, 'compareApiResults')\n .mockResolvedValue(mockFacetsResponse)\n\n const result = await fetchFacets(ctx, {\n args: mockArgs,\n selectedFacets: mockSelectedFacets,\n })\n\n expect(compareApiResultsSpy).toHaveBeenCalled()\n expect(result).toEqual(mockFacetsResponse)\n\n compareApiResultsSpy.mockRestore()\n })\n\n it('should handle shipping options correctly', async () => {\n const ctx = createContext({\n accountName: 'testaccount',\n appSettings: {\n shouldUseNewPLPEndpoint: false,\n },\n intelligentSearchApiSettings: {\n facets: mockFacetsResponse,\n },\n })\n\n const shippingOptions = ['delivery', 'pickup']\n\n await fetchFacets(ctx, {\n args: mockArgs,\n selectedFacets: mockSelectedFacets,\n shippingOptions,\n })\n\n expect(ctx.clients.intelligentSearchApi.facets).toHaveBeenCalledWith(\n expect.objectContaining({ query: 'test query' }),\n expect.any(String),\n shippingOptions\n )\n })\n\n it('should set translated flag in context when tenant is present', async () => {\n const ctx = createContext({\n accountName: 'testaccount',\n appSettings: {\n shouldUseNewPLPEndpoint: false,\n },\n intelligentSearchApiSettings: {\n facets: { ...mockFacetsResponse, translated: true },\n },\n tenantLocale: 'en-US',\n })\n\n await fetchFacets(ctx, {\n args: mockArgs,\n selectedFacets: mockSelectedFacets,\n })\n\n expect(ctx.translated).toBe(true)\n })\n})\n\n```" } ]
code_search-resolver_84eae603
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/services/product.test.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { fetchProduct, buildVtexSegment } from './product'\nimport { createContext } from '../mocks/contextFactory'\n\ndescribe('fetchProduct service', () => {\n const mockProduct = {\n productId: 'test-product',\n productName: 'Test Product',\n brand: 'Test Brand',\n } as SearchProduct\n\n beforeEach(() => {\n jest.clearAllMocks()\n })\n\n it('should build vtex segment correctly', () => {\n const vtexSegment = buildVtexSegment({\n vtexSegment: {\n campaigns: null,\n channel: '1',\n priceTables: null,\n regionId: 'U1cjMQ==',\n utm_campaign: null,\n utm_source: null,\n utmi_campaign: null,\n currencyCode: 'ARS',\n currencySymbol: '$',\n countryCode: 'ARG',\n cultureInfo: 'es-AR',\n admin_cultureInfo: 'es-AR',\n channelPrivacy: 'public',\n },\n salesChannel: '2',\n regionId: '3',\n })\n\n const result = JSON.parse(Buffer.from(vtexSegment, 'base64').toString())\n\n expect(result.regionId).toBe('3')\n expect(result.countryCode).toBe('ARG')\n expect(result.currencySymbol).toBe('$')\n expect(result.currencyCode).toBe('ARS')\n expect(result.channel).toBe('2')\n expect(result.cultureInfo).toBe('es-AR')\n expect(result.admin_cultureInfo).toBe('es-AR')\n expect(result.channelPrivacy).toBe('public')\n expect(result.campaigns).toBeNull()\n expect(result.priceTables).toBeNull()\n expect(result.utm_campaign).toBeNull()\n expect(result.utm_source).toBeNull()\n expect(result.utmi_campaign).toBeNull()\n })\n\n it('should use intsch directly for b2bstoreqa account', async () => {\n const ctx = createContext({\n accountName: 'b2bstoreqa',\n appSettings: {\n shouldUseNewPDPEndpoint: true,\n },\n })\n\n // Mock the intsch client to return a product\n jest\n .spyOn(ctx.clients.intsch, 'fetchProduct')\n .mockImplementation()\n .mockResolvedValue(mockProduct)\n\n const args = {\n identifier: { field: 'id' as const, value: 'test-id' },\n salesChannel: 1,\n }\n\n const result = await fetchProduct(ctx, args)\n\n expect(ctx.clients.intsch.fetchProduct).toHaveBeenCalled()\n expect(result).toEqual([mockProduct])\n })\n\n it('should use intsch directly for biggy account', async () => {\n const ctx = createContext({\n accountName: 'biggy',\n appSettings: {\n shouldUseNewPDPEndpoint: true,\n },\n })\n\n // Mock the intsch client to return a product\n jest\n .spyOn(ctx.clients.intsch, 'fetchProduct')\n .mockImplementation()\n .mockResolvedValue(mockProduct)\n\n const args = {\n identifier: { field: 'id' as const, value: 'test-id' },\n salesChannel: 1,\n }\n\n const result = await fetchProduct(ctx, args)\n\n expect(ctx.clients.intsch.fetchProduct).toHaveBeenCalled()\n expect(result).toEqual([mockProduct])\n })\n})\n\n```" } ]
code_search-resolver_5b1a4340
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/services/productSearch.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n buildAttributePath,\n convertOrderBy,\n} from '../commons/compatibility-layer'\nimport { getWorkspaceSearchParamsFromStorage } from '../routes/workspaceSearchParams'\nimport { compareApiResults } from '../utils/compareResults'\nimport { fetchAppSettings } from './settings'\nimport type { ProductSearchInput } from '../typings/Search'\nimport { decodeQuery } from '../clients/intelligent-search-api'\nimport { parseState } from '../utils/searchState'\n\n/**\n * Builds a query string from an object of params, filtering out undefined/null values\n */\nfunction buildQueryString(params: Record<string, any>): string {\n const searchParams = new URLSearchParams()\n\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined && value !== null && value !== '') {\n searchParams.append(key, String(value))\n }\n }\n\n return searchParams.toString()\n}\n\n/**\n * Builds curl commands for debugging API requests\n */\nfunction buildCurlCommands(\n ctx: Context,\n path: string,\n params: Record<string, any>,\n shippingOptions?: string[]\n): { biggyCurl: string; intschCurl: string } {\n const { workspace, account } = ctx.vtex\n const queryString = buildQueryString(params)\n\n const shippingHeader = shippingOptions?.length\n ? ` -H \"x-vtex-shipping-options: ${shippingOptions.join(',')}\"`\n : ''\n\n const biggyCurl = `curl \"https://${workspace}--${account}.myvtex.com/_v/api/intelligent-search/product_search/${path}?${queryString}\"${shippingHeader}`\n const intschCurl = `curl \"https://${account}.myvtex.com/api/intelligent-search/v0/product-search/${path}?${queryString}\"${shippingHeader}`\n\n return { biggyCurl, intschCurl }\n}\n\nconst defaultAdvertisementOptions = {\n showSponsored: false,\n sponsoredCount: 3,\n repeatSponsoredProducts: true,\n}\n\n/**\n * Fetches product search results using the intelligentSearchApi client (Biggy)\n */\n// eslint-disable-next-line max-params\nasync function fetchProductSearchFromBiggy(\n ctx: Context,\n args: ProductSearchInput,\n selectedFacets: SelectedFacet[],\n shippingOptions?: string[]\n) {\n const { intelligentSearchApi } = ctx.clients\n const { fullText, advertisementOptions = defaultAdvertisementOptions } = args\n\n const workspaceSearchParams = await getWorkspaceSearchParamsFromStorage(ctx)\n\n const biggyArgs: { [key: string]: any } = {\n ...advertisementOptions,\n ...args,\n query: fullText,\n sort: convertOrderBy(args.orderBy),\n ...args.options,\n ...workspaceSearchParams,\n }\n\n // unnecessary field. It's is an object and breaks the @vtex/api cache\n delete biggyArgs.selectedFacets\n delete biggyArgs.advertisementOptions\n\n const result: any = await intelligentSearchApi.productSearch(\n { ...biggyArgs },\n buildAttributePath(selectedFacets),\n shippingOptions\n )\n\n if (ctx.vtex.tenant && !args.productOriginVtex) {\n ctx.translated = result.translated\n }\n\n return {\n searchState: args.searchState,\n ...result,\n }\n}\n\n/**\n * Fetches product search results using the intsch client (Intelligent Search)\n */\n// eslint-disable-next-line max-params\nasync function fetchProductSearchFromIntsch(\n ctx: Context,\n args: ProductSearchInput,\n selectedFacets: SelectedFacet[],\n shippingOptions?: string[]\n) {\n const { intsch } = ctx.clients\n const { fullText, advertisementOptions = defaultAdvertisementOptions } = args\n\n const workspaceSearchParams = await getWorkspaceSearchParamsFromStorage(ctx)\n\n const intschArgs: { [key: string]: any } = {\n ...advertisementOptions,\n ...args,\n query: fullText,\n sort: convertOrderBy(args.orderBy),\n ...args.options,\n ...workspaceSearchParams,\n }\n\n // unnecessary field. It's is an object and breaks the @vtex/api cache\n delete intschArgs.selectedFacets\n delete intschArgs.advertisementOptions\n\n const result: any = await intsch.productSearch(\n { ...intschArgs },\n buildAttributePath(selectedFacets),\n shippingOptions\n )\n\n if (ctx.vtex.tenant && !args.productOriginVtex) {\n ctx.translated = result.translated\n }\n\n return {\n searchState: args.searchState,\n ...result,\n }\n}\n\n/**\n * ProductSearch service that extracts product search fetching logic and implements comparison or flag-based routing\n */\n// eslint-disable-next-line max-params\nexport async function fetchProductSearch(\n ctx: Context,\n args: ProductSearchInput,\n selectedFacets: SelectedFacet[],\n shippingOptions?: string[]\n) {\n const { shouldUseNewPLPEndpoint } = await fetchAppSettings(ctx)\n\n if (shouldUseNewPLPEndpoint) {\n return fetchProductSearchFromIntsch(\n ctx,\n args,\n selectedFacets,\n shippingOptions\n )\n }\n\n // Build the exact request params as the clients do for debugging\n const path = buildAttributePath(selectedFacets)\n const workspaceSearchParams = await getWorkspaceSearchParamsFromStorage(ctx)\n const { advertisementOptions = defaultAdvertisementOptions } = args\n\n const clientArgs: { [key: string]: any } = {\n ...advertisementOptions,\n ...args,\n query: args.fullText,\n sort: convertOrderBy(args.orderBy),\n ...args.options,\n ...workspaceSearchParams,\n }\n\n delete clientArgs.selectedFacets\n delete clientArgs.advertisementOptions\n\n const { leap, searchState } = args as { leap?: boolean; searchState?: string }\n\n const requestParams = {\n query: args.fullText && decodeQuery(args.fullText),\n locale: ctx.vtex.locale ?? ctx.vtex.tenant?.locale,\n bgy_leap: leap ? true : undefined,\n ...parseState(searchState),\n ...clientArgs,\n }\n\n const { biggyCurl, intschCurl } = buildCurlCommands(\n ctx,\n path,\n requestParams,\n shippingOptions\n )\n\n return compareApiResults(\n () =>\n fetchProductSearchFromBiggy(ctx, args, selectedFacets, shippingOptions),\n () =>\n fetchProductSearchFromIntsch(ctx, args, selectedFacets, shippingOptions),\n ctx.vtex.production ? 1 : 100,\n ctx.vtex.logger,\n {\n logPrefix: 'ProductSearch',\n args: {\n biggyCurl,\n intschCurl,\n },\n }\n )\n}\n\n```" } ]
code_search-resolver_f80a680f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/clients/intsch/types.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { SearchResultArgs } from '../../typings/Search'\nimport type { FacetsArgs } from '../intelligent-search-api'\n\nexport type AutocompleteSuggestionsArgs = {\n query: string\n}\n\nexport type AutocompleteSuggestionsArgsV1 = {\n locale: string\n query: string\n}\n\nexport type AutocompleteSuggestionsResponse = {\n searches: Array<{\n term: string\n count: number\n attributes?: Array<{\n key: string\n value: string\n labelKey: string\n labelValue: string\n }>\n }>\n}\n\nexport type TopSearchesResponse = {\n searches: Array<{\n term: string\n count: number\n }>\n}\n\nexport type SearchSuggestionsArgs = {\n query: string\n}\n\nexport type SearchSuggestionsArgsV1 = {\n query: string\n locale: string\n}\n\nexport type SearchSuggestionsResponse = {\n searches: Array<{\n term: string\n count: number\n }>\n}\n\nexport type CorrectionArgs = {\n query: string\n}\n\nexport type CorrectionArgsV1 = {\n query: string\n locale: string\n}\n\nexport type CorrectionResponse = {\n correction: {\n text: string\n highlighted: string\n misspelled: boolean\n correction: boolean\n }\n}\n\nexport type FetchBannersArgs = {\n query: string\n path: string\n}\n\nexport type FetchBannersArgsV1 = {\n locale: string\n query: string\n path: string\n}\n\nexport type FetchBannersResponse = {\n banners: Array<{\n id: string\n name: string\n area: string\n html: string\n }>\n}\n\nexport type FetchProductArgs = {\n field: 'id' | 'slug' | 'ean' | 'reference' | 'sku'\n value: string\n salesChannel?: string\n regionId?: string\n locale?: string\n}\n\nexport type FetchProductResponse = SearchProduct\n\nexport type ProductSearchResponse = {\n products: SearchProduct[]\n}\n\nexport type FacetsResponse = any\n\nexport interface IIntelligentSearchClient {\n fetchAutocompleteSuggestions(\n args: AutocompleteSuggestionsArgs\n ): Promise<AutocompleteSuggestionsResponse>\n fetchTopSearches(): Promise<TopSearchesResponse>\n fetchSearchSuggestions(\n args: SearchSuggestionsArgs\n ): Promise<SearchSuggestionsResponse>\n fetchCorrection(args: CorrectionArgs): Promise<CorrectionResponse>\n fetchBanners(args: FetchBannersArgs): Promise<FetchBannersResponse>\n fetchProduct(args: FetchProductArgs): Promise<FetchProductResponse>\n fetchAutocompleteSuggestionsV1(\n args: AutocompleteSuggestionsArgsV1\n ): Promise<AutocompleteSuggestionsResponse>\n fetchTopSearchesV1(locale: string): Promise<TopSearchesResponse>\n fetchSearchSuggestionsV1(\n args: SearchSuggestionsArgsV1\n ): Promise<SearchSuggestionsResponse>\n fetchCorrectionV1(args: CorrectionArgsV1): Promise<CorrectionResponse>\n fetchBannersV1(args: FetchBannersArgsV1): Promise<FetchBannersResponse>\n productSearch(\n args: SearchResultArgs,\n path: string,\n shippingHeader?: string[]\n ): Promise<ProductSearchResponse>\n facets(\n params: FacetsArgs,\n path: string,\n shippingHeader?: string[]\n ): Promise<FacetsResponse>\n}\n\n```" } ]
code_search-resolver_7c985e2c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/clients/intsch/index.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { InstanceOptions, IOContext } from '@vtex/api'\nimport { JanusClient } from '@vtex/api'\n\nimport type {\n AutocompleteSuggestionsArgs,\n AutocompleteSuggestionsArgsV1,\n AutocompleteSuggestionsResponse,\n CorrectionArgs,\n CorrectionArgsV1,\n CorrectionResponse,\n FacetsResponse,\n FetchBannersArgs,\n FetchBannersArgsV1,\n FetchBannersResponse,\n FetchProductArgs,\n FetchProductResponse,\n IIntelligentSearchClient,\n ProductSearchResponse,\n SearchSuggestionsArgs,\n SearchSuggestionsArgsV1,\n SearchSuggestionsResponse,\n TopSearchesResponse,\n} from './types'\nimport type { SearchResultArgs } from '../../typings/Search'\nimport type { FacetsArgs } from '../intelligent-search-api'\nimport { decodeQuery, isPathTraversal } from '../intelligent-search-api'\nimport { parseState } from '../../utils/searchState'\n\nexport class Intsch extends JanusClient implements IIntelligentSearchClient {\n private locale: string | undefined\n\n constructor(ctx: IOContext, options?: InstanceOptions) {\n const env = ctx.production ? 'stable' : 'beta'\n\n super(ctx, options, env)\n\n const { locale, tenant } = ctx\n\n this.locale = locale ?? tenant?.locale\n }\n\n public fetchProduct(args: FetchProductArgs): Promise<FetchProductResponse> {\n // The admin auth token is releavant for CallCenter users when the sales channel is private.\n const authToken =\n this.context.storeUserAuthToken ?? this.context.adminUserAuthToken\n\n return this.http.get('/api/intelligent-search/v1/products', {\n params: {\n field: args.field,\n value: args.value,\n sc: args.salesChannel ?? 1,\n regionId: args.regionId,\n locale: args.locale,\n },\n metric: 'search-product-new',\n headers: {\n ...(authToken ? { VtexIdclientAutCookie: authToken } : {}),\n },\n })\n }\n\n public fetchAutocompleteSuggestions(\n args: AutocompleteSuggestionsArgs\n ): Promise<AutocompleteSuggestionsResponse> {\n return this.http.get(\n '/api/intelligent-search/v0/autocomplete-suggestions',\n {\n params: { query: args.query, locale: this.locale },\n metric: 'autocompleteSearchSuggestions-new',\n }\n )\n }\n\n public fetchTopSearches(): Promise<TopSearchesResponse> {\n return this.http.get('/api/intelligent-search/v0/top-searches', {\n params: { locale: this.locale },\n metric: 'topSearches-new',\n })\n }\n\n public fetchSearchSuggestions(\n args: SearchSuggestionsArgs\n ): Promise<SearchSuggestionsResponse> {\n return this.http.get('/api/intelligent-search/v0/search-suggestions', {\n params: { query: args.query, locale: this.locale },\n metric: 'searchSuggestions-new',\n })\n }\n\n public fetchCorrection(args: CorrectionArgs): Promise<CorrectionResponse> {\n return this.http.get('/api/intelligent-search/v0/correction-search', {\n params: { query: args.query, locale: this.locale },\n metric: 'correction-new',\n })\n }\n\n public fetchBanners(args: FetchBannersArgs): Promise<FetchBannersResponse> {\n return this.http.get(`/api/intelligent-search/v0/banners/${args.path}`, {\n params: { query: args.query, locale: this.locale },\n metric: 'banners-new',\n })\n }\n\n public fetchAutocompleteSuggestionsV1(\n args: AutocompleteSuggestionsArgsV1\n ): Promise<AutocompleteSuggestionsResponse> {\n return this.http.get(\n '/api/intelligent-search/v1/autocomplete-suggestions',\n {\n params: { query: args.query, locale: args.locale },\n metric: 'autocompleteSearchSuggestions-new-v1',\n }\n )\n }\n\n public fetchTopSearchesV1(locale: string): Promise<TopSearchesResponse> {\n return this.http.get('/api/intelligent-search/v1/top-searches', {\n params: { locale },\n metric: 'topSearches-new-v1',\n })\n }\n\n public fetchSearchSuggestionsV1(\n args: SearchSuggestionsArgsV1\n ): Promise<SearchSuggestionsResponse> {\n return this.http.get('/api/intelligent-search/v1/search-suggestions', {\n params: { query: args.query, locale: args.locale },\n metric: 'searchSuggestions-new-v1',\n })\n }\n\n public fetchCorrectionV1(\n args: CorrectionArgsV1\n ): Promise<CorrectionResponse> {\n return this.http.get('/api/intelligent-search/v1/correction-search', {\n params: { query: args.query, locale: args.locale },\n metric: 'correction-new-v1',\n })\n }\n\n public fetchBannersV1(\n args: FetchBannersArgsV1\n ): Promise<FetchBannersResponse> {\n return this.http.get(`/api/intelligent-search/v1/banners/${args.path}`, {\n params: { query: args.query, locale: args.locale },\n metric: 'banners-new-v1',\n })\n }\n\n public productSearch(\n params: SearchResultArgs,\n path: string,\n shippingHeader?: string[]\n ): Promise<ProductSearchResponse> {\n const { query, leap, searchState } = params\n\n if (isPathTraversal(path)) {\n throw new Error('Malformed URL')\n }\n\n // The admin auth token is releavant for CallCenter users when the sales channel is private.\n const authToken =\n this.context.storeUserAuthToken ?? this.context.adminUserAuthToken\n\n return this.http.get(`/api/intelligent-search/v0/product-search/${path}`, {\n params: {\n query: query && decodeQuery(query),\n locale: this.locale,\n bgy_leap: leap ? true : undefined,\n ...parseState(searchState),\n ...params,\n },\n metric: 'product-search-new',\n headers: {\n 'x-vtex-shipping-options': shippingHeader ?? '',\n ...(authToken ? { VtexIdclientAutCookie: authToken } : {}),\n },\n })\n }\n\n public facets(\n params: FacetsArgs,\n path: string,\n shippingHeader?: string[]\n ): Promise<FacetsResponse> {\n if (isPathTraversal(path)) {\n throw new Error('Malformed URL')\n }\n\n const { query, leap, searchState } = params\n\n // The admin auth token is releavant for CallCenter users when the sales channel is private.\n const authToken =\n this.context.storeUserAuthToken ?? this.context.adminUserAuthToken\n\n return this.http.get(`/api/intelligent-search/v0/facets/${path}`, {\n params: {\n ...params,\n query: query && decodeQuery(query),\n locale: this.locale,\n bgy_leap: leap ? true : undefined,\n ...parseState(searchState),\n },\n metric: 'facets-new',\n headers: {\n 'x-vtex-shipping-options': shippingHeader ?? '',\n ...(authToken ? { VtexIdclientAutCookie: authToken } : {}),\n },\n })\n }\n}\n\n```" } ]
code_search-resolver_7bf2c877
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/typings/@gocommerce/utils.d.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '@gocommerce/utils' {\n const Functions: any\n}\n\n```" } ]
code_search-resolver_ec5f11e0
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/search/category.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { compose, last, prop, split } from 'ramda'\n\nimport { getCategoryInfo, logDegradedSearchError } from './utils'\nimport { formatTranslatableProp, shouldTranslateToBinding } from '../../utils/i18n'\nimport { Slugify } from '../../utils/slug'\nimport { APP_NAME } from './constants'\n\nconst lastSegment = compose<string, string[], string>(\n last,\n split('/')\n)\n\nfunction cleanUrl(url: string) {\n return url.replace(/https:\\/\\/[A-z0-9]+\\.vtexcommercestable\\.com\\.br/, '').toLowerCase()\n}\n\n/** This type has to be created because the Catlog API to get category by ID does not return the url or children for now.\n * These fields only come if you get the category from the categroy tree api.\n */\n\ntype SafeCategory = CategoryByIdResponse | CategoryTreeResponse\n\nexport const resolvers = {\n Category: {\n name: formatTranslatableProp<SafeCategory, 'name', 'id'>(\n 'name',\n 'id'\n ),\n\n cacheId: prop('id'),\n\n href: async ({ url, id }: SafeCategory, _: unknown, ctx: Context) => {\n const settings: AppSettings = await ctx.clients.apps.getAppSettings(APP_NAME)\n\n if (shouldTranslateToBinding(ctx)) {\n try {\n const rewriterUrl = await ctx.clients.rewriter.getRoute(id.toString(), 'anyCategoryEntity', ctx.vtex.binding!.id!)\n if (rewriterUrl) {\n url = rewriterUrl\n }\n } catch (e) {\n logDegradedSearchError(ctx.vtex.logger, {\n service: 'Rewriter getRoute',\n error: `Rewriter getRoute query returned an error for category ${id}. Category href may be incorrect.`,\n errorStack: e,\n })\n }\n }\n const pathname = cleanUrl(url)\n\n return settings.slugifyLinks ? Slugify(pathname) : pathname\n },\n\n metaTagDescription: formatTranslatableProp<SafeCategory, 'MetaTagDescription', 'id'>(\n 'MetaTagDescription',\n 'id'\n ),\n\n titleTag: formatTranslatableProp<SafeCategory, 'Title', 'id'>(\n 'Title',\n 'id'\n ),\n\n slug: async ({ url, id }: SafeCategory, _: unknown, ctx: Context) => {\n if (shouldTranslateToBinding(ctx)) {\n try {\n const rewriterUrl = await ctx.clients.rewriter.getRoute(id.toString(), 'anyCategoryEntity', ctx.vtex.binding!.id!)\n if (rewriterUrl) {\n url = rewriterUrl\n }\n } catch (e) {\n logDegradedSearchError(ctx.vtex.logger, {\n service: 'Rewriter getRoute',\n error: `Rewriter getRoute query returned an error for category ${id}. Category slug may be incorrect.`,\n errorStack: e,\n })\n }\n }\n return url ? lastSegment(url) : null\n },\n\n children: async (\n { id, children }: SafeCategory,\n _: any,\n { clients: { search } }: Context\n ) => {\n if (children == null) {\n const category = await getCategoryInfo(search, id, 5)\n children = category.children\n }\n return children\n },\n },\n}\n\n```" } ]
code_search-resolver_959c3ebb
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/search/searchBreadcrumb.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { APP_NAME } from './constants'\nimport { Slugify } from '../../utils/slug'\n\nexport const resolvers = {\n SearchBreadcrumb: {\n href: async ({ href }: { href: string }, _: unknown, ctx: Context) => {\n const settings: AppSettings = await ctx.clients.apps.getAppSettings(APP_NAME)\n\n return settings.slugifyLinks ? Slugify(href) : href\n },\n },\n}\n\n```" } ]
code_search-resolver_68d31df5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/search/assemblyOption.test.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { resolvers } from './assemblyOption'\n\ntest('should return a TEXT type', async () => {\n const inputValues: InputValues = {\n 'Line 1': {\n maximumNumberOfCharacters: 20,\n domain: []\n }\n }\n\n const result = await resolvers.AssemblyOption.inputValues(\n { inputValues } as AssemblyOption\n )\n\n expect(result).toHaveLength(1)\n expect(result[0].label).toBe('Line 1')\n expect(result[0].type).toBe('TEXT')\n expect(result[0].maxLength).toBe(20)\n expect(result[0].domain).not.toBeDefined()\n expect(result[0].defaultValue).toBe('')\n})\n\ntest('should return an OPTIONS type', async () => {\n const inputValues: InputValues = {\n 'Line 1': {\n maximumNumberOfCharacters: 10,\n domain: ['One option']\n },\n 'Line 2': {\n maximumNumberOfCharacters: 7,\n domain: ['Two', 'Options']\n },\n }\n\n const result = await resolvers.AssemblyOption.inputValues(\n { inputValues } as AssemblyOption\n )\n\n expect(result).toHaveLength(2)\n\n const [line1, line2] = result\n expect(line1.label).toBe('Line 1')\n expect(line1.type).toBe('OPTIONS')\n expect(line1.maxLength).toBe(undefined)\n expect(line1.domain).toHaveLength(1)\n expect(line1.domain![0]).toBe('One option')\n expect(line1.defaultValue).toBe('One option')\n\n expect(line2.label).toBe('Line 2')\n expect(line2.type).toBe('OPTIONS')\n expect(line2.maxLength).toBe(undefined)\n expect(line2.domain).toHaveLength(2)\n expect(line2.defaultValue).toBe('Two')\n})\n\ntest('should return a BOOLEAN type', async () => {\n const inputValues: InputValues = {\n 'Use thing A': {\n maximumNumberOfCharacters: 5,\n domain: ['true', 'false']\n },\n 'Use thing B': {\n maximumNumberOfCharacters: 5,\n domain: ['false', 'true']\n },\n }\n\n const result = await resolvers.AssemblyOption.inputValues(\n { inputValues } as AssemblyOption\n )\n\n expect(result).toHaveLength(2)\n\n const [thingA, thingB] = result\n expect(thingA.label).toBe('Use thing A')\n expect(thingA.type).toBe('BOOLEAN')\n expect(thingA.maxLength).toBe(undefined)\n expect(thingA.domain).not.toBeDefined()\n expect(thingA.defaultValue).toBe(true)\n\n expect(thingB.label).toBe('Use thing B')\n expect(thingB.type).toBe('BOOLEAN')\n expect(thingB.maxLength).toBe(undefined)\n expect(thingB.domain).not.toBeDefined()\n expect(thingB.defaultValue).toBe(false)\n})\n\n```" } ]
code_search-resolver_7dd0bd3a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/search/brand.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { prop } from 'ramda'\n\nimport { formatTranslatableProp } from '../../utils/i18n'\nimport { searchSlugify } from '../../utils/slug'\n\nexport const resolvers = {\n Brand: {\n name: formatTranslatableProp<Brand, 'name', 'id'>(\n 'name',\n 'id'\n ),\n\n titleTag: formatTranslatableProp<Brand, 'title', 'id'>(\n 'title',\n 'id'\n ),\n\n metaTagDescription: formatTranslatableProp<Brand, 'metaTagDescription', 'id'>(\n 'metaTagDescription',\n 'id'\n ),\n\n active: prop('isActive'),\n\n cacheId: (brand: Brand) => searchSlugify(brand.name),\n\n slug: (brand: Brand) => searchSlugify(brand.name),\n },\n}\n\n```" } ]
code_search-resolver_c0302004
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/search/itemMetadataUnit.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { prop } from 'ramda'\n\nexport const resolvers = {\n ItemMetadataUnit: {\n imageUrl: prop('MainImage'),\n skuName: prop('Name'),\n name: prop('NameComplete'),\n productId: prop('ProductId'),\n },\n}\n\n```" } ]
code_search-resolver_30cdfff4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/search/autocomplete.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { path, split } from 'ramda'\n\n/**\n * It will extract the slug from the HREF in the item\n * passed as parameter.\n *\n * That is needed once the API provide only the old link\n * (from CMS portal) to access the product page, nothing\n * more.\n *\n * HREF provided:\n * https://portal.vtexcommercestable.com.br/:slug/p\n *\n * @param item The item to extract the information\n */\nconst extractSlug = (item: SearchAutocompleteUnit) => {\n const href = split('/', item.href)\n return item.criteria ? `${href[3]}/${href[4]}` : href[3]\n}\n\nexport const resolvers = {\n Items: {\n slug: (root: SearchAutocompleteUnit) => extractSlug(root),\n\n productId: ({ items }: SearchAutocompleteUnit) =>\n items ? path([0, 'productId'], items) : null,\n },\n}\n\n```" } ]
code_search-resolver_8080d1df
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/search/productSearch.test.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* eslint-disable jest/no-mocks-import */\n\nimport { queries } from './index'\nimport { resolvers } from './productSearch'\nimport { mockContext, resetContext } from '../../__mocks__/helpers'\nimport { getProduct } from '../../__mocks__/product'\n\ndescribe('tests related to the searchMetadata query', () => {\n beforeEach(() => {\n jest.clearAllMocks()\n resetContext()\n })\n\n it('get search metadata from pageType for category', async () => {\n const args = { query: 'Department/Category', map: 'c,c' }\n\n const result = await queries.searchMetadata({}, args, mockContext as any)\n\n expect(result.titleTag).toBe('department/category-title')\n expect(result.metaTagDescription).toBe(\n 'department/category-metaTagDescription (((1))) <<<pt-BR>>> [[[original]]]'\n )\n expect(mockContext.clients.search.pageType).toBeCalledTimes(1)\n })\n\n it('get search metadata from pageType for brand', async () => {\n const args = { query: 'Brand', map: 'b' }\n\n const result = await queries.searchMetadata({}, args, mockContext as any)\n\n expect(result.titleTag).toBe('Brand-title')\n expect(result.metaTagDescription).toBe(\n 'Brand-metaTagDescription (((1))) <<<pt-BR>>> [[[original]]]'\n )\n expect(mockContext.clients.search.pageType).toBeCalledTimes(1)\n })\n\n it('get search metadata for ft search', async () => {\n const args = { query: 'Shoes', map: 'ft' }\n\n const result = await queries.searchMetadata({}, args, mockContext as any)\n\n expect(result.titleTag).toBe('Shoes')\n expect(result.metaTagDescription).toBeNull()\n expect(mockContext.clients.search.pageType).toBeCalledTimes(0)\n })\n\n it('get search metadata for specification filter search', async () => {\n const args = { query: 'Large', map: 'specificationFilter_10' }\n\n const result = await queries.searchMetadata({}, args, mockContext as any)\n\n expect(result.titleTag).toBe('Large')\n expect(result.metaTagDescription).toBeNull()\n expect(mockContext.clients.search.pageType).toBeCalledTimes(0)\n })\n\n it('get search metadata from pageType for category with brand', async () => {\n const args = { query: 'Department/Category/Brand', map: 'c,c,b' }\n\n const result = await queries.searchMetadata({}, args, mockContext as any)\n\n expect(result.titleTag).toBe('brand - department/category-title')\n expect(result.metaTagDescription).toBe(\n 'department/category-metaTagDescription (((1))) <<<pt-BR>>> [[[original]]]'\n )\n expect(mockContext.clients.search.pageType).toBeCalledTimes(2)\n })\n\n it('get search metadata from pageType for brand with category', async () => {\n const args = { query: 'Brand/Department/Category', map: 'b,c,c' }\n\n const result = await queries.searchMetadata({}, args, mockContext as any)\n\n expect(result.titleTag).toBe('department/category - Brand-title')\n expect(result.metaTagDescription).toBe(\n 'Brand-metaTagDescription (((1))) <<<pt-BR>>> [[[original]]]'\n )\n expect(mockContext.clients.search.pageType).toBeCalledTimes(2)\n })\n\n it('get search metadata from pageType for category with brand & specification filter', async () => {\n const args = {\n query: 'Department/Category/Brand/Large',\n map: 'c,c,b,specificationFilter_15',\n }\n\n const result = await queries.searchMetadata({}, args, mockContext as any)\n\n expect(result.titleTag).toBe('Large - brand - department/category-title')\n expect(result.metaTagDescription).toBe(\n 'department/category-metaTagDescription (((1))) <<<pt-BR>>> [[[original]]]'\n )\n expect(mockContext.clients.search.pageType).toBeCalledTimes(2)\n })\n\n it('get search metadata from pageType for category with brand in the middle', async () => {\n const args = {\n query: 'Department/Category/Brand/SubCategory',\n map: 'c,c,b,c',\n }\n\n const result = await queries.searchMetadata({}, args, mockContext as any)\n\n expect(result.titleTag).toBe(\n 'brand - department/category/subcategory-title'\n )\n expect(result.metaTagDescription).toBe(\n 'department/category/subcategory-metaTagDescription (((1))) <<<pt-BR>>> [[[original]]]'\n )\n expect(mockContext.clients.search.pageType).toBeCalledTimes(2)\n })\n\n it('get search metadata for search ft with category', async () => {\n const args = {\n query: 'Shoes/Department/Category',\n map: 'ft,c,c',\n }\n\n const result = await queries.searchMetadata({}, args, mockContext as any)\n\n expect(result.titleTag).toBe('department/category - Shoes')\n expect(result.metaTagDescription).toBeNull()\n expect(mockContext.clients.search.pageType).toBeCalledTimes(1)\n })\n\n it('get search metadata for search ft with brand', async () => {\n const args = {\n query: 'Shoes/Brand',\n map: 'ft,b',\n }\n\n const result = await queries.searchMetadata({}, args, mockContext as any)\n\n expect(result.titleTag).toBe('brand - Shoes')\n expect(result.metaTagDescription).toBeNull()\n expect(mockContext.clients.search.pageType).toBeCalledTimes(1)\n })\n\n it('get search metadata for search ft with specification filter', async () => {\n const args = {\n query: 'Shoes/Large',\n map: 'ft,specificationFilter_10',\n }\n\n const result = await queries.searchMetadata({}, args, mockContext as any)\n\n expect(result.titleTag).toBe('Large - Shoes')\n expect(result.metaTagDescription).toBeNull()\n expect(mockContext.clients.search.pageType).toBeCalledTimes(0)\n })\n it('get search metadata from pageType for category with correct locale variables', async () => {\n const args = { query: 'Department/Category', map: 'c,c' }\n\n mockContext.vtex.locale = 'es-ES'\n mockContext.vtex.tenant.locale = 'fr-FR'\n\n const result = await queries.searchMetadata({}, args, mockContext as any)\n\n expect(result.titleTag).toBe('department/category-title-es-ES')\n expect(result.metaTagDescription).toBe(\n 'department/category-metaTagDescription (((1))) <<<fr-FR>>> [[[original]]]'\n )\n expect(mockContext.clients.search.pageType).toBeCalledTimes(1)\n expect(mockContext.state.messagesBindingLanguage.loadMany).toBeCalledTimes(\n 1\n )\n })\n\n it('get search metadata from pageType for category with translated flag true', async () => {\n const args = { query: 'Department/Category', map: 'c,c' }\n\n mockContext.translated = true\n\n const result = await queries.searchMetadata({}, args, mockContext as any)\n\n expect(result.titleTag).toBe('department/category-title')\n expect(result.metaTagDescription).toBe(\n 'department/category-metaTagDescription (((1))) <<<pt-BR>>> [[[translated]]]'\n )\n expect(result.metaTagDescription).not.toContain('[[[original]]]')\n expect(mockContext.clients.search.pageType).toBeCalledTimes(1)\n })\n\n it('get search metadata from pageType for category with translated flag false', async () => {\n const args = { query: 'Department/Category', map: 'c,c' }\n\n mockContext.translated = false\n\n const result = await queries.searchMetadata({}, args, mockContext as any)\n\n expect(result.titleTag).toBe('department/category-title')\n expect(result.metaTagDescription).toBe(\n 'department/category-metaTagDescription (((1))) <<<pt-BR>>> [[[original]]]'\n )\n expect(mockContext.clients.search.pageType).toBeCalledTimes(1)\n })\n})\n\ndescribe('tests for breadcrumb resolver', () => {\n beforeEach(() => {\n jest.clearAllMocks()\n resetContext()\n })\n it('create correct params for search with department', async () => {\n const products = [getProduct()]\n const args = {\n translatedArgs: {\n query: 'category',\n map: 'c',\n },\n productsRaw: { data: products },\n }\n\n const result = await resolvers.ProductSearch.breadcrumb(\n args as any,\n {},\n mockContext as any\n )\n\n expect(result).toHaveLength(1)\n const head = result[0]\n\n expect(head.queryUnit).toBe('category')\n expect(head.mapUnit).toBe('c')\n expect(head.categories).toHaveLength(0)\n expect(head.metadataMap).toMatchObject({})\n expect(head.categoriesSearched).toMatchObject(['category'])\n expect(head.hrefs).toBeNull()\n expect(head.index).toBe(0)\n expect(head.queryArray).toMatchObject(['category'])\n expect(head.mapArray).toMatchObject(['c'])\n expect(head.products).toBeDefined()\n expect(mockContext.clients.rewriter.getRoute).toBeCalledTimes(0)\n })\n it('create correct params for search with category', async () => {\n const products = [getProduct()]\n const args = {\n translatedArgs: {\n query: 'category/category2',\n map: 'c,c',\n },\n productsRaw: { data: products },\n }\n\n const result = await resolvers.ProductSearch.breadcrumb(\n args as any,\n {},\n mockContext as any\n )\n\n expect(result).toHaveLength(2)\n const head = result[0]\n const expectedQueryArray = ['category', 'category2']\n const expectedMapArray = ['c', 'c']\n\n expect(head.queryUnit).toBe('category')\n expect(head.mapUnit).toBe('c')\n expect(head.categories).toHaveLength(0)\n expect(head.metadataMap).toMatchObject({})\n expect(head.categoriesSearched).toMatchObject(['category', 'category2'])\n expect(head.hrefs).toBeNull()\n expect(head.index).toBe(0)\n expect(head.queryArray).toMatchObject(expectedQueryArray)\n expect(head.mapArray).toMatchObject(expectedMapArray)\n const tail = result[1]\n\n expect(tail.queryUnit).toBe('category2')\n expect(tail.mapUnit).toBe('c')\n expect(tail.categories).toHaveLength(0)\n expect(tail.metadataMap).toMatchObject({})\n expect(tail.categoriesSearched).toMatchObject(expectedQueryArray)\n expect(tail.hrefs).toBeNull()\n expect(tail.index).toBe(1)\n expect(tail.queryArray).toMatchObject(expectedQueryArray)\n expect(tail.mapArray).toMatchObject(expectedMapArray)\n expect(mockContext.clients.rewriter.getRoute).toBeCalledTimes(0)\n })\n\n it('create correct params for search with category binding translations', async () => {\n const products = [getProduct()]\n const args = {\n translatedArgs: {\n query: 'category/category2',\n map: 'c,c',\n },\n productsRaw: { data: products },\n }\n\n mockContext.vtex.binding.locale = 'es-ES'\n\n const result = await resolvers.ProductSearch.breadcrumb(\n args as any,\n {},\n mockContext as any\n )\n\n expect(result).toHaveLength(2)\n const head = result[0]\n const expectedQueryArray = ['category', 'category2']\n const expectedMapArray = ['c', 'c']\n\n expect(head.queryUnit).toBe('category')\n expect(head.mapUnit).toBe('c')\n expect(head.categories).toHaveLength(0)\n expect(head.categoriesSearched).toMatchObject(['category', 'category2'])\n expect(head.hrefs).toMatchObject([\n '/1-department-abc-es-ES',\n '/1-category-abc-es-ES',\n ])\n expect(head.index).toBe(0)\n expect(head.queryArray).toMatchObject(expectedQueryArray)\n expect(head.mapArray).toMatchObject(expectedMapArray)\n expect(head.metadataMap).toMatchObject({\n 'category-c': { name: 'category', id: '1' },\n 'category2-c': { name: 'category/category2', id: '1' },\n })\n const tail = result[1]\n\n expect(tail.queryUnit).toBe('category2')\n expect(tail.mapUnit).toBe('c')\n expect(tail.categories).toHaveLength(0)\n expect(tail.metadataMap).toMatchObject({\n 'category-c': { name: 'category', id: '1' },\n 'category2-c': { name: 'category/category2', id: '1' },\n })\n expect(tail.categoriesSearched).toMatchObject(expectedQueryArray)\n expect(tail.hrefs).toMatchObject([\n '/1-department-abc-es-ES',\n '/1-category-abc-es-ES',\n ])\n expect(tail.index).toBe(1)\n expect(tail.queryArray).toMatchObject(expectedQueryArray)\n expect(tail.mapArray).toMatchObject(expectedMapArray)\n expect(mockContext.clients.rewriter.getRoute).toBeCalledTimes(2)\n })\n})\n\ndescribe.skip('tests related to the productSearch query', () => {\n beforeEach(() => {\n jest.clearAllMocks()\n resetContext()\n })\n\n it('should not translate args that are not ft', async () => {\n const args = {\n query: 'shoes/sneakers',\n map: 'c,c',\n }\n\n const result = await queries.productSearch(\n {},\n args as any,\n mockContext as any\n )\n\n expect(result.translatedArgs).toMatchObject({\n query: 'shoes/sneakers',\n map: 'c,c',\n })\n })\n\n it('should not translate ft args if user locale matches tenant locale', async () => {\n const args = {\n query: 'tenis/shoes/sneakers',\n map: 'ft,c,c',\n }\n\n const result = await queries.productSearch(\n {},\n args as any,\n mockContext as any\n )\n\n expect(result.translatedArgs).toMatchObject({\n query: 'tenis/shoes/sneakers',\n map: 'ft,c,c',\n })\n })\n\n it('should translate ft args if user locale differs tenant locale', async () => {\n mockContext.vtex.locale = 'es-ES'\n const args = {\n query: 'tenis/shoes/sneakers',\n map: 'ft,c,c',\n }\n\n const result = await queries.productSearch(\n {},\n args as any,\n mockContext as any\n )\n\n expect(result.translatedArgs).toMatchObject({\n query: 'tenis-pt-BR/shoes/sneakers',\n map: 'ft,c,c',\n })\n })\n})\n\n```" } ]
code_search-resolver_77d62511
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/search/index.test.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { queries } from './index'\nimport { mockContext } from '../../__mocks__/helpers'\nimport { getProduct, getItem } from '../../__mocks__/product'\n\nbeforeEach(() => {\n jest.clearAllMocks()\n})\n\ndescribe('product recommendations query tests', () => {\n test('test if productRecommendations products have correct custom cacheId', async () => {\n const product1 = getProduct()\n const product2 = getProduct()\n\n const item1 = getItem()\n const item2 = getItem('2')\n\n product1.items = [item1 as any]\n product2.items = [item2 as any]\n mockContext.clients.search.crossSelling.mockImplementation(() => [\n product1,\n product2,\n ])\n const results = await queries.productRecommendations(\n {},\n { identifier: { field: 'id', value: '1' }, type: 'similars' as any },\n mockContext as any\n )\n expect(results.every(p => Boolean(p.cacheId))).toBeTruthy()\n expect(results[0].cacheId).toBe('classic-shoes-1')\n expect(results[1].cacheId).toBe('classic-shoes-2')\n })\n\n test('ensure correct types call the correct APIs', async () => {\n mockContext.clients.search.crossSelling.mockImplementation(() => [])\n await queries.productRecommendations(\n {},\n { identifier: { field: 'id', value: '1' }, type: 'similars' as any },\n mockContext as any\n )\n expect(mockContext.clients.search.crossSelling.mock.calls[0][1]).toBe(\n 'similars'\n )\n\n await queries.productRecommendations(\n {},\n { identifier: { field: 'id', value: '1' }, type: 'view' as any },\n mockContext as any\n )\n expect(mockContext.clients.search.crossSelling.mock.calls[1][1]).toBe(\n 'whosawalsosaw'\n )\n\n await queries.productRecommendations(\n {},\n { identifier: { field: 'id', value: '1' }, type: 'buy' as any },\n mockContext as any\n )\n expect(mockContext.clients.search.crossSelling.mock.calls[2][1]).toBe(\n 'whoboughtalsobought'\n )\n\n await queries.productRecommendations(\n {},\n { identifier: { field: 'id', value: '1' }, type: 'viewAndBought' as any },\n mockContext as any\n )\n expect(mockContext.clients.search.crossSelling.mock.calls[3][1]).toBe(\n 'whosawalsobought'\n )\n\n await queries.productRecommendations(\n {},\n { identifier: { field: 'id', value: '1' }, type: 'suggestions' as any },\n mockContext as any\n )\n expect(mockContext.clients.search.crossSelling.mock.calls[4][1]).toBe(\n 'suggestions'\n )\n\n await queries.productRecommendations(\n {},\n { identifier: { field: 'id', value: '1' }, type: 'accessories' as any },\n mockContext as any\n )\n expect(mockContext.clients.search.crossSelling.mock.calls[5][1]).toBe(\n 'accessories'\n )\n })\n})\n\n```" } ]
code_search-resolver_570e4d5e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/search/product.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { compose, flatten, last, omit, pathOr, split } from 'ramda'\n\nimport {\n addContextToTranslatableString,\n formatTranslatableProp,\n shouldTranslateToBinding,\n shouldTranslateToUserLocale,\n} from '../../utils/i18n'\nimport { getBenefits } from '../benefits'\nimport { buildCategoryMap, logDegradedSearchError } from './utils'\n\ntype DynamicKey<T> = Record<string, T>\n\nconst urlToSlug = (slug: string | undefined) => {\n if (!slug) {\n return slug\n }\n\n const erasedSlash = slug.replace(/^\\//g, '') // removing starting / char\n const finalSlug = erasedSlash.replace(/(\\/p)$/g, '') // remove ending /p chars\n\n return finalSlug\n}\n\nconst objToNameValue = (\n keyName: string,\n valueName: string,\n record: Record<string, any> | null | undefined\n) => {\n if (!record) {\n return []\n }\n\n return Object.keys(record).reduce((acc, key: any) => {\n const value = record[key]\n\n if (typeof value === 'string') {\n acc.push({ [keyName]: key, [valueName]: value })\n }\n\n return acc\n }, [] as Array<Record<string, string>>)\n}\n\ntype SearchProductWithCache = SearchProduct & { cacheId?: string }\ntype ItemsFilter = 'ALL' | 'FIRST_AVAILABLE' | 'ALL_AVAILABLE'\ntype ItemArg = {\n filter?: ItemsFilter\n}\n\nconst isSellerAvailable = (seller: Seller) =>\n pathOr(0, ['commertialOffer', 'AvailableQuantity'], seller) > 0\n\nconst isAvailable = (item: SearchItem): boolean => {\n return item.sellers.find(isSellerAvailable) !== undefined\n}\n\nconst knownNotPG = [\n 'allSpecifications',\n 'brand',\n 'categoriesIds',\n 'categoryId',\n 'clusterHighlights',\n 'productClusters',\n 'items',\n 'productId',\n 'link',\n 'linkText',\n 'productReference',\n]\n\nconst removeTrailingSlashes = (str: string) =>\n str.endsWith('/') ? str.slice(0, str.length - 1) : str\n\nconst removeStartingSlashes = (str: string) =>\n str.startsWith('/') ? str.slice(1) : str\n\nconst getProductFilterIdMap = async (product: SearchProduct, ctx: Context) => {\n const filters = await ctx.clients.search.filtersInCategoryFromId(\n product.categoryId\n )\n\n const filterMapFromName = filters.reduce((acc, curr) => {\n acc[curr.Name] = curr.FieldId.toString()\n\n return acc\n }, {} as Record<string, string>)\n\n return filterMapFromName\n}\n\nconst getLastCategory = compose<string, string, string[], string>(\n last,\n split('/'),\n removeTrailingSlashes\n)\n\nconst treeStringToArray = compose(\n split('/'),\n removeTrailingSlashes,\n removeStartingSlashes\n)\n\nconst findMainTree = (categoriesIds: string[], prodCategoryId: string) => {\n const mainTree = categoriesIds.find(\n (treeIdString) => getLastCategory(treeIdString) === prodCategoryId\n )\n\n if (mainTree) {\n return treeStringToArray(mainTree)\n }\n\n // If we are here, did not find the specified main category ID in given strings. It is probably a bug.\n // We will return the biggest tree we find\n\n const trees = categoriesIds.map(treeStringToArray)\n\n return trees.reduce(\n (acc, currTree) => (currTree.length > acc.length ? currTree : acc),\n []\n )\n}\n\nconst productCategoriesToCategoryTree = async (\n { categories, categoriesIds, categoryId: prodCategoryId }: SearchProduct,\n _: any,\n { clients: { search }, vtex: { platform, logger } }: Context\n) => {\n if (!categories || !categoriesIds) {\n return []\n }\n\n const mainTreeIds = findMainTree(categoriesIds, prodCategoryId)\n\n if (platform === 'vtex') {\n return mainTreeIds.map((categoryId) => search.category(Number(categoryId)))\n }\n\n logger.info({\n message: 'productCategoriesToCategoryTree: not vtex platform',\n platform,\n })\n const categoriesTree = await search.categories(mainTreeIds.length)\n const categoryMap = buildCategoryMap(categoriesTree)\n const mappedCategories = mainTreeIds\n .map((id) => categoryMap[id])\n .filter(Boolean)\n\n return mappedCategories.length ? mappedCategories : null\n}\n\nconst addTranslationParamsToSpecification =\n (filterIdFromNameMap: Record<string, string>, ctx: Context) =>\n (specification: { name: string; values: string[] }) => {\n const { name, values } = specification\n const filterId = filterIdFromNameMap[name]\n\n return {\n originalName: name,\n name: addContextToTranslatableString(\n { content: name, context: filterId },\n ctx\n ),\n values: values.map((value) =>\n addContextToTranslatableString(\n { content: value, context: filterId },\n ctx\n )\n ),\n }\n }\n\nexport const resolvers = {\n Product: {\n brand: formatTranslatableProp<SearchProduct, 'brand', 'brandId'>(\n 'brand',\n 'brandId'\n ),\n\n benefits: async (\n { items, productId }: SearchProduct,\n _: any,\n ctx: Context\n ) => {\n const promises = items?.map((item) => getBenefits(item.itemId, ctx))\n const promisesResult = flatten(\n await Promise.all(promises.map((p) => p.catch((error) => error)))\n )\n\n const benefitsWithoutError = promisesResult.filter(\n (result) => !(result instanceof Error)\n )\n\n if (benefitsWithoutError.length !== promisesResult.length) {\n logDegradedSearchError(ctx.vtex.logger, {\n service: 'Checkout simulation',\n error: `Checkout simulation API returned an error for product ${productId}.\n Simulation will be skipped for one or more items and the benefits list may be incomplete.`,\n })\n }\n\n return benefitsWithoutError\n },\n\n categoryTree: productCategoriesToCategoryTree,\n\n cacheId: ({ linkText, cacheId }: SearchProductWithCache) =>\n cacheId ?? linkText,\n\n clusterHighlights: ({ origin, clusterHighlights }: SearchProduct) => {\n if (origin === 'intelligent-search') {\n return clusterHighlights\n }\n\n return objToNameValue('id', 'name', clusterHighlights)\n },\n\n jsonSpecifications: (product: SearchProduct) => {\n const { Specifications = [] } = product\n const specificationsMap = Specifications.reduce(\n (acc: Record<string, string>, key: string) => {\n acc[key] = (product as any)[key]\n\n return acc\n },\n {}\n )\n\n return JSON.stringify(specificationsMap)\n },\n\n productClusters: ({ origin, productClusters }: SearchProduct) => {\n if (origin === 'intelligent-search') {\n return productClusters\n }\n\n return objToNameValue('id', 'name', productClusters)\n },\n\n properties: async (product: SearchProduct, _: unknown, ctx: Context) => {\n let valuesUntranslated = []\n\n if (product.origin === 'intelligent-search') {\n valuesUntranslated = product.properties ?? []\n } else {\n valuesUntranslated = (product.allSpecifications ?? []).map(\n (name: string) => {\n const value = (product as unknown as DynamicKey<string[]>)[name]\n\n return { name, originalName: name, values: value }\n }\n )\n }\n\n if (!shouldTranslateToUserLocale(ctx)) {\n return valuesUntranslated\n }\n\n const filterIdFromNameMap = await getProductFilterIdMap(product, ctx)\n const valuesWithTranslations = valuesUntranslated.map(\n addTranslationParamsToSpecification(filterIdFromNameMap, ctx)\n )\n\n return valuesWithTranslations\n },\n\n propertyGroups: (product: SearchProduct) => {\n const { allSpecifications = [] } = product\n const notPG = knownNotPG.concat(allSpecifications)\n\n return objToNameValue('name', 'values', omit(notPG, product))\n },\n\n recommendations: (product: SearchProduct, args: any) => {\n const { groupBy } = args\n\n return { product, groupBy }\n },\n\n description: formatTranslatableProp<\n SearchProduct,\n 'description',\n 'productId'\n >('description', 'productId'),\n\n metaTagDescription: formatTranslatableProp<\n SearchProduct,\n 'metaTagDescription',\n 'productId'\n >('metaTagDescription', 'productId'),\n\n titleTag: (\n { productId, productTitle, productName }: SearchProduct,\n _: unknown,\n ctx: Context\n ) =>\n addContextToTranslatableString(\n {\n content: productTitle ?? productName ?? '',\n context: productId,\n },\n ctx\n ),\n\n productName: formatTranslatableProp<\n SearchProduct,\n 'productName',\n 'productId'\n >('productName', 'productId'),\n\n linkText: async (\n { productId, linkText, origin }: SearchProduct,\n _: unknown,\n ctx: Context\n ) => {\n const {\n clients: { rewriter },\n vtex: { binding },\n } = ctx\n\n if (origin === 'intelligent-search' || !shouldTranslateToBinding(ctx)) {\n return linkText\n }\n\n try {\n const route = await rewriter.getRoute(\n productId,\n 'product',\n binding!.id!\n )\n\n return urlToSlug(route) ?? linkText\n } catch (e) {\n logDegradedSearchError(ctx.vtex.logger, {\n service: 'Rewriter getRoute',\n error: `Rewriter getRoute query returned an error for productId ${productId}. Linktext may be incorrect.`,\n errorStack: e,\n })\n }\n\n return linkText\n },\n\n specificationGroups: async (\n product: SearchProduct,\n _: unknown,\n ctx: Context\n ) => {\n if (product.origin === 'intelligent-search') {\n return product.specificationGroups\n }\n\n const allSpecificationsGroups = (\n product.allSpecificationsGroups ?? []\n ).concat(['allSpecifications'])\n\n const visibleSpecifications = product.completeSpecifications\n ? product.completeSpecifications.reduce<Record<string, boolean>>(\n (acc, specification) => {\n acc[specification.Name] = specification.IsOnProductDetails\n\n return acc\n },\n {}\n )\n : null\n\n let noTranslationSpecificationGroups = allSpecificationsGroups.map(\n (groupName: string) => {\n let groupSpecifications =\n (product as unknown as DynamicKey<string[]>)?.[groupName] ?? []\n\n groupSpecifications = groupSpecifications.filter(\n (specificationName) => {\n if (visibleSpecifications?.[specificationName] != null)\n return visibleSpecifications[specificationName]\n\n return true\n }\n )\n\n return {\n originalName: groupName,\n name: groupName,\n specifications: groupSpecifications.map((name) => {\n const values =\n (product as unknown as DynamicKey<string[]>)[name] || []\n\n return {\n originalName: name,\n name,\n values,\n }\n }),\n }\n }\n )\n\n noTranslationSpecificationGroups =\n noTranslationSpecificationGroups.filter(\n (group) => group.specifications.length > 0\n )\n\n if (!shouldTranslateToUserLocale(ctx)) {\n return noTranslationSpecificationGroups\n }\n\n const filterIdFromNameMap = await getProductFilterIdMap(product, ctx)\n const translatedGroups = noTranslationSpecificationGroups.map((group) => {\n return {\n originalName: group.name,\n name: addContextToTranslatableString(\n { content: group.name, context: product.productId },\n ctx\n ),\n specifications: group.specifications.map(\n addTranslationParamsToSpecification(filterIdFromNameMap, ctx)\n ),\n }\n })\n\n return translatedGroups\n },\n items: (\n { items: searchItems, skuSpecifications = [] }: SearchProduct,\n { filter }: ItemArg\n ) => {\n const searchItemsWithVariations = searchItems.map((item) => ({\n ...item,\n skuSpecifications,\n }))\n\n if (filter === 'ALL') {\n return searchItemsWithVariations\n }\n\n if (filter === 'FIRST_AVAILABLE') {\n const firstAvailable = searchItemsWithVariations.find(isAvailable)\n\n return firstAvailable\n ? [firstAvailable]\n : [searchItemsWithVariations[0]]\n }\n\n if (filter === 'ALL_AVAILABLE') {\n const onlyAvailable = searchItemsWithVariations.filter(isAvailable)\n\n return onlyAvailable.length > 0\n ? onlyAvailable\n : [searchItemsWithVariations[0]]\n }\n\n return searchItemsWithVariations\n },\n priceRange: ({ items: searchItems }: SearchProduct) => {\n const offers = searchItems.reduce<CommertialOffer[]>(\n (acc, currentItem) => {\n for (const seller of currentItem.sellers) {\n if (isSellerAvailable(seller)) {\n acc.push(seller.commertialOffer)\n }\n }\n\n return acc\n },\n []\n )\n\n return { offers }\n },\n\n itemMetadata: ({\n items,\n origin,\n itemMetadata,\n brand,\n categoryId,\n productId,\n }: SearchProduct) => {\n // Since the IS doesn't return the itemMetadata, we need to build it from the items.attachments\n if (origin === 'intelligent-search') {\n // Build itemMetadata from items.attachments\n const metadataItems = items.map((item) => {\n // Build assemblyOptions from attachments\n const assemblyOptions = (item.attachments || []).map((attachment) => {\n // Build inputValues from attachment fields\n const inputValues: Record<\n string,\n { maximumNumberOfCharacters: number; domain: string[] }\n > = {}\n\n if (attachment.fields) {\n attachment.fields.forEach((field) => {\n const domain = field.domainValues\n ? field.domainValues\n .split(',')\n .map((v) => v.trim())\n .filter(Boolean)\n : []\n\n inputValues[field.fieldName] = {\n maximumNumberOfCharacters:\n parseInt(field.maxCharacters, 10) || 0,\n domain,\n }\n })\n }\n\n return {\n id: attachment.name,\n name: attachment.name,\n required: attachment.required || attachment.isRequired || false,\n inputValues,\n composition: null,\n }\n })\n\n // Get the first available seller or default to '1'\n const firstSeller =\n item.sellers && item.sellers[0] ? item.sellers[0].sellerId : '1'\n\n // Get the main image URL\n const mainImage =\n item.images && item.images[0] ? item.images[0].imageUrl : ''\n\n return {\n Name: item.name,\n NameComplete: item.nameComplete,\n MainImage: mainImage,\n BrandName: brand,\n CategoryId: parseInt(categoryId, 10),\n ProductId: parseInt(productId, 10),\n id: item.itemId,\n seller: firstSeller,\n assemblyOptions,\n }\n })\n\n return {\n items: metadataItems,\n }\n }\n\n return itemMetadata\n },\n },\n OnlyProduct: {\n categoryTree: productCategoriesToCategoryTree,\n productClusters: ({ productClusters }: any) =>\n ([] as any[]).concat(productClusters ?? []),\n clusterHighlights: ({ clusterHighlights }: any) =>\n ([] as any[]).concat(clusterHighlights ?? []),\n },\n}\n\n```" } ]
code_search-resolver_bd28fa7f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/search/discount.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { has, prop } from 'ramda'\n\nexport const resolvers = {\n Discount: {\n name: (discount: any) =>\n has('name', discount)\n ? prop('name', discount)\n : prop('<Name>k__BackingField', discount),\n },\n Teaser: {\n name: (teaser: any) =>\n has('name', teaser)\n ? prop('name', teaser)\n : prop('<Name>k__BackingField', teaser),\n\n conditions: (teaser: any) =>\n has('conditions', teaser)\n ? prop('conditions', teaser)\n : prop('<Conditions>k__BackingField', teaser),\n\n effects: (teaser: any) =>\n has('effects', teaser)\n ? prop('effects', teaser)\n : prop('<Effects>k__BackingField', teaser),\n },\n TeaserCondition: {\n minimumQuantity: (teaserCondition: any) =>\n has('minimumQuantity', teaserCondition)\n ? prop('minimumQuantity', teaserCondition)\n : prop('<MinimumQuantity>k__BackingField', teaserCondition),\n\n parameters: (teaserCondition: any) =>\n has('parameters', teaserCondition)\n ? prop('parameters', teaserCondition)\n : prop('<Parameters>k__BackingField', teaserCondition),\n },\n TeaserEffects: {\n parameters: (teaserEffects: any) =>\n has('parameters', teaserEffects)\n ? prop('parameters', teaserEffects)\n : prop('<Parameters>k__BackingField', teaserEffects),\n },\n TeaserValue: {\n name: (teaserValue: any) =>\n has('name', teaserValue)\n ? prop('name', teaserValue)\n : prop('<Name>k__BackingField', teaserValue),\n\n value: (teaserValue: any) =>\n has('value', teaserValue)\n ? prop('value', teaserValue)\n : prop('<Value>k__BackingField', teaserValue),\n },\n}\n\n```" } ]
code_search-resolver_24dd2158
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/search/skuSpecificationField.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { addContextToTranslatableString } from '../../utils/i18n'\n\n// if it has `originalName`, the specification is already coming in the appropriate format and language\nexport const resolvers = {\n SKUSpecificationField: {\n originalName: (value: SKUSpecificationField) => {\n return value.originalName ? value.originalName : value.name\n },\n name: (field: SKUSpecificationField, _: any, ctx: Context) => {\n return field.originalName ? field.name : addContextToTranslatableString(\n {\n content: field.name,\n context: field.id\n },\n ctx\n )\n }\n }\n}\n\n```" } ]
code_search-resolver_937cd2a7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/search/newURLs.test.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable new-cap */\n/* eslint-disable no-await-in-loop */\n\nimport * as TypeMoq from 'typemoq'\nimport type { IOContext } from '@vtex/api'\nimport { VBase } from '@vtex/api'\n\nimport { Search } from '../../clients/search'\nimport { mountCompatibilityQuery } from './newURLs'\nimport { getCompatibilityArgs } from '.'\nimport { Clients } from '../../clients'\n\nconst contextMock = TypeMoq.Mock.ofType<IOContext>()\nconst categoryTreeResponseMock = TypeMoq.Mock.ofType<CategoryTreeResponse>()\nconst facetsMock = TypeMoq.Mock.ofType<SearchFacets>()\nconst vbaseTypeMock = TypeMoq.Mock.ofInstance(VBase)\nconst state = TypeMoq.Mock.ofType<State>()\nconst customContext = TypeMoq.Mock.ofType<CustomContext>()\n\ndescribe('Search new URLs dicovery', () => {\n class VBaseMock extends vbaseTypeMock.object {\n private jsonData: any\n\n constructor() {\n super(contextMock.object)\n this.jsonData = {}\n }\n\n public getJSON = async <T>(\n bucket: string,\n file: string,\n nullOrUndefined?: boolean | undefined\n ): Promise<T> => {\n if (!this.jsonData[bucket]) {\n return (nullOrUndefined ? null : {}) as T\n }\n\n return Promise.resolve(this.jsonData[bucket][file] as T)\n }\n\n public saveJSON = async <T>(\n bucket: string,\n file: string,\n data: T\n ): Promise<any> => {\n if (!this.jsonData[bucket]) {\n this.jsonData[bucket] = {}\n }\n\n this.jsonData[bucket][file] = data\n }\n }\n\n const search = class SearchMock extends Search {\n private categoriesResponse: CategoryTreeResponse[]\n private categoryChildrenResponse: Record<number, Record<string, string>>\n private facetsResponse: SearchFacets\n\n constructor(\n categories: CategoryTreeResponse[],\n categoryChildren: Record<number, Record<string, string>>,\n facets: SearchFacets\n ) {\n super(contextMock.object)\n this.categoriesResponse = categories\n this.categoryChildrenResponse = categoryChildren\n this.facetsResponse = facets\n }\n\n public categories = async (_: number) => {\n return Promise.resolve(this.categoriesResponse)\n }\n\n public getCategoryChildren = (id: number) => {\n return Promise.resolve(this.categoryChildrenResponse[id])\n }\n\n public facets = (_?: string) => {\n return Promise.resolve(this.facetsResponse)\n }\n }\n\n it('Should transform /category in /category?map=c', async () => {\n const args = {\n query: 'category',\n map: '',\n }\n\n const categoryTree: CategoryTreeResponse[] = [\n {\n ...categoryTreeResponseMock.object,\n id: 1,\n name: 'category',\n hasChildren: false,\n },\n ]\n\n const facets = {\n ...facetsMock.object,\n SpecificationFilters: {},\n }\n\n const vbaseMock = new VBaseMock()\n const searchMock = new search(categoryTree, {}, facets)\n const result = await mountCompatibilityQuery({\n vbase: vbaseMock,\n search: searchMock,\n args,\n })\n\n expect(result).toStrictEqual({ query: 'category', map: 'c' })\n })\n\n it('Should transform /department/category/subcategory in /department/category/subcategory?map=c,c,c', async () => {\n const args = {\n query: 'department/category/subcategory',\n map: '',\n }\n\n const categoryTree: CategoryTreeResponse[] = [\n {\n ...categoryTreeResponseMock.object,\n id: 1,\n name: 'department',\n hasChildren: true,\n },\n ]\n\n const categoryChildren = {\n 1: { '2': 'category' },\n 2: { '3': 'subcategory' },\n }\n\n const facets = {\n ...facetsMock.object,\n SpecificationFilters: {},\n }\n\n const vbaseMock = new VBaseMock()\n const searchMock = new search(categoryTree, categoryChildren, facets)\n const result = await mountCompatibilityQuery({\n vbase: vbaseMock,\n search: searchMock,\n args,\n })\n\n expect(result).toStrictEqual({\n query: 'department/category/subcategory',\n map: 'c,c,c',\n })\n })\n\n it('Should transform /category/brand?map=b in /category?map=c,b', async () => {\n const args = {\n query: 'category/brand',\n map: 'b',\n }\n\n const categoryTree: CategoryTreeResponse[] = [\n {\n ...categoryTreeResponseMock.object,\n id: 1,\n name: 'category',\n hasChildren: false,\n },\n ]\n\n const categoryChildren = { 1: {} }\n\n const facets = {\n ...facetsMock.object,\n SpecificationFilters: {},\n }\n\n const vbaseMock = new VBaseMock()\n const searchMock = new search(categoryTree, categoryChildren, facets)\n const result = await mountCompatibilityQuery({\n vbase: vbaseMock,\n search: searchMock,\n args,\n })\n\n expect(result).toStrictEqual({ query: 'category/brand', map: 'c,b' })\n })\n\n it('Should transform /collection?map=productClusterIds in /collection?map=productClusterIds', async () => {\n const args = {\n query: 'collection',\n map: 'productClusterIds',\n }\n\n const categoryTree: CategoryTreeResponse[] = []\n\n const categoryChildren = {}\n\n const facets = {\n ...facetsMock.object,\n SpecificationFilters: {},\n }\n\n const vbaseMock = new VBaseMock()\n const searchMock = new search(categoryTree, categoryChildren, facets)\n const result = await mountCompatibilityQuery({\n vbase: vbaseMock,\n search: searchMock,\n args,\n })\n\n expect(result).toStrictEqual({\n query: 'collection',\n map: 'productClusterIds',\n })\n })\n\n it('Should transform /filterxpto?map=specificationFilter_0 in /filterxpto?map=specificationFilter_0', async () => {\n const args = {\n query: 'filterxpto',\n map: 'specificationFilter_0',\n }\n\n const categoryTree: CategoryTreeResponse[] = []\n\n const categoryChildren = {}\n\n const facets = {\n ...facetsMock.object,\n SpecificationFilters: {},\n }\n\n const vbaseMock = new VBaseMock()\n const searchMock = new search(categoryTree, categoryChildren, facets)\n const result = await mountCompatibilityQuery({\n vbase: vbaseMock,\n search: searchMock,\n args,\n })\n\n expect(result).toStrictEqual({\n query: 'filterxpto',\n map: 'specificationFilter_0',\n })\n })\n\n it('Should transform /department/style_1/color_2/size_3 in /department/1/2/3?map=c,specificationFilter_1,specificationFilter_2,specificationFilter_3', async () => {\n const args = {\n query: 'department/style_1/color_2/size_3',\n map: '',\n }\n\n const categoryTree: CategoryTreeResponse[] = [\n {\n ...categoryTreeResponseMock.object,\n id: 1,\n name: 'department',\n hasChildren: false,\n },\n ]\n\n const categoryChildren = { 1: {} }\n\n const facets = {\n ...facetsMock.object,\n SpecificationFilters: {\n style: [\n {\n Name: '1',\n Map: 'specificationFilter_1',\n Value: '1',\n },\n ],\n color: [\n {\n Name: '2',\n Map: 'specificationFilter_2',\n Value: '2',\n },\n ],\n size: [\n {\n Name: '3',\n Map: 'specificationFilter_3',\n Value: '3',\n },\n ],\n },\n }\n\n const vbaseMock = new VBaseMock()\n const searchMock = new search(categoryTree, categoryChildren, facets as any)\n const result = await mountCompatibilityQuery({\n vbase: vbaseMock,\n search: searchMock,\n args,\n })\n\n expect(result).toStrictEqual({\n query: 'department/1/2/3',\n map: 'c,specificationFilter_1,specificationFilter_2,specificationFilter_3',\n })\n })\n\n it('Should transform /department/style_1/brand?map=b in /department/style_1/brand?map=c,specificationFilter_1,b', async () => {\n const args = {\n query: 'department/style_1/brand',\n map: 'b',\n }\n\n const categoryTree: CategoryTreeResponse[] = [\n {\n ...categoryTreeResponseMock.object,\n id: 1,\n name: 'department',\n hasChildren: false,\n },\n ]\n\n const categoryChildren = { 1: {} }\n\n const facets = {\n ...facetsMock.object,\n SpecificationFilters: {\n style: [\n {\n Name: '1',\n Map: 'specificationFilter_1',\n Value: '1',\n },\n ],\n },\n }\n\n const vbaseMock = new VBaseMock()\n const searchMock = new search(categoryTree, categoryChildren, facets as any)\n const result = await mountCompatibilityQuery({\n vbase: vbaseMock,\n search: searchMock,\n args,\n })\n\n expect(result).toStrictEqual({\n query: 'department/1/brand',\n map: 'c,specificationFilter_1,b',\n })\n })\n\n it('Should not transform urls in the format query?map=c', async () => {\n const argsList = [\n {\n map: 'c',\n query: 'category',\n },\n {\n map: 'specificationFilter_1',\n query: 'filtertest',\n },\n {\n map: 'c,specificationFilter_1',\n query: 'category/filtertest',\n },\n {\n map: 'specificationFilter_1,c,b',\n query: 'filtertest/category/brand',\n },\n ]\n\n for (const args of argsList) {\n const ClientsImpl = class ClientsMock extends Clients {\n public get search() {\n try {\n return new search([], {}, { SpecificationFilters: {} } as any)\n } catch (error) {\n console.error('Error getting search client:', error)\n\n return {} as any\n }\n }\n\n public get vbase() {\n try {\n return new VBaseMock()\n } catch (error) {\n console.error('Error getting vbase client:', error)\n\n return {} as any\n }\n }\n }\n\n const context = {\n metrics: {} as any,\n clients: new ClientsImpl({}, contextMock.object),\n ...contextMock.object,\n ...customContext.object,\n state: {\n ...state.object,\n },\n } as any\n\n const result = await getCompatibilityArgs(context, args)\n\n expect(result).toStrictEqual(args)\n }\n })\n})\n\n```" } ]
code_search-resolver_d561b1cb
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/search/utils.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport crypto from 'crypto'\nimport { compose, last, split, toLower, zip } from 'ramda'\nimport { Functions } from '@gocommerce/utils'\n\nimport { searchSlugify, Slugify } from '../../utils/slug'\nimport { Logger } from '@vtex/api'\n\nexport enum SearchCrossSellingTypes {\n whoboughtalsobought = 'whoboughtalsobought',\n similars = 'similars',\n whosawalsosaw = 'whosawalsosaw',\n whosawalsobought = 'whosawalsobought',\n accessories = 'accessories',\n suggestions = 'suggestions',\n}\n\nexport enum GroupByCrossSellingTypes {\n PRODUCT = 'PRODUCT',\n NONE = 'NONE',\n}\n\nconst pageTypeMapping: Record<string, string> = {\n Brand: 'brand',\n Department: 'department',\n Category: 'category',\n SubCategory: 'subcategory',\n NotFound: 'search',\n FullText: 'search',\n Search: 'search',\n}\n\nconst lastSegment = compose<string, string[], string>(\n last,\n split('/')\n)\n\nexport const zipQueryAndMap = (query?: string | null, map?: string | null) => {\n const cleanQuery = query || ''\n const cleanMap = map || ''\n return zip(\n cleanQuery\n .toLowerCase()\n .split('/')\n .map(decodeURIComponent),\n cleanMap.split(',')\n )\n}\n\nexport function hashMD5(text: string) {\n const hash = crypto.createHash('md5')\n return hash.update(text).digest('hex')\n}\n\nexport function findCategoryInTree(\n tree: CategoryTreeResponse[],\n values: string[],\n index = 0\n): CategoryTreeResponse | null {\n for (const node of tree) {\n const slug = lastSegment(node.url)\n if (slug.toUpperCase() === values[index].toUpperCase()) {\n if (index === values.length - 1) {\n return node\n }\n return findCategoryInTree(node.children, values, index + 1)\n }\n }\n return null\n}\n\nexport const getBrandFromSlug = async (\n brandSlug: string,\n search: Context['clients']['search']\n) => {\n const brands = await search.brands()\n return brands.find(\n brand =>\n brand.isActive &&\n (toLower(searchSlugify(brand.name)) === brandSlug ||\n toLower(Slugify(brand.name)) === brandSlug)\n )\n}\n\ntype CategoryMap = Record<string, CategoryTreeResponse>\n\n/**\n * We are doing this because the `get category` API is not returning the values\n * for slug and href. So we get the whole category tree and get that info from\n * there instead until the Search team fixes this issue with the category API.\n */\nexport async function getCategoryInfo(\n search: Context['clients']['search'],\n id: number,\n levels: number\n) {\n const categories = await search.categories(levels)\n const mapCategories = categories.reduce(appendToMap, {}) as CategoryMap\n\n const category = mapCategories[id] || { url: '' }\n\n return category\n}\n\nexport function buildCategoryMap(categoryTree: CategoryTreeResponse[]) {\n return categoryTree.reduce(appendToMap, {}) as CategoryMap\n}\n\n/**\n * That's a recursive function to fill an object like { [categoryId]: Category }\n * It will go down the category.children appending its children and so on.\n */\nfunction appendToMap(\n mapCategories: CategoryMap,\n category: CategoryTreeResponse\n) {\n mapCategories[category.id] = category\n\n mapCategories = category.children.reduce(appendToMap, mapCategories)\n\n return mapCategories\n}\n\nexport function translatePageType(searchPageType: string): string {\n return pageTypeMapping[searchPageType] || 'search'\n}\n\nexport const searchEncodeURI = (account: string) => (str: string) => {\n if (!Functions.isGoCommerceAcc(account)) {\n return str.replace(/[%\"'.()]/g, (c: string) => {\n switch (c) {\n case '%':\n return '@perc@'\n case '\"':\n return '@quo@'\n case \"'\":\n return '@squo@'\n case '.':\n return '@dot@'\n case '(':\n return '@lpar@'\n case ')':\n return '@rpar@'\n default: {\n return c\n }\n }\n })\n }\n return str\n}\n\nexport const searchDecodeURI = (str: string) => {\n return str.replace(/(\\@perc\\@|\\@slash\\@|\\@quo\\@|\\@squo\\@|\\@dot\\@|\\@lpar\\@|\\@rpar\\@)/g, (c: string) => {\n switch (c) {\n case '@perc@':\n return '%'\n case '@quo@':\n return \"\\\"\"\n case '@squo@':\n return \"\\'\"\n case '@dot@':\n return \".\"\n case '@lpar@':\n return \"(\"\n case '@rpar@':\n return \")\"\n case '@slash@':\n return \"/\"\n default: {\n return c\n }\n }\n })\n}\n\nexport const getMapAndPriceRangeFromSelectedFacets = (\n selectedFacets: SelectedFacet[]\n) => {\n const priceRangeIndex = selectedFacets.findIndex(\n facet => facet.key === 'priceRange'\n )\n const priceRange =\n priceRangeIndex > -1\n ? selectedFacets.splice(priceRangeIndex, 1)[0].value\n : undefined\n\n const map = selectedFacets.map(facet => facet.key).join(',')\n\n return [map, priceRange]\n}\n\nexport const breadcrumbMapKey = (queryUnit: string, mapUnit: string) => {\n return `${queryUnit}-${mapUnit}`\n}\n\nexport const validMapAndQuery = (query?: string, map?: string) => {\n const values = query?.split('/').filter(value => value)\n const facets = map?.split(',').filter(facetKey => facetKey)\n return values?.length === facets?.length\n}\n\nexport const logDegradedSearchError = (\n logger: Logger,\n error: DegradedSearchError\n) => {\n logger.warn({\n message: 'Degraded search',\n ...error,\n })\n}\n\nexport const getShippingOptionsFromSelectedFacets = (\n selectedFacets: SelectedFacet[] = []\n): [string[], SelectedFacet[]] => {\n const shippingOptions: string[] = []\n const filteredFacets: SelectedFacet[] = []\n\n selectedFacets.forEach((facet) => {\n if (facet.key === 'shipping-option') {\n shippingOptions.push(facet.value)\n } else {\n filteredFacets.push(facet)\n }\n })\n\n return [shippingOptions, filteredFacets]\n}\n\n```" } ]
code_search-resolver_1b6a0f49
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/search/recommendation.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { GroupByCrossSellingTypes, SearchCrossSellingTypes } from './utils'\n\ninterface RecommendationParentProps {\n product: SearchProduct\n groupBy: string\n}\n\nexport const resolvers = {\n Recommendation: {\n buy: (\n { product: {productId},\n groupBy = GroupByCrossSellingTypes.PRODUCT\n }: RecommendationParentProps,\n _: any,\n { clients: { search } }: Context\n ) =>\n {\n const groupByProduct =\n groupBy === GroupByCrossSellingTypes.PRODUCT ? true : false\n\n return search.crossSelling(\n productId,\n SearchCrossSellingTypes.whoboughtalsobought,\n groupByProduct\n )\n },\n\n similars: (\n { product: {productId},\n groupBy = GroupByCrossSellingTypes.PRODUCT\n }: RecommendationParentProps,\n _: any,\n { clients: { search } }: Context\n ) =>\n {\n const groupByProduct =\n groupBy === GroupByCrossSellingTypes.PRODUCT ? true : false\n\n return search.crossSelling(\n productId,\n SearchCrossSellingTypes.similars,\n groupByProduct\n )\n },\n\n view: (\n { product: {productId},\n groupBy = GroupByCrossSellingTypes.PRODUCT\n }: RecommendationParentProps,\n _: any,\n { clients: { search } }: Context\n ) =>\n {\n const groupByProduct =\n groupBy === GroupByCrossSellingTypes.PRODUCT ? true : false\n\n return search.crossSelling(\n productId,\n SearchCrossSellingTypes.whosawalsosaw,\n groupByProduct\n )\n },\n },\n}\n\n```" } ]
code_search-resolver_68bc767c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/search/skuSpecificationValue.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { addContextToTranslatableString } from '../../utils/i18n'\n\n// if it has `originalName`, the specification is already coming in the appropriate format and language\nexport const resolvers = {\n SKUSpecificationValue: {\n originalName: (value: SKUSpecificationValue) => {\n return value.originalName ? value.originalName : value.name\n },\n name: (value: SKUSpecificationValue, _: any, ctx: Context) => {\n return value.originalName ? value.name : addContextToTranslatableString(\n {\n content: value.name,\n context: value.fieldId\n },\n ctx\n )\n }\n }\n}\n\n```" } ]
code_search-resolver_02b5108d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/search/itemMetadata.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { Segment } from '@vtex/api'\nimport camelCase from 'camelcase'\nimport { both, pickBy } from 'ramda'\nimport { renameKeysWith } from '../../utils'\n\nconst isTruthy = (val?: string) => !!val\nconst isUtm = (_: any, key: string | number) => String(key).startsWith('utm')\nconst isValidUtm = both(isUtm, isTruthy)\n\ninterface Parent {\n items: SearchMetadataItem[]\n}\n\ninterface SimulationPayload {\n countryCode: string\n marketingData: Record<string, string>\n}\n\nconst getSimulationPayload = async (\n segment: Segment\n): Promise<SimulationPayload> => {\n const segmentData = await segment.getSegment()\n\n let marketingData: Record<string, string> = {}\n try {\n marketingData = renameKeysWith(\n camelCase,\n pickBy(isValidUtm, segmentData)\n ) as Record<string, string>\n } catch (e) {\n // TODO: Log to Splunk\n console.error(e)\n }\n\n return {\n countryCode: segmentData.countryCode,\n marketingData,\n }\n}\n\ntype PriceTableMap = Record<\n string,\n {\n compositionItem: CompositionItem\n simulationPayload: SimulationPayload\n items: SearchMetadataItem[]\n parent: SearchMetadataItem\n assemblyOption: AssemblyOption\n }[]\n>\n\nexport const resolvers = {\n ItemMetadata: {\n priceTable: async (\n { items }: Parent,\n _: any,\n { clients: { segment } }: Context\n ) => {\n const simulationPayload = await getSimulationPayload(segment)\n\n const itemsWithAssembly = items.filter(\n item => item.assemblyOptions.length > 0\n )\n\n const priceTableMap: PriceTableMap = itemsWithAssembly.reduce<PriceTableMap>((acc, item) => {\n for (const assemblyOption of item.assemblyOptions) {\n if (!assemblyOption.composition || !assemblyOption.composition.items) {\n continue\n }\n\n for (const compItem of assemblyOption.composition.items) {\n const currentArray = acc[compItem.priceTable] || []\n currentArray.push({\n compositionItem: compItem,\n simulationPayload,\n items: itemsWithAssembly,\n parent: item,\n assemblyOption,\n })\n acc[compItem.priceTable] = currentArray\n }\n }\n\n return acc\n }, {})\n\n return Object.entries(priceTableMap).map(\n ([priceTableName, priceTableValues]) => ({\n type: priceTableName,\n values: priceTableValues,\n })\n )\n },\n },\n}\n\n```" } ]
code_search-resolver_34d35ab0
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/search/constants.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const SEARCH_URLS_BUCKET = 'newSearchURLs'\nexport const SELLERS_BUCKET = 'sellersByRegionId'\nexport const CATEGORY_TREE_ROOT_BUCKET = 'categoryTree'\nexport const CATEGORY_TREE_CHILDREN_BUCKET = 'categoryTreeChildren'\nexport const SPECIFICATION_BUCKET = 'specificationField'\nexport const LIST_SPECIFICATIONS_BY_CATEGORY_ID = 'specificationByCategoryId'\nexport const CATEGORY_TREE_ROOT_PATH = 'categoryTree.json'\nexport const FACETS_BUCKET = 'facets'\nexport const SPEC_FILTER = 'specificationFilter'\nexport const MAP_QUERY_KEY = 'map'\nexport const MAP_VALUES_SEP = ','\nexport const PATH_SEPARATOR = '/'\nexport const SPACE_REPLACER = '-'\nexport const FILTER_TITLE_SEP = '_'\nexport const CATEGORY_SEGMENT = 'c'\nexport const FULL_TEXT_SEGMENT = 'ft'\n\nexport const APP_NAME = 'vtex.search-resolver@1.x'\n\n```" } ]
code_search-resolver_055ff471
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/search/newURLs.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { Search } from '../../clients/search'\nimport { VBase } from '@vtex/api'\nimport {\n SEARCH_URLS_BUCKET,\n CATEGORY_SEGMENT,\n FACETS_BUCKET,\n FULL_TEXT_SEGMENT,\n} from './constants'\nimport { CategoryTreeSegmentsFinder, CategoryIdNamePair } from '../../utils/CategoryTreeSegmentsFinder'\nimport { staleFromVBaseWhileRevalidate } from '../../utils/vbase'\nimport { searchSlugify } from '../../utils/slug'\nimport { PATH_SEPARATOR, MAP_SEPARATOR } from '../stats/constants'\n\nexport const hasFacetsBadArgs = ({ query, map }: QueryArgs) => !query || !map\n\nexport const toCompatibilityArgs = async (vbase:VBase, search: Search, args: QueryArgs): Promise<QueryArgs|undefined> => {\n const {query} = args\n if(!query){\n return\n }\n const { query: compatibilityQuery, map: compatibilityMap } = await staleFromVBaseWhileRevalidate(\n vbase, SEARCH_URLS_BUCKET, query, mountCompatibilityQuery, {vbase, search, args} )\n return { query: compatibilityQuery, map: compatibilityMap }\n}\n\nexport const mountCompatibilityQuery = async (params: {vbase: VBase, search: Search, args: any}) => {\n const {vbase, search, args} = params\n const { query, map } = args\n const querySegments = query.startsWith(PATH_SEPARATOR)? query.split(PATH_SEPARATOR).slice(1): query.split(PATH_SEPARATOR)\n\n const categoryTreeFinder = new CategoryTreeSegmentsFinder({vbase, search}, querySegments)\n const categories = await categoryTreeFinder.find()\n const facetsQuery = getFacetsQueryFromCategories(categories)\n \n const fieldsLookup = facetsQuery? await getCategoryFilters(vbase, search, facetsQuery): {}\n const mapSegments = fillCategoriesMapSegments(categories, map)\n\n const compatMapSegments = []\n const compatQuerySegments = []\n\n for(let segmentIndex = 0; segmentIndex < querySegments.length; segmentIndex++ ) {\n const querySegment = querySegments[segmentIndex]\n \n const [fieldName, fieldValue] = querySegment.split('_')\n const compatMapSegmentField = fieldsLookup[fieldName]\n \n const mapSegment = compatMapSegmentField || mapSegments.shift() || FULL_TEXT_SEGMENT\n compatMapSegments.push(mapSegment)\n compatQuerySegments.push(fieldValue || querySegment)\n }\n\n const compatibilityQuery = compatQuerySegments.join('/')\n const compatibilityMap = compatMapSegments.join(',')\n return { query: compatibilityQuery, map: compatibilityMap}\n}\n\nconst normalizeName = (name: string): string => searchSlugify(name)\n\nconst fillCategoriesMapSegments = (categories: (CategoryIdNamePair|null)[], map: string): (string|undefined)[] => {\n const mapSegments = map.split(MAP_SEPARATOR).filter(segment=> segment !== CATEGORY_SEGMENT)\n const segmentsFound = []\n\n for( const category of categories){\n if(!category){\n segmentsFound.push(mapSegments.shift())\n }else{\n segmentsFound.push(CATEGORY_SEGMENT)\n }\n }\n return [...segmentsFound, ...mapSegments]\n}\n\nconst getFacetsQueryFromCategories = (categories: (CategoryIdNamePair|null)[]) => {\n const queryArgs = categories.reduce((acc: QueryArgs, category) => {\n if(category){\n acc.query = acc.query? acc.query + PATH_SEPARATOR + category.name.toLocaleLowerCase(): category.name.toLocaleLowerCase()\n acc.map = acc.map? acc.map + MAP_SEPARATOR + CATEGORY_SEGMENT: CATEGORY_SEGMENT\n }\n return acc\n }, {query: '', map: ''} as QueryArgs)\n return !hasFacetsBadArgs(queryArgs)? `${queryArgs.query}?map=${queryArgs.map}`: null\n}\n\nconst getCategoryFilters = async (vbase: VBase, search: Search, query: string) => {\n const facets = await staleFromVBaseWhileRevalidate<SearchFacets>(\n vbase, FACETS_BUCKET, query, search.facets, query)\n return normalizedFiltersFromFacets(facets)\n}\n\nconst normalizedFiltersFromFacets = async (facets: SearchFacets) => {\n const specificationFilters = facets['SpecificationFilters']\n return Object.keys(specificationFilters).reduce((acc, filterKey) => {\n const facets = specificationFilters[filterKey]\n const normalizedFilterName = normalizeName(filterKey)\n acc[normalizedFilterName] = facets[0].Map\n return acc\n }, {} as Record<string, string>)\n}\n\n```" } ]
code_search-resolver_91afad46
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/search/itemMetadataPriceTableItem.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { Logger } from '@vtex/api'\nimport { isEmpty, path } from 'ramda'\nimport { getItemChoiceType, CHOICE_TYPES } from '../../utils/attachments'\nimport { logDegradedSearchError } from './utils'\n\ninterface Params {\n compositionItem: CompositionItem\n simulationPayload: {\n marketingData: Record<string, string>\n countryCode: string\n }\n items: SearchMetadataItem[]\n parent: SearchMetadataItem\n assemblyOption: AssemblyOption\n}\n\n// Generate a valid simulation list with this child, considering its a single item type\nconst getSimulationPayloadItemsForSingleFromTree = (\n parent: SearchMetadataItem,\n childId: string,\n seller: string,\n parentAssemblyBinding: string\n) => {\n return [\n { id: parent.id, quantity: 1, seller: parent.seller },\n {\n id: childId,\n seller,\n quantity: 1,\n parentItemIndex: 0,\n parentAssemblyBinding,\n },\n ]\n}\n\n// Generate a valid simulation list with this child, considering its a TOGGLE item type\nconst getSimulationPayloadItemsForToggleFromTree = (\n parent: SearchMetadataItem,\n childId: string,\n seller: string,\n assemblyOption: AssemblyOption,\n parentBasicTree: PayloadItem[]\n) => {\n const parentPayloadItem = {\n id: parent.id,\n quantity: 1,\n seller: parent.seller,\n }\n const basicChildItem = {\n id: childId,\n seller,\n quantity: 1,\n parentItemIndex: 0,\n parentAssemblyBinding: assemblyOption.id,\n }\n const siblings = parentBasicTree.filter(\n ({ parentAssemblyBinding }) => parentAssemblyBinding === assemblyOption.id\n )\n const siblingCount = siblings.length\n // See if we can add this item, considering the group max quantity\n if (siblingCount < assemblyOption.composition!.maxQuantity) {\n return [parentPayloadItem, basicChildItem]\n }\n\n // If there are siblings on the basic tree, remove it and add this child\n const brotherToBeRemoved = siblings.find(item => {\n const brotherComposition = assemblyOption.composition!.items.find(\n comp => comp.id === item.id\n )\n return brotherComposition!.minQuantity === 0\n })\n if (!brotherToBeRemoved) {\n return []\n }\n const withoutBrother = parentBasicTree.filter(\n ({ id, parentAssemblyBinding }) =>\n id !== brotherToBeRemoved.id &&\n parentAssemblyBinding !== brotherToBeRemoved.parentAssemblyBinding\n )\n return [parentPayloadItem, ...withoutBrother, basicChildItem]\n}\n\n// Generate a valid simulation list with this child, considering its a MULTIPLE item type\nconst getSimulationPayloadItemsForMultipleFromTree = (\n parent: SearchMetadataItem,\n assemblyOption: AssemblyOption,\n parentBasicTree: PayloadItem[],\n childCompositionItem: CompositionItem\n) => {\n const parentPayloadItem = {\n id: parent.id,\n quantity: 1,\n seller: parent.seller,\n }\n\n const basicItemQuantity = childCompositionItem.minQuantity || 1\n const familyMinimum = assemblyOption.composition!.minQuantity\n const basicChildItem = {\n id: childCompositionItem.id,\n seller: childCompositionItem.seller,\n quantity: basicItemQuantity,\n parentItemIndex: 0,\n parentAssemblyBinding: assemblyOption.id,\n }\n\n // Corner case that can be easily solved: when a single child can fill alone the whole group\n if (childCompositionItem.maxQuantity >= familyMinimum) {\n return [\n parentPayloadItem,\n { ...basicChildItem, quantity: familyMinimum || basicItemQuantity },\n ]\n }\n\n const siblings = parentBasicTree.filter(\n ({ parentAssemblyBinding, parentItemIndex }) =>\n parentAssemblyBinding === assemblyOption.id && parentItemIndex === 0\n )\n\n const siblingCount = siblings.reduce((sum, sib) => sum + sib.quantity, 0)\n const siblingsAllowed = assemblyOption.composition!.maxQuantity - siblingCount\n if (basicItemQuantity <= siblingsAllowed) {\n return [parentPayloadItem, ...siblings, basicChildItem]\n }\n\n let currentSiblingCount = siblingCount\n // We will iterate through the childs siblings and remove the minimum we should\n for (const brother of siblings) {\n const brotherComposition = assemblyOption.composition!.items.find(\n comp => comp.id === brother.id\n )\n const oldBrotherQuantity = brother.quantity\n brother.quantity = brotherComposition!.minQuantity\n currentSiblingCount -= oldBrotherQuantity - brotherComposition!.minQuantity\n const currentSiblingsAllowed =\n assemblyOption.composition!.maxQuantity - currentSiblingCount\n if (currentSiblingsAllowed >= basicItemQuantity) {\n // We can now break because we can add out chuld item safely\n break\n }\n }\n\n const nonEmptySiblings = siblings.filter(({ quantity }) => quantity > 0)\n return [parentPayloadItem, ...nonEmptySiblings, basicChildItem]\n}\n\nconst simulateAndGetPrice = async (\n payload: SimulationPayload,\n checkout: Context['clients']['checkout'],\n itemId: string,\n assemblyId: string,\n logger: Logger,\n) => {\n try {\n const simulation = await checkout.simulation(payload)\n const childInTree = simulation.items.find(\n item => itemId === item.id && assemblyId === item.parentAssemblyBinding\n )\n return childInTree ? childInTree.sellingPrice : 0\n } catch (e) {\n logDegradedSearchError(logger, {\n service: 'Checkout simulation',\n error: `Checkout simulation API returned an error for item ${itemId}.\n Simulation will be skipped for this item and the price of priceTable may be incorrect.`,\n errorStack: e,\n })\n return 0\n }\n}\n\nconst getSimulationPayloadItems = (\n assemblyOption: AssemblyOption,\n compositionItem: CompositionItem,\n parent: SearchMetadataItem,\n fatherBasicTree: PayloadItem[]\n) => {\n const assemblyType = getItemChoiceType(assemblyOption)\n\n if (assemblyType === CHOICE_TYPES.SINGLE) {\n return getSimulationPayloadItemsForSingleFromTree(\n parent,\n compositionItem.id,\n compositionItem.seller,\n assemblyOption.id\n )\n }\n if (assemblyType === CHOICE_TYPES.TOGGLE) {\n return getSimulationPayloadItemsForToggleFromTree(\n parent,\n compositionItem.id,\n compositionItem.seller,\n assemblyOption,\n fatherBasicTree\n )\n }\n return getSimulationPayloadItemsForMultipleFromTree(\n parent,\n assemblyOption,\n fatherBasicTree,\n compositionItem\n )\n}\n\nexport const resolvers = {\n PriceTableItem: {\n assemblyId: path(['assemblyOption', 'id']),\n id: path(['compositionItem', 'id']),\n price: async (\n { parent, simulationPayload, assemblyOption, compositionItem }: Params,\n _: any,\n { clients: { checkout }, vtex: { logger } }: Context\n ) => {\n const { id, priceTable } = compositionItem\n const { marketingData, countryCode } = simulationPayload\n const payload = {\n country: countryCode,\n isCheckedIn: false,\n priceTables: [priceTable],\n ...(isEmpty(marketingData) ? {} : { marketingData }),\n }\n\n const parentBasicTree = [\n { id: parent.id, seller: parent.seller, quantity: 1 },\n ] as PayloadItem[]\n\n for (const fatherAssemblyOption of parent.assemblyOptions) {\n const assemblyId = fatherAssemblyOption.id\n if (!fatherAssemblyOption.composition) {\n continue\n }\n const groupMinimum = fatherAssemblyOption.composition!.minQuantity\n const itemsInitialsSum = fatherAssemblyOption.composition!.items.reduce(\n (sum, item) => sum + item.initialQuantity,\n 0\n )\n // The basic tree will not contain children of this group\n if (groupMinimum !== itemsInitialsSum) {\n continue\n }\n for (const compItem of fatherAssemblyOption.composition!.items) {\n if (compItem.initialQuantity > 0) {\n parentBasicTree.push({\n id: compItem.id,\n quantity: compItem.initialQuantity,\n seller: compItem.seller,\n parentItemIndex: 0,\n parentAssemblyBinding: assemblyId,\n })\n }\n }\n }\n\n const itemInTree = parentBasicTree.find(\n item =>\n id === item.id && assemblyOption.id === item.parentAssemblyBinding\n )\n // If item is already in tree, just simulate and return the price\n if (itemInTree) {\n return simulateAndGetPrice(\n { ...payload, items: parentBasicTree },\n checkout,\n id,\n assemblyOption.id,\n logger,\n )\n }\n\n // If not in tree, include it, then simulate and get price\n const newSimulationPayloadItems = getSimulationPayloadItems(\n assemblyOption,\n compositionItem,\n parent,\n parentBasicTree\n )\n return simulateAndGetPrice(\n { ...payload, items: newSimulationPayloadItems },\n checkout,\n id,\n assemblyOption.id,\n logger,\n )\n },\n },\n}\n\n```" } ]
code_search-resolver_9c0e37f1
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/search/skuSpecification.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const resolvers = {\n SkuSpecification: {\n values: (skuSpecification: SkuSpecification) => {\n const fieldId = skuSpecification.field.id\n return skuSpecification.values.map(value => ({\n ...value,\n fieldId,\n }))\n },\n },\n}\n\n```" } ]
code_search-resolver_4bc0fd1b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/search/index.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { NotFoundError, UserInputError, createMessagesLoader } from '@vtex/api'\nimport { pathOr } from 'ramda'\n\nimport {\n buildAttributePath,\n convertOrderBy,\n} from '../../commons/compatibility-layer'\nimport { getWorkspaceSearchParamsFromStorage } from '../../routes/workspaceSearchParams'\nimport {\n fetchAutocompleteSuggestions,\n fetchCorrection,\n fetchSearchSuggestions,\n fetchTopSearches,\n} from '../../services/autocomplete'\nimport { fetchBanners } from '../../services/banners'\nimport { fetchFacets } from '../../services/facets'\nimport {\n ProductArgs,\n ProductIdentifier,\n ProductsByIdentifierArgs,\n resolveProduct,\n resolveProductsByIdentifier\n} from '../../services/product'\nimport { fetchProductSearch } from '../../services/productSearch'\nimport { fetchAppSettings } from '../../services/settings'\nimport { AdvertisementOptions, FacetsInput, ProductSearchInput, ProductsInput, SuggestionProductsArgs } from '../../typings/Search'\nimport { shouldTranslateToTenantLocale } from '../../utils/i18n'\nimport { resolvers as assemblyOptionResolvers } from './assemblyOption'\nimport { resolvers as autocompleteResolvers } from './autocomplete'\nimport { resolvers as brandResolvers } from './brand'\nimport { resolvers as categoryResolvers } from './category'\nimport { MAP_VALUES_SEP, PATH_SEPARATOR } from './constants'\nimport { resolvers as discountResolvers } from './discount'\nimport { resolvers as itemMetadataResolvers } from './itemMetadata'\nimport { resolvers as itemMetadataPriceTableItemResolvers } from './itemMetadataPriceTableItem'\nimport { resolvers as itemMetadataUnitResolvers } from './itemMetadataUnit'\nimport { getSearchMetaData } from './modules/metadata'\nimport { toCompatibilityArgs } from './newURLs'\nimport { resolvers as offerResolvers } from './offer'\nimport { resolvers as productResolvers } from './product'\nimport { resolvers as productPriceRangeResolvers } from './productPriceRange'\nimport { resolvers as recommendationResolvers } from './recommendation'\nimport { resolvers as searchBreadcrumbResolvers } from './searchBreadcrumb'\nimport { resolvers as skuResolvers } from './sku'\nimport { resolvers as skuSpecificationResolver } from './skuSpecification'\nimport { resolvers as skuSpecificationFieldResolver } from './skuSpecificationField'\nimport { resolvers as skuSpecificationValueResolver } from './skuSpecificationValue'\nimport {\n SearchCrossSellingTypes,\n getMapAndPriceRangeFromSelectedFacets,\n getShippingOptionsFromSelectedFacets,\n validMapAndQuery,\n} from './utils'\n\n\nenum CrossSellingInput {\n view = 'view',\n buy = 'buy',\n similars = 'similars',\n viewAndBought = 'viewAndBought',\n suggestions = 'suggestions',\n accessories = 'accessories',\n}\n\nenum CrossSellingGroupByInput {\n PRODUCT = 'PRODUCT',\n NONE = 'NONE',\n}\n\n// Legacy search format is our search with path?map=c,c,specificationFilter\n// Where it has specificationFilters and all segments in path are mapped in `map` querystring\nconst isLegacySearchFormat = ({\n query,\n map,\n}: {\n query: string\n map?: string\n}) => {\n if (!map) {\n return false\n }\n\n return map.split(MAP_VALUES_SEP).length === query.split(PATH_SEPARATOR).length\n}\n\nexport const getCompatibilityArgs = async <T extends QueryArgs>(\n ctx: Context,\n args: T\n) => {\n const {\n clients: { vbase, search },\n } = ctx\n\n const compatArgs = isLegacySearchFormat(args)\n ? args\n : await toCompatibilityArgs(vbase, search, args)\n\n const formattedArgs = compatArgs ? { ...args, ...compatArgs } : args\n\n // VTEX search does not understand brand/category/department and fails with error:\n // Query contains something not suited for search\n formattedArgs.map = formattedArgs.map\n ?.replace(/brand/g, 'b')\n ?.replace(/category(-[0-9]*)?/g, 'c')\n\n return formattedArgs\n}\n\ninterface ProductRecommendationArg {\n identifier?: ProductIdentifier\n type?: CrossSellingInput\n groupBy?: CrossSellingGroupByInput\n}\n\n\nconst inputToSearchCrossSelling = {\n [CrossSellingInput.buy]: SearchCrossSellingTypes.whoboughtalsobought,\n [CrossSellingInput.view]: SearchCrossSellingTypes.whosawalsosaw,\n [CrossSellingInput.similars]: SearchCrossSellingTypes.similars,\n [CrossSellingInput.viewAndBought]: SearchCrossSellingTypes.whosawalsobought,\n [CrossSellingInput.accessories]: SearchCrossSellingTypes.accessories,\n [CrossSellingInput.suggestions]: SearchCrossSellingTypes.suggestions,\n}\n\n/**\n * There is an URL pattern in VTEX where the number of mapSegments doesn't match the number of querySegments. This function deals with these cases.\n * Since this should not be a search concern, this function will be removed soon.\n *\n * @param {Context} ctx\n * @param {QueryArgs} args\n * @returns\n */\nconst getCompatibilityArgsFromSelectedFacets = async (\n ctx: Context,\n args: QueryArgs\n) => {\n const { selectedFacets, query } = args\n\n if (!selectedFacets || selectedFacets.length === 0 || !query) {\n return args\n }\n\n const [map, priceRange] = getMapAndPriceRangeFromSelectedFacets([\n ...selectedFacets,\n ])\n\n args.map = map\n\n if (isLegacySearchFormat({ query: args.query, map: args.map })) {\n return args\n }\n\n const compatibilityArgs = (await getCompatibilityArgs(ctx, args)) as QueryArgs\n\n const mapSegments = compatibilityArgs.map!.split(MAP_VALUES_SEP)\n const querySegments = compatibilityArgs.query!.split(PATH_SEPARATOR)\n\n args.selectedFacets = mapSegments.map((map, index) => {\n return {\n key: map,\n value: querySegments[index],\n }\n })\n\n if (priceRange) {\n args.selectedFacets.push({\n key: 'priceRange',\n value: priceRange,\n })\n }\n\n return args\n}\n\nconst translateToStoreDefaultLanguage = async (\n ctx: Context,\n term: string\n): Promise<string> => {\n const {\n clients,\n state,\n vtex: { locale: from, tenant },\n } = ctx\n\n const { locale: to } = tenant!\n\n if (!shouldTranslateToTenantLocale(ctx)) {\n // Do not translate if string already in correct language\n return term\n }\n\n if (!state.messagesTenantLanguage) {\n state.messagesTenantLanguage = createMessagesLoader(clients, to)\n }\n\n return state.messagesTenantLanguage!.load({\n from: from!,\n content: term,\n })\n}\n\nconst noop = () => {}\n\n// Does prefetching and warms up cache for up to the 10 first elements of a search, so if user clicks on product page\nconst searchFirstElements = (\n products: SearchProduct[],\n from: number | null = 0,\n search: Context['clients']['search']\n) => {\n if (from !== 0 || from == null) {\n // We do not want this for pages other than the first\n return\n }\n\n products\n .slice(0, Math.min(10, products.length))\n .forEach((product) =>\n search\n .productById(product.productId, undefined, undefined, false)\n .catch(noop)\n )\n}\n\nexport const fieldResolvers = {\n ...autocompleteResolvers,\n ...brandResolvers,\n ...categoryResolvers,\n ...itemMetadataResolvers,\n ...itemMetadataUnitResolvers,\n ...itemMetadataPriceTableItemResolvers,\n ...offerResolvers,\n ...discountResolvers,\n ...productResolvers,\n ...recommendationResolvers,\n ...skuResolvers,\n ...skuSpecificationResolver,\n ...skuSpecificationFieldResolver,\n ...skuSpecificationValueResolver,\n ...assemblyOptionResolvers,\n ...productPriceRangeResolvers,\n ...searchBreadcrumbResolvers,\n}\n\nconst getTranslatedSearchTerm = async (\n query: SearchArgs['query'],\n map: SearchArgs['map'],\n ctx: Context\n) => {\n if (!query || !map || !shouldTranslateToTenantLocale(ctx)) {\n return query\n }\n\n const ftSearchIndex = map.split(',').findIndex((m) => m === 'ft')\n\n if (ftSearchIndex === -1) {\n return query\n }\n\n const queryArray = query.split('/')\n const queryUnit = queryArray[ftSearchIndex]\n const translated = await translateToStoreDefaultLanguage(ctx, queryUnit)\n const queryTranslated = [\n ...queryArray.slice(0, ftSearchIndex),\n translated,\n ...queryArray.slice(ftSearchIndex + 1),\n ]\n\n return queryTranslated.join('/')\n}\n\nconst buildSpecificationFiltersAsFacets = (\n specificationFilters: string[]\n): SelectedFacet[] => {\n return specificationFilters.map((specificationFilter: string) => {\n const [key, value] = specificationFilter.split(':')\n\n return { key, value }\n })\n}\n\nconst buildCategoriesAndSubcategoriesAsFacets = (\n categories: string\n): SelectedFacet[] => {\n const categoriesAndSubcategories = categories.split('/')\n\n return categoriesAndSubcategories.map((c: string) => {\n return { key: 'c', value: c }\n })\n}\n\nconst buildSelectedFacets = (args: SearchArgs) => {\n const selectedFacets: SelectedFacet[] = []\n\n if (args.priceRange) {\n selectedFacets.push({ key: 'priceRange', value: args.priceRange })\n }\n\n if (args.category) {\n selectedFacets.push(\n ...buildCategoriesAndSubcategoriesAsFacets(args.category)\n )\n }\n\n if (args.collection) {\n selectedFacets.push({ key: 'productClusterIds', value: args.collection })\n }\n\n if (args.specificationFilters) {\n selectedFacets.push(\n ...buildSpecificationFiltersAsFacets(args.specificationFilters)\n )\n }\n\n return selectedFacets\n}\n\nconst defaultAdvertisementOptions: AdvertisementOptions = {\n showSponsored: false,\n sponsoredCount: 3,\n repeatSponsoredProducts: true,\n}\n\nexport const queries = {\n autocomplete: async (\n _: any,\n args: { maxRows: number; searchTerm?: string },\n ctx: Context\n ) => {\n const {\n clients: { search },\n } = ctx\n\n if (!args.searchTerm) {\n throw new UserInputError('No search term provided')\n }\n\n const translatedTerm = await translateToStoreDefaultLanguage(\n ctx,\n args.searchTerm\n )\n\n const { itemsReturned } = await search.autocomplete({\n maxRows: args.maxRows,\n searchTerm: translatedTerm,\n })\n\n return {\n cacheId: args.searchTerm,\n itemsReturned,\n }\n },\n facets: async (_: any, args: FacetsInput, ctx: any) => {\n const [shippingOptions, facets] = getShippingOptionsFromSelectedFacets(\n args.selectedFacets\n )\n\n args.selectedFacets = facets\n\n args = (await getCompatibilityArgsFromSelectedFacets(\n ctx,\n args\n )) as FacetsInput\n\n const { selectedFacets } = args\n\n return fetchFacets(ctx, { args, selectedFacets, shippingOptions })\n },\n\n product: async (_: any, rawArgs: ProductArgs, ctx: Context) => {\n const product = await resolveProduct(ctx, rawArgs)\n\n if (!product) {\n const identifier = rawArgs?.identifier || {\n field: 'slug',\n value: rawArgs.slug!,\n }\n\n throw new NotFoundError(\n `No product was found with requested ${\n identifier.field\n } ${JSON.stringify({ identifier })}`\n )\n }\n\n return product\n },\n\n products: async (_: any, args: ProductsInput, ctx: Context) => {\n const {\n clients: { intelligentSearchApi },\n } = ctx\n\n const {\n to,\n orderBy,\n advertisementOptions = defaultAdvertisementOptions,\n } = args\n\n if (to && to > 2500) {\n throw new UserInputError(\n `The maximum value allowed for the 'to' argument is 2500`\n )\n }\n\n const selectedFacets: SelectedFacet[] = buildSelectedFacets(args)\n const workspaceSearchParams = await getWorkspaceSearchParamsFromStorage(ctx)\n\n const biggyArgs = {\n ...advertisementOptions,\n ...args,\n sort: convertOrderBy(orderBy),\n ...workspaceSearchParams,\n }\n\n // unnecessary field. It's is an object and breaks the @vtex/api cache\n delete biggyArgs.selectedFacets\n\n const result = await intelligentSearchApi.productSearch(\n biggyArgs,\n buildAttributePath(selectedFacets),\n args.shippingOptions\n )\n\n if (ctx.vtex.tenant) {\n ctx.translated = result.translated\n }\n\n return result.products\n },\n\n productsByIdentifier: async (\n _: any,\n args: ProductsByIdentifierArgs,\n ctx: Context\n ) => {\n const products = await resolveProductsByIdentifier(ctx, args)\n\n if (products.length > 0) {\n return products\n }\n\n throw new NotFoundError(\n `No products were found with requested ${args.field}`\n )\n },\n\n productSearch: async (_: any, args: ProductSearchInput, ctx: any) => {\n const [shippingOptions, facets] = getShippingOptionsFromSelectedFacets(\n args.selectedFacets\n )\n\n args.selectedFacets = facets\n\n args = (await getCompatibilityArgsFromSelectedFacets(\n ctx,\n args\n )) as ProductSearchInput\n\n if (!validMapAndQuery(args.query, args.map)) {\n ctx.vtex.logger.warn({\n message: 'Invalid map or query',\n query: args.query,\n map: args.map,\n })\n }\n\n const { selectedFacets } = args\n\n return fetchProductSearch(ctx, args, selectedFacets, shippingOptions)\n },\n\n sponsoredProducts: async (_: any, args: ProductSearchInput, ctx: any) => {\n const [shippingOptions, facets] = getShippingOptionsFromSelectedFacets(\n args.selectedFacets\n )\n\n args.selectedFacets = facets\n\n args = (await getCompatibilityArgsFromSelectedFacets(\n ctx,\n args\n )) as ProductSearchInput\n\n if (!validMapAndQuery(args.query, args.map)) {\n ctx.vtex.logger.warn({\n message: 'Invalid map or query',\n query: args.query,\n map: args.map,\n })\n }\n\n const { intelligentSearchApi } = ctx.clients\n const { selectedFacets, fullText } = args\n\n const workspaceSearchParams = await getWorkspaceSearchParamsFromStorage(ctx)\n\n const biggyArgs: { [key: string]: any } = {\n ...args,\n query: fullText,\n sort: convertOrderBy(args.orderBy),\n ...args.options,\n ...workspaceSearchParams,\n }\n\n // unnecessary field. It's is an object and breaks the @vtex/api cache\n delete biggyArgs.selectedFacets\n\n const result = await intelligentSearchApi.sponsoredProducts(\n { ...biggyArgs },\n buildAttributePath(selectedFacets),\n shippingOptions\n )\n\n if (ctx.vtex.tenant && !args.productOriginVtex) {\n ctx.translated = result.translated\n }\n\n return result\n },\n\n productRecommendations: async (\n _: any,\n { identifier, type, groupBy }: ProductRecommendationArg,\n ctx: Context\n ) => {\n if (identifier == null || type == null) {\n throw new UserInputError('Wrong input provided')\n }\n\n const { shouldUseNewPDPEndpoint } = await fetchAppSettings(ctx)\n const searchType = inputToSearchCrossSelling[type]\n let productId = identifier.value\n\n if (identifier.field !== 'id') {\n const product = await queries.product(_, { identifier }, ctx)\n\n productId = product!.productId\n }\n\n const groupByProduct =\n groupBy === CrossSellingGroupByInput.PRODUCT ? true : false\n\n if (shouldUseNewPDPEndpoint) {\n ctx.translated = true\n }\n\n const products = await ctx.clients.search.crossSelling(\n productId,\n searchType,\n groupByProduct,\n shouldUseNewPDPEndpoint ? ctx.vtex.locale : undefined\n )\n\n searchFirstElements(products, 0, ctx.clients.search)\n // We add a custom cacheId because these products are not exactly like the other products from search apis.\n // Each product is basically a SKU and you may have two products in response with same ID but each one representing a SKU.\n\n return products.map((product) => {\n const skuId = pathOr('', ['items', '0', 'itemId'], product)\n\n return {\n ...product,\n cacheId: `${product.linkText}-${skuId}`,\n }\n })\n },\n\n searchMetadata: async (_: any, args: SearchMetadataArgs, ctx: Context) => {\n if (args.selectedFacets) {\n const { maps, queries } = args.selectedFacets.reduce(\n (acc, { key, value }) => {\n if (key !== 'region-id') {\n acc.maps.push(key)\n acc.queries.push(value)\n }\n\n return acc\n },\n { maps: [] as string[], queries: [] as string[] }\n )\n\n const map = maps.join(',')\n const query = queries.join('/')\n\n args.map = map\n args.query = args.query || query || undefined\n }\n\n const query = await getTranslatedSearchTerm(\n args.query ?? '',\n args.map ?? '',\n ctx\n )\n\n const translatedArgs = {\n ...args,\n query,\n }\n\n const compatibilityArgs = await getCompatibilityArgs<SearchArgs>(\n ctx,\n translatedArgs as SearchArgs\n )\n\n return getSearchMetaData(_, compatibilityArgs, ctx)\n },\n topSearches: (_: any, __: any, ctx: Context) => {\n return fetchTopSearches(ctx)\n },\n autocompleteSearchSuggestions: (\n _: any,\n args: { fullText: string },\n ctx: Context\n ) => {\n return fetchAutocompleteSuggestions(ctx, args.fullText)\n },\n productSuggestions: async (\n _: any,\n args: SuggestionProductsArgs,\n ctx: Context\n ) => {\n const {\n clients: { intelligentSearchApi },\n } = ctx\n\n const workspaceSearchParams = await getWorkspaceSearchParamsFromStorage(ctx)\n const selectedFacets: SelectedFacet[] =\n args.facetKey && args.facetValue\n ? [{ key: args.facetKey, value: args.facetValue }]\n : []\n\n const { advertisementOptions = defaultAdvertisementOptions } = args\n\n const biggyArgs: { [key: string]: any } = {\n ...advertisementOptions,\n ...args,\n query: args.fullText,\n from: 0,\n to: args.count ? args.count - 1 : 4,\n sort: convertOrderBy(args.orderBy),\n allowRedirect: false, // When there is a redirect, no product is returned.\n ...workspaceSearchParams,\n }\n\n // unnecessary field. It's is an object and breaks the @vtex/api cache\n delete biggyArgs.selectedFacets\n\n const result = await intelligentSearchApi.productSearch(\n biggyArgs,\n buildAttributePath(selectedFacets),\n args.shippingOptions\n )\n\n if (ctx.vtex.tenant && !args.productOriginVtex) {\n ctx.translated = result.translated\n }\n\n return {\n ...result,\n count: result.recordsFiltered,\n }\n },\n banners: (\n _: any,\n args: { fullText: string; selectedFacets: SelectedFacet[] },\n ctx: Context\n ) => {\n return fetchBanners(ctx, args)\n },\n correction: (_: any, args: { fullText: string }, ctx: Context) => {\n return fetchCorrection(ctx, args.fullText)\n },\n searchSuggestions: (_: any, args: { fullText: string }, ctx: Context) => {\n return fetchSearchSuggestions(ctx, args.fullText)\n },\n}\n\n```" } ]
code_search-resolver_7b2e9bb4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/search/assemblyOption.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const resolvers = {\n AssemblyOption: {\n inputValues: (\n { inputValues }: AssemblyOption,\n ): InputValue[] => {\n return Object.keys(inputValues).reduce<InputValue[]>((acc, label) => {\n const inputValue = inputValues[label]\n const type = defineInputValueType(inputValue)\n\n const maxLength = type === InputValueType.TEXT\n ? inputValue.maximumNumberOfCharacters : undefined\n\n const domain = type === InputValueType.OPTIONS\n ? inputValue.domain\n : undefined\n\n const defaultValue = type === InputValueType.OPTIONS\n ? inputValue.domain[0]\n : type === InputValueType.BOOLEAN\n ? stringToBoolean(inputValue.domain[0])\n : ''\n\n acc.push({\n label,\n type,\n maxLength,\n defaultValue,\n domain,\n })\n\n return acc\n }, [])\n }\n },\n}\n\nfunction defineInputValueType(inputValue: RawInputValue): InputValueType {\n const domain = inputValue.domain\n\n // If domain is something like ['true', 'false'] or ['false', 'true']\n if (\n domain && domain.length === 2 &&\n domain.indexOf('true') !== -1 && domain.indexOf('false') !== -1\n ) {\n return InputValueType.BOOLEAN\n }\n\n // If domain is something like ['Sans serif', 'Roman']\n if (domain && domain.length > 0) {\n return InputValueType.OPTIONS\n }\n\n return InputValueType.TEXT\n}\n\nfunction stringToBoolean(value: string) {\n return value === 'true'\n ? true\n : false\n}\n\n\ninterface InputValue {\n label: string\n maxLength?: number\n type: InputValueType\n defaultValue: string|boolean\n domain?: string[]\n}\n\nenum InputValueType {\n TEXT = 'TEXT',\n BOOLEAN = 'BOOLEAN',\n OPTIONS = 'OPTIONS',\n}\n```" } ]
code_search-resolver_aac76b4f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/search/offer.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { propOr } from 'ramda'\n\nconst InstallmentsCriteria = {\n ALL: 'ALL',\n MAX: 'MAX',\n MIN: 'MIN',\n MAX_WITHOUT_INTEREST: 'MAX_WITHOUT_INTEREST',\n MAX_WITH_INTEREST: 'MAX_WITH_INTEREST',\n}\n\nconst gte = (a: number, b: number) => a > b\nconst lte = (a: number, b: number) => a < b\n\nconst includesCaseInsensitive = (list: string[], item: string) => {\n const normalizedList = list.map(j => String(j).toUpperCase())\n\n return normalizedList.indexOf(String(item).toUpperCase()) > -1\n}\n\n\nexport const resolvers = {\n Offer: {\n Installments: (\n { Installments }: CommertialOffer,\n {\n criteria,\n rates,\n excludedPaymentSystems,\n includedPaymentSystems,\n } : {\n criteria?: string\n rates?: boolean\n excludedPaymentSystems?: string[]\n includedPaymentSystems?: string[]\n }\n ) => {\n if (criteria === InstallmentsCriteria.ALL || Installments.length === 0) {\n return Installments\n }\n\n /** TODO: Transforms arguments for backwards-compatibility. Should be cleaned up in the future */\n if (criteria === InstallmentsCriteria.MAX_WITH_INTEREST || criteria === InstallmentsCriteria.MAX_WITHOUT_INTEREST){\n rates = criteria === InstallmentsCriteria.MAX_WITHOUT_INTEREST\n criteria = InstallmentsCriteria.MAX\n }\n\n let filteredInstallments = !rates\n ? Installments\n : Installments.filter(({ InterestRate }) => !InterestRate)\n\n if (includedPaymentSystems) {\n filteredInstallments = filteredInstallments.filter(\n ({ PaymentSystemName }) =>\n includesCaseInsensitive(includedPaymentSystems, PaymentSystemName)\n )\n }\n\n if (excludedPaymentSystems) {\n filteredInstallments = filteredInstallments.filter(\n ({ PaymentSystemName }) =>\n (includesCaseInsensitive(excludedPaymentSystems, PaymentSystemName) === false))\n }\n\n const compareFunc = criteria === InstallmentsCriteria.MAX ? gte : lte\n const value = filteredInstallments.reduce(\n (acc, currentValue) =>\n compareFunc(\n currentValue.NumberOfInstallments,\n acc.NumberOfInstallments\n )\n ? currentValue\n : acc,\n filteredInstallments[0]\n )\n return [value]\n },\n teasers: (offer: CommertialOffer) => {\n return offer.teasers ?? offer.Teasers ?? []\n },\n giftSkuIds: propOr([], 'GiftSkuIds'),\n gifts: async ({ GiftSkuIds }: CommertialOffer, _: any, ctx: Context) => {\n if (GiftSkuIds.length === 0) {\n return []\n }\n\n const catalogGiftProducts = await ctx.clients.search.productsBySku(GiftSkuIds).catch(() => null)\n\n if (!catalogGiftProducts || catalogGiftProducts.length === 0) {\n return []\n }\n\n const giftProducts = GiftSkuIds.map(skuId => {\n let giftSku = null\n let giftProduct = null\n\n for (const currGiftProduct of catalogGiftProducts) {\n const currGiftSku = currGiftProduct.items.find(item => item.itemId === skuId)\n if (currGiftSku) {\n giftSku = currGiftSku\n giftProduct = currGiftProduct\n break\n }\n }\n if (!giftProduct || !giftSku) {\n return null\n }\n const {\n productName,\n brand,\n linkText,\n description,\n } = giftProduct\n return {\n productName,\n brand,\n linkText,\n description,\n skuName: giftSku?.nameComplete ?? '',\n images: giftSku?.images.map(({ imageLabel, imageUrl, imageText }) => ({\n imageUrl,\n imageLabel,\n imageText,\n })) ?? [],\n }\n })\n const filteredGiftProducts = giftProducts.filter(Boolean)\n\n return filteredGiftProducts\n },\n discountHighlights: (offer: CommertialOffer) => {\n return offer.DiscountHighLight || offer.discountHighlights || []\n },\n spotPrice: (offer: CommertialOffer) => {\n if (offer.spotPrice) {\n return offer.spotPrice\n }\n const sellingPrice = offer.Price\n const spotPrice: number | undefined = offer.Installments.find(({NumberOfInstallments, Value}) => {\n return (NumberOfInstallments === 1 && Value < sellingPrice)\n })?.Value;\n return spotPrice || sellingPrice\n },\n taxPercentage: (offer: CommertialOffer) => {\n if (!offer.Price) {\n return 0\n }\n\n return offer.Tax / offer.Price\n }\n },\n}\n\n```" } ]
code_search-resolver_e96a33d5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/search/productPriceRange.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface Root {\n offers: CommertialOffer[]\n}\n\nconst getMaxAndMinForAttribute = (\n offers: CommertialOffer[],\n attribute: 'Price' | 'ListPrice'\n) => {\n return offers.reduce(\n (acc, currentOffer) => {\n const highPrice =\n currentOffer[attribute] > acc.highPrice\n ? currentOffer[attribute]\n : acc.highPrice\n const lowPrice =\n currentOffer[attribute] < acc.lowPrice && currentOffer[attribute] > 0\n ? currentOffer[attribute]\n : acc.lowPrice\n return { highPrice, lowPrice }\n },\n { highPrice: 0, lowPrice: Infinity }\n )\n}\n\nexport const resolvers = {\n ProductPriceRange: {\n sellingPrice: ({ offers }: Root) => {\n return getMaxAndMinForAttribute(offers, 'Price')\n },\n listPrice: ({ offers }: Root) => {\n return getMaxAndMinForAttribute(offers, 'ListPrice')\n },\n },\n PriceRange: {\n lowPrice: ({ lowPrice }: any) => lowPrice !== Infinity ? lowPrice : null\n }\n}\n\n```" } ]
code_search-resolver_25c6b452
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/search/productPriceRange.test.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { resolvers } from './product'\nimport { resolvers as productPriceResolvers } from './productPriceRange'\nimport { mockContext } from '../../__mocks__/helpers'\nimport { productPriceRange } from '../../__mocks__/productPriceRange'\nimport { clone } from 'ramda'\n\ndescribe('tests related to ProductPriceRange type', () => {\n beforeEach(() => {\n jest.clearAllMocks()\n mockContext.vtex.platform = 'vtex'\n })\n\n test('gets correct value for product with many skus and prices', () => {\n const { offers } = resolvers.Product.priceRange(\n productPriceRange as any\n ) as { offers: CommertialOffer[] }\n\n const sellingPrice = productPriceResolvers.ProductPriceRange.sellingPrice({\n offers,\n })\n expect(sellingPrice).toMatchObject({ highPrice: 100, lowPrice: 20 })\n\n const listPrice = productPriceResolvers.ProductPriceRange.listPrice({\n offers,\n })\n\n expect(listPrice).toMatchObject({ highPrice: 150, lowPrice: 30 })\n })\n test('works for products with many sellers', () => {\n const cloneProduct = clone(productPriceRange)\n cloneProduct.items[0].sellers.push({\n sellerId: '99',\n commertialOffer: {\n Price: 10,\n ListPrice: 160,\n AvailableQuantity: 10,\n },\n } as any)\n\n const { offers } = resolvers.Product.priceRange(cloneProduct as any) as {\n offers: CommertialOffer[]\n }\n const sellingPrice = productPriceResolvers.ProductPriceRange.sellingPrice({\n offers,\n })\n expect(sellingPrice).toMatchObject({ highPrice: 100, lowPrice: 10 })\n\n const listPrice = productPriceResolvers.ProductPriceRange.listPrice({\n offers,\n })\n\n expect(listPrice).toMatchObject({ highPrice: 160, lowPrice: 30 })\n })\n\n test('ignores sellers with no availability', () => {\n const cloneProduct = clone(productPriceRange)\n cloneProduct.items[0].sellers.push({\n sellerId: '99',\n commertialOffer: {\n Price: 10,\n ListPrice: 10,\n AvailableQuantity: 0,\n },\n } as any)\n\n const { offers } = resolvers.Product.priceRange(cloneProduct as any) as {\n offers: CommertialOffer[]\n }\n const sellingPrice = productPriceResolvers.ProductPriceRange.sellingPrice({\n offers,\n })\n expect(sellingPrice).toMatchObject({ highPrice: 100, lowPrice: 20 })\n\n const listPrice = productPriceResolvers.ProductPriceRange.listPrice({\n offers,\n })\n\n expect(listPrice).toMatchObject({ highPrice: 150, lowPrice: 30 })\n })\n})\n\n```" } ]
code_search-resolver_7b9dcf22
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/search/product.test.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* eslint-disable jest/no-mocks-import */\n/* eslint-disable jest/no-identical-title */\n\nimport {\n getBindingLocale,\n mockContext,\n resetContext,\n} from '../../__mocks__/helpers'\nimport { getProduct } from '../../__mocks__/product'\nimport productSpecs from '../../__mocks__/productSpecs'\nimport { resolvers } from './product'\n\ndescribe('tests related to product resolver', () => {\n beforeEach(() => {\n jest.clearAllMocks()\n resetContext()\n })\n describe('categoryTree resolver', () => {\n it('ensure that VTEX account never calls the category tree search API', async () => {\n const searchProduct = getProduct()\n\n await resolvers.Product.categoryTree(\n searchProduct as any,\n {},\n mockContext as any\n )\n expect(mockContext.clients.search.category).toBeCalledTimes(2)\n expect(mockContext.clients.search.categories).toBeCalledTimes(0)\n })\n\n it('get correct main category tree for product with only one tree', async () => {\n const searchProduct = getProduct()\n\n await resolvers.Product.categoryTree(\n searchProduct as any,\n {},\n mockContext as any\n )\n expect(mockContext.clients.search.category).toBeCalledTimes(2)\n expect(mockContext.clients.search.category.mock.calls[0][0]).toBe(25)\n expect(mockContext.clients.search.category.mock.calls[1][0]).toBe(10)\n })\n\n it('get correct main category tree for product with more than one tree', async () => {\n const categoriesIds = [\n '/101/101003/101003009/',\n '/101/101003/',\n '/101/',\n '/101/101019/101019004/',\n '/101/101019/',\n '/103/103023/103023003/',\n '/103/103023/',\n '/103/',\n ]\n\n const searchProduct = getProduct({\n categoriesIds,\n categoryId: '101003009',\n })\n\n await resolvers.Product.categoryTree(\n searchProduct as any,\n {},\n mockContext as any\n )\n expect(mockContext.clients.search.category).toBeCalledTimes(3)\n expect(mockContext.clients.search.category.mock.calls[0][0]).toBe(101)\n expect(mockContext.clients.search.category.mock.calls[1][0]).toBe(101003)\n expect(mockContext.clients.search.category.mock.calls[2][0]).toBe(\n 101003009\n )\n })\n\n it('ensure that GC account calls the category tree API', async () => {\n const searchProduct = getProduct()\n\n mockContext.vtex.platform = 'gocommerce'\n mockContext.vtex.logger = { info: jest.fn() } as any\n mockContext.clients.search.categories.mockImplementation(() => [\n {\n id: '10',\n name: 'a',\n url: 'a',\n children: [],\n },\n {\n id: '25',\n name: 'a',\n url: 'a',\n children: [],\n },\n ])\n const result = await resolvers.Product.categoryTree(\n searchProduct as any,\n {},\n mockContext as any\n )\n\n expect(mockContext.clients.search.category).toBeCalledTimes(0)\n expect(mockContext.clients.search.categories).toBeCalledTimes(1)\n expect(mockContext.clients.search.categories.mock.calls[0][0]).toBe(2) // ensure maximum level was correct\n expect(result!).toHaveLength(2)\n })\n\n it('if categoryId does not match any id in categoriesIds, find biggest tree', async () => {\n const searchProduct = getProduct()\n\n searchProduct.categoryId = '1'\n searchProduct.categoriesIds = ['/2064927469/', '/2064927469/630877787/']\n await resolvers.Product.categoryTree(\n searchProduct as any,\n {},\n mockContext as any\n )\n expect(mockContext.clients.search.category).toBeCalledTimes(2)\n expect(mockContext.clients.search.category.mock.calls[0][0]).toBe(\n 2064927469\n )\n expect(mockContext.clients.search.category.mock.calls[1][0]).toBe(\n 630877787\n )\n })\n })\n\n it('if custom cacheId is given, it should be returned', async () => {\n const searchProduct = getProduct()\n const cacheAsSlug = await resolvers.Product.cacheId(searchProduct as any)\n\n expect(cacheAsSlug).toBe(searchProduct.linkText)\n\n searchProduct.cacheId = 'CUSTOM_CACHE'\n\n const customCache = await resolvers.Product.cacheId(searchProduct as any)\n\n expect(customCache).toBe('CUSTOM_CACHE')\n })\n\n it('productClusters should be properly formatted', () => {\n const product = getProduct()\n\n product.productClusters = {\n '140': 'Casual Footwear',\n '195': 'All products',\n '201': 'Third',\n }\n const result = resolvers.Product.productClusters(product as any)\n\n expect(result).toMatchObject([\n { id: '140', name: 'Casual Footwear' },\n { id: '195', name: 'All products' },\n { id: '201', name: 'Third' },\n ])\n })\n\n it('productClusters should not break if value is null', () => {\n const product = getProduct()\n\n product.productClusters = null as any\n const result = resolvers.Product.productClusters(product as any)\n\n expect(result).toMatchObject([])\n })\n\n it('clusterHighlights should be properly formatted', () => {\n const product = getProduct()\n\n product.clusterHighlights = {\n '140': 'Casual Footwear',\n '195': 'All products',\n '201': 'Third',\n }\n const result = resolvers.Product.clusterHighlights(product as any)\n\n expect(result).toMatchObject([\n { id: '140', name: 'Casual Footwear' },\n { id: '195', name: 'All products' },\n { id: '201', name: 'Third' },\n ])\n })\n\n it('clusterHighlights should not break if value is null', () => {\n const product = getProduct()\n\n product.clusterHighlights = null as any\n const result = resolvers.Product.clusterHighlights(product as any)\n\n expect(result).toMatchObject([])\n })\n\n it('clusterHighlights should be properly formatted', () => {\n const product = getProduct()\n\n product.clusterHighlights = {\n '140': 'Casual Footwear',\n '195': 'All products',\n '201': 'Third',\n }\n const result = resolvers.Product.clusterHighlights(product as any)\n\n expect(result).toMatchObject([\n { id: '140', name: 'Casual Footwear' },\n { id: '195', name: 'All products' },\n { id: '201', name: 'Third' },\n ])\n })\n\n it('clusterHighlights should not break if value is null', () => {\n const product = getProduct()\n\n product.clusterHighlights = null as any\n const result = resolvers.Product.clusterHighlights(product as any)\n\n expect(result).toMatchObject([])\n })\n\n describe('linkText resolver', () => {\n it('linkText with binding with different locales', async () => {\n const product = getProduct()\n\n mockContext.vtex.binding.locale = 'fr-FR'\n mockContext.clients.rewriter.getRoute.mockImplementationOnce(\n (id: string, type: string, bindingId: string) =>\n Promise.resolve(`/${id}-${type}-${bindingId}-${getBindingLocale()}/p`)\n )\n const result = await resolvers.Product.linkText(\n product as any,\n {},\n mockContext as any\n )\n\n expect(result).toBe('16-product-abc-fr-FR')\n })\n it('linkText for same binding language', async () => {\n const product = getProduct()\n const result = await resolvers.Product.linkText(\n product as any,\n {},\n mockContext as any\n )\n\n expect(result).toBe(product.linkText)\n })\n })\n\n describe('specificationGroups resolver', () => {\n it('specifications groups should have expected format but not translated if same locale as tenant', async () => {\n const product = getProduct()\n const result = (await resolvers.Product.specificationGroups(\n product as any,\n {},\n mockContext as any\n )) as any\n\n expect(result[0]).toMatchObject({\n name: 'Tamanho',\n specifications: [{ name: 'Numero do calçado', values: ['35'] }],\n })\n expect(result[1]).toMatchObject({\n name: 'allSpecifications',\n specifications: [{ name: 'Numero do calçado', values: ['35'] }],\n })\n })\n\n it('specifications groups should have expected format and translated values', async () => {\n mockContext.vtex.locale = 'fr-FR'\n const product = getProduct()\n\n mockContext.clients.search.filtersInCategoryFromId.mockImplementationOnce(\n () => [\n {\n Name: 'Numero do calçado',\n FieldId: 'specification-Id',\n },\n ]\n )\n const result = (await resolvers.Product.specificationGroups(\n product as any,\n {},\n mockContext as any\n )) as any\n\n expect(result[0]).toMatchObject({\n name: 'Tamanho (((16))) <<<pt-BR>>> [[[original]]]',\n specifications: [\n {\n name: 'Numero do calçado (((specification-Id))) <<<pt-BR>>> [[[original]]]',\n values: ['35 (((specification-Id))) <<<pt-BR>>> [[[original]]]'],\n },\n ],\n })\n expect(result[1]).toMatchObject({\n name: 'allSpecifications (((16))) <<<pt-BR>>> [[[original]]]',\n specifications: [\n {\n name: 'Numero do calçado (((specification-Id))) <<<pt-BR>>> [[[original]]]',\n values: ['35 (((specification-Id))) <<<pt-BR>>> [[[original]]]'],\n },\n ],\n })\n })\n\n it('should filter specifications that are not visible', async () => {\n const specificationGroups = await resolvers.Product.specificationGroups(\n productSpecs as any,\n {},\n mockContext\n )\n\n expect(specificationGroups).toHaveLength(5)\n\n // If the completeSpecifications doesn't give info on the specs, return it\n const cucardas = specificationGroups?.find(\n (group) => group.name === 'Cucardas'\n )\n\n expect(cucardas).toBeTruthy()\n })\n })\n\n describe('properties resolver', () => {\n it('properties should have expected format but not translated if same locale as tenant', async () => {\n const product = getProduct()\n const result = await resolvers.Product.properties(\n product as any,\n {},\n mockContext as any\n )\n\n expect(result).toMatchObject([\n { name: 'Numero do calçado', values: ['35'] },\n ])\n })\n it('specifications groups should have expected format and translated values', async () => {\n mockContext.vtex.locale = 'fr-FR'\n const product = getProduct({\n allSpecifications: ['Numero do calçado', 'testeName'],\n testeName: ['teste value'],\n })\n\n mockContext.clients.search.filtersInCategoryFromId.mockImplementationOnce(\n () => [\n {\n Name: 'Numero do calçado',\n FieldId: 'specification-Id',\n },\n {\n Name: 'testeName',\n FieldId: 'teste-id',\n },\n ]\n )\n const result = await resolvers.Product.properties(\n product as any,\n {},\n mockContext as any\n )\n\n expect(result).toMatchObject([\n {\n name: 'Numero do calçado (((specification-Id))) <<<pt-BR>>> [[[original]]]',\n values: ['35 (((specification-Id))) <<<pt-BR>>> [[[original]]]'],\n },\n {\n name: 'testeName (((teste-id))) <<<pt-BR>>> [[[original]]]',\n values: ['teste value (((teste-id))) <<<pt-BR>>> [[[original]]]'],\n },\n ])\n })\n })\n})\n\n```" } ]
code_search-resolver_2bd15554
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/search/productSearch.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { path } from 'ramda'\nimport { IOResponse } from '@vtex/api'\nimport { Functions } from '@gocommerce/utils'\nimport { zipQueryAndMap, breadcrumbMapKey, logDegradedSearchError } from './utils'\nimport { shouldTranslateToBinding } from '../../utils/i18n'\n\ninterface ProductSearchParent {\n productsRaw: IOResponse<SearchProduct[]>\n translatedArgs: SearchArgs\n searchMetaData: {\n titleTag: string | null\n metaTagDescription: string | null\n }\n}\n\ninterface Metadata {\n id: string\n name: string\n}\n\nconst getTypeForCategory = (index: number) => {\n if (index === 0) {\n return 'department'\n }\n if (index === 1) {\n return 'category'\n }\n return 'subcategory'\n}\n\nconst getRouteForQueryUnit = async (queryUnit: string, mapUnit: string, categoriesSearched: string[], index: number, ctx: Context) => {\n const bindingId = ctx.vtex.binding!.id!\n const key = `${queryUnit}-${mapUnit}`\n\n if (mapUnit === 'b') {\n const brandPageType = await ctx.clients.search.pageType(queryUnit, 'map=b')\n\n if (index === 0) {\n try {\n // if it is a brand page, we should check if there is a route on rewriter for this brand\n const brandFromRewriter = await ctx.clients.rewriter.getRoute(brandPageType.id, 'brand', bindingId)\n if (brandFromRewriter) {\n return { path: brandFromRewriter, key, name: brandPageType.name, id: brandPageType.id }\n }\n } catch (e) {\n logDegradedSearchError(ctx.vtex.logger, {\n service: 'Rewriter getRoute',\n error: `Rewriter getRoute query returned an error for brand ${queryUnit}. Breadcrumb data may be incorrect.`,\n errorStack: e,\n })\n }\n }\n return { path: queryUnit, key, name: brandPageType.name, id: brandPageType.id }\n }\n\n if (mapUnit === 'c') {\n const categoryPosition = categoriesSearched.findIndex(cat => cat === queryUnit)\n const category = await ctx.clients.search.pageType(categoriesSearched.slice(0, categoryPosition + 1).join('/'))\n try {\n const route = await ctx.clients.rewriter.getRoute(category.id, getTypeForCategory(categoryPosition), bindingId)\n return { path: route ?? queryUnit, key, name: category.name, id: category.id }\n } catch (e) {\n logDegradedSearchError(ctx.vtex.logger, {\n service: 'Rewriter getRoute',\n error: `Rewriter getRoute query returned an error for category ${category.id}. Breadcrumb data may be incorrect.`,\n errorStack: e,\n })\n return { path: queryUnit, key, name: category.name, id: category.id }\n }\n }\n\n return { path: queryUnit, key, name: null, id: null }\n}\n\nconst breadcrumbDataWithBinding = async (queryAndMap: [string, string][], categoriesSearched: string[], mapArray: string[], ctx: Context) => {\n const queryTranslationsAndKeys = await Promise.all(queryAndMap.map(([queryUnit, mapUnit], index) => {\n return getRouteForQueryUnit(queryUnit, mapUnit, categoriesSearched, index, ctx)\n }))\n const queryTranslations = queryTranslationsAndKeys.reduce((acc, curr) => {\n acc[curr.key] = curr.path\n return acc\n }, {} as Record<string, string>)\n\n const metadataMap = queryTranslationsAndKeys.filter(({ name }) => Boolean(name)).reduce((acc, curr) => {\n acc[curr.key] = { name: curr.name!, id: curr.id! }\n return acc\n }, {} as Record<string, Metadata>)\n\n const indexFirstCategory = mapArray.findIndex(m => m === 'c')\n const hrefs = queryAndMap.reduce((acc, curr) => {\n const [queryUnit, mapUnit] = curr\n const slug = mapUnit === 'c' || mapUnit === 'b' ? queryTranslations[breadcrumbMapKey(queryUnit, mapUnit)] : queryUnit\n let prefix = acc.length > 0 ? acc[acc.length - 1] : ''\n if (mapUnit === 'c') {\n prefix = indexFirstCategory > 0 ? acc[indexFirstCategory - 1] : ''\n }\n const noSlashSlug = slug.startsWith('/') ? slug.slice(1) : slug\n const url = `${prefix}/${noSlashSlug}`\n acc.push(url)\n return acc\n }, [] as string[])\n\n return { hrefs, metadataMap }\n}\n\nexport const resolvers = {\n ProductSearch: {\n titleTag: path(['searchMetaData', 'titleTag']),\n metaTagDescription: path(['searchMetaData', 'metaTagDescription']),\n recordsFiltered: ({ productsRaw }: ProductSearchParent) => {\n const {\n headers: { resources },\n } = productsRaw\n const quantity = resources.split('/')[1]\n return parseInt(quantity, 10)\n },\n products: ({ productsRaw }: ProductSearchParent, _: any, ctx: Context) => {\n let hasBroken = false\n for (const product of productsRaw.data) {\n for (const item of product.items) {\n if (item.sellers == null) {\n const config: any = (productsRaw as any).config\n ctx.vtex.logger.error({\n message: 'Item missing sellers!',\n searchUrl: config.url.replace(/\\/proxy\\/authenticated\\/catalog|\\/proxy\\/catalog/, ''),\n params: JSON.stringify(config.params)\n })\n hasBroken = true\n break\n }\n }\n if (hasBroken) {\n break\n }\n }\n return productsRaw.data\n },\n breadcrumb: async (\n { translatedArgs, productsRaw: { data: products } }: ProductSearchParent,\n _: any,\n ctx: Context\n ) => {\n const { vtex: { account }, clients: { search } } = ctx\n const query = translatedArgs?.query || ''\n const map = translatedArgs?.map || ''\n const queryAndMap = zipQueryAndMap(\n translatedArgs?.query,\n translatedArgs?.map\n )\n const categoriesSearched = queryAndMap\n .filter(([_, m]) => m === 'c')\n .map(([q]) => q)\n\n const categoriesCount = map.split(',').filter(m => m === 'c').length\n const categories =\n !!categoriesCount && Functions.isGoCommerceAcc(account)\n ? await search.categories(categoriesCount)\n : []\n\n const queryArray = query.split('/')\n const mapArray = map.split(',')\n\n const { metadataMap, hrefs } =\n shouldTranslateToBinding(ctx) ?\n await breadcrumbDataWithBinding(queryAndMap, categoriesSearched, mapArray, ctx)\n : { metadataMap: {}, hrefs: null }\n\n return queryAndMap.map(\n ([queryUnit, mapUnit]: [string, string], index: number) => ({\n queryUnit,\n mapUnit,\n index,\n queryArray,\n mapArray,\n categories,\n categoriesSearched,\n products,\n metadataMap,\n hrefs\n })\n )\n },\n },\n}\n\n```" } ]
code_search-resolver_efee4310
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/search/sku.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { find, head, map, replace, slice } from 'ramda'\n\nimport {\n formatTranslatableProp,\n addContextToTranslatableString,\n} from '../../utils/i18n'\n\ntype Attachment = {\n id: number\n name: string\n required: boolean\n domainValues: DomainValue[]\n}\n\ntype DomainValue = {\n FieldName: string\n MaxCaracters: string\n DomainValues: string\n}\n\nexport const resolvers = {\n SKU: {\n name: formatTranslatableProp<SearchItem, 'name', 'itemId'>(\n 'name',\n 'itemId'\n ),\n\n nameComplete: formatTranslatableProp<SearchItem, 'nameComplete', 'itemId'>(\n 'nameComplete',\n 'itemId'\n ),\n\n attachments: ({ attachments = [] }: SearchItem) => {\n const attachmentsResults: Attachment[] = []\n\n attachments.forEach((attachment) => {\n // Response from Portal Search\n if (typeof attachment.domainValues === 'string') {\n attachmentsResults.push({\n ...attachment,\n required: attachment.required ?? false,\n domainValues: JSON.parse(attachment.domainValues) as DomainValue[],\n })\n }\n\n // Response from IS API\n if (attachment.fields) {\n attachmentsResults.push({\n ...attachment,\n required: attachment.isRequired ?? false,\n domainValues: attachment.fields.map((field) => ({\n FieldName: field.fieldName,\n MaxCaracters: field.maxCharacters,\n DomainValues: field.domainValues,\n })),\n })\n }\n })\n\n return attachmentsResults\n },\n\n images: ({ images = [] }: SearchItem, { quantity }: { quantity: number }) =>\n map(\n (image) => ({\n cacheId: image.imageId,\n ...image,\n imageUrl: replace('http://', 'https://', image.imageUrl),\n }),\n quantity > 0 ? slice(0, quantity, images) : images\n ),\n\n kitItems: (\n { kitItems }: SearchItem,\n _: any,\n { clients: { search } }: Context\n ) =>\n !kitItems\n ? []\n : kitItems.map(async (kitItem) => {\n const products = await search.productBySku(kitItem.itemId)\n const { items: skus = [], ...product } = head(products) || {}\n const sku = find(({ itemId }) => itemId === kitItem.itemId, skus)\n\n return { ...kitItem, product, sku }\n }),\n\n variations: (sku: SearchItemExtended, _: any, ctx: Context) => {\n if (!sku) {\n return sku\n }\n\n const variations = (sku.variations || []).map((variationObj) => {\n const variationName =\n typeof variationObj === 'string'\n ? variationObj\n : (variationObj as { name: string }).name\n\n const fieldId = (sku.skuSpecifications || []).find(\n (specification) => specification.field.name === variationName\n )?.field?.id\n\n const variationsValues = (sku as any)[variationName] as string[]\n\n return {\n name: addContextToTranslatableString(\n { content: variationName, context: fieldId },\n ctx\n ),\n values: variationsValues.map((value) =>\n addContextToTranslatableString(\n { content: value, context: fieldId },\n ctx\n )\n ),\n }\n })\n\n return variations\n },\n\n videos: ({ Videos, videos }: SearchItem) => {\n const sanitizedVideo = Videos ?? videos\n\n const formattedVideo = sanitizedVideo.map((video: string) => ({\n videoUrl: video,\n }))\n\n return formattedVideo\n },\n },\n}\n\n```" } ]
code_search-resolver_d0209c13
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/benefits/index.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { flatten, indexOf, path } from 'ramda'\n\nconst SKU_SEPARATOR = ','\nconst CATALOG = 'Catalog'\nconst DEFAULT_SELLER = '1'\nconst DEFAULT_QUANTITY = 1\n\nexport const fieldResolvers = {\n Benefit: {\n items: async (benefit: any, _: any, { clients: { search } }: Context) => {\n const { teaserType, conditions, effects } = benefit\n\n if (teaserType === CATALOG) {\n const {\n parameters: conditionsParameters,\n minimumQuantity = DEFAULT_QUANTITY,\n } = conditions\n\n const { parameters: effectsParameters } = effects\n\n const items = await Promise.all(\n conditionsParameters.map(\n async (conditionsParameter: any, index: any) => {\n const skuIds: string[] = conditionsParameter.value.split(\n SKU_SEPARATOR\n )\n const discount = effectsParameters[index].value\n const products = await search.productsBySku(skuIds)\n\n return products.map((product: any) => {\n const benefitSKUIds: any = []\n\n product.items.map((item: any) => {\n if (indexOf(item.itemId, skuIds) > -1) {\n benefitSKUIds.push(item.itemId)\n }\n })\n\n return {\n benefitProduct: product,\n benefitSKUIds,\n discount,\n minQuantity: minimumQuantity,\n }\n })\n }\n )\n )\n return flatten(items)\n }\n return\n },\n },\n}\n\nexport const getBenefits = async (\n itemId: string,\n { clients: { checkout } }: Context\n): Promise<unknown[]> => {\n const requestBody = {\n items: [\n {\n id: itemId,\n quantity: DEFAULT_QUANTITY,\n seller: DEFAULT_SELLER,\n },\n ],\n }\n const benefitsData = await checkout.simulation(requestBody)\n return path(['ratesAndBenefitsData', 'teaser'], benefitsData) || []\n}\n\n```" } ]
code_search-resolver_4044660c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/stats/searchURLsCount.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { VBase } from '@vtex/api'\nimport { VBASE_BUCKET, URL_COUNT_FILE_PATH } from './constants'\nimport { SearchStatsUrlCount } from './searchStats'\n\nexport enum SORT {\n ASC = 'ASC',\n DESC = 'DESC',\n}\n\nexport const searchURLsCount = async (\n vbase: VBase,\n limit: number,\n sort: SORT = SORT.DESC\n) => {\n const data = (await vbase.getJSON<SearchStatsUrlCount>(\n VBASE_BUCKET,\n URL_COUNT_FILE_PATH,\n true\n )) as SearchStatsUrlCount\n let comparator = urlsCountDESCComparator\n\n if (sort === SORT.ASC) {\n comparator = urlsCountASCComparator\n }\n\n return (\n (data &&\n Object.entries(data.searchUrlCount)\n .sort(comparator)\n .slice(0, limit)\n .map(searchUrlStat => {\n return { path: searchUrlStat[0], count: searchUrlStat[1] }\n })) ||\n []\n )\n}\n\nconst urlsCountASCComparator = (\n urlStatsA: [string, number],\n urlStatsB: [string, number]\n) => {\n return urlStatsA[1] - urlStatsB[1]\n}\n\nconst urlsCountDESCComparator = (\n urlStatsA: [string, number],\n urlStatsB: [string, number]\n) => {\n return urlStatsB[1] - urlStatsA[1]\n}\n\n```" } ]
code_search-resolver_2d4853d6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/stats/searchStats.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n PATH_SEPARATOR,\n MAP_QUERY_PARAM,\n MAP_SEPARATOR,\n VBASE_BUCKET,\n URL_COUNT_FILE_PATH,\n INDEXING_UPDATE_FREQUENCY,\n INDEXING_EVENT_ROUTE_NAME,\n} from './constants'\n\nexport interface SearchStatsUrlCount {\n updatedCount: number\n searchUrlCount: Record<string, number>\n}\n\nexport const count = async (ctx: Context, args: SearchArgs) => {\n const {\n clients: { vbase },\n } = ctx\n\n const searchURLPath = `${PATH_SEPARATOR}${args.query}?${MAP_QUERY_PARAM}=${args.map}`\n const pathSegments = args.query && args.query.split(PATH_SEPARATOR)\n const mapSegments = args.map && args.map.split(MAP_SEPARATOR)\n\n if (pathSegments && mapSegments && pathSegments.length === mapSegments.length) {\n const data = ((await vbase.getJSON<SearchStatsUrlCount>(\n VBASE_BUCKET,\n URL_COUNT_FILE_PATH,\n true\n )) || { updatedCount: 0, searchUrlCount: {} }) as SearchStatsUrlCount\n\n data.searchUrlCount[searchURLPath] = (data.searchUrlCount[searchURLPath] || 0) + 1\n data.updatedCount = data.updatedCount + 1\n if (data.updatedCount === INDEXING_UPDATE_FREQUENCY) {\n data.updatedCount = 0\n sendIndexSearchUrlsEvent(ctx)\n }\n\n vbase.saveJSON<SearchStatsUrlCount>(VBASE_BUCKET, URL_COUNT_FILE_PATH, data)\n }\n}\n\nconst sendIndexSearchUrlsEvent = async (ctx: Context) => {\n const { clients: { events }, vtex: { locale, tenant, binding } } = ctx\n events.sendEvent('', INDEXING_EVENT_ROUTE_NAME, {locale, tenant, binding})\n}\n```" } ]
code_search-resolver_da18a215
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/stats/constants.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const VBASE_BUCKET = 'searchStats'\nexport const URL_COUNT_FILE_PATH = 'searchUrlsCount'\n\nexport const INDEXING_UPDATE_FREQUENCY = 500\nexport const INDEXING_EVENT_ROUTE_NAME = 'searchUrlsCountIndex'\n\nexport const MAP_QUERY_PARAM = 'map'\nexport const PATH_SEPARATOR = '/'\nexport const MAP_SEPARATOR = ','\n```" } ]
code_search-resolver_4f0a61e7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/stats/index.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { searchURLsCount, SORT } from \"./searchURLsCount\"\n\nexport const queries = {\n searchURLsCount: async (\n _: any,\n args: { limit: number, sort?: SORT },\n ctx: Context\n ) => {\n const { clients: { vbase } } = ctx\n const count = searchURLsCount(vbase, args.limit, args.sort)\n return count\n },\n}\n\n```" } ]
code_search-resolver_8977301d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-resolver/node/resolvers/search/modules/metadata.ts from the search-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n tail,\n head,\n compose,\n prop,\n join,\n map,\n filter,\n findLastIndex,\n split,\n toLower,\n reverse,\n complement,\n isNil,\n} from 'ramda'\nimport { Functions } from '@gocommerce/utils'\n\nimport { zipQueryAndMap, findCategoryInTree, getBrandFromSlug, searchDecodeURI } from '../utils'\nimport { toTitleCase } from '../../../utils/string'\nimport { formatTranslatableProp, translateManyToCurrentLanguage, Message, shouldTranslateToUserLocale } from '../../../utils/i18n'\n\ntype TupleString = [string, string]\n\nconst categoryKeys = ['c', 'category', 'category-1', 'category-2', 'category-3']\n\nconst isTupleMap = (t: TupleString) => t[1] ? categoryKeys.includes(t[1]) : false\n\nconst getLastCategoryIndex = findLastIndex(isTupleMap)\n\nconst categoriesOnlyQuery = compose<\n TupleString[],\n TupleString[],\n string[],\n string\n>(\n join('/'),\n map(prop('0')),\n filter(isTupleMap)\n)\n\nconst getAndParsePagetype = async (path: string, ctx: Context) => {\n const pagetype = await ctx.clients.search.pageType(path).catch((e) => {\n ctx.vtex.logger.error({\n message: 'Failed to call the pageType API.',\n data: e\n })\n\n return null\n })\n\n if (!pagetype) {\n return emptyTitleTag\n }\n\n return {\n titleTag: pagetype.title || pagetype.name,\n metaTagDescription: pagetype.metaTagDescription,\n id: pagetype.id,\n }\n}\n\nconst getCategoryMetadata = async (\n { map, query }: SearchMetadataArgs,\n ctx: Context\n): Promise<SearchMetadata> => {\n const {\n vtex: { account },\n clients: { search },\n } = ctx\n const queryAndMap = zipQueryAndMap(query, map)\n const cleanQuery = categoriesOnlyQuery(queryAndMap)\n\n if (Functions.isGoCommerceAcc(account)) {\n // GoCommerce does not have pagetype query implemented yet\n const category =\n findCategoryInTree(\n await search.categories(cleanQuery.split('/').length),\n cleanQuery.split('/')\n )\n return {\n id: null,\n metaTagDescription: category?.MetaTagDescription,\n titleTag: category?.Title ?? category?.name,\n }\n }\n\n return getAndParsePagetype(cleanQuery, ctx)\n}\n\nconst getBrandMetadata = async (\n query: SearchMetadataArgs['query'],\n ctx: Context\n): Promise<SearchMetadata> => {\n const {\n vtex: { account },\n clients: { search },\n } = ctx\n const cleanQuery = head(split('/', query || '')) || ''\n\n if (Functions.isGoCommerceAcc(account)) {\n const brand = await getBrandFromSlug(toLower(cleanQuery), search)\n return {\n id: null,\n metaTagDescription: brand?.metaTagDescription,\n titleTag: brand?.title ?? brand?.name,\n }\n }\n return getAndParsePagetype(cleanQuery, ctx)\n}\n\nexport const getSpecificationFilterName = (name: string) => {\n return toTitleCase(searchDecodeURI(decodeURI(name)))\n}\n\nconst getClusterMetadata = async (\n args: SearchMetadataArgs,\n ctx: Context,\n): Promise<SearchMetadata> => {\n const {\n clients: { search }\n } = ctx\n\n const searchArgs: SearchArgs = Object.assign({}, {\n query: args.query ?? \"\",\n map: args.map ?? \"\",\n selectedFacets: args.selectedFacets\n }, {\n category: null,\n specificationFilters: null,\n collection: null,\n salesChannel: null,\n orderBy: null,\n from: null,\n to: null,\n hideUnavailableItems: null,\n simulationBehavior: null,\n completeSpecifications: false,\n })\n\n const clusterId = head(args.query?.split(',') ?? [])\n const products = await search.products(searchArgs)\n const productWithCluster = products?.find(\n ({ productClusters }) => !!productClusters[clusterId]\n )\n const clusterName = (productWithCluster && productWithCluster.productClusters[clusterId]) || \"\"\n\n try {\n return {\n titleTag: decodeURI(clusterName),\n metaTagDescription: null,\n }\n } catch {\n return {\n titleTag: clusterName,\n metaTagDescription: null,\n }\n }\n}\n\nconst getPrimaryMetadata = (\n args: SearchMetadataArgs,\n ctx: Context\n): Promise<SearchMetadata> | SearchMetadata => {\n const map = args.map || ''\n const firstMap = head(map.split(','))\n if (categoryKeys.includes(firstMap)) {\n return getCategoryMetadata(args, ctx)\n }\n if (firstMap === 'b' || firstMap === 'brand') {\n return getBrandMetadata(args.query, ctx)\n }\n if (firstMap === 'productClusterIds') {\n return getClusterMetadata(args, ctx)\n }\n if (firstMap && firstMap.includes('specificationFilter')) {\n const cleanQuery = args.query || ''\n const name = head(cleanQuery.split('/')) || ''\n return {\n titleTag: getSpecificationFilterName(name),\n metaTagDescription: null,\n }\n }\n if (firstMap === 'ft') {\n const cleanQuery = args.query || ''\n const term = head(cleanQuery.split('/')) || ''\n return {\n titleTag: decodeURI(term),\n metaTagDescription: null,\n }\n }\n return emptyTitleTag\n}\n\nconst getNameForRemainingMaps = async (\n remainingTuples: [string, string][],\n ctx: Context\n) => {\n const {\n vtex: { account },\n clients: { search },\n } = ctx\n const lastCategoryIndex = getLastCategoryIndex(remainingTuples)\n const isGC = Functions.isGoCommerceAcc(account)\n const names = await Promise.all(\n remainingTuples.map(async ([query, map], index) => {\n if (map === 'c' && index === lastCategoryIndex && !isGC) {\n const cleanQuery = categoriesOnlyQuery(remainingTuples)\n const pagetype = await search.pageType(cleanQuery).catch(() => null)\n if (pagetype) {\n return pagetype.name\n }\n }\n if ((map === 'b' || map === 'brand') && !isGC) {\n const brand = await search.pageType(decodeURI(query), 'map=b').catch(() => null)\n if (brand) {\n return brand.name\n }\n }\n if (map.includes('specificationFilter')) {\n return getSpecificationFilterName(query)\n }\n return null\n })\n )\n return names\n}\n\nexport const emptyTitleTag = {\n titleTag: null,\n metaTagDescription: null,\n}\n\ntype StringNull = string | null | undefined\n\nconst removeNulls = <T>(array: (T | null | undefined)[]): T[] => array.filter(Boolean) as T[]\n\nconst isNotNil = complement(isNil)\nconst joinNames = compose<StringNull[], string[], string[], string>(\n join(' - '),\n reverse,\n filter(isNotNil) as any\n)\n\nconst translateTitles = (metadata: SearchMetadata, otherNames: (string | null)[], ctx: Context) => {\n const messages: Message[] = []\n if (metadata.titleTag) {\n messages.push({ content: metadata.titleTag, context: metadata.id ?? undefined })\n }\n messages.push(...removeNulls(otherNames).map(name => ({ content: name })))\n return translateManyToCurrentLanguage(messages, ctx)\n}\n\n/**\n * Get metadata of category/brand APIs\n *\n * @param _\n * @param args\n * @param ctx\n */\nexport const getSearchMetaData = async (\n _: any,\n args: SearchMetadataArgs,\n ctx: Context\n) => {\n const queryAndMap = zipQueryAndMap(args.query, args.map)\n if (queryAndMap.length === 0) {\n return emptyTitleTag\n }\n\n const isFirstCategory = queryAndMap[0][1] === 'c'\n const tailTuples = tail(queryAndMap)\n\n const validTuples = tailTuples.filter(\n ([_, m]) =>\n m === 'b' ||\n m === 'brand' ||\n m.includes('specificationFilter') ||\n (m === 'c' && !isFirstCategory)\n )\n const [metadata, otherNames] = await Promise.all([\n getPrimaryMetadata(args, ctx),\n getNameForRemainingMaps(validTuples, ctx),\n ])\n\n const titleTagNames =\n shouldTranslateToUserLocale(ctx) ?\n (await translateTitles(metadata, otherNames, ctx))\n : [metadata.titleTag, ...otherNames]\n return {\n titleTag: joinNames(titleTagNames),\n metaTagDescription: formatTranslatableProp<SearchMetadata, 'metaTagDescription', 'id'>('metaTagDescription', 'id')(metadata, {}, ctx),\n }\n}\n\n```" } ]
code_trusted_cc677185
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of trusted/docs/README.md from the trusted VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# Trusted\n\nOpen the VTEX APP Store and install the app on your store.\n\nor\n\nRun the following command:\n\n```sh\nvtex install vtexeurope.trusted@0.x\n```\n\nNext, open the app settings on your admin and fill the form with your appKey, and the days after you should receive the email.\n\n```" } ]
code_trusted_1927f9ee
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of trusted/react/index.tsx from the trusted VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { canUseDOM } from 'vtex.render-runtime'\nimport { PixelMessage } from './typings/events'\nimport { createIFrame } from './utils'\n\nexport async function handleEvents(e: PixelMessage) {\n switch (e.data.eventName) {\n case 'vtex:orderPlaced': {\n\n const eventData = e?.data\n const email = eventData?.visitorContactInfo?.[0]\n const firstName = eventData?.visitorContactInfo?.[1]\n const orderId = eventData?.transactionId\n\n const DEFAULT_VISITOR_ADDRESS_STATE = window?.__trusted?.defaultAddressState\n const shippingCounty = eventData?.visitorAddressState || DEFAULT_VISITOR_ADDRESS_STATE\n\n createIFrame({\n appKey: window?.__trusted?.appKey,\n days: window?.__trusted?.days,\n email,\n firstName,\n orderId,\n shippingCounty,\n })\n return\n }\n default: {\n return\n }\n }\n}\n\nif (canUseDOM) {\n window.addEventListener('message', handleEvents)\n}\n\n```" } ]
code_trusted_9c3a6b13
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of trusted/react/utils.ts from the trusted VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const createIFrame = (params: Params) => {\n const iframe = document.createElement('iframe')\n iframe.height = '1'\n iframe.width = '1'\n iframe.scrolling = 'no'\n iframe.marginHeight = '0'\n iframe.marginWidth = '0'\n const iframeSrc =\n `https://feedback.trusted.ro/api/${params.appKey}/?email=${params.email}&name=${params.firstName}&order=${params.orderId}&county=${params.shippingCounty}&email_after=${params.days}`\n\n iframe.src = iframeSrc\n\n document.body.appendChild(iframe)\n}\n\n```" } ]
code_trusted_e97e08ec
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of trusted/react/package.json from the trusted VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"scripts\": {\n \"test\": \"vtex-test-tools test\"\n },\n \"dependencies\": {\n \"axios\": \"^0.21.1\",\n \"ramda\": \"^0.26.1\",\n \"moment\": \"^2.29.1\"\n },\n \"devDependencies\": {\n \"@types/graphql\": \"^14.5.0\",\n \"@types/jest\": \"^24.0.11\",\n \"@types/node\": \"^11.13.0\",\n \"@types/ramda\": \"^0.26.5\",\n \"@vtex/test-tools\": \"^1.1.0\",\n \"eslint\": \"^5.16.0\",\n \"eslint-config-vtex-react\": \"^4.1.0\",\n \"graphql\": \"^14.5.4\",\n \"prettier\": \"^1.18.2\",\n \"tslint-eslint-rules\": \"^5.4.0\",\n \"typescript\": \"3.9.7\",\n \"vtex.pixel-interfaces\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.pixel-interfaces@1.1.1/public/_types/react\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.126.11/public/@types/vtex.render-runtime\"\n },\n \"version\": \"0.1.4\"\n}\n\n```" } ]
code_trusted_de4daab4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of trusted/store/interfaces.json from the trusted VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"pixel.trusted\": {\n \"component\": \"index\"\n }\n}\n\n```" } ]
code_trusted_15d68a35
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of trusted/react/typings/events.d.ts from the trusted VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport interface PixelMessage extends MessageEvent {\n data:\n | ProductViewData\n | ProductClickData\n | OrderPlacedData\n | OrderPlacedTrackedData\n | PageViewData\n | ProductImpressionData\n | AddToCartData\n | RemoveToCartData\n | UserData\n}\n\nexport interface EventData {\n event: string\n eventName: string\n currency: string\n}\n\nexport interface PageViewData extends EventData {\n event: 'pageView'\n eventName: 'vtex:pageView'\n pageTitle: string\n pageUrl: string\n referrer: string\n}\n\nexport interface UserData extends EventData {\n event: 'userData'\n eventName: 'vtex:userData'\n email: string\n firstName: string\n id: string\n isAuthenticated: boolean\n lastName: string\n phone: string\n}\n\nexport interface AddToCartData extends EventData {\n event: 'addToCart'\n eventName: 'vtex:addToCart'\n items: CartItem[]\n}\n\nexport interface RemoveToCartData extends EventData {\n event: 'removeFromCart'\n eventName: 'vtex:removeFromCart'\n items: CartItem[]\n}\n\nexport interface OrderPlacedData extends Order, EventData {\n event: 'orderPlaced'\n eventName: 'vtex:orderPlaced'\n}\n\nexport interface OrderPlacedTrackedData extends Order, EventData {\n event: 'orderPlacedTracked'\n eventName: 'vtex:orderPlacedTracked'\n}\n\nexport interface ProductViewData extends EventData {\n event: 'productView'\n eventName: 'vtex:productView'\n product: Product\n}\n\nexport interface ProductClickData extends EventData {\n event: 'productClick'\n eventName: 'vtex:productClick'\n product: Product\n}\n\nexport interface ProductImpressionData extends EventData {\n event: 'productImpression'\n eventName: 'vtex:productImpression'\n impressions: Impression[]\n product?: Product // deprecated, use impressions list!\n position?: number // deprecated, use impressions list!\n list: string\n}\n\ninterface CartItem {\n skuId: string\n variant: string\n price: number\n name: string\n quantity: number\n productRefId: string\n brand: string\n category: string\n}\n\nexport interface Order {\n currency: string\n accountName: string\n orderGroup: string\n salesChannel: string\n coupon: string\n visitorType: string\n visitorContactInfo: string[]\n visitorAddressState: string\n visitorAddressCountry: string\n visitorAddressPostalCode: string\n transactionId: string\n transactionDate: string\n transactionAffiliation: string\n transactionTotal: number\n transactionShipping: number\n transactionSubtotal: number\n transactionDiscounts: number\n transactionTax: number\n transactionCurrency: string\n transactionPaymentType: PaymentType[]\n transactionShippingMethod: ShippingMethod[]\n transactionProducts: ProductOrder[]\n transactionPayment: {\n id: string\n }\n}\n\nexport interface Impression {\n product: Product\n position: number\n}\n\ninterface PaymentType {\n group: string\n paymentSystemName: string\n installments: number\n value: number\n}\n\ninterface ShippingMethod {\n itemId: string\n selectedSla: string\n}\n\ninterface ProductOrder {\n id: string\n name: string\n sku: string\n skuRefId: string\n skuName: string\n productRefId: string\n ean: string\n slug: string\n brand: string\n brandId: string\n seller: string\n sellerId: string\n category: string\n categoryId: string\n categoryTree: string[]\n categoryIdTree: string[]\n priceTags: PriceTag[]\n originalPrice: number\n price: number\n sellingPrice: number\n tax: number\n quantity: number\n components: any[]\n measurementUnit: string\n unitMultiplier: number\n}\n\ninterface PriceTag {\n identifier: string\n isPercentual: boolean\n value: number\n}\n\ninterface Product {\n brand: string\n categoryId?: string // inconsistency\n categories: string[]\n productId: string\n productName: string\n selectedSku?: string // inconsistency\n items: Item[]\n sku: Item\n [key: string]: any\n}\n\ninterface Item {\n itemId: string\n name: string\n seller?: Seller\n [key: string]: any\n}\n\ninterface Seller {\n commertialOffer: CommertialOffer\n [key: string]: any\n}\n\ninterface CommertialOffer {\n Price: number\n [key: string]: any\n}\n\n```" } ]
code_trusted_c73b0126
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of trusted/react/typings/vtex.render-runtime.d.ts from the trusted VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.render-runtime' {\n export const canUseDOM: boolean\n}\n\n```" } ]
code_trusted_3d8d2e8b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of trusted/react/typings/global.d.ts from the trusted VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface Window extends Window {\n __trusted: {\n appKey: string\n days: number\n defaultAddressState: string\n }\n}\n\ninterface Params {\n appKey: string\n email: string\n firstName: string\n orderId: string\n shippingCounty: string\n days: number\n}\n\n```" } ]
code_jivochat_0a5901a2
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of jivochat/docs/README.md from the jivochat VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# JivoChat\n\nThis app provides a native integration for all [JivoChat](https://www.jivochat.com/?utm_campaign=direct&utm_source=google.com&_ga=2.144978160.551999859.1580832835-1477813135.1580832835) customer comunication functionality.\n\n## Configuration\n\n1. [Install](https://vtex.io/docs/recipes/store/installing-an-app) the `vtex.jivochat@1.x` app in the desired account using your terminal. You can also install the app through the VTEX App Store.\n2. In the admin's account, access the **Apps** section and then select the **JivoChat** box\n3. Fill out the form with your **JivoChat's Widget ID** and save your changes.\n\n```" } ]
code_jivochat_56183b1b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of jivochat/public/metadata/messages/es-AR.json from the jivochat VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"JivoChat\",\n \"headline\": \"Con unos pocos clics, acceda a chats, correos electrónicos y llamadas en un solo lugar.\",\n \"overview\": \"JivoChat es un completo servicio de mensajería en línea centrado en la conversión y la retención. Le permite comunicarse con visitantes y clientes desde cualquier lugar: Chat, Teléfono, Callback, E-mail, Facebook Messenger, Telegram y Viber.\\r\\nLos operadores reciben todos los chats, correos electrónicos y llamadas en una aplicación Jivo, por lo que ya no tienen que cambiar entre múltiples ventanas y pueden usarse en dispositivos móviles y computadoras, lo que significa menos distracciones y todas las herramientas que necesita. para una atención al cliente excepcional.\",\n \"features\": [\n \"Obtener información detallada del visitante\",\n \"Configurar activadores automáticos\",\n \"Monitorear visitantes en tiempo real\",\n \"Recibir opiniones sobre la calidad del servicio\",\n \"Formulario de contacto offline\"\n ],\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```" } ]
code_jivochat_1a0f2880
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of jivochat/public/metadata/messages/pt-BR.json from the jivochat VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"JivoChat\",\n \"headline\": \"Com poucos cliques, acesse os serviços de chats, e-mails e ligações em um só lugar.\",\n \"overview\": \"O JivoChat é um messenger completo para lojas virtuais e focado em conversão e retenção. Permite que você se comunique com visitantes e clientes de qualquer lugar: Chat, Telefone, Callback, E-mail, Facebook Messenger, Telegram e Viber.\\r\\nOs operadores recebem todos os chats, e-mails e ligações em um só app do Jivo, então não precisam mais ficar alternando entre várias janelas e pode ser utilizado no celular e no computador ao mesmo tempo, isso significa menos distrações e todas as ferramentas necessárias para um excepcional serviço de suporte ao cliente.\",\n \"features\": [\n \"Obtenha informações detalhadas de visitantes\",\n \"Configure gatilhos automáticos\",\n \"Monitore visitantes em tempo real\",\n \"Receba avaliações da qualidade do serviço\",\n \"Ofereça formulário de contato offline\"\n ],\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```" } ]
code_jivochat_6170abb1
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of jivochat/public/metadata/messages/en-US.json from the jivochat VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"JivoChat\",\n \"headline\": \"With a few clicks, access the services of chats, e-mails and calls in one place.\",\n \"overview\": \"JivoChat is a complete online store messenger focused on conversion and retention. Allows you to communicate with visitors and customers from anywhere: Chat, Phone, Callback, Email, Facebook Messenger, Telegram and Viber.\\r\\nOperators receive all chats, emails and calls in one Jivo app, so they no longer have to switch between multiple windows and can be used on both mobile and computer, meaning fewer distractions and all the tools you need. for exceptional customer support.\",\n \"features\": [\n \"Get detailed visitor information\",\n \"Set up automatic triggers\",\n \"Monitor visitors in real time\",\n \"Receive quality of service reviews\",\n \"Offer offline contact form\"\n ],\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```" } ]
code_my-authentication_646e0602
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-authentication/messages/nl.json from the my-authentication VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"warn.aboutToBlock\": \"Nog een ongeldige poging blokkeert uw account gedurende één uur.\",\n \"error.unknown\": \"Sorry, er is een onbekende fout opgetreden. Probeer het nog eens\",\n \"error.connection\": \"Er is een fout opgetreden bij het verbinden met het systeem, probeer de pagina opnieuw te laden.\",\n \"error.wrongPass\": \"Huidig wachtwoord is onjuist.\",\n \"error.wrongCode\": \"De code is verkeerd.\",\n \"error.blockedUser\": \"U bent geblokkeerd. Probeer het later opnieuw.\",\n \"error.throttled\": \"Wacht enkele minuten voordat u de code opnieuw verstuurt.\",\n \"feedback.codeSent\": \"Code verzonden via e-mail.\",\n \"feedback.passwordUpdated\": \"Wachtwoord bijgewerkt.\",\n \"feedback.logoutSuccess\": \"Sessie afgemeld.\",\n \"ExtensionLinks.authentication\": \"Authenticatie\",\n \"ReloadableError.reload\": \"Opnieuw laden\",\n \"AuthenticationScreen.title\": \"Authenticatie\",\n \"AuthenticationScreen.backButton\": \"Profiel\",\n \"AuthenticationScreen.EditPassword.MaskedPassword.label\": \"Wachtwoord\",\n \"AuthenticationScreen.EditPassword.MaskedPassword.CreatePassButton.text\": \"Wachtwoord instellen\",\n \"AuthenticationScreen.EditPassword.MaskedPassword.ChangePassButton.text\": \"Wachtwoord opnieuw instellen\",\n \"AuthenticationScreen.EditPassword.MakedPassword.noPass\": \"U heeft nog geen wachtwoord ingesteld.\",\n \"AuthenticationScreen.EditPassword.SavePassButton.text\": \"Wachtwoord opslaan\",\n \"AuthenticationScreen.EditPassword.NewPassInput.label\": \"Nieuw wachtwoord\",\n \"AuthenticationScreen.EditPassword.PassValidation.title\": \"Uw wachtwoord moet bevatten ten minste:\",\n \"AuthenticationScreen.EditPassword.PassValidation.minLength\": \"8 tekens\",\n \"AuthenticationScreen.EditPassword.PassValidation.number\": \"1 cijfer\",\n \"AuthenticationScreen.EditPassword.PassValidation.upper\": \"1 hoofdletter\",\n \"AuthenticationScreen.EditPassword.PassValidation.lower\": \"1 kleine letter\",\n \"AuthenticationScreen.EditPassword.CreatePassword.emailSentText\": \"Er is een verificatiecode naar {email} gestuurd.\",\n \"AuthenticationScreen.EditPassword.CreatePassword.CodeInput.label\": \"Code\",\n \"AuthenticationScreen.EditPassword.CreatePassword.ResendCodeButton.text\": \"Code opnieuw verzenden\",\n \"AuthenticationScreen.EditPassword.ChangePassword.CurrPassInput.label\": \"Huidig wachtwoord\",\n \"AuthenticationScreen.LoginSessions.label\": \"Sessiebeheer\",\n \"AuthenticationScreen.LoginSessions.activeSessions\": \"U hebt {amount} actieve sessies\",\n \"AuthenticationScreen.LoginSessions.OpenSessionsButton.text\": \"Sessies controleren\",\n \"LoginSessionsScreen.title\": \"Sessiebeheer\",\n \"LoginSessionsScreen.backButton\": \"Authenticatie\",\n \"LoginSessionsScreen.LoginSession.currentSession\": \"Huidige sessie\",\n \"LoginSessionsScreen.LoginSession.lastAccess\": \"Laatste toegang: {lastAccess}\",\n \"LoginSessionsScreen.LoginSession.ipDetails\": \"IP: {ip}\",\n \"LoginSessionsScreen.LoginSession.firstAccess\": \"Eerste toegang: {dateTime}\",\n \"LoginSessionsScreen.LoginSession.LogoutButton.text\": \"Afmelden\",\n \"LoginSessionsScreen.LoginSession.DeviceMsg.desktop\": \"Desktop\",\n \"LoginSessionsScreen.LoginSession.DeviceMsg.mobile\": \"Mobiel\",\n \"LoginSessionsScreen.LoginSession.DeviceMsg.tablet\": \"Tablet\"\n}\n\n```" } ]
code_my-authentication_c6f3b1b9
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-authentication/messages/ja.json from the my-authentication VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"warn.aboutToBlock\": \"あと 1 回無効になると、アカウントが 1 時間ブロックされます。\",\n \"error.unknown\": \"申し訳ありません、不明なエラーが発生しました。もう一度やり直してください\",\n \"error.connection\": \"システムへの接続時にエラーが発生しました。ページを再読み込みしてください。\",\n \"error.wrongPass\": \"このパスワードは間違っています。\",\n \"error.wrongCode\": \"コードが違います。\",\n \"error.blockedUser\": \"ブロックされました。後でもう一度やり直してください。\",\n \"error.throttled\": \"数分待ってから、コードを再送してください。\",\n \"feedback.codeSent\": \"コードがメール経由で送信されました。\",\n \"feedback.passwordUpdated\": \"パスワードが更新されました。\",\n \"feedback.logoutSuccess\": \"セッションをログアウトしました。\",\n \"ExtensionLinks.authentication\": \"認証\",\n \"ReloadableError.reload\": \"再読み込み\",\n \"AuthenticationScreen.title\": \"認証\",\n \"AuthenticationScreen.backButton\": \"プロフィール\",\n \"AuthenticationScreen.EditPassword.MaskedPassword.label\": \"パスワード\",\n \"AuthenticationScreen.EditPassword.MaskedPassword.CreatePassButton.text\": \"パスワードを設定\",\n \"AuthenticationScreen.EditPassword.MaskedPassword.ChangePassButton.text\": \"パスワードを設定し直す\",\n \"AuthenticationScreen.EditPassword.MakedPassword.noPass\": \"パスワードをまだ設定していません。\",\n \"AuthenticationScreen.EditPassword.SavePassButton.text\": \"パスワードを保存\",\n \"AuthenticationScreen.EditPassword.NewPassInput.label\": \"新しいパスワード\",\n \"AuthenticationScreen.EditPassword.PassValidation.title\": \"パスワードには少なくとも以下が含まれている必要があります:\",\n \"AuthenticationScreen.EditPassword.PassValidation.minLength\": \"8 つの文字\",\n \"AuthenticationScreen.EditPassword.PassValidation.number\": \"1 つの数字\",\n \"AuthenticationScreen.EditPassword.PassValidation.upper\": \"1 つの大文字\",\n \"AuthenticationScreen.EditPassword.PassValidation.lower\": \"1 つの小文字\",\n \"AuthenticationScreen.EditPassword.CreatePassword.emailSentText\": \"確認コードが {email} に送信されました。\",\n \"AuthenticationScreen.EditPassword.CreatePassword.CodeInput.label\": \"コード\",\n \"AuthenticationScreen.EditPassword.CreatePassword.ResendCodeButton.text\": \"コードを再送\",\n \"AuthenticationScreen.EditPassword.ChangePassword.CurrPassInput.label\": \"現在のパスワード\",\n \"AuthenticationScreen.LoginSessions.label\": \"セッション管理\",\n \"AuthenticationScreen.LoginSessions.activeSessions\": \"{amount} のアクティブセッションがあります\",\n \"AuthenticationScreen.LoginSessions.OpenSessionsButton.text\": \"セッションを確認\",\n \"LoginSessionsScreen.title\": \"セッション管理\",\n \"LoginSessionsScreen.backButton\": \"認証\",\n \"LoginSessionsScreen.LoginSession.currentSession\": \"現在のセッション\",\n \"LoginSessionsScreen.LoginSession.lastAccess\": \"前回のアクセス: {lastAccess}\",\n \"LoginSessionsScreen.LoginSession.ipDetails\": \"IP: {ip}\",\n \"LoginSessionsScreen.LoginSession.firstAccess\": \"初回のアクセス: {dateTime}\",\n \"LoginSessionsScreen.LoginSession.LogoutButton.text\": \"ログアウト\",\n \"LoginSessionsScreen.LoginSession.DeviceMsg.desktop\": \"デスクトップ\",\n \"LoginSessionsScreen.LoginSession.DeviceMsg.mobile\": \"モバイル\",\n \"LoginSessionsScreen.LoginSession.DeviceMsg.tablet\": \"タブレット\"\n}\n\n```" } ]
code_my-authentication_2a5ce966
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-authentication/messages/de.json from the my-authentication VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"warn.aboutToBlock\": \"Bei einem weiteren ungültigen Versuch wird Ihr Konto für eine Stunde gesperrt.\",\n \"error.unknown\": \"Entschuldigung, es ist ein unbekannter Fehler aufgetreten. Bitte versuchen Sie es erneut\",\n \"error.connection\": \"Es gab einen Fehler beim Verbindungsaufbau mit dem System, versuchen Sie, die Seite neu zu laden.\",\n \"error.wrongPass\": \"Aktuelles Passwort ist falsch.\",\n \"error.wrongCode\": \"Der Code ist falsch.\",\n \"error.blockedUser\": \"Sie wurden blockiert, versuchen Sie es später noch einmal.\",\n \"error.throttled\": \"Bitte warten Sie einige Minuten, bevor Sie den Code erneut senden.\",\n \"feedback.codeSent\": \"Code per email zugesandt.\",\n \"feedback.passwordUpdated\": \"Passwort aktualisiert.\",\n \"feedback.logoutSuccess\": \"Sitzung abgemeldet.\",\n \"ExtensionLinks.authentication\": \"Authentifizierung\",\n \"ReloadableError.reload\": \"Neu laden\",\n \"AuthenticationScreen.title\": \"Authentifizierung\",\n \"AuthenticationScreen.backButton\": \"Profil\",\n \"AuthenticationScreen.EditPassword.MaskedPassword.label\": \"Passwort\",\n \"AuthenticationScreen.EditPassword.MaskedPassword.CreatePassButton.text\": \"Passwort festlegen\",\n \"AuthenticationScreen.EditPassword.MaskedPassword.ChangePassButton.text\": \"Passwort neu definieren\",\n \"AuthenticationScreen.EditPassword.MakedPassword.noPass\": \"Sie haben noch kein Passwort definiert.\",\n \"AuthenticationScreen.EditPassword.SavePassButton.text\": \"Passwort speichern\",\n \"AuthenticationScreen.EditPassword.NewPassInput.label\": \"Neues Passwort\",\n \"AuthenticationScreen.EditPassword.PassValidation.title\": \"Ihr Passwort muss mindestens Folgendes enthalten:\",\n \"AuthenticationScreen.EditPassword.PassValidation.minLength\": \"8 Zeichen\",\n \"AuthenticationScreen.EditPassword.PassValidation.number\": \"1 Nummer\",\n \"AuthenticationScreen.EditPassword.PassValidation.upper\": \"1 Großbuchstabe\",\n \"AuthenticationScreen.EditPassword.PassValidation.lower\": \"1 Kleinbuchstabe\",\n \"AuthenticationScreen.EditPassword.CreatePassword.emailSentText\": \"Ein Verifizierungscode wurde an {email} gesendet.\",\n \"AuthenticationScreen.EditPassword.CreatePassword.CodeInput.label\": \"Code\",\n \"AuthenticationScreen.EditPassword.CreatePassword.ResendCodeButton.text\": \"Code erneut senden\",\n \"AuthenticationScreen.EditPassword.ChangePassword.CurrPassInput.label\": \"Aktuelles Passwort\",\n \"AuthenticationScreen.LoginSessions.label\": \"Sitzungs-Management\",\n \"AuthenticationScreen.LoginSessions.activeSessions\": \"Sie haben {amount} aktive Sitzungen\",\n \"AuthenticationScreen.LoginSessions.OpenSessionsButton.text\": \"Sitzungen prüfen\",\n \"LoginSessionsScreen.title\": \"Sitzungs-Management\",\n \"LoginSessionsScreen.backButton\": \"Authentifizierung\",\n \"LoginSessionsScreen.LoginSession.currentSession\": \"Aktuelle Sitzung\",\n \"LoginSessionsScreen.LoginSession.lastAccess\": \"Letzter Zugriff: {lastAccess}\",\n \"LoginSessionsScreen.LoginSession.ipDetails\": \"IP: {ip}\",\n \"LoginSessionsScreen.LoginSession.firstAccess\": \"Erster Zugriff: {dateTime}\",\n \"LoginSessionsScreen.LoginSession.LogoutButton.text\": \"Abmelden\",\n \"LoginSessionsScreen.LoginSession.DeviceMsg.desktop\": \"Desktop\",\n \"LoginSessionsScreen.LoginSession.DeviceMsg.mobile\": \"Mobil\",\n \"LoginSessionsScreen.LoginSession.DeviceMsg.tablet\": \"Tablet\"\n}\n\n```" } ]
code_my-authentication_ea78780d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-authentication/messages/fi.json from the my-authentication VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"warn.aboutToBlock\": \"Vielä yksi virheellinen yritys estää tilisi tunniksi.\",\n \"error.unknown\": \"Pahoittelut, tapahtui odottamaton virhe. Yritä uudelleen\",\n \"error.connection\": \"Virhe muodostettaessa yhteyttä järjestelmään. Kokeile ladata sivu uudelleen.\",\n \"error.wrongPass\": \"Nykyinen salasana on väärin.\",\n \"error.wrongCode\": \"Koodi on väärä.\",\n \"error.blockedUser\": \"Sinut on estetty. Yritä uudelleen myöhemmin.\",\n \"error.throttled\": \"Odota muutama minuutti ennen koodin uudelleen lähettämistä.\",\n \"feedback.codeSent\": \"Koodi lähetetty sähköpostina.\",\n \"feedback.passwordUpdated\": \"Salasana päivitetty.\",\n \"feedback.logoutSuccess\": \"Kirjauduttu ulos istunnosta.\",\n \"ExtensionLinks.authentication\": \"Todennus\",\n \"ReloadableError.reload\": \"Lataa uudelleen\",\n \"AuthenticationScreen.title\": \"Todennus\",\n \"AuthenticationScreen.backButton\": \"Profiili\",\n \"AuthenticationScreen.EditPassword.MaskedPassword.label\": \"Salasana\",\n \"AuthenticationScreen.EditPassword.MaskedPassword.CreatePassButton.text\": \"Määritä salasana\",\n \"AuthenticationScreen.EditPassword.MaskedPassword.ChangePassButton.text\": \"Määritä salasana uudelleen\",\n \"AuthenticationScreen.EditPassword.MakedPassword.noPass\": \"Et ole vielä määrittänyt salasanaa.\",\n \"AuthenticationScreen.EditPassword.SavePassButton.text\": \"Tallenna salasana\",\n \"AuthenticationScreen.EditPassword.NewPassInput.label\": \"Uusi salasana\",\n \"AuthenticationScreen.EditPassword.PassValidation.title\": \"Salasanassasi tulee olla vähintään:\",\n \"AuthenticationScreen.EditPassword.PassValidation.minLength\": \"8 merkkiä\",\n \"AuthenticationScreen.EditPassword.PassValidation.number\": \"1 numero\",\n \"AuthenticationScreen.EditPassword.PassValidation.upper\": \"1 iso kirjain\",\n \"AuthenticationScreen.EditPassword.PassValidation.lower\": \"1 pieni kirjain\",\n \"AuthenticationScreen.EditPassword.CreatePassword.emailSentText\": \"Vahvistuskoodi lähetettiin osoitteeseen {email}.\",\n \"AuthenticationScreen.EditPassword.CreatePassword.CodeInput.label\": \"Koodi\",\n \"AuthenticationScreen.EditPassword.CreatePassword.ResendCodeButton.text\": \"Lähetä koodi uudelleen\",\n \"AuthenticationScreen.EditPassword.ChangePassword.CurrPassInput.label\": \"Nykyinen salasana\",\n \"AuthenticationScreen.LoginSessions.label\": \"Istunnon hallinta\",\n \"AuthenticationScreen.LoginSessions.activeSessions\": \"Sinulla on {amount} aktiivista istuntoa\",\n \"AuthenticationScreen.LoginSessions.OpenSessionsButton.text\": \"Tarkista istunnot\",\n \"LoginSessionsScreen.title\": \"Istunnon hallinta\",\n \"LoginSessionsScreen.backButton\": \"Todennus\",\n \"LoginSessionsScreen.LoginSession.currentSession\": \"Nykyinen istunto\",\n \"LoginSessionsScreen.LoginSession.lastAccess\": \"Käytetty viimeksi: {lastAccess}\",\n \"LoginSessionsScreen.LoginSession.ipDetails\": \"IP: {ip}\",\n \"LoginSessionsScreen.LoginSession.firstAccess\": \"Käytetty ensimmäisen kerran: {dateTime}\",\n \"LoginSessionsScreen.LoginSession.LogoutButton.text\": \"Kirjaudu ulos\",\n \"LoginSessionsScreen.LoginSession.DeviceMsg.desktop\": \"Tietokone\",\n \"LoginSessionsScreen.LoginSession.DeviceMsg.mobile\": \"Mobiili\",\n \"LoginSessionsScreen.LoginSession.DeviceMsg.tablet\": \"Tabletti\"\n}\n\n```" } ]
code_my-authentication_c2dc4b94
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-authentication/messages/pt.json from the my-authentication VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"warn.aboutToBlock\": \"Mais uma tentativa inválida bloqueará sua conta por uma hora.\",\n \"error.unknown\": \"Desculpe, um erro inesperado ocorreu. Por favor, tente novamente\",\n \"error.connection\": \"Houve um erro de comunicação com o sistema, tente recarregar a página.\",\n \"error.wrongPass\": \"A senha atual está incorreta.\",\n \"error.wrongCode\": \"O código está incorreto.\",\n \"error.blockedUser\": \"Você está bloqueado, tente novamente mais tarde.\",\n \"error.throttled\": \"Favor aguarde alguns minutos antes de reenviar o código.\",\n \"feedback.codeSent\": \"Código enviado por email.\",\n \"feedback.passwordUpdated\": \"Senha atualizada.\",\n \"feedback.logoutSuccess\": \"Sessão deslogada.\",\n \"ExtensionLinks.authentication\": \"Autenticação\",\n \"ReloadableError.reload\": \"Recarregar\",\n \"AuthenticationScreen.title\": \"Autenticação\",\n \"AuthenticationScreen.backButton\": \"Dados pessoais\",\n \"AuthenticationScreen.EditPassword.MaskedPassword.label\": \"Senha\",\n \"AuthenticationScreen.EditPassword.MaskedPassword.CreatePassButton.text\": \"Definir senha\",\n \"AuthenticationScreen.EditPassword.MaskedPassword.ChangePassButton.text\": \"Redefinir senha\",\n \"AuthenticationScreen.EditPassword.MakedPassword.noPass\": \"Você ainda não possui uma senha definida.\",\n \"AuthenticationScreen.EditPassword.SavePassButton.text\": \"Salvar senha\",\n \"AuthenticationScreen.EditPassword.NewPassInput.label\": \"Nova senha\",\n \"AuthenticationScreen.EditPassword.PassValidation.title\": \"Sua senha deve ter pelo menos:\",\n \"AuthenticationScreen.EditPassword.PassValidation.minLength\": \"8 caracteres\",\n \"AuthenticationScreen.EditPassword.PassValidation.number\": \"1 número\",\n \"AuthenticationScreen.EditPassword.PassValidation.upper\": \"1 letra maiúscula\",\n \"AuthenticationScreen.EditPassword.PassValidation.lower\": \"1 letra minúscula\",\n \"AuthenticationScreen.EditPassword.CreatePassword.emailSentText\": \"Um código de verificação foi enviado para {email}.\",\n \"AuthenticationScreen.EditPassword.CreatePassword.CodeInput.label\": \"Código\",\n \"AuthenticationScreen.EditPassword.CreatePassword.ResendCodeButton.text\": \"Reenviar código\",\n \"AuthenticationScreen.EditPassword.ChangePassword.CurrPassInput.label\": \"Senha atual\",\n \"AuthenticationScreen.LoginSessions.label\": \"Gerenciamento de Sessões\",\n \"AuthenticationScreen.LoginSessions.activeSessions\": \"Você tem {amount} sessões ativas\",\n \"AuthenticationScreen.LoginSessions.OpenSessionsButton.text\": \"Ver sessões\",\n \"LoginSessionsScreen.title\": \"Gerenciamento de Sessões\",\n \"LoginSessionsScreen.backButton\": \"Autenticação\",\n \"LoginSessionsScreen.LoginSession.currentSession\": \"Sessão Atual\",\n \"LoginSessionsScreen.LoginSession.lastAccess\": \"Último acesso: {lastAccess}\",\n \"LoginSessionsScreen.LoginSession.ipDetails\": \"IP: {ip}\",\n \"LoginSessionsScreen.LoginSession.firstAccess\": \"Primeiro acesso: {dateTime}\",\n \"LoginSessionsScreen.LoginSession.LogoutButton.text\": \"Deslogar\",\n \"LoginSessionsScreen.LoginSession.DeviceMsg.desktop\": \"Desktop\",\n \"LoginSessionsScreen.LoginSession.DeviceMsg.mobile\": \"Mobile\",\n \"LoginSessionsScreen.LoginSession.DeviceMsg.tablet\": \"Tablet\"\n}\n\n```" } ]
code_my-authentication_9f906d92
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-authentication/messages/en.json from the my-authentication VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"warn.aboutToBlock\": \"One more invalid attempt will block your account for one hour.\",\n \"error.unknown\": \"Sorry, an unknown error has ocurred. Please, try again\",\n \"error.connection\": \"There was an error connecting with the system, try reloading the page.\",\n \"error.wrongPass\": \"Current password is wrong.\",\n \"error.wrongCode\": \"The code is wrong.\",\n \"error.blockedUser\": \"You have been blocked, try again later.\",\n \"error.throttled\": \"Please wait some minutes before resending the code.\",\n \"feedback.codeSent\": \"Code sent via email.\",\n \"feedback.passwordUpdated\": \"Password updated.\",\n \"feedback.logoutSuccess\": \"Session logged out.\",\n \"ExtensionLinks.authentication\": \"Authentication\",\n \"ReloadableError.reload\": \"Reload\",\n \"AuthenticationScreen.title\": \"Authentication\",\n \"AuthenticationScreen.backButton\": \"Profile\",\n \"AuthenticationScreen.EditPassword.MaskedPassword.label\": \"Password\",\n \"AuthenticationScreen.EditPassword.MaskedPassword.CreatePassButton.text\": \"Set password\",\n \"AuthenticationScreen.EditPassword.MaskedPassword.ChangePassButton.text\": \"Redefine password\",\n \"AuthenticationScreen.EditPassword.MakedPassword.noPass\": \"You do not have a password defined yet.\",\n \"AuthenticationScreen.EditPassword.SavePassButton.text\": \"Save password\",\n \"AuthenticationScreen.EditPassword.NewPassInput.label\": \"New password\",\n \"AuthenticationScreen.EditPassword.PassValidation.title\": \"Your password must have at least:\",\n \"AuthenticationScreen.EditPassword.PassValidation.minLength\": \"8 characters\",\n \"AuthenticationScreen.EditPassword.PassValidation.number\": \"1 number\",\n \"AuthenticationScreen.EditPassword.PassValidation.upper\": \"1 uppercase letter\",\n \"AuthenticationScreen.EditPassword.PassValidation.lower\": \"1 lowercase letter\",\n \"AuthenticationScreen.EditPassword.CreatePassword.emailSentText\": \"A verification code was sent to {email}.\",\n \"AuthenticationScreen.EditPassword.CreatePassword.CodeInput.label\": \"Code\",\n \"AuthenticationScreen.EditPassword.CreatePassword.ResendCodeButton.text\": \"Resend code\",\n \"AuthenticationScreen.EditPassword.ChangePassword.CurrPassInput.label\": \"Current password\",\n \"AuthenticationScreen.LoginSessions.label\": \"Session Management\",\n \"AuthenticationScreen.LoginSessions.activeSessions\": \"You have {amount} active sessions\",\n \"AuthenticationScreen.LoginSessions.OpenSessionsButton.text\": \"Check sessions\",\n \"LoginSessionsScreen.title\": \"Session Management\",\n \"LoginSessionsScreen.backButton\": \"Authentication\",\n \"LoginSessionsScreen.LoginSession.currentSession\": \"Current Session\",\n \"LoginSessionsScreen.LoginSession.lastAccess\": \"Last access: {lastAccess}\",\n \"LoginSessionsScreen.LoginSession.ipDetails\": \"IP: {ip}\",\n \"LoginSessionsScreen.LoginSession.firstAccess\": \"First access: {dateTime}\",\n \"LoginSessionsScreen.LoginSession.LogoutButton.text\": \"Log out\",\n \"LoginSessionsScreen.LoginSession.DeviceMsg.desktop\": \"Desktop\",\n \"LoginSessionsScreen.LoginSession.DeviceMsg.mobile\": \"Mobile\",\n \"LoginSessionsScreen.LoginSession.DeviceMsg.tablet\": \"Tablet\"\n}\n\n```" } ]
code_my-authentication_891c6e02
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-authentication/messages/it.json from the my-authentication VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"warn.aboutToBlock\": \"Un altro tentativo errato bloccherà per un'ora il tuo account.\",\n \"error.unknown\": \"Spiacenti, si è verificato un errore sconosciuto. Si prega di riprovare\",\n \"error.connection\": \"Si è verificato un errore collegandosi al sistema, prova a ricaricare la pagina.\",\n \"error.wrongPass\": \"La password che hai inserito è sbagliata.\",\n \"error.wrongCode\": \"Il codice è sbagliato.\",\n \"error.blockedUser\": \"Il tuo account è stato bloccato, riprova più tardi.\",\n \"error.throttled\": \"Attendi alcuni minuti prima che il codice venga inviato nuovamente.\",\n \"feedback.codeSent\": \"Codice mandato per mail.\",\n \"feedback.passwordUpdated\": \"Password aggiornata.\",\n \"feedback.logoutSuccess\": \"Sessione disconnessa.\",\n \"ExtensionLinks.authentication\": \"Autenticazione\",\n \"ReloadableError.reload\": \"Ricarica\",\n \"AuthenticationScreen.title\": \"Autenticazione\",\n \"AuthenticationScreen.backButton\": \"Profilo\",\n \"AuthenticationScreen.EditPassword.MaskedPassword.label\": \"Password\",\n \"AuthenticationScreen.EditPassword.MaskedPassword.CreatePassButton.text\": \"Imposta password\",\n \"AuthenticationScreen.EditPassword.MaskedPassword.ChangePassButton.text\": \"Cambia la password\",\n \"AuthenticationScreen.EditPassword.MakedPassword.noPass\": \"Non hai ancora definito una password.\",\n \"AuthenticationScreen.EditPassword.SavePassButton.text\": \"Salva password\",\n \"AuthenticationScreen.EditPassword.NewPassInput.label\": \"Nuova password\",\n \"AuthenticationScreen.EditPassword.PassValidation.title\": \"La tua password deve contenere almeno:\",\n \"AuthenticationScreen.EditPassword.PassValidation.minLength\": \"8 caratteri\",\n \"AuthenticationScreen.EditPassword.PassValidation.number\": \"1 numero\",\n \"AuthenticationScreen.EditPassword.PassValidation.upper\": \"1 lettera maiuscola\",\n \"AuthenticationScreen.EditPassword.PassValidation.lower\": \"1 lettera minuscola\",\n \"AuthenticationScreen.EditPassword.CreatePassword.emailSentText\": \"Un codice di verifica è stato inviato a {email}.\",\n \"AuthenticationScreen.EditPassword.CreatePassword.CodeInput.label\": \"Codice\",\n \"AuthenticationScreen.EditPassword.CreatePassword.ResendCodeButton.text\": \"Rinvia codice\",\n \"AuthenticationScreen.EditPassword.ChangePassword.CurrPassInput.label\": \"Password attuale\",\n \"AuthenticationScreen.LoginSessions.label\": \"Gestione sessioni\",\n \"AuthenticationScreen.LoginSessions.activeSessions\": \"Hai {amount} sessioni attive\",\n \"AuthenticationScreen.LoginSessions.OpenSessionsButton.text\": \"Controlla sessioni\",\n \"LoginSessionsScreen.title\": \"Gestione sessioni\",\n \"LoginSessionsScreen.backButton\": \"Autenticazione\",\n \"LoginSessionsScreen.LoginSession.currentSession\": \"Sessione Corrente\",\n \"LoginSessionsScreen.LoginSession.lastAccess\": \"Ultimo accesso: {lastAccess}\",\n \"LoginSessionsScreen.LoginSession.ipDetails\": \"IP: {ip}\",\n \"LoginSessionsScreen.LoginSession.firstAccess\": \"Primo accesso: {dateTime}\",\n \"LoginSessionsScreen.LoginSession.LogoutButton.text\": \"Disconnetti\",\n \"LoginSessionsScreen.LoginSession.DeviceMsg.desktop\": \"Desktop\",\n \"LoginSessionsScreen.LoginSession.DeviceMsg.mobile\": \"Mobile\",\n \"LoginSessionsScreen.LoginSession.DeviceMsg.tablet\": \"Tablet\"\n}\n\n```" } ]
code_my-authentication_64b217fb
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-authentication/messages/fr.json from the my-authentication VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"warn.aboutToBlock\": \"Une autre tentative non valide bloquera votre compte pendant une heure.\",\n \"error.unknown\": \"Désolé, une erreur inattendue s’est produite. Veuillez réessayer\",\n \"error.connection\": \"Une erreur s'est produite lors de la connexion avec le système, essayez de recharger la page.\",\n \"error.wrongPass\": \"Le mot de passe actuel est incorrect.\",\n \"error.wrongCode\": \"Le code est erroné.\",\n \"error.blockedUser\": \"Vous avez été bloqué, réessayez plus tard.\",\n \"error.throttled\": \"Veuillez attendre quelques minutes avant de renvoyer le code.\",\n \"feedback.codeSent\": \"Code envoyé par e-mail.\",\n \"feedback.passwordUpdated\": \"Mot de passe mis à jour.\",\n \"feedback.logoutSuccess\": \"Session déconnectée.\",\n \"ExtensionLinks.authentication\": \"Authentification\",\n \"ReloadableError.reload\": \"Recharger\",\n \"AuthenticationScreen.title\": \"Authentification\",\n \"AuthenticationScreen.backButton\": \"Profil\",\n \"AuthenticationScreen.EditPassword.MaskedPassword.label\": \"Mot de passe\",\n \"AuthenticationScreen.EditPassword.MaskedPassword.CreatePassButton.text\": \"Définir le mot de passe\",\n \"AuthenticationScreen.EditPassword.MaskedPassword.ChangePassButton.text\": \"Redéfinir mot de passe\",\n \"AuthenticationScreen.EditPassword.MakedPassword.noPass\": \"Vous n’avez pas encore de mot de passe.\",\n \"AuthenticationScreen.EditPassword.SavePassButton.text\": \"Sauvegarder le mot de passe\",\n \"AuthenticationScreen.EditPassword.NewPassInput.label\": \"Nouveau mot de passe\",\n \"AuthenticationScreen.EditPassword.PassValidation.title\": \"Votre mot de passe doit avoir au moins:\",\n \"AuthenticationScreen.EditPassword.PassValidation.minLength\": \"8 caractères\",\n \"AuthenticationScreen.EditPassword.PassValidation.number\": \"1 chiffre\",\n \"AuthenticationScreen.EditPassword.PassValidation.upper\": \"1 lettre majuscule\",\n \"AuthenticationScreen.EditPassword.PassValidation.lower\": \"1 lettre minuscule\",\n \"AuthenticationScreen.EditPassword.CreatePassword.emailSentText\": \"Un code de vérification a été envoyé à {email}.\",\n \"AuthenticationScreen.EditPassword.CreatePassword.CodeInput.label\": \"Code\",\n \"AuthenticationScreen.EditPassword.CreatePassword.ResendCodeButton.text\": \"Renvoyer le code\",\n \"AuthenticationScreen.EditPassword.ChangePassword.CurrPassInput.label\": \"Mot de passe actuel\",\n \"AuthenticationScreen.LoginSessions.label\": \"Gestion de session\",\n \"AuthenticationScreen.LoginSessions.activeSessions\": \"Vous avez {amount} sessions actives\",\n \"AuthenticationScreen.LoginSessions.OpenSessionsButton.text\": \"Vérifier les sessions\",\n \"LoginSessionsScreen.title\": \"Gestion de session\",\n \"LoginSessionsScreen.backButton\": \"Authentification\",\n \"LoginSessionsScreen.LoginSession.currentSession\": \"Session actuelle\",\n \"LoginSessionsScreen.LoginSession.lastAccess\": \"Dernier accès: {lastAccess}\",\n \"LoginSessionsScreen.LoginSession.ipDetails\": \"IP: {ip}\",\n \"LoginSessionsScreen.LoginSession.firstAccess\": \"Premier accès: {dateTime}\",\n \"LoginSessionsScreen.LoginSession.LogoutButton.text\": \"Se déconnecter\",\n \"LoginSessionsScreen.LoginSession.DeviceMsg.desktop\": \"Bureau\",\n \"LoginSessionsScreen.LoginSession.DeviceMsg.mobile\": \"Mobile\",\n \"LoginSessionsScreen.LoginSession.DeviceMsg.tablet\": \"Tablette\"\n}\n\n```" } ]
code_my-authentication_45361845
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-authentication/messages/ro.json from the my-authentication VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"warn.aboutToBlock\": \"O nouă încercare incorectă va bloca contul tău timp de o oră.\",\n \"error.unknown\": \"Ne pare rău, am întâmpinat o eroare necunoscută. Te rugăm să încerci din nou\",\n \"error.connection\": \"A apărut o eroare la conectarea cu sistemul, încearcă să reîncarci pagina.\",\n \"error.wrongPass\": \"Parola actuală este greșită.\",\n \"error.wrongCode\": \"Codul este greșit.\",\n \"error.blockedUser\": \"Ai fost blocat, încearcă din nou mai târziu.\",\n \"error.throttled\": \"Te rugăm să aștepți câteva minute înainte de retransmiterea codului.\",\n \"feedback.codeSent\": \"Cod trimis prin e-mail.\",\n \"feedback.passwordUpdated\": \"Parolă actualizată.\",\n \"feedback.logoutSuccess\": \"Sesiune deconectată.\",\n \"ExtensionLinks.authentication\": \"Autentificare\",\n \"ReloadableError.reload\": \"Reîncărcare\",\n \"AuthenticationScreen.title\": \"Autentificare\",\n \"AuthenticationScreen.backButton\": \"Profil\",\n \"AuthenticationScreen.EditPassword.MaskedPassword.label\": \"Parolă\",\n \"AuthenticationScreen.EditPassword.MaskedPassword.CreatePassButton.text\": \"Parola activată\",\n \"AuthenticationScreen.EditPassword.MaskedPassword.ChangePassButton.text\": \"Redefinește parola\",\n \"AuthenticationScreen.EditPassword.MakedPassword.noPass\": \"Nu ai încă o parolă definită.\",\n \"AuthenticationScreen.EditPassword.SavePassButton.text\": \"Salvează parola\",\n \"AuthenticationScreen.EditPassword.NewPassInput.label\": \"Parolă nouă\",\n \"AuthenticationScreen.EditPassword.PassValidation.title\": \"Parola ta trebuie să conțină cel puțin:\",\n \"AuthenticationScreen.EditPassword.PassValidation.minLength\": \"8 caractere\",\n \"AuthenticationScreen.EditPassword.PassValidation.number\": \"1 număr\",\n \"AuthenticationScreen.EditPassword.PassValidation.upper\": \"1 literă majusculă\",\n \"AuthenticationScreen.EditPassword.PassValidation.lower\": \"1 literă mică\",\n \"AuthenticationScreen.EditPassword.CreatePassword.emailSentText\": \"Codul de verificare a fost trimis către {email}.\",\n \"AuthenticationScreen.EditPassword.CreatePassword.CodeInput.label\": \"Cod\",\n \"AuthenticationScreen.EditPassword.CreatePassword.ResendCodeButton.text\": \"Trimite codul\",\n \"AuthenticationScreen.EditPassword.ChangePassword.CurrPassInput.label\": \"Parola actuală\",\n \"AuthenticationScreen.LoginSessions.label\": \"Gestionarea sesiunii\",\n \"AuthenticationScreen.LoginSessions.activeSessions\": \"Există {amount} sesiuni active\",\n \"AuthenticationScreen.LoginSessions.OpenSessionsButton.text\": \"Verifică sesiunile\",\n \"LoginSessionsScreen.title\": \"Gestionarea sesiunii\",\n \"LoginSessionsScreen.backButton\": \"Autentificare\",\n \"LoginSessionsScreen.LoginSession.currentSession\": \"Sesiunea curentă\",\n \"LoginSessionsScreen.LoginSession.lastAccess\": \"Ultima accesare: {lastAccess}\",\n \"LoginSessionsScreen.LoginSession.ipDetails\": \"IP: {ip}\",\n \"LoginSessionsScreen.LoginSession.firstAccess\": \"Prima accesare: {dateTime}\",\n \"LoginSessionsScreen.LoginSession.LogoutButton.text\": \"Deconectare\",\n \"LoginSessionsScreen.LoginSession.DeviceMsg.desktop\": \"Desktop\",\n \"LoginSessionsScreen.LoginSession.DeviceMsg.mobile\": \"Mobil\",\n \"LoginSessionsScreen.LoginSession.DeviceMsg.tablet\": \"Tabletă\"\n}\n\n```" } ]
code_my-authentication_5e6f2460
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-authentication/messages/ko.json from the my-authentication VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"warn.aboutToBlock\": \"한번 더 잘못된 비밀번호를 입력하는 경우 계정이 1시간 동안 차단됩니다.\",\n \"error.unknown\": \"알 수 없는 오류가 발생했습니다. 다시 시도하십시오\",\n \"error.connection\": \"시스템에 연결하는 동안 오류가 발생했습니다. 페이지를 다시 로딩하십시오.\",\n \"error.wrongPass\": \"현재의 비밀번호가 틀립니다.\",\n \"error.wrongCode\": \"코드가 잘못되었습니다.\",\n \"error.blockedUser\": \"차단 되었습니다, 나중에 다시 시도하십시오.\",\n \"error.throttled\": \"코드를 다시 보내기 전에 잠시 기다려주세요.\",\n \"feedback.codeSent\": \"이메일을 통해 전송된 코드.\",\n \"feedback.passwordUpdated\": \"암호가 업데이트됨.\",\n \"feedback.logoutSuccess\": \"세션이 로그아웃됨.\",\n \"ExtensionLinks.authentication\": \"인증\",\n \"ReloadableError.reload\": \"다시 로딩\",\n \"AuthenticationScreen.title\": \"인증\",\n \"AuthenticationScreen.backButton\": \"프로필\",\n \"AuthenticationScreen.EditPassword.MaskedPassword.label\": \"비밀번호\",\n \"AuthenticationScreen.EditPassword.MaskedPassword.CreatePassButton.text\": \"비밀번호 설정\",\n \"AuthenticationScreen.EditPassword.MaskedPassword.ChangePassButton.text\": \"비밀번호 재설정\",\n \"AuthenticationScreen.EditPassword.MakedPassword.noPass\": \"아직 비밀번호를 설정하지 않았습니다.\",\n \"AuthenticationScreen.EditPassword.SavePassButton.text\": \"비밀번호 저장\",\n \"AuthenticationScreen.EditPassword.NewPassInput.label\": \"새로운 비밀번호\",\n \"AuthenticationScreen.EditPassword.PassValidation.title\": \"비밀번호는 최소한 다음의 항목을 포함해야 합니다:\",\n \"AuthenticationScreen.EditPassword.PassValidation.minLength\": \"8개의 글자\",\n \"AuthenticationScreen.EditPassword.PassValidation.number\": \"1개의 숫자\",\n \"AuthenticationScreen.EditPassword.PassValidation.upper\": \"1개의 대문자\",\n \"AuthenticationScreen.EditPassword.PassValidation.lower\": \"1개의 소문자\",\n \"AuthenticationScreen.EditPassword.CreatePassword.emailSentText\": \"{email}에 인증 코드가 전송되었습니다.\",\n \"AuthenticationScreen.EditPassword.CreatePassword.CodeInput.label\": \"코드\",\n \"AuthenticationScreen.EditPassword.CreatePassword.ResendCodeButton.text\": \"코드 재전송\",\n \"AuthenticationScreen.EditPassword.ChangePassword.CurrPassInput.label\": \"현재 비밀번호\",\n \"AuthenticationScreen.LoginSessions.label\": \"세션 관리\",\n \"AuthenticationScreen.LoginSessions.activeSessions\": \"활성 세션이 {amount}개 있습니다.\",\n \"AuthenticationScreen.LoginSessions.OpenSessionsButton.text\": \"세션 확인\",\n \"LoginSessionsScreen.title\": \"세션 관리\",\n \"LoginSessionsScreen.backButton\": \"인증\",\n \"LoginSessionsScreen.LoginSession.currentSession\": \"현제 세션\",\n \"LoginSessionsScreen.LoginSession.lastAccess\": \"마지막 액세스: {lastAccess}\",\n \"LoginSessionsScreen.LoginSession.ipDetails\": \"IP: {ip}\",\n \"LoginSessionsScreen.LoginSession.firstAccess\": \"첫 번째 액세스: {dateTime}\",\n \"LoginSessionsScreen.LoginSession.LogoutButton.text\": \"로그아웃\",\n \"LoginSessionsScreen.LoginSession.DeviceMsg.desktop\": \"데스크톱\",\n \"LoginSessionsScreen.LoginSession.DeviceMsg.mobile\": \"모바일\",\n \"LoginSessionsScreen.LoginSession.DeviceMsg.tablet\": \"태블릿\"\n}\n\n```" } ]
code_my-authentication_6f4ab914
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-authentication/messages/da.json from the my-authentication VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"warn.aboutToBlock\": \"Et ugyldigt forsøg blokerer din konto yderligere i en time.\",\n \"error.unknown\": \"Beklager, der opstod en uventet fejl. Prøv igen\",\n \"error.connection\": \"Der opstod en fejl under forbindelse med systemet, prøv at indlæse siden igen.\",\n \"error.wrongPass\": \"Den aktuelle adgangskode er forkert.\",\n \"error.wrongCode\": \"Koden er forkert.\",\n \"error.blockedUser\": \"Du er blevet blokeret, prøv igen senere.\",\n \"error.throttled\": \"Vent nogle minutter, inden du sender koden igen.\",\n \"feedback.codeSent\": \"Kode sendt via e-mail.\",\n \"feedback.passwordUpdated\": \"Adgangskode opdateret.\",\n \"feedback.logoutSuccess\": \"Session logget ud.\",\n \"ExtensionLinks.authentication\": \"Godkendelse\",\n \"ReloadableError.reload\": \"Genindlæs\",\n \"AuthenticationScreen.title\": \"Godkendelse\",\n \"AuthenticationScreen.backButton\": \"Profil\",\n \"AuthenticationScreen.EditPassword.MaskedPassword.label\": \"Adgangskode\",\n \"AuthenticationScreen.EditPassword.MaskedPassword.CreatePassButton.text\": \"Indstil adgangskode\",\n \"AuthenticationScreen.EditPassword.MaskedPassword.ChangePassButton.text\": \"Omdefiner adgangskode\",\n \"AuthenticationScreen.EditPassword.MakedPassword.noPass\": \"Du har ikke defineret en adgangskode endnu.\",\n \"AuthenticationScreen.EditPassword.SavePassButton.text\": \"Gem adgangskode\",\n \"AuthenticationScreen.EditPassword.NewPassInput.label\": \"Ny adgangskode\",\n \"AuthenticationScreen.EditPassword.PassValidation.title\": \"Din adgangskode skal have mindst:\",\n \"AuthenticationScreen.EditPassword.PassValidation.minLength\": \"8 tegn\",\n \"AuthenticationScreen.EditPassword.PassValidation.number\": \"1 tal\",\n \"AuthenticationScreen.EditPassword.PassValidation.upper\": \"1 stort bogstav\",\n \"AuthenticationScreen.EditPassword.PassValidation.lower\": \"1 lille bogstav\",\n \"AuthenticationScreen.EditPassword.CreatePassword.emailSentText\": \"En verifikationskode blev sendt til {email}.\",\n \"AuthenticationScreen.EditPassword.CreatePassword.CodeInput.label\": \"Kode\",\n \"AuthenticationScreen.EditPassword.CreatePassword.ResendCodeButton.text\": \"Send kode igen\",\n \"AuthenticationScreen.EditPassword.ChangePassword.CurrPassInput.label\": \"Nuværende adgangskode\",\n \"AuthenticationScreen.LoginSessions.label\": \"Sessionshåndtering\",\n \"AuthenticationScreen.LoginSessions.activeSessions\": \"Du har {amount} aktive sessioner\",\n \"AuthenticationScreen.LoginSessions.OpenSessionsButton.text\": \"Tjek sessioner\",\n \"LoginSessionsScreen.title\": \"Sessionshåndtering\",\n \"LoginSessionsScreen.backButton\": \"Godkendelse\",\n \"LoginSessionsScreen.LoginSession.currentSession\": \"Nuværende session\",\n \"LoginSessionsScreen.LoginSession.lastAccess\": \"Sidste adgang: {lastAccess}\",\n \"LoginSessionsScreen.LoginSession.ipDetails\": \"IP: {ip}\",\n \"LoginSessionsScreen.LoginSession.firstAccess\": \"Første adgang: {dateTime}\",\n \"LoginSessionsScreen.LoginSession.LogoutButton.text\": \"Log ud\",\n \"LoginSessionsScreen.LoginSession.DeviceMsg.desktop\": \"Desktop\",\n \"LoginSessionsScreen.LoginSession.DeviceMsg.mobile\": \"Mobil\",\n \"LoginSessionsScreen.LoginSession.DeviceMsg.tablet\": \"Tablet\"\n}\n\n```" } ]
code_my-authentication_e1db55dc
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-authentication/docs/README.md from the my-authentication VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# My Authentication\n\n<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->\n\n[![All Contributors](https://img.shields.io/badge/all_contributors-0-orange.svg?style=flat-square)](#contributors-)\n\n<!-- ALL-CONTRIBUTORS-BADGE:END -->\n\n## Description\n\nThis VTEX IO app extends the [MyAccount](https://github.com/vtex-apps/my-account) app to add authentication-related menu options (`Authentication` tab). It is installed by default in every VTEX account. Just like `MyAccount`, this can be used in either `IO` or `Portal` stores.\n\n![image](https://user-images.githubusercontent.com/22064061/112358629-47ff2100-8caf-11eb-8f89-80bdb48d2e68.png)\n\n## Table of Contents\n\n- [Usage](#usage)\n - [Visibility](#visibility)\n- [Customization](#customization)\n - [IO Stores](#io-stores)\n - [Portal Stores](#portal-stores)\n- [CSS Handles List](#css-handles-list)\n- [Contributors](#contributors)\n\n## Usage\n\n### Visibility\n\nBy default, the `Authentication` tab is not visible in the left-side menu of the [MyAccount UI](https://github.com/vtex-apps/my-account).\n\nTo make it visible, go into\n\nhttps://`{{accountName}}`.myvtex.com/admin/apps/\n\nand search for `My Account` among the `installed` apps. Then click `Settings`.\n\n![image](https://user-images.githubusercontent.com/22064061/112537384-5de31380-8d8d-11eb-80a5-902d1e0922db.png)\n\nSet `Authentication` option to :white_check_mark: `Visible`, then click `Save`.\n\n![image](https://user-images.githubusercontent.com/22064061/112537098-0b095c00-8d8d-11eb-915a-3dd7e8da86da.png)\n\n:loudspeaker: **Disclaimer:** in a close future, the `Authentication` tab visibility will become always true.\n\n:information_source: **Before making this tab visible**, you should [customize](#customization) it to match your store visual identity\n\n## Customization\n\n### IO Stores\n\nIn order to apply CSS customizations to the app, follow the instructions given in the recipe on [Using CSS Handles for store customization](https://vtex.io/docs/recipes/style/using-css-handles-for-store-customization) (you don't have to worry about `block` or `blockClass`).\n\nA list of all `CSS Handles` is in [this section](#css-handles-list).\n\nYou can see the `Authentication` UI being customized in:\n\nhttps://`{{workspaceName}}`--`{{accountName}}`.myvtex.com/account#/authentication\n\n### Portal Stores\n\nIn order to customize the app, create a `.css` file with your own rules. Your class selectors should reference the UI's pre-existing classes.\n\nA list of all `CSS Handles` is in [this section](#css-handles-list).\n\n:loudspeaker: **Avoid** using element or position-based selectors, as the customization may break in the face of the smallest UI changes.\n\nTo upload your `.css` file, go to the VTEX CMS (`/admin/a`) and open the `CMS/Files Manager/.css` file. Click `Add` and you'll be able to upload it. This file is accessible from [VTEX CMS storage](https://help.vtex.com/en/tutorial/ver-o-conteudo-dos-arquivos-css-da-loja--U5v7DXpRSee86uqiKQUQi).\n\nLastly, you should link that `.css` file to the Account Page HTML Head by [editing the \"Account\" CMS template](https://help.vtex.com/en/tracks/cms--2YcpgIljVaLVQYMzxQbc3z/Y6dPEF6GzROQ8PuYKxrKe).\n\nYou can see the `Authentication` UI being customized in:\n\nhttps://`{{accountName}}`.vtexcommercestable.com.br/\\_secure/account#/authentication\n\n(if you want to use IO workspaces, just add the query string \"?workspace=`{{workspaceName}}`\")\n\n## CSS Handles List\n\n:information_source: **If you're in a Portal Store**, append the prefix `vtex_my-authentication_` to each handle for your CSS class selectors.\n\n| CSS Handles |\n| ----------------------------------- |\n| `box_container` |\n| `box_header` |\n| `box_headerSeparator` |\n| `box_content` |\n| `box_footer` |\n| `errorAlert_container` |\n| `warnAlert_container` |\n| `authenticationScreen_container` |\n| `authenticationScreen_passBox` |\n| `newPassInput_container` |\n| `passValidation_container` |\n| `passValidation_title` |\n| `passValidation_content` |\n| `passValidation_minLengthNumber` |\n| `passValidation_minLength` |\n| `passValidation_number` |\n| `passValidation_lowerUpper` |\n| `passValidation_lower` |\n| `passValidation_upper` |\n| `passValidation_iconSuccess` |\n| `passValidation_iconFailure` |\n| `savePassButton_container` |\n| `skeletonEditPassword_content` |\n| `skeletonEditPassword_button` |\n| `currPassInput_container` |\n| `createPassword_text` |\n| `codeInput_container` |\n| `resendCodeButton_container` |\n| `maskedPassword_title` |\n| `maskedPassword_content` |\n| `loginSessionsBox_title` |\n| `loginSessionsBox_content` |\n| `skeletonLoginSessions_content` |\n| `skeletonLoginSessions_button` |\n| `loginSessionsScreen_container` |\n| `loginSessions_skeleton` |\n| `loginSessions_error` |\n| `loginSessions_list` |\n| `loginSessions_box` |\n| `skeletonLoginSessionsScreen_title` |\n| `skeletonLoginSessionsScreen_text1` |\n| `skeletonLoginSessionsScreen_text2` |\n| `loginSession_currSession` |\n| `loginSession_currSessionIcon` |\n| `loginSession_currSessionText` |\n| `loginSession_device` |\n| `loginSession_lastAccess` |\n| `loginSession_originDetails` |\n| `loginSession_fullAddress` |\n| `loginSession_firstAccess` |\n\n<!-- DOCS-IGNORE:start -->\n\n## Contributors ✨\n\nThanks goes to these wonderful people:\n\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n<!-- markdownlint-enable -->\n<!-- prettier-ignore-end -->\n\n<!-- ALL-CONTRIBUTORS-LIST:END -->\n\nThis project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind are welcome!\n\n<!-- DOCS-IGNORE:end -->\n\n```" } ]
code_ebit_adb366d2
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of ebit/messages/pt.json from the ebit VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/test\": \"teste\",\n \"store/test\": \"teste\"\n}\n```" } ]
code_ebit_c65084b7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of ebit/messages/en.json from the ebit VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/test\": \"test\",\n \"store/test\": \"test\"\n}\n\n```" } ]
code_ebit_b4ed6dca
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of ebit/messages/es.json from the ebit VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/test\": \"teste\",\n \"store/test\": \"teste\"\n}\n```" } ]
code_ebit_446102e1
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of ebit/docs/README.md from the ebit VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\nFirst of all (even before the block's name), its README.md should contain the following sentence at the very beginning:\n\n`📢 Use this project, [contribute](https://github.com/{OrganizationName}/{AppName}) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).`\n\n> :warning: *Remember to replace the values between braces according to your scenario. For example: https://github.com/vtex-apps/breadcrumb*\n\n# BLOCK NAME\n\nUnder the block's name, you should explain the topic, giving a **brief description** of the **block's functionality** in a store.\n\nNext, **add media** (either an image of a GIF) with the rendered block, so that users can better understand how the block works in practice. \n\n![Media Placeholder](https://user-images.githubusercontent.com/52087100/71204177-42ca4f80-227e-11ea-89e6-e92e65370c69.png)\n\n## Configuration \n\nIn this section, you first must **add the primary instructions** that will allow users to use the block in their store, such as adding the block's app as a dependency in the `manifest.json` and declaring the block itself in a given template.\n\nNext, add the **block's props table**:\n\n| Prop name | Type | Description | Default value |\n| ------------ | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | \n| `XXXXX` | `XXXXXX` | XXXXXXXX | `XXXXXX` |\n\n\nRemember to also **showcase any necessary disclaimer** related to the block in this section, such as the different behavior it may display during its configuration. \n\n## Modus Operandi *(not mandatory)*\n\nThere are scenarios in which a block can behave differently in a store, according to how it was added to the catalog, for example. It's crucial to go through these **behavioral changes** in this section, allowing users to fully understand the **practical application** of the block in their store.\n\nIf you feel compelled to give further details about the block, such as it's **relationship with the VTEX admin**, don't hesitate to use this section. \n\n## Customization\n\nThe first thing that should be present in this section is the sentence below, showing users the recipe pertaining to CSS customization in blocks:\n\n`In order to apply CSS customizations in this and other blocks, follow the instructions given in the recipe on [Using CSS Handles for store customization](https://vtex.io/docs/recipes/style/using-css-handles-for-store-customization).`\n\nThereafter, you should add a single column table with the available CSS handles for that block:\n\n| CSS Handles |\n| ----------- | \n| `XXXXX` | \n| `XXXXX` | \n| `XXXXX` | \n| `XXXXX` | \n| `XXXXX` |\n\n\nIf there are none, add the following sentence instead:\n\n`The component still doesn't have CSS Handles for its specific customization.`\n\n---\n\nCheck out some documentation models that are already live: \n- [Breadcrumb](https://github.com/vtex-apps/breadcrumb)\n- [Image](https://vtex.io/docs/components/general/vtex.store-components/image)\n\n\n```" } ]
code_ebit_b8d9b58a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of ebit/react/package.json from the ebit VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"CHANGE_ME\",\n \"version\": \"0.0.0\",\n \"scripts\": {\n \"test\": \"vtex-test-tools test\"\n },\n \"dependencies\": {\n \"apollo-client\": \"^2.6.8\",\n \"react\": \"^16.12.0\",\n \"react-apollo\": \"^3.1.3\",\n \"react-dom\": \"^16.12.0\",\n \"react-intl\": \"^3.12.0\"\n },\n \"devDependencies\": {\n \"@apollo/react-testing\": \"^3.1.3\",\n \"@types/jest\": \"^25.1.4\",\n \"@types/node\": \"^13.9.8\",\n \"@types/react\": \"^16.9.31\",\n \"@vtex/test-tools\": \"^3.1.0\",\n \"@vtex/tsconfig\": \"^0.4.4\",\n \"apollo-cache-inmemory\": \"^1.6.5\",\n \"graphql\": \"^14.6.0\",\n \"prop-types\": \"^15.7.2\",\n \"typescript\": \"3.8.3\"\n }\n}\n\n```" } ]
code_ebit_90654ebe
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of ebit/react/__tests__/index.test.tsx from the ebit VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\ndescribe('Orders List Scenarios', () => {\n it('should work', () => {\n expect(1).toBe(1)\n })\n})\n\n```" } ]
code_epica-pixel_7c380156
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of epica-pixel/docs/README.md from the epica-pixel VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# epica-pixel\n\nOpen the VTEX App Store and install the app on your store.\n\nor\n\nRun the following command:\n\n```sh\nvtex install vtex.epica-pixel@0.x\n```\n\nNext, open the app settings on your admin and fill the form with your Epica app ID.\n\n```" } ]
code_epica-pixel_3cb00f99
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of epica-pixel/react/index.tsx from the epica-pixel VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { canUseDOM } from 'vtex.render-runtime'\nimport { ProductOrder, Impression, PixelMessage } from './typings/events'\n\nexport function handleEvents(e: PixelMessage) {\n switch (e.data.eventName) {\n case 'vtex:userData': {\n const {\n isAuthenticated,\n firstName,\n lastName,\n document,\n id,\n email,\n phone,\n } = e.data\n if (!isAuthenticated) {\n return\n } \n epica('identify', id, {\n isAuthenticated,\n firstName,\n lastName,\n document,\n id,\n email,\n phone \n })\n break\n } \n case 'vtex:pageView': {\n epica('track', 'Page Viewed', {\n title: e.data.pageTitle,\n url: e.data.pageUrl,\n referrer: e.data.referrer \n })\n break\n }\n case 'vtex:addToCart': {\n const { items } = e.data\n epica('track', 'Product Added', {\n product_id: items[0].productRefId,\n sku: items[0].skuId,\n category: items[0].category,\n name: items[0].name,\n brand: items[0].brand,\n variant: items[0].variant,\n price: items[0].price,\n quantity: items[0].quantity \n })\n break\n }\n case 'vtex:removeFromCart': {\n const { items } = e.data\n epica('track', 'Product Removed', {\n product_id: items[0].productRefId,\n sku: items[0].skuId,\n category: items[0].category,\n name: items[0].name,\n brand: items[0].brand,\n variant: items[0].variant,\n price: items[0].price,\n quantity: items[0].quantity \n })\n break\n }\n case 'vtex:orderPlaced': {\n const { transactionProducts } = e.data\n epica('track','Order Completed', {\n checkout_id: e.data.transactionId,\n order_id: e.data.orderGroup,\n affiliation: e.data.transactionAffiliation,\n total: e.data.transactionTotal,\n revenue: e.data.transactionSubtotal,\n shipping: e.data.transactionShipping,\n tax: e.data.transactionTax,\n discount: e.data.transactionDiscounts,\n currency: e.data.currency,\n products: transactionProducts.map(\n (product: ProductOrder) => ({\n product_id: product.id,\n sku: product.sku,\n name: product.name,\n price: product.price,\n quantity: product.quantity,\n category: product.category \n })\n )\n })\n break\n }\n case 'vtex:productView': { \n const { product, currency } = e.data\n epica('track', 'Product Viewed', {\n product_id: product.productId,\n sku: product.selectedSku.itemId,\n category: getCategory(product.categories),\n name: product.productName,\n brand: product.brand,\n variant: product.selectedSku.name,\n price: product.selectedSku.sellers[0].commertialOffer.Price,\n currency \n })\n break\n }\n case 'vtex:productClick': {\n const { product } = e.data\n epica('track', 'Product Clicked', {\n product_id: product.productId,\n sku: product.sku.itemId,\n category: getCategory(product.categories),\n name: product.productName,\n brand: product.brand,\n variant: product.sku.name,\n price: product.sku.seller?.commertialOffer.Price,\n url: product.linkText,\n image_url: product.sku.image.imageUrl\n })\n break\n }\n case 'vtex:productImpression': {\n const { impressions, list, position, product } = e.data\n\n let oldImpresionFormat: Record<string, any> | null = null\n if (product != null && position != null) {\n oldImpresionFormat = [\n getProductImpressionObjectData(list)({\n product,\n position,\n }),\n ]\n }\n\n const parsedImpressions = (impressions || []).map(\n getProductImpressionObjectData(list)\n ) \n\n epica('track','Product List Viewed', {\n list_id: list,\n products: oldImpresionFormat || parsedImpressions\n })\n break\n }\n default: {\n break\n }\n }\n}\n\nfunction removeStartAndEndSlash(category: string) {\n return category && category.replace(/^\\/|\\/$/g, '')\n}\n\nfunction getCategory(rawCategories: string[]) {\n if (!rawCategories || !rawCategories.length) {\n return\n }\n\n return removeStartAndEndSlash(rawCategories[0])\n}\n\nconst getProductImpressionObjectData = (list: string) => ({\n product,\n position,\n}: Impression) => ({\n brand: product.brand,\n category: getCategory(product.categories),\n product_id: product.sku.itemId,\n list,\n name: product.productName,\n position,\n price: `${product.sku.seller!.commertialOffer.Price}`,\n variant: product.sku.name,\n})\n\nif (canUseDOM) {\n window.addEventListener('message', handleEvents)\n}\n\n```" } ]
code_epica-pixel_a83a58c9
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of epica-pixel/react/package.json from the epica-pixel VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"scripts\": {\n \"test\": \"vtex-test-tools test\"\n },\n \"dependencies\": {\n \"ramda\": \"^0.26.1\"\n },\n \"devDependencies\": {\n \"@types/graphql\": \"^14.5.0\",\n \"@types/jest\": \"^24.0.11\",\n \"@types/node\": \"^11.13.0\",\n \"@types/ramda\": \"^0.26.5\",\n \"@vtex/test-tools\": \"^1.1.0\",\n \"eslint\": \"^5.16.0\",\n \"eslint-config-vtex-react\": \"^4.1.0\",\n \"graphql\": \"^14.5.4\",\n \"prettier\": \"^1.18.2\",\n \"tslint-eslint-rules\": \"^5.4.0\",\n \"typescript\": \"3.5.2\"\n },\n \"version\": \"0.1.1\"\n}\n\n```" } ]
code_epica-pixel_03ca35ff
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of epica-pixel/store/interfaces.json from the epica-pixel VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"pixel.epicaPixel\": {\n \"component\": \"index\"\n }\n}\n```" } ]
code_epica-pixel_04d09826
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of epica-pixel/react/typings/events.d.ts from the epica-pixel VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport interface PixelMessage extends MessageEvent {\n data:\n | ProductViewData\n | ProductClickData\n | OrderPlacedData\n | PageViewData\n | ProductImpressionData\n | AddToCartData\n | RemoveToCartData\n | HomePageInfo\n | ProductPageInfoData\n | SearchPageInfoData\n | UserData\n}\n\nexport interface EventData {\n event: string\n eventName: string\n currency: string\n}\n\nexport interface PageInfoData extends EventData {\n event: 'pageInfo'\n eventName: 'vtex:pageInfo'\n accountName: string\n pageTitle: string\n pageUrl: string\n}\n\nexport interface HomePageInfo extends PageInfoData {\n eventType: 'homeView'\n}\n\nexport interface ProductPageInfoData extends PageInfoData {\n eventType: 'productView'\n}\n\nexport interface SearchPageInfoData extends PageInfoData {\n eventType:\n | 'internalSiteSearchView'\n | 'categoryView'\n | 'departmentView'\n | 'emptySearchView'\n category?: CategoryMetaData\n department?: DepartmentMetaData\n search?: SearchMetaData\n}\n\ninterface CategoryMetaData {\n id: string\n name: string\n}\n\ninterface DepartmentMetaData {\n id: string\n name: string\n}\n\ninterface SearchMetaData {\n term: string\n category: CategoryMetaData\n results: number\n}\n\nexport interface PageViewData extends EventData {\n event: 'pageView'\n eventName: 'vtex:pageView'\n pageTitle: string\n pageUrl: string\n referrer: string\n}\n\nexport interface AddToCartData extends EventData {\n event: 'addToCart'\n eventName: 'vtex:addToCart'\n items: CartItem[]\n}\n\nexport interface RemoveToCartData extends EventData {\n event: 'removeFromCart'\n eventName: 'vtex:removeFromCart'\n items: CartItem[]\n}\n\nexport interface OrderPlacedData extends Order, EventData {\n event: 'orderPlaced'\n eventName: 'vtex:orderPlaced'\n}\n\nexport interface ProductViewData extends EventData {\n event: 'productView'\n eventName: 'vtex:productView'\n product: ProductDetail\n selectedSku: Item\n}\n\nexport interface ProductClickData extends EventData {\n event: 'productClick'\n eventName: 'vtex:productClick'\n product: ProductSummary\n}\n\nexport interface ProductImpressionData extends EventData {\n event: 'productImpression'\n eventName: 'vtex:productImpression'\n impressions: Impression[]\n product?: ProductSummary // deprecated, use impressions list!\n position?: number // deprecated, use impressions list!\n list: string\n}\n\nexport interface UserData extends EventData {\n event: 'userData'\n eventName: 'vtex:userData'\n isAuthenticated: boolean\n firstName: string\n lastName: string\n document: string\n id: string\n email: string\n phone: string\n}\n\ninterface CartItem {\n skuId: string\n variant: string\n price: number\n name: string\n quantity: number\n productRefId: string\n brand: string\n category: string\n}\n\nexport interface Order {\n currency: string\n accountName: string\n orderGroup: string\n salesChannel: string\n coupon: string\n visitorType: string\n visitorContactInfo: string[]\n visitorAddressState: string\n visitorAddressCountry: string\n visitorAddressPostalCode: string\n transactionId: string\n transactionDate: string\n transactionAffiliation: string\n transactionTotal: number\n transactionShipping: number\n transactionSubtotal: number\n transactionDiscounts: number\n transactionTax: number\n transactionCurrency: string\n transactionPaymentType: PaymentType[]\n transactionShippingMethod: ShippingMethod[]\n transactionProducts: ProductOrder[]\n transactionPayment: {\n id: string\n }\n}\n\nexport interface Impression {\n product: ProductSummary\n position: number\n}\n\nexport interface PaymentType {\n group: string\n paymentSystemName: string\n installments: number\n value: number\n}\n\nexport interface ShippingMethod {\n itemId: string\n selectedSla: string\n}\n\nexport interface ProductOrder {\n id: string\n name: string\n sku: string\n skuRefId: string\n skuName: string\n productRefId: string\n ean: string\n slug: string\n brand: string\n brandId: string\n seller: string\n sellerId: string\n category: string\n categoryId: string\n categoryTree: string[]\n categoryIdTree: string[]\n priceTags: PriceTag[]\n originalPrice: number\n price: number\n sellingPrice: number\n tax: number\n quantity: number\n components: any[]\n measurementUnit: string\n unitMultiplier: number\n}\n\nexport interface PriceTag {\n identifier: string\n isPercentual: boolean\n value: number\n}\n\ninterface Product {\n brand: string\n brandId: string\n categories: string[]\n productId: string\n productName: string\n productReference: string\n linkText: string\n items: Item[]\n}\n\nexport interface ProductSummary extends Product {\n sku: Item\n}\n\nexport interface ProductDetail extends Product {\n categoryId: string\n categoryTree: { id: string; name: string }[]\n selectedSku: Item\n}\n\nexport interface Item {\n itemId: string\n name: string\n ean?: string // TODO: provide this info at productImpression\n referenceId: { Key: string; Value: string }\n seller?: Seller\n sellers: Seller[]\n image: any\n}\n\nexport interface Seller {\n commertialOffer: CommertialOffer\n sellerId: string\n}\n\nexport interface CommertialOffer {\n Price: number\n ListPrice: number\n AvailableQuantity: number\n}\n\n```" } ]
code_epica-pixel_beb24fb3
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of epica-pixel/react/typings/vtex.render-runtime.d.ts from the epica-pixel VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.render-runtime' {\n export const canUseDOM: boolean\n}\n\n```" } ]
code_epica-pixel_816601f9
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of epica-pixel/react/typings/global.d.ts from the epica-pixel VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare function epica(s: string, t: string, o?: any): void\n\ninterface Window extends Window {\n dataLayer: any[]\n}\n\n```" } ]
code_Indexer-listener_a01cb170
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of Indexer-listener/node/service.json from the Indexer-listener VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"memory\": 256,\n \"ttl\": 10,\n \"timeout\": 2,\n \"minReplicas\": 2,\n \"maxReplicas\": 4,\n \"routes\": {\n \"status\": {\n \"path\": \"/_v/public/listener\",\n \"public\": true\n },\n \"settings\":{\n \"path\": \"/settings\",\n \"public\": false,\n \"policies\": [{\n \"effect\": \"allow\",\n \"actions\": [\"get\"],\n \"principals\": [\n \"vrn:apps:*:*:*:app/vtex.broadcaster-listenery@0.*\"\n ]\n }]\n }\n }\n}\n\n```" } ]