id
stringlengths
12
53
messages
listlengths
3
3
code_cross-device-cart_ba6daeb1
[ { "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 cross-device-cart/react/typings/global.d.ts from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface OrderFormContext {\n orderForm: PartialOrderForm\n setOrderForm: (orderForm: any) => void\n initialFetchComplete: boolean\n}\n\ninterface ToastParam {\n message: string\n duration?: number\n horizontalPosition?: 'left' | 'right'\n}\n\ninterface PartialOrderForm {\n id: string\n items: any[]\n}\n\ninterface ReplaceCartVariables {\n savedCart: string\n currentCart: string\n strategy: Strategy,\n userType?: string\n}\n\ninterface CrossCartData {\n id: string\n}\n\ninterface CrossCartVars {\n userId: string\n nullOnEmpty?: boolean\n userType?: string\n}\n\ninterface NewCrossCart {\n userId: string\n orderFormId: string | null,\n userType?: string\n}\n\ntype NewOrderForm = { [key: string]: any }\n\ntype Success = 'success'\n\ninterface AppSettings {\n isAutomatic: boolean\n strategy: Strategy\n}\n\ntype Strategy = 'ADD' | 'COMBINE' | 'REPLACE'\n\ninterface AppSettingsData {\n settings: AppSettings\n}\n\n```" } ]
code_cross-device-cart_3b4e5bfc
[ { "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 cross-device-cart/react/typings/admin.d.ts from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface Settings {\n isAutomatic: boolean\n strategy: Strategy\n}\n\n```" } ]
code_cross-device-cart_52da7f23
[ { "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 cross-device-cart/react/utils/insertRootPath.ts from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport default function insertRootPath(\n rootPath: string | undefined,\n apiRoute: string\n) {\n const pathWithRootPath = rootPath ? `${rootPath}${apiRoute}` : apiRoute\n\n return pathWithRootPath\n}\n\n```" } ]
code_cross-device-cart_47d464ed
[ { "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 cross-device-cart/react/utils/constants.ts from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const ADD = 'ADD'\nexport const ADD_DESCRIPTION = 'Add missing items'\n\nexport const COMBINE = 'COMBINE'\nexport const COMBINE_DESCRIPTION = 'Combine current and missing items'\n\nexport const REPLACE = 'REPLACE'\nexport const REPLACE_DESCRIPTION = 'Replace current items entirely'\n\nexport const SESSION_ITEM = 'cartAlreadyCombined'\n\n```" } ]
code_cross-device-cart_b6e9c564
[ { "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 cross-device-cart/react/components/CrossCart.tsx from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { FC, useEffect, useState } from 'react'\nimport { useLazyQuery, useMutation } from 'react-apollo'\nimport { useIntl } from 'react-intl'\nimport { useRuntime } from 'vtex.render-runtime'\nimport { useOrderForm } from 'vtex.order-manager/OrderForm'\nimport axios from 'axios'\n\nimport GET_ID_BY_USER from '../graphql/getSavedCart.gql'\nimport SAVE_ID_BY_USER from '../graphql/saveCurrentCart.gql'\nimport MUTATE_CART from '../graphql/replaceCart.gql'\nimport ChallengeBlock from './ChallengeBlock'\nimport insertRootPath from '../utils/insertRootPath'\n\ninterface Props {\n userId: string\n isAutomatic: boolean\n showToast: (toast: ToastParam) => void\n strategy: Strategy\n userType: string\n}\n\nconst CrossCart: FC<Props> = ({ userId, isAutomatic, strategy, showToast, userType }) => {\n const {\n orderForm,\n initialFetchComplete,\n setOrderForm,\n } = useOrderForm() as OrderFormContext\n\n const { rootPath = '' } = useRuntime()\n\n const [hasMerged, setMergeStatus] = useState(false)\n const [challengeActive, setChallenge] = useState(false)\n const intl = useIntl()\n\n const hasItems = orderForm.items.length\n\n const [getSavedCart, { data, loading }] = useLazyQuery<\n CrossCartData,\n CrossCartVars\n >(GET_ID_BY_USER, {\n fetchPolicy: 'no-cache',\n })\n\n const [saveCurrentCart] = useMutation<Success, NewCrossCart>(SAVE_ID_BY_USER)\n\n const [replaceCart, { error, loading: mutationLoading }] = useMutation<\n NewOrderForm | null,\n ReplaceCartVariables\n >(MUTATE_CART)\n\n useEffect(() => {\n getSavedCart({\n variables: {\n userId,\n nullOnEmpty: !isAutomatic,\n userType\n },\n })\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [])\n\n const handleDeclineMerge = async () => {\n challengeActive && setChallenge(false)\n\n await saveCurrentCart({\n variables: {\n userId,\n orderFormId: hasItems ? orderForm.id : null,\n userType\n },\n })\n }\n\n const handleMerge = async () => {\n if (!data?.id || hasMerged) return\n\n setMergeStatus(true)\n\n const mutationResult = await replaceCart({\n variables: {\n currentCart: orderForm.id,\n savedCart: data.id,\n strategy,\n userType\n },\n })\n\n if (error || !mutationResult.data || !mutationResult.data.newOrderForm) {\n error && console.error(error)\n\n showToast({\n message: intl.formatMessage({ id: 'store/crossCart.toast.error' }),\n })\n\n return\n }\n\n try {\n const orderFormURLWithRootPath = insertRootPath(\n rootPath,\n `/api/checkout/pub/orderForm/${data.id}`\n )\n\n await axios.post(\n orderFormURLWithRootPath,\n {},\n {\n headers: {\n 'set-cookie': `checkout.vtex.com=__ofid=${data.id}`,\n },\n }\n )\n } catch (e) {\n challengeActive && setChallenge(false)\n\n showToast({\n message: intl.formatMessage({ id: 'store/crossCart.toast.error' }),\n })\n\n return\n }\n\n const { newOrderForm } = mutationResult.data\n\n setOrderForm(newOrderForm)\n\n challengeActive && setChallenge(false)\n\n showToast({\n message: intl.formatMessage({ id: 'store/crossCart.toast.success' }),\n })\n\n getSavedCart({\n variables: {\n userId,\n nullOnEmpty: !isAutomatic,\n },\n })\n }\n\n useEffect(() => {\n if (\n loading ||\n !data ||\n !initialFetchComplete ||\n orderForm?.id === 'default-order-form'\n )\n return\n\n const crossCart = data?.id !== 'default-order-form' && data?.id\n\n if (!crossCart) {\n saveCurrentCart({\n variables: {\n userId,\n orderFormId: orderForm.id,\n userType\n },\n })\n\n return\n }\n\n const equalCarts = crossCart === orderForm.id\n\n if (!equalCarts) {\n !isAutomatic && setChallenge(true)\n isAutomatic && handleMerge()\n\n return\n }\n\n if (!hasItems && !isAutomatic) {\n saveCurrentCart({\n variables: {\n userId,\n orderFormId: null,\n userType\n },\n })\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [loading, data, hasItems, initialFetchComplete, orderForm.id])\n\n if (!challengeActive || isAutomatic) {\n return null\n }\n\n return (\n <ChallengeBlock\n handleAccept={handleMerge}\n handleDecline={handleDeclineMerge}\n mutationLoading={mutationLoading}\n />\n )\n}\n\nexport { CrossCart }\n\n```" } ]
code_cross-device-cart_018ee279
[ { "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 cross-device-cart/react/components/ChallengeBlock.tsx from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { FC, Fragment } from 'react'\nimport { useDevice } from 'vtex.device-detector'\nimport { FormattedMessage } from 'react-intl'\nimport { Button, ButtonWithIcon, IconClose } from 'vtex.styleguide'\nimport { useCssHandles } from 'vtex.css-handles'\n\nconst CSS_HANDLES = ['actionBar', 'challengeText'] as const\n\nconst closeIcon = <IconClose />\n\ninterface Props {\n handleAccept: () => void\n handleDecline: () => void\n mutationLoading: boolean\n}\n\nconst ChallengeBlock: FC<Props> = ({\n handleAccept,\n handleDecline,\n mutationLoading,\n}) => {\n const { device } = useDevice()\n const handles = useCssHandles(CSS_HANDLES)\n\n const deviceClass = `${device === 'phone' ? 'flex-column' : ''}`\n\n return (\n <Fragment>\n <div\n className={`${deviceClass} pa4 tc w-100 bg-base flex items-center justify-center ${handles.actionBar}`}\n >\n <span\n className={`${handles.challengeText} t-small ${\n device === 'phone' ? 'pb3' : ''\n }`}\n >\n <FormattedMessage id=\"store/crossCart.challenge.text\" />\n </span>\n <div className=\"flex\">\n <span className=\"mh4\">\n <Button\n size=\"small\"\n variation=\"secondary\"\n onClick={() => {\n handleAccept()\n }}\n isLoading={mutationLoading}\n >\n <FormattedMessage id=\"store/crossCart.challenge.cta\" />\n </Button>\n </span>\n <span>\n <ButtonWithIcon\n size=\"small\"\n icon={closeIcon}\n variation=\"tertiary\"\n onClick={() => {\n handleDecline()\n }}\n isLoading={mutationLoading}\n />\n </span>\n </div>\n </div>\n </Fragment>\n )\n}\n\nexport default ChallengeBlock\n\n```" } ]
code_cross-device-cart_40394003
[ { "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 cross-device-cart/react/components/SessionWrapper.tsx from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { FC, useState, useEffect } from 'react'\nimport { SessionSuccess, useRenderSession } from 'vtex.session-client'\nimport { useOrderForm } from 'vtex.order-manager/OrderForm'\nimport { ToastConsumer } from 'vtex.styleguide'\nimport { useQuery } from 'react-apollo'\n\nimport { CrossCart } from './CrossCart'\nimport getAppSettings from '../graphql/getAppSettings.gql'\n\nconst SessionWrapper: FC = () => {\n const { loading, session, error } = useRenderSession()\n const { loading: orderLoading, orderForm: {userType} } = useOrderForm()\n const [settings, setAppSettings] = useState({} as AppSettings)\n const { data } = useQuery<AppSettingsData>(getAppSettings, {\n ssr: false,\n })\n\n useEffect(() => {\n if (!data) {\n return\n }\n\n setAppSettings(data.settings)\n }, [data])\n\n if (error || loading || !session || orderLoading || !data) {\n return null\n }\n\n const {\n namespaces: { profile },\n } = session as SessionSuccess\n\n const { isAutomatic, strategy } = settings\n\n const isAuthenticated = profile?.isAuthenticated.value === 'true'\n\n if (!isAuthenticated) {\n return null\n }\n\n const userId = profile?.id.value\n\n return (\n <ToastConsumer>\n {({ showToast }: { showToast: (toast: ToastParam) => void }) => (\n <CrossCart\n showToast={showToast}\n userId={userId}\n isAutomatic={isAutomatic}\n userType={userType}\n strategy={strategy}\n />\n )}\n </ToastConsumer>\n )\n}\n\nexport { SessionWrapper }\n\n```" } ]
code_cross-device-cart_ffc67edc
[ { "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 cross-device-cart/react/graphql/getSavedCart.gql from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nquery getSavedCart($userId: String!, $nullOnEmpty: Boolean, $userType: String) {\n id: getSavedCart(userId: $userId, nullOnEmpty: $nullOnEmpty, userType: $userType)\n}\n\n```" } ]
code_cross-device-cart_5d1803dd
[ { "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 cross-device-cart/react/graphql/saveCurrentCart.gql from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nmutation saveCurrentCart($userId: String!, $orderFormId: String, $userType: String) {\n saveCurrentCart(userId: $userId, orderFormId: $orderFormId, userType: $userType)\n}\n\n```" } ]
code_cross-device-cart_8babf00a
[ { "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 cross-device-cart/react/graphql/replaceCart.gql from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nmutation replaceCart(\n $savedCart: String!\n $currentCart: String!\n $strategy: Strategy!\n $userType: String\n) {\n newOrderForm: replaceCart(\n savedCart: $savedCart\n currentCart: $currentCart\n strategy: $strategy\n userType: $userType\n )\n}\n\n```" } ]
code_cross-device-cart_8b3903d5
[ { "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 cross-device-cart/react/graphql/getAppSettings.gql from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nquery getAppSettings {\n settings: getAppSettings {\n isAutomatic\n strategy\n }\n}\n\n```" } ]
code_cross-device-cart_5b85fa92
[ { "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 cross-device-cart/react/graphql/saveAppSettings.gql from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nmutation saveAppSettings($settings: SaveSettings) {\n saveAppSettings(settings: $settings)\n}\n\n```" } ]
code_cross-device-cart_ef9d636b
[ { "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 cross-device-cart/react/components/admin/AdminPanel.tsx from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { FC, Fragment, useEffect, useState } from 'react'\nimport { FormattedMessage } from 'react-intl'\nimport {\n Alert,\n Layout,\n PageBlock,\n PageHeader,\n SelectableCard,\n Spinner,\n Toggle,\n Divider,\n} from 'vtex.styleguide'\nimport { useMutation, useQuery } from 'react-apollo'\n\nimport GET_APP_SETTINGS from '../../graphql/getAppSettings.gql'\nimport SAVE_APP_SETTINGS from '../../graphql/saveAppSettings.gql'\nimport { ADD, COMBINE, REPLACE } from '../../utils/constants'\n\nconst AdminPanel: FC = () => {\n const [settings, setSettings] = useState({} as AppSettings)\n\n const { data, loading: loadingSettings, error: settingsError } = useQuery<{\n settings: AppSettings\n }>(GET_APP_SETTINGS, { ssr: false })\n\n const [saveSettings] = useMutation(SAVE_APP_SETTINGS)\n\n const handleUpdateSettings = ({\n type,\n value,\n }: {\n type: 'IS_AUTOMATIC' | 'STRATEGY'\n value: boolean | Strategy\n }) => {\n switch (type) {\n case 'IS_AUTOMATIC':\n setSettings((prevSettings) => ({\n ...prevSettings,\n isAutomatic: value as boolean,\n }))\n break\n\n case 'STRATEGY':\n setSettings((prevSettings) => ({\n ...prevSettings,\n strategy: value as Strategy,\n }))\n break\n\n default:\n console.error('Settings could not be updated')\n break\n }\n\n saveSettings({\n variables: {\n settings: {\n isAutomatic: type === 'IS_AUTOMATIC' ? value : settings.isAutomatic,\n strategy: type === 'STRATEGY' ? value : settings.strategy,\n },\n },\n })\n }\n\n useEffect(() => {\n if (!data?.settings) {\n return\n }\n\n const { isAutomatic, strategy } = data.settings\n\n setSettings({ isAutomatic, strategy })\n }, [data?.settings])\n\n if (settingsError) {\n console.error(settingsError)\n }\n\n const { isAutomatic, strategy } = settings\n\n return (\n <Layout\n pageHeader={\n <PageHeader\n title={<FormattedMessage id=\"admin/cross-device-cart.title\" />}\n subtitle={<FormattedMessage id=\"admin/cross-device-cart.subtitle\" />}\n />\n }\n >\n <PageBlock>\n {settingsError ? (\n <Alert type=\"error\">\n <FormattedMessage id=\"admin/cross-device-cart.error\" />\n </Alert>\n ) : loadingSettings ? (\n <div className=\"flex justify-center mv5\">\n <Spinner />\n </div>\n ) : (\n <Fragment>\n <Toggle\n label={\n isAutomatic ? (\n <FormattedMessage id=\"admin/cross-device-cart.automatic-toggle-automatic\" />\n ) : (\n <FormattedMessage id=\"admin/cross-device-cart.automatic-toggle-manual\" />\n )\n }\n semantic\n checked={isAutomatic}\n onChange={() =>\n handleUpdateSettings({\n type: 'IS_AUTOMATIC',\n value: !settings.isAutomatic,\n })\n }\n helpText={\n <FormattedMessage id=\"admin/cross-device-cart.automatic-toggle-help-text\" />\n }\n />\n <p className=\"gray lh-copy\">\n <FormattedMessage id=\"admin/cross-device-cart.automatic-toggle-explanation\" />\n </p>\n\n <div className=\"pt6\">\n <Divider />\n </div>\n <h3>Merge strategies</h3>\n <div className=\"flex justify-center\">\n <div className=\"mr5 w-33\">\n <SelectableCard\n hasGroupRigth\n hasGroupLeft\n noPadding\n selected={strategy === REPLACE}\n onClick={() =>\n handleUpdateSettings({ type: 'STRATEGY', value: REPLACE })\n }\n >\n <div className=\"pa7\">\n <div className=\"f5 tc\">Replace</div>\n </div>\n </SelectableCard>\n </div>\n <div className=\"mr5 w-34\">\n <SelectableCard\n hasGroupRigth\n hasGroupLeft\n noPadding\n selected={strategy === ADD}\n onClick={() =>\n handleUpdateSettings({ type: 'STRATEGY', value: ADD })\n }\n >\n <div className=\"pa7\">\n <div className=\"f5 tc\">Add</div>\n </div>\n </SelectableCard>\n </div>\n <div className=\"w-33\">\n <SelectableCard\n hasGroupRigth\n noPadding\n selected={strategy === COMBINE}\n onClick={() =>\n handleUpdateSettings({ type: 'STRATEGY', value: COMBINE })\n }\n >\n <div className=\"pa7\">\n <div className=\"f5 tc\">Combine</div>\n </div>\n </SelectableCard>\n </div>\n </div>\n <p className=\"pt5 gray lh-copy\">\n {strategy === REPLACE ? (\n <FormattedMessage id=\"admin/cross-device-cart.strategy-explanation.replace\" />\n ) : strategy === COMBINE ? (\n <FormattedMessage id=\"admin/cross-device-cart.strategy-explanation.combine\" />\n ) : (\n <FormattedMessage id=\"admin/cross-device-cart.strategy-explanation.add\" />\n )}\n </p>\n </Fragment>\n )}\n </PageBlock>\n </Layout>\n )\n}\n\nexport { AdminPanel }\n\n```" } ]
code_us-address-validation_018cc13d
[ { "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 us-address-validation/checkout-ui-custom/checkout6-custom.js from the us-address-validation VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n// us address validation\n\n\n\nclass _addressValidation {\n\tconstructor() {\n\t\tthis.orderForm = null\n\t\tthis.validatedAddress = null\n\t\tthis.checkoutAddress = null\n this.lang = null\n\n\t\tthis._addressValidationStatus = false\n\t\tthis._addressValidationId = false\n\t}\n\n debounce(func,wait) {\n let timeout\n\n return function executedFunction(...args) {\n const later = () => {\n clearTimeout(timeout)\n func(...args)\n }\n\n clearTimeout(timeout)\n timeout = setTimeout(later, wait)\n }\n }\n\n\tbind() {\n\t\tconst _this = this\n\n\t\t$(\"body\").on(\"click\", \".addressValidation__box--addressOption\", function(e) {\n\t\t\t$(\".addressValidation__box--addressOption\").removeClass(\"ischecked\")\n\t\t\t$(this).addClass(\"ischecked\")\n\t\t})\n\n\t\t$(\"body\").on(\"click\", \".js-addressValidation__box--button\", function(e) {\n\t\t\te.preventDefault()\n\t\t\te.stopPropagation()\n\t\t\t_this.saveAddress()\n\t\t})\n\n\t\t$(\"body\").on(\"click\", \".js-addressCheck__box--button\", function(e) {\n\t\t\te.preventDefault()\n\t\t\te.stopPropagation()\n _this.desactiveAddressValidation();\n _this.closeModal(\".addressInvalidation__box\")\n\t\t})\n\t}\n\n\tcloseModal(selectedElement) {\n\t\tconst _this = this\n\n\t\t$(selectedElement).slideUp(500, function() {\n\t\t\t$(selectedElement).remove()\n\t\t\t_this._addressValidationStatus = true\n\t\t\t//_this._addressValidationId = _this.orderForm.shippingData.selectedAddresses[0].addressId\n if(selectedElement == \".addressInvalidation__box\") {\n $('body').addClass('v-custom-addressForm-on v-custom-googleForm-on')\n }\n\t\t})\n\n _this.desactiveAddressValidation();\n\t}\n\n\tshowInvalidAddressModal() {\n\t\tconst _this = this\n\n const _modalHTML = `\n\t\t\t<div class=\"addressInvalidation__box\">\n\t\t\t\t<div class=\"addressValidation__box--wrap\">\n\t\t\t\t\t<h4 class=\"addressValidation__box--title\">Address Verification</h4>\n\t\t\t\t\t<p class=\"addressValidation__box--text\">\n <span class=\"icon\">x</span>\n <b>We couldn't find your address</b>\n </p>\n\t\t\t\t\t<p class=\"addressValidation__box--text\">Please review it. Bear in mind that we will might be unabled to send your order.</p>\n\t\t\t\t\t<button class=\"js-addressCheck__box--button js-addressValidation__box--close\">Change Address</button>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t`\n\n\t\tif($(\".addressInvalidation__box\").length) return\n\t\t$(\"#shipping-data\").after(_modalHTML)\n\t}\n\n\tshowModal() {\n\t\tconst _this = this\n\n\t\tconst _modalHTML = `\n\t\t\t<div class=\"addressValidation__box\">\n\t\t\t\t<div class=\"addressValidation__box--wrap\">\n\t\t\t\t\t<h4 class=\"addressValidation__box--title\">Address Verification</h4>\n\t\t\t\t\t<p class=\"addressValidation__box--text\">\n <span class=\"icon\"><svg viewBox=\"0 0 15 17\"><g stroke=\"#231F20\" fill=\"#231F20\" stroke-width=\"1\"><path d=\"M.5 16.5v-5a6.81 6.81 0 015-2c3 0 4 2 6 2a5.35 5.35 0 003-1v-9a5.35 5.35 0 01-3 1c-2 0-3-2-6-2a6.81 6.81 0 00-5 2v9\" fill=\"#FEFEFE\" stroke-linecap=\"round\" stroke-linejoin=\"round\"></path></g></svg></span>\n <b>The address you entered may be undeliverable. Please make sure it is correct before proceeding.</b>\n </p>\n\t\t\t\t\t<form class=\"addressValidation__box--addresses\">\n\t\t\t\t\t\t<label class=\"addressValidation__box--addressOption\">\n\t\t\t\t\t\t\t<p>You entered:</p>\n\t\t\t\t\t\t\t<input type=\"radio\" name=\"addressvalidation\"/>\n\t\t\t\t\t\t\t<span>\n\t\t\t\t\t\t\t\t${_this.checkoutAddress.street}\n\t\t\t\t\t\t\t\t<br/>\n\t\t\t\t\t\t\t\t${_this.checkoutAddress.city ? `${_this.checkoutAddress.city}, ` : \"\"}${_this.checkoutAddress.state} ${_this.checkoutAddress.postalCode}\n\t\t\t\t\t\t\t</span>\n <b>*This address may be undeliverable</b>\n\t\t\t\t\t\t</label>\n\t\t\t\t\t\t<label class=\"addressValidation__box--addressOption addressValidation__box--addressOption--validated ischecked\">\n\t\t\t\t\t\t\t<p>Suggested address:</p>\n\t\t\t\t\t\t\t<input type=\"radio\" name=\"addressvalidation\" checked=\"checked\"/>\n\t\t\t\t\t\t\t<span>\n\t\t\t\t\t\t\t\t${_this.validatedAddress.components.primary_number} ${_this.validatedAddress.components.street_predirection !== undefined ? _this.validatedAddress.components.street_predirection : ''} ${_this.validatedAddress.components.street_name} ${_this.validatedAddress.components.street_postdirection ? _this.validatedAddress.components.street_postdirection : \"\"}\n\t\t\t\t\t\t\t\t<br/>\n\t\t\t\t\t\t\t\t${_this.validatedAddress.components.default_city_name === \"Null\" ? \"\" : _this.validatedAddress.components.default_city_name}, ${_this.validatedAddress.components.state_abbreviation} ${_this.validatedAddress.components.zipcode}\n\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t</label>\n\t\t\t\t\t</form>\n\t\t\t\t\t<button class=\"addressValidation__box--button js-addressValidation__box--button\">Continue with this address</button>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t`\n\n\t\tif($(\".addressValidation__box\").length) return\n\t\t$(\"#shipping-data\").after(_modalHTML)\n\t}\n\n\tsaveAddress() {\n\t\tconst _this = this\n\n\t\tif(!$(\".addressValidation__box--addressOption--validated\").hasClass(\"ischecked\")) {\n\t\t\t_this.closeModal('.addressValidation__box')\n _this.desactiveAddressValidation();\n\t\t\treturn\n\t\t}\n\n\n\n\n\t\t// fetch(`/api/checkout/pub/orderForm/${_this.orderForm.orderFormId}/attachments/shippingData`,\n // {\n // \"credentials\":\"include\",\n // \"headers\":{\n // \"accept\":\"application/json, text/javascript, */* q=0.01\",\n // \"cache-control\":\"no-cache\",\n // \"content-type\":\"application/json charset=UTF-8\",\n // \"pragma\":\"no-cache\",\n // \"sec-fetch-mode\":\"cors\",\n // \"sec-fetch-site\":\"same-origin\",\n // \"x-requested-with\":\"XMLHttpRequest\"\n // },\n // \"referrerPolicy\":\"no-referrer-when-downgrade\",\n // \"body\":JSON.stringify({\n // 'selectedAddresses':[\n // {\n // 'addressType':'residential',\n // 'receiverName':'',\n // 'addressId':'',\n // 'isDisposable':true,\n // 'postalCode':_this.validatedAddress.components.zipcode,\n // 'city':_this.validatedAddress.components.default_city_name,\n // 'state':_this.validatedAddress.components.state_abbreviation,\n // 'country':_this.checkoutAddress.country,\n // 'geoCoordinates':[ _this.validatedAddress.metadata.longitude, _this.validatedAddress.metadata.latitude ],\n // 'street':_this.validatedAddress.delivery_line_1,\n // 'number':_this.validatedAddress.components.primary_number||\"\",\n // 'neighborhood':'',\n // 'complement':_this.checkoutAddress.complement,\n // 'reference':null,\n // 'addressQuery':`${_this.validatedAddress.delivery_line_1} ${_this.validatedAddress.last_line}`\n // }\n // ],\n // 'clearAddressIfPostalCodeNotFound':false,\n // }),\n // \"method\":\"POST\",\n // \"mode\":\"cors\"\n // })\n\n var shippingInfo = {\n \"selectedAddresses\": [{\n \"addressType\": \"residential\",\n \"receiverName\": \"\",\n \"isDisposable\": true,\n \"postalCode\": _this.validatedAddress.components.zipcode,\n \"city\": _this.validatedAddress.components.default_city_name,\n \"state\": this.validatedAddress.components.state_abbreviation,\n \"country\": _this.checkoutAddress.country,\n \"street\":_this.validatedAddress.delivery_line_1,\n \"number\": _this.validatedAddress.components.primary_number||\"\",\n \"neighborhood\": \"\",\n \"complement\": _this.checkoutAddress.complement,\n \"reference\": null,\n \"geoCoordinates\": [ _this.validatedAddress.metadata.longitude, _this.validatedAddress.metadata.latitude ],\n \"addressQuery\": `${_this.validatedAddress.delivery_line_1} ${_this.validatedAddress.last_line}`\n }],\n \"clearAddressIfPostalCodeNotFound\": false\n }\n\n _this.triggerEvent(\"saveAddress\")\n vtexjs.checkout.sendAttachment(\"shippingData\", {}).done(function(orderForm) {\n $(\"button.vtex-front-messages-close-all.close\").trigger(\"click\");\n $(\".vtex-omnishipping-1-x-warning\").hide();\n _this.closeModal(\".addressValidation__box\")\n vtexjs.checkout.sendAttachment(\"shippingData\", shippingInfo).done(function(orderForm) {\n _this.desactiveAddressValidation()\n _this.triggerEvent(\"savedAddress\")\n })\n .fail(function(error) {\n console.error(`Something went wrong: ${error}`)\n })\n })\n\t}\n\n ifAllUnavailable(orderForm) {\n if(orderForm.items.filter( item => item.availability == \"cannotBeDelivered\").length == orderForm.items.length) {\n $(\".orderform-template-holder .step.shipping-data .box-step\").hide();\n } else {\n $(\".orderform-template-holder .step.shipping-data .box-step\").show();\n }\n }\n\n triggerEvent(evt) {\n $(window).trigger(`addressValidation__${evt}`)\n }\n\n\tvalidate(orderForm) {\n\t\tconst _this = this\n\n\t\t_this.orderForm = orderForm\n\n\t\ttry {\n\n\t\t\tif(\n\t\t\t\t_this.orderForm &&\n\t\t\t\t_this.orderForm.shippingData &&\n\t\t\t\t_this.orderForm.shippingData.selectedAddresses.length &&\n\t\t\t\t!_this._addressValidationStatus &&\n !(~_this.orderForm.shippingData.selectedAddresses[0].city.indexOf('*')) &&\n\t\t\t\t(_this.orderForm.shippingData.selectedAddresses[0].city || _this.orderForm.shippingData.selectedAddresses[0].neighborhood) &&\n\t\t\t\t_this.orderForm.shippingData.selectedAddresses[0].postalCode &&\n\t\t\t\t_this.orderForm.shippingData.selectedAddresses[0].state &&\n\t\t\t\t_this.orderForm.shippingData.selectedAddresses[0].street\n\n\t\t\t) {\n\n\t\t\t\t_this.checkoutAddress = _this.orderForm.shippingData.selectedAddresses[0]\n\n _this.triggerEvent(\"validate\")\n if(window.vtexjs.checkout.orderForm && window.vtexjs.checkout.orderForm.shippingData && window.vtexjs.checkout.orderForm.shippingData.logisticsInfo &&\n window.vtexjs.checkout.orderForm.shippingData.logisticsInfo[0].selectedDeliveryChannel !== 'pickup-in-point') {\n\t\t\t\tfetch(`/smartystreets-validation/?street=${_this.checkoutAddress.street}&city=${_this.checkoutAddress.city ? _this.checkoutAddress.city : _this.checkoutAddress.neighborhood}&state=${_this.checkoutAddress.state}&zipcode=${_this.checkoutAddress.postalCode}`,\n\t\t\t\t{\n method: 'GET',\n redirect: 'follow'\n })\n\t\t\t\t.then(response => response.text())\n\t\t\t\t.then(function(result) {\n\n _this.triggerEvent(\"validated\")\n _this.validatedAddress = JSON.parse(result)[0]\n\n if(\n (typeof _this.validatedAddress == \"undefined\") || (\n _this.validatedAddress.components &&\n _this.validatedAddress.components.default_city_name === _this.checkoutAddress.city &&\n _this.validatedAddress.components.zipcode === _this.checkoutAddress.postalCode &&\n _this.validatedAddress.components.state_abbreviation === _this.checkoutAddress.state &&\n _this.validatedAddress.delivery_line_1 === _this.checkoutAddress.street)\n ) return\n\n\t\t\t\t\tif(_this.validatedAddress.analysis.dpv_match_code) {\n\t\t\t\t\t\t_this.showModal()\n _this.activeAddressValidation();\n _this.triggerEvent(\"showModal\")\n\t\t\t\t\t} else if(_this.validatedAddress.analysis.dpv_footnotes.includes('A1')) {\n\t\t\t\t\t\t_this.showInvalidAddressModal()\n _this.activeAddressValidation();\n _this.triggerEvent(\"showModal\")\n }\n\n\n _this.ifAllUnavailable(_this.orderForm);\n\n })\n\t\t\t\t.catch(function(e) {\n console.error(e);\n })\n }\n\n\n\t\t\t}\n\t\t} catch(e) {\n\t\t\tconsole.error(e)\n _this.desactiveAddressValidation();\n\t\t}\n\t}\n\n activeAddressValidation() {\n $(\"body\").addClass(\"js-addressValidation-active\")\n }\n\n desactiveAddressValidation() {\n $(\"body\").removeClass(\"js-addressValidation-active\")\n }\n\n\tcompareSelectAddresses(oldOrderForm, orderFormUpdated) {\n\t\tconst _this = this\n\n\t\tif(JSON.stringify(orderFormUpdated?.shippingData?.selectedAddresses[0]) !== JSON.stringify(oldOrderForm?.shippingData?.selectedAddresses[0])) {\n\t\t\t_this._addressValidationStatus = false\n\t\t} else {\n\t\t\t_this._addressValidationStatus = true\n\t\t}\n\t}\n\n\tinit() {\n\t\tconst _this = this\n\n $(\"body\").addClass(\"js-addressValidation-on\")\n _this.bind()\n\n\t\t$(window).on('orderFormUpdated.vtex load', function(evt, orderForm) {\n\n if(_this.orderForm && (_this.orderForm !== orderForm) && _this.orderForm.shippingData && _this.orderForm.shippingData.selectedAddresses ) _this.compareSelectAddresses(_this.orderForm, orderForm)\n\n\t\t\t_this.orderForm = orderForm\n\t\t\t_this.lang = vtex ? vtex.i18n.locale : \"en\"\n\n\t\t\tif(window.location.hash===\"#/shipping\" || window.location.hash===\"#/payment\") {\n\t\t\t\t_this.debounce(function() {\n\t\t\t\t\t_this.validate(orderForm)\n\t\t\t\t}, 350)()\n\t\t\t}\n\t\t})\n\n\t}\n}\n\nwindow.addressValidation = new _addressValidation()\n$(window).load(() => {addressValidation.init()})\n\n\n```" } ]
code_us-address-validation_75a2fdcf
[ { "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 us-address-validation/checkout-ui-custom/checkout6-custom.css from the us-address-validation VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.addressValidation__box,\n.addressInvalidation__box {\n clear: both;\n padding: 5px 30px 30px 30px;\n background: #FFF;\n margin-bottom: 30px;\n}\n\n.addressValidation__box--wrap {\n color: #333333;\n}\n\nbutton.addressValidation__box--button,\nbutton.js-addressCheck__box--button {\n background: #1a73e8;\n padding: 10px;\n display: inline-block;\n border: none;\n border-radius: 3px;\n color: #fff;\n}\n.addressValidation__box--button.js-loading,\n.js-addressCheck__box--button.js-loading {\n\topacity: 0.8;\n}\n.addressValidation__box--button.js-loading:after,\n.js-addressCheck__box--button.js-loading:after {\n border: 3px solid #f3f3f3;\n border-top: 3px solid #1a73e8;\n border-radius: 50%;\n width: 10px;\n height: 10px;\n animation: spin 1s linear infinite;\n content: \"\";\n display: inline-block;\n margin-left: 8px;\n vertical-align: middle;\n}\n\nh4.addressValidation__box--title {\n font-size: 16px;\n font-weight: bold;\n color: #000;\n}\n\n.addressValidation__box--addresses {\n width: 100%;\n margin: 10px 0px;\n}\n\n\n\n.addressValidation__box--addressOption {\n display: block;\n transition: all ease 0.3s;\n padding: 10px 10px 10px 35px;\n margin: 15px 0;\n background: #f9f9f9;\n position:relative;\n border:1px solid transparent;\n transition: all ease 0.3s;\n}\n\n.addressValidation__box--addressOption p {\n font-weight: bold;\n}\n\n.addressValidation__box--addressOption > * {display:block;}\n\n.addressValidation__box--addressOption b {font-style: italic;}\n\n\n.addressValidation__box--addressOption:hover{\n border-color:#333;\n}\n\n.addressValidation__box--addressOption input {\n position:absolute;\n top:7px;\n left:10px;\n width:15px;\n height:15px\n}\n\np.addressValidation__box--text {\n margin-bottom: 0;\n border: 1px solid #fadda9;\n display: flex;\n align-items: center;\n\n}\n\np.addressValidation__box--text .icon {\n background:#fadda9;\n padding: 16px;\n margin-right: 15px;\n}\n\np.addressValidation__box--text svg {\n height: 26px;\n}\n\nbutton.addressValidation__box--close {\n position: absolute;\n top: -2px;\n right: -2px;\n background: #1a73e8;\n border: none;\n font-size: 20px;\n color: #fff;\n padding: 10px;\n line-height: 12px;\n box-sizing: border-box;\n margin: 0;\n}\n\n\n.addressValidation__box.addressValidation__box--error .addressValidation__box--text {\n margin-bottom:12px;\n}\n\n.addressValidation__box.addressValidation__box--error h4.addressValidation__box--title:before {\n content:\"x\";\n width:30px;\n height:30px;\n display:inline-block;\n background: #ff4e4e;\n text-align:center;\n line-height:30px;\n color:#FFF;\n margin-right:10px;\n border-radius:100%;\n font-weight: normal;\n}\n\n\nbody.js-addressValidation-active {}\n body.js-addressValidation-active.v-custom-fnsCustomAddressForm div#shipping-data {\n margin-bottom: 0 !important;\n padding-bottom: 0;\n }\n body.js-addressValidation-active .orderform-template-holder #shipping-data .accordion-inner {\n display:none;\n }\n\n@keyframes spin {\n 0% {\n transform: rotate(0deg);\n }\n 100% {\n transform: rotate(360deg);\n }\n}\n\n```" } ]
code_us-address-validation_001c8001
[ { "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 us-address-validation/docs/README.md from the us-address-validation VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n\n<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->\n[![All Contributors](https://img.shields.io/badge/all_contributors-7-orange.svg?style=flat-square)](#contributors-)\n<!-- ALL-CONTRIBUTORS-BADGE:END -->\n\n# US Address Validation\n\nThis apps uses [SmartyStreets](https://www.smartystreets.com/) to validates **only** US addresses. \n\nKeep in mind you have to go to [SmartyStreets](https://www.smartystreets.com/) and generates your `Auth Id` and `Auth Token`.\n\nYou can install the app simply running `vtex intall vtex.us-address-validation-checkout` in your Workspace / Enviroment.\n```" } ]
code_us-address-validation_8ac3d0f9
[ { "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 us-address-validation/node/service.json from the us-address-validation VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"stack\": \"nodejs\",\n \"memory\": 1024,\n \"ttl\": 300,\n \"timeout\": 60,\n \"cpu\": {\n \"type\": \"shared\",\n \"value\": 5,\n \"scalingPercentage\": 20\n },\n \"minReplicas\": 8,\n \"maxReplicas\": 80,\n \"workers\": 1,\n \"routes\": {\n \"smartystreets\": {\n \"path\": \"/smartystreets-validation/\",\n \"public\": true\n }\n }\n}\n\n```" } ]
code_us-address-validation_5bca3b77
[ { "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 us-address-validation/node/typings.d.ts from the us-address-validation VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface ReqContext {\n account: string\n workspace: string\n authToken: string\n region: string\n production: boolean\n userAgent: string\n}\n\ninterface Logger {\n log(content: string, level: LogLevel, details?: any): PromiseLike<void>\n}\n\ninterface OrderFormConfiguration {\n paymentConfiguration?: PaymentConfiguration\n taxConfiguration?: TaxConfiguration\n minimumQuantityAccumulatedForItems?: number\n decimalDigitsPrecision?: number\n minimumValueAccumulated?: number\n apps?: [App]\n allowMultipleDeliveries?: boolean\n allowManualPrice?: boolean\n maxIntOfWhiteLabelSellers?: number\n maskFirstPurchaseData?: boolean\n recaptchaValidation?: boolean\n}\n\ninterface OperationState {\n orderFormId: string\n ctx: ReqContext\n data?: OperationData\n logger: Logger\n}\n\ninterface OperationData {\n orderForm?: any\n userProfileId: string\n cookie: string\n}\n\ntype ProcessPaymentStep = (\n state: OperationState,\n next: () => Promise<void>\n) => Promise<void>\n\ntype LogLevel = 'info' | 'error' | 'warning'\n\ntype Timings = { [middleware: string]: [number, number] }\n\ndeclare module '*.json' {\n const value: any\n export default value\n}\n\ninterface OrganizationInput {\n name: string\n b2bCustomerAdmin: B2BCustomerInput\n defaultCostCenter: DefaultCostCenterInput\n}\n\ninterface B2BCustomerInput {\n firstName: string\n lastName: string\n email: string\n}\n\ninterface DefaultCostCenterInput {\n name: string\n address: AddressInput\n}\n\ninterface CostCenterInput {\n name: string\n addresses: AddressInput[]\n}\n\ninterface AddressInput {\n addressId: string\n addressType: string\n postalCode: string\n country: string\n receiverName: string\n city: string\n state: string\n street: string\n number: string\n complement: string\n neighborhood: string\n geoCoordinates: [number]\n}\n\ninterface OrganizationRequest {\n name: string\n defaultCostCenter: DefaultCostCenterInput\n b2bCustomerAdmin: string\n status: string\n created: string\n}\n\ninterface Organization {\n id: string\n name: string\n costCenters: string[]\n status: string\n created: string\n}\n\ninterface CostCenter {\n id: string\n name: string\n organization: string\n addresses: any[]\n}\n\ninterface UserArgs {\n id?: string\n roleId: string\n userId?: string\n orgId?: string\n costId?: string\n clId?: string\n canImpersonate?: boolean\n name: string\n email: string\n}\n\n```" } ]
code_us-address-validation_6256bd1f
[ { "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 us-address-validation/node/package.json from the us-address-validation VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"vtex.us-address-validation-checkout\",\n \"version\": \"2.0.7\",\n \"dependencies\": {\n \"@vtex/api\": \"6.46.0\",\n \"atob\": \"^2.1.2\",\n \"co-body\": \"^6.0.0\",\n \"graphql\": \"^14.5.0\",\n \"graphql-tools\": \"^4.0.6\",\n \"jsonwebtoken\": \"^8.5.0\",\n \"qs\": \"^6.9.4\",\n \"ramda\": \"^0.25.0\"\n },\n \"devDependencies\": {\n \"@types/atob\": \"^2.1.2\",\n \"@types/bluebird\": \"^3.5.25\",\n \"@types/co-body\": \"0.0.3\",\n \"@types/graphql\": \"^14.5.0\",\n \"@types/jest\": \"^27.0.2\",\n \"@types/jsonwebtoken\": \"^8.5.0\",\n \"@types/node\": \"^12.0.0\",\n \"@types/ramda\": \"types/npm-ramda#dist\",\n \"@vtex/api\": \"6.46.0\",\n \"@vtex/prettier-config\": \"^0.3.1\",\n \"@vtex/tsconfig\": \"^0.6.0\",\n \"tslint\": \"^5.12.0\",\n \"tslint-config-prettier\": \"^1.18.0\",\n \"tslint-config-vtex\": \"^2.1.0\",\n \"typescript\": \"3.9.7\",\n \"vtex.checkout\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.checkout@0.6.0/public/_types/react\",\n \"vtex.graphql-server\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.graphql-server@1.66.12/public/_types/react\",\n \"vtex.order-manager\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.order-manager@0.11.1/public/@types/vtex.order-manager\"\n },\n \"scripts\": {\n \"lint\": \"tsc --noEmit && tslint -c tslint.json './**/*.ts'\"\n }\n}\n\n```" } ]
code_us-address-validation_0371f2fa
[ { "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 us-address-validation/node/index.ts from the us-address-validation VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type {\n ClientsConfig,\n ServiceContext,\n ParamsContext,\n RecorderState,\n} from '@vtex/api'\nimport { LRUCache, Service } from '@vtex/api'\n\nimport { Clients } from './clients'\nimport { resolvers } from './resolvers'\n\nconst TIMEOUT_MS = 3000\n\n// Create a LRU memory cache for the Status client.\n// The @vtex/api HttpClient respects Cache-Control headers and uses the provided cache.\nconst memoryCache = new LRUCache<string, any>({ max: 5000 })\n\nmetrics.trackCache('status', memoryCache)\n\n// This is the configuration for clients available in `ctx.clients`.\nconst clients: ClientsConfig<Clients> = {\n // We pass our custom implementation of the clients bag, containing the Status client.\n implementation: Clients,\n options: {\n // All IO Clients will be initialized with these options, unless otherwise specified.\n default: {\n retries: 2,\n timeout: TIMEOUT_MS,\n },\n // This key will be merged with the default options and add this cache to our Status client.\n status: {\n memoryCache,\n },\n },\n}\n\ndeclare global {\n type Context = ServiceContext<Clients>\n}\n\nexport default new Service<Clients, RecorderState, ParamsContext>({\n clients,\n routes: resolvers.Routes,\n})\n\n```" } ]
code_us-address-validation_69b8fa81
[ { "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 us-address-validation/node/clients/smartystreets.ts from the us-address-validation 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\nexport class SmartyStreets extends JanusClient {\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super(ctx, {\n ...options,\n headers: {\n ...(ctx.adminUserAuthToken\n ? {\n VtexIdclientAutCookie: ctx.adminUserAuthToken,\n }\n : {}),\n },\n })\n }\n}\n\n```" } ]
code_us-address-validation_6d111511
[ { "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 us-address-validation/node/clients/index.ts from the us-address-validation VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { IOClients } from '@vtex/api'\n\nimport { SmartyStreets } from './smartystreets'\n\n// Extend the default IOClients implementation with our own custom clients.\nexport class Clients extends IOClients {\n public get smartystreets() {\n return this.getOrSet('smartystreets', SmartyStreets)\n }\n}\n\n```" } ]
code_us-address-validation_759aab7a
[ { "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 us-address-validation/node/utils/index.ts from the us-address-validation VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/no-non-null-assertion */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport * as crypto from 'crypto'\n\nimport type { AxiosError } from 'axios'\nimport { AuthenticationError, ForbiddenError, UserInputError } from '@vtex/api'\n\nexport const toHash = (obj: any) => {\n return crypto.createHash('md5').update(JSON.stringify(obj)).digest('hex')\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\n if (status === 403) {\n throw new ForbiddenError(e)\n }\n\n if (status === 400) {\n throw new UserInputError(e)\n }\n\n throw e\n}\n\n```" } ]
code_us-address-validation_91cb7ce6
[ { "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 us-address-validation/node/resolvers/index.ts from the us-address-validation VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/naming-convention */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport axios from 'axios'\n\nconst getAppId = (): string => {\n return process.env.VTEX_APP_ID ?? ''\n}\n\nconst getUrlParameter = (path: string, sParam: string) => {\n const results = new RegExp(`[\\?&]${sParam}=([^&#]*)`).exec(path)\n\n if (results == null) {\n return null\n }\n\n return decodeURI(results[1]) || 0\n}\n\nexport const resolvers = {\n Routes: {\n smartystreets: async (ctx: Context) => {\n const {\n clients: { apps },\n vtex: {},\n request: { url },\n } = ctx\n\n ctx.set('Content-Type', 'application/json')\n ctx.set('Cache-Control', 'no-cache, no-store')\n\n const app: string = getAppId()\n const accountSettings = await apps.getAppSettings(app)\n\n if (!accountSettings.authId || !accountSettings.authToken) {\n ctx.response.body = false\n }\n\n const street = getUrlParameter(url, 'street')\n const city = getUrlParameter(url, 'city')\n const state = getUrlParameter(url, 'state')\n const zipcode = getUrlParameter(url, 'zipcode')\n\n const { data: validatedAddress } = await axios.get(\n `https://us-street.api.smartystreets.com/street-address?candidates=2&street=${street}&city=${city}&state=${state}&zipcode=${zipcode}&match=enhanced&auth-id=${accountSettings.authId}&auth-token=${accountSettings.authToken}`\n )\n\n ctx.response.status = 200\n ctx.response.body = validatedAddress\n },\n },\n}\n\n```" } ]
code_ads-txt_00a274a1
[ { "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 ads-txt/docs/README.md from the ads-txt VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# Ads Txt\n\nExposes a `/ads.txt` route that serves custom content from the app's settings.\n\nTo be used for Google Ads verification.\n\n## Installation\n\n1. On your account, run:\n`vtex install vtex.ads-txt@1.x`.\n2. After that, go to `https://{{account}}.myvtex.com/admin/apps` and search for the app \"Ads Txt\".\n3. Click on **\"Settings\"** and set the text content to be returned on the `/ads.txt` route.\n4. **Save it.**\n5. Check if working on `https://{{account}}.myvtex.com/ads.txt`.\n\n\n_Settings page for the app_\n![](https://i.imgur.com/UAoWFjv.png)\n\n```" } ]
code_ads-txt_11804039
[ { "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 ads-txt/node/service.json from the ads-txt 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 \"workers\": 1,\n \"routes\": {\n \"ads\": {\n \"path\": \"/ads.txt\",\n \"public\": true\n }\n }\n}\n\n```" } ]
code_ads-txt_366223b4
[ { "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 ads-txt/node/package.json from the ads-txt VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"devDependencies\": {\n \"@types/node\": \"^12.0.0\",\n \"@vtex/api\": \"6.31.1\",\n \"typescript\": \"3.8.3\"\n },\n \"scripts\": {\n \"lint\": \"tsc --noEmit --pretty && tslint -c tslint.json --fix './**/*.ts'\"\n },\n \"version\": \"1.0.0\"\n}\n\n```" } ]
code_ads-txt_f73c7d04
[ { "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 ads-txt/node/index.ts from the ads-txt VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { Service, ServiceContext } from '@vtex/api'\n\nexport default new Service({\n routes: {\n ads: async (ctx: ServiceContext) => {\n try {\n const appSettings = await ctx.clients.apps.getAppSettings(\n '' + process.env.VTEX_APP_ID\n )\n ctx.response.body = appSettings.textContent\n } catch (e) {\n ctx.status = 404\n }\n },\n },\n})\n\n```" } ]
code_tiktok-tbp-callback_44b6c381
[ { "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 tiktok-tbp-callback/docs/README.md from the tiktok-tbp-callback VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# TikTok Business Plugin - Callback Handler\n\n> ⚠️ This app is no longer maintained by VTEX. This means support and maintenance are no longer provided.\n\nThis is a secondary app that handles callbacks for the TikTok Business Plugin. Its purpose is to provide a generic, account agnostic route that TikTok will call upon completing the onboarding flow. The redirect URL which is specified in the TikTok App is fixed and should not be bound to any specific account - and for that purpose, this App is going to be installed on the `vtex` account.\n\n## Callback Route\n\nThe redirect URL is defined as follows:\n\n```\nhttps://vtex.myvtex.com/v0/tiktok-tbp-callback/redirect\n```\n\nAnd expects the following parameters:\n\n- `state`: A URL-encoded JSON string containing some extra information from the onboarding flow:\n - `account`: The VTEX account which requested integrating to TikTok.\n - `workspace`: The workspace of the VTEX account which requested integrating to TikTok.\n - `tradePolicyId`: The selected trade policy for the integration.\n - `passPhrase`: A random passPhrase to ensure callback security.\n- `authCode`: The auth code used to request the access token from TikTok and finish the integration process.\n\nUpon receiving a request, the callback handler will:\n\n- Parse the `state` and `authCode` parameters.\n- Try to redirect the request to the VTEX account specified in the `state` parameter, using this URL `https://{workspace}--{account}.myvtex.com/v0/tiktok-tbp/connect` (if `workspace` is different from `master`) or this URL `https://{account}.myvtex.com/v0/tiktok-tbp/connect` (if `workspace` is equal to `master`) and resending the parameters `tradePolicyId`, `passPhrase` and `authCode`.\n- That route will be in charge of handling the remaining steps of the integration (validating the `passPhrase`, saving the `tradePolicyId` and the `accessToken` to the app settings, etc).\n\n## Health Route\n\nThe health URL is defined as follows:\n\n```\nhttps://vtex.myvtex.com/v0/tiktok-tbp-callback/health\n```\n\n- This endpoint aims to wake up the app and to avoid timeout error that occurs if an app in IO doesn't receive a call for a long period of time.\n\n```" } ]
code_tiktok-tbp-callback_78216ebb
[ { "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 tiktok-tbp-callback/node/service.json from the tiktok-tbp-callback VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"memory\": 256,\n \"ttl\": 60,\n \"timeout\": 10,\n \"minReplicas\": 2,\n \"maxReplicas\": 4,\n \"workers\": 1,\n \"routes\": {\n \"redirect\": {\n \"path\": \"/v0/tiktok-tbp-callback/redirect\",\n \"public\": true\n },\n \"health\": {\n \"path\": \"/v0/tiktok-tbp-callback/health\",\n \"public\": true\n }\n }\n}\n\n```" } ]
code_tiktok-tbp-callback_0c79d7c3
[ { "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 tiktok-tbp-callback/node/package.json from the tiktok-tbp-callback VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"dependencies\": {\n \"co-body\": \"^6.0.0\",\n \"ramda\": \"^0.25.0\"\n },\n \"devDependencies\": {\n \"@types/co-body\": \"^0.0.3\",\n \"@types/jest\": \"^24.0.18\",\n \"@types/node\": \"^12.0.0\",\n \"@types/ramda\": \"types/npm-ramda#dist\",\n \"@vtex/api\": \"6.45.6\",\n \"@vtex/test-tools\": \"^1.0.0\",\n \"@vtex/tsconfig\": \"^0.5.6\",\n \"typescript\": \"3.9.7\"\n },\n \"scripts\": {\n \"lint\": \"tsc --noEmit --pretty\"\n },\n \"version\": \"0.5.3\"\n}\n\n```" } ]
code_tiktok-tbp-callback_8f302157
[ { "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 tiktok-tbp-callback/node/index.ts from the tiktok-tbp-callback VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { ClientsConfig, ServiceContext, RecorderState } from '@vtex/api'\nimport { Service, method } from '@vtex/api'\n\nimport { Clients } from './clients'\nimport { checkHealth } from './middlewares/checkHealth'\nimport { parseParams } from './middlewares/parseParams'\nimport { redirect } from './middlewares/redirect'\n\nconst TIMEOUT_MS = 10 * 1000\n\n// This is the configuration for clients available in `ctx.clients`.\nconst clients: ClientsConfig<Clients> = {\n // We pass our custom implementation of the clients bag, containing the Status client.\n implementation: Clients,\n options: {\n // All IO Clients will be initialized with these options, unless otherwise specified.\n default: {\n retries: 2,\n timeout: TIMEOUT_MS,\n },\n },\n}\n\ndeclare global {\n // We declare a global Context type just to avoid re-writing ServiceContext<Clients, State> in every handler and resolver\n type Context = ServiceContext<Clients, State>\n\n // The shape of our State object found in `ctx.state`. This is used as state bag to communicate between middlewares.\n interface State extends RecorderState, URLState {\n authCode: string\n }\n}\n\n// Export a service that defines route handlers and client options.\nexport default new Service({\n clients,\n routes: {\n redirect: method({\n GET: [parseParams, redirect],\n }),\n health: method({\n GET: [checkHealth],\n }),\n },\n})\n\n```" } ]
code_tiktok-tbp-callback_f955583e
[ { "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 tiktok-tbp-callback/node/clients/index.ts from the tiktok-tbp-callback VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { IOClients } from '@vtex/api'\n\n// Extend the default IOClients implementation with our own custom clients.\nexport class Clients extends IOClients {}\n\n```" } ]
code_tiktok-tbp-callback_a53a7897
[ { "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 tiktok-tbp-callback/node/typings/urlState.d.ts from the tiktok-tbp-callback VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface URLState {\n account: string\n workspace: string\n tradePolicyId: number\n passPhrase: string\n}\n\n```" } ]
code_tiktok-tbp-callback_e5efca19
[ { "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 tiktok-tbp-callback/node/middlewares/parseParams.ts from the tiktok-tbp-callback VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport async function parseParams(ctx: Context, next: () => Promise<void>) {\n const authCode = ctx.URL.searchParams.get('auth_code') as string\n\n const state = ctx.URL.searchParams.get('state') as string\n const decodeState = decodeURIComponent(state)\n const parsedState: URLState = JSON.parse(decodeState)\n\n ctx.state.account = parsedState.account\n ctx.state.workspace = parsedState.workspace\n ctx.state.tradePolicyId = parsedState.tradePolicyId\n ctx.state.passPhrase = parsedState.passPhrase\n ctx.state.authCode = authCode\n\n await next()\n}\n\n```" } ]
code_tiktok-tbp-callback_20c73d63
[ { "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 tiktok-tbp-callback/node/middlewares/redirect.ts from the tiktok-tbp-callback VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { ServiceContext } from '@vtex/api'\n\nexport async function redirect(ctx: ServiceContext, next: () => Promise<void>) {\n const redirectState = ctx.state as State\n\n const redirectUri = `https://${\n redirectState.workspace && redirectState.workspace !== 'master'\n ? `${redirectState.workspace}--`\n : ''\n }${redirectState.account}.myvtex.com/admin/app/tiktok-loading?authCode=${\n redirectState.authCode\n }&tradePolicyId=${redirectState.tradePolicyId}&passPhrase=${\n redirectState.passPhrase\n }`\n\n ctx.redirect(redirectUri)\n\n await next()\n}\n\n```" } ]
code_tiktok-tbp-callback_a59b1a87
[ { "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 tiktok-tbp-callback/node/middlewares/checkHealth.ts from the tiktok-tbp-callback VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport async function checkHealth(ctx: Context, next: () => Promise<void>) {\n const OK = 200\n\n ctx.status = OK\n\n await next()\n}\n\n```" } ]
code_admin-ab-tester_158717ef
[ { "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 admin-ab-tester/messages/pt.json from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/admin-abtest.navigation.label\": \"AB Tester\",\n \"admin/admin.app.abtest.title\": \"AB Tester\",\n \"admin/admin.app.abtest.form.label.winnerLabel\": \"Vencedor\",\n \"admin/admin.app.abtest.form.label.createTestAB\": \"Criar Novo Teste AB\",\n \"admin/admin.app.abtest.form.label.proportion\": \"Proporção de tráfego ao workspace (1 a 100)\",\n \"admin/admin.app.abtest.form.label.hours\": \"Quantas horas o teste durara\",\n \"admin/admin.app.abtest.form.label.type\": \"Tipo de teste\",\n \"admin/admin.app.abtest.form.label.invalidWorkspaceName\": \"That's not a valid workspace name. Please use only lowercase letters and numbers\",\n \"admin/admin.app.abtest.form.createTest.success\": \"Test A/B criado com sucesso\",\n \"admin/admin.app.abtest.form.finishTest.success\": \"Test A/B concluído com sucesso\",\n \"admin/admin.app.abtest.form.saveButton\": \"Salve\",\n \"admin/admin.app.abtest.table.label.finish\": \"Concluir Test A/B\",\n \"admin/admin.app.abtest.table.label.workspaceName\": \"Nome Workspace\",\n \"admin/admin.app.abtest.table.label.conversionLastHours\": \"Conversão (últimas 24 hs)\",\n \"admin/admin.app.abtest.table.label.sessions\": \"Sessões\",\n \"admin/admin.app.abtest.table.label.sessionsLastHours\": \"Sessões (últimas 24h)\",\n \"admin/admin.app.abtest.table.label.hours\": \"Duração\",\n \"admin/admin.app.abtest.table.label.proportion\": \"Proporção\",\n \"admin/admin.app.abtest.table.label.type\": \"Modelo\",\n \"admin/admin.app.abtest.table.label.conversion\": \"Conversion\",\n \"admin/admin.app.abtest.table.label.abtestbeginning\": \"Data de criação\",\n \"admin/admin.app.abtest.table.label.workspace\": \"Workspace\",\n \"admin/admin.app.abtest.table.label.workspaceb\": \"Workspace B\",\n \"admin/admin.app.abtest.table.label.winner\": \"Vencedor\",\n \"admin/admin.app.abtest.table.label.conversiona\": \"Conversão A\",\n \"admin/admin.app.abtest.table.label.conversionb\": \"Conversão B\",\n \"admin/admin.app.abtest.table.label.conversionlast24hours\": \"Conversão (últimas 24h)\",\n \"admin/admin.app.abtest.table.label.workspaceasessions\": \"Workspace A Sessões\",\n \"admin/admin.app.abtest.table.label.workspacesessions\": \"Sessões do espaço de trabalho\",\n \"admin/admin.app.abtest.table.label.workspacebsessions\": \"Workspace B Sessões\",\n \"admin/admin.app.abtest.table.label.workspacesessionslast24hours\": \"Sessões do espaço de trabalho A (últimas 24h)\",\n \"admin/admin.app.abtest.table.label.finishLabel\": \"Concluir\"\n}\n\n```" } ]
code_admin-ab-tester_512db636
[ { "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 admin-ab-tester/messages/en.json from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/admin-abtest.navigation.label\": \"AB Tester\",\n \"admin/admin.app.abtest.title\": \"AB Tester\",\n \"admin/admin.app.abtest.form.label.winnerLabel\": \"Winner\",\n \"admin/admin.app.abtest.form.label.createTestAB\": \"Create New AB Test\",\n \"admin/admin.app.abtest.form.label.proportion\": \"Traffic Proportion for workspace (1 to 100)\",\n \"admin/admin.app.abtest.form.label.hours\": \"How many hours will last\",\n \"admin/admin.app.abtest.form.label.type\": \"Test Type\",\n \"admin/admin.app.abtest.form.label.invalidWorkspaceName\": \"That's not a valid workspace name. Please use only lowercase letters and numbers\",\n \"admin/admin.app.abtest.form.createTest.success\": \"A/B Test beginning saved successfully\",\n \"admin/admin.app.abtest.form.finishTest.success\": \"A/B Test finished successfully\",\n \"admin/admin.app.abtest.form.saveButton\": \"Save\",\n \"admin/admin.app.abtest.table.label.finish\": \"Finish A/B Test\",\n \"admin/admin.app.abtest.table.label.workspaceName\": \"Workspace Name\",\n \"admin/admin.app.abtest.table.label.conversionLastHours\": \"Conversion (last 24h)\",\n \"admin/admin.app.abtest.table.label.sessions\": \"Sessions\",\n \"admin/admin.app.abtest.table.label.sessionsLastHours\": \"Sessions (last 24h)\",\n \"admin/admin.app.abtest.table.label.hours\": \"Duration\",\n \"admin/admin.app.abtest.table.label.proportion\": \"Proportion\",\n \"admin/admin.app.abtest.table.label.type\": \"Type\",\n \"admin/admin.app.abtest.table.label.conversion\": \"Conversion\",\n \"admin/admin.app.abtest.table.label.abtestbeginning\": \"Creation Date\",\n \"admin/admin.app.abtest.table.label.workspace\": \"Workspace\",\n \"admin/admin.app.abtest.table.label.workspaceb\": \"Workspace B\",\n \"admin/admin.app.abtest.table.label.winner\": \"Winner\",\n \"admin/admin.app.abtest.table.label.conversiona\": \"Conversion A\",\n \"admin/admin.app.abtest.table.label.conversionb\": \"Conversion B\",\n \"admin/admin.app.abtest.table.label.conversionlast24hours\": \"Conversion (last 24h)\",\n \"admin/admin.app.abtest.table.label.workspaceasessions\": \"Workspace A Sessions\",\n \"admin/admin.app.abtest.table.label.workspacesessions\": \"Workspace Sessions\",\n \"admin/admin.app.abtest.table.label.workspacebsessions\": \"Workspace B Sessions\",\n \"admin/admin.app.abtest.table.label.workspacesessionslast24hours\": \"Workspace Sessions (last 24h)\",\n \"admin/admin.app.abtest.table.label.finishLabel\": \"Finish\"\n}\n\n```" } ]
code_admin-ab-tester_0d88bad5
[ { "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 admin-ab-tester/messages/context.json from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/admin-abtest.navigation.label\": \"AB Tester\",\n \"admin/admin.app.abtest.title\": \"AB Tester\",\n \"admin/admin.app.abtest.form.label.winnerLabel\": \"Winner\",\n \"admin/admin.app.abtest.form.label.createTestAB\": \"Create New AB Test\",\n \"admin/admin.app.abtest.form.label.proportion\": \"Traffic Proportion for workspace (1 to 100)\",\n \"admin/admin.app.abtest.form.label.hours\": \"How many hours will last\",\n \"admin/admin.app.abtest.form.label.type\": \"Test Type\",\n \"admin/admin.app.abtest.form.label.invalidWorkspaceName\": \"That's not a valid workspace name. Please use only lowercase letters and numbers\",\n \"admin/admin.app.abtest.form.createTest.success\": \"A/B Test beginning saved successfully\",\n \"admin/admin.app.abtest.form.finishTest.success\": \"A/B Test finished successfully\",\n \"admin/admin.app.abtest.form.saveButton\": \"Save\",\n \"admin/admin.app.abtest.table.label.finish\": \"Finish A/B Test\",\n \"admin/admin.app.abtest.table.label.workspaceName\": \"Workspace Name\",\n \"admin/admin.app.abtest.table.label.conversionLastHours\": \"Conversion (last 24h)\",\n \"admin/admin.app.abtest.table.label.sessions\": \"Sessions\",\n \"admin/admin.app.abtest.table.label.sessionsLastHours\": \"Sessions (last 24h)\",\n \"admin/admin.app.abtest.table.label.hours\": \"Duration\",\n \"admin/admin.app.abtest.table.label.proportion\": \"Proportion\",\n \"admin/admin.app.abtest.table.label.type\": \"Type\",\n \"admin/admin.app.abtest.table.label.conversion\": \"Conversion\",\n \"admin/admin.app.abtest.table.label.abtestbeginning\": \"Creation Date\",\n \"admin/admin.app.abtest.table.label.workspace\": \"Workspace\",\n \"admin/admin.app.abtest.table.label.workspaceb\": \"Workspace B\",\n \"admin/admin.app.abtest.table.label.winner\": \"Winner\",\n \"admin/admin.app.abtest.table.label.conversiona\": \"Conversion A\",\n \"admin/admin.app.abtest.table.label.conversionb\": \"Conversion B\",\n \"admin/admin.app.abtest.table.label.conversionlast24hours\": \"Conversion (last 24h)\",\n \"admin/admin.app.abtest.table.label.workspaceasessions\": \"Workspace A Sessions\",\n \"admin/admin.app.abtest.table.label.workspacesessions\": \"Workspace Sessions\",\n \"admin/admin.app.abtest.table.label.workspacebsessions\": \"Workspace B Sessions\",\n \"admin/admin.app.abtest.table.label.workspacesessionslast24hours\": \"Workspace Sessions (last 24h)\",\n \"admin/admin.app.abtest.table.label.finishLabel\": \"Finish\"\n}\n\n```" } ]
code_admin-ab-tester_bb31b4c5
[ { "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 admin-ab-tester/messages/es.json from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/admin-abtest.navigation.label\": \"AB Tester\",\n \"admin/admin.app.abtest.title\": \"AB Tester\",\n \"admin/admin.app.abtest.form.label.winnerLabel\": \"Ganador\",\n \"admin/admin.app.abtest.form.label.createTestAB\": \"Crear Nuevo Test AB\",\n \"admin/admin.app.abtest.form.label.proportion\": \"Proporción del tráfico al workspace (1 a 100)\",\n \"admin/admin.app.abtest.form.label.hours\": \"Cuántas horas durará\",\n \"admin/admin.app.abtest.form.label.type\": \"Tipo del test\",\n \"admin/admin.app.abtest.form.label.invalidWorkspaceName\": \"No es un nombre de workspace válido. Utilice solo letras y números en minúscula\",\n \"admin/admin.app.abtest.form.createTest.success\": \"Test A/B creado correctamente\",\n \"admin/admin.app.abtest.form.finishTest.success\": \"Test A/B finalizado correctamente\",\n \"admin/admin.app.abtest.form.saveButton\": \"Guardar\",\n \"admin/admin.app.abtest.table.label.finish\": \"Terminar Test A/B\",\n \"admin/admin.app.abtest.table.label.workspaceName\": \"Nombre del Workspace\",\n \"admin/admin.app.abtest.table.label.conversionLastHours\": \"Conversión (últimas 24h)\",\n \"admin/admin.app.abtest.table.label.sessions\": \"Sesiones\",\n \"admin/admin.app.abtest.table.label.sessionsLastHours\": \"Sesiones (últimas 24h)\",\n \"admin/admin.app.abtest.table.label.hours\": \"Duración\",\n \"admin/admin.app.abtest.table.label.proportion\": \"Proporción\",\n \"admin/admin.app.abtest.table.label.type\": \"Tipo\",\n \"admin/admin.app.abtest.table.label.conversion\": \"Conversión\",\n \"admin/admin.app.abtest.table.label.abtestbeginning\": \"Fecha de creación\",\n \"admin/admin.app.abtest.table.label.workspace\": \"Workspace\",\n \"admin/admin.app.abtest.table.label.workspaceb\": \"Workspace B\",\n \"admin/admin.app.abtest.table.label.winner\": \"Ganador\",\n \"admin/admin.app.abtest.table.label.conversiona\": \"Conversión A\",\n \"admin/admin.app.abtest.table.label.conversionb\": \"Conversión B\",\n \"admin/admin.app.abtest.table.label.conversionlast24hours\": \"Conversión (últimas 24h)\",\n \"admin/admin.app.abtest.table.label.workspaceasessions\": \"Workspace A Sesiones\",\n \"admin/admin.app.abtest.table.label.workspacesessions\": \"Sesiones Workspace\",\n \"admin/admin.app.abtest.table.label.workspacebsessions\": \"Workspace B Sesiones\",\n \"admin/admin.app.abtest.table.label.workspacesessionslast24hours\": \"Sesiones Workspace (últimas 24h)\",\n \"admin/admin.app.abtest.table.label.finishLabel\": \"Finalizar\"\n}\n\n```" } ]
code_admin-ab-tester_c47c2f92
[ { "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 admin-ab-tester/admin/navigation.json from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"section\": \"other\",\n \"titleId\": \"admin/admin-abtest.navigation.label\",\n \"path\": \"/admin/ab-test\"\n}\n\n```" } ]
code_admin-ab-tester_b01974ba
[ { "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 admin-ab-tester/admin/routes.json from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin.app\": {\n \"component\": \"ABTest\",\n \"path\": \"/admin/app/ab-test\"\n }\n}\n\n```" } ]
code_admin-ab-tester_d97565de
[ { "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 admin-ab-tester/docs/README.md from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n> 📢 Use this project, [contribute](https://github.com/vtex-apps/admin-ab-tester) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).\n\n# AB Tester\n\n<!-- DOCS-IGNORE:start -->\n<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->\n[![All Contributors](https://img.shields.io/badge/all_contributors-0-orange.svg?style=flat-square)](#contributors-)\n<!-- ALL-CONTRIBUTORS-BADGE:END -->\n<!-- DOCS-IGNORE:end -->\n\n## ⚠️ Maintenance ⚠️\n*Starting June 1st 2023, this application will no longer be maintained by VTEX.*\n\n---\n\nThe A/B Tester app allows you to list, start and finish A/B tests via the VTEX Admin.\n\n![A/B Tester Settings](https://user-images.githubusercontent.com/36748003/138300964-63bc3545-efd7-435c-acd6-3e3e3a35b285.png)\n\nIn the following, you'll learn how to install and use the A/B Tester app.\n\n---- \n\n## Configuration \n\nTake the following steps to install the AB Tester app on your VTEX Admin. \n\n1. Open the terminal and use the [VTEX IO CLI](https://developers.vtex.com/vtex-developer-docs/docs/vtex-io-documentation-vtex-io-cli-installation-and-command-reference) to log in to the desired VTEX account.\n2. Install the A/B Tester app in the `master` workspace to enable A/B testing on your store website by running:\n ```\n vtex use master\n vtex install vtex.ab-tester\n ```\n3. Install the **A/B Tester Admin app** in the `master` workspace: \n ```\n vtex install vtexarg.abtester\n ```\n\n## Usage\n\nAfter installing the AB Tester app, you'll be able to:\n- Create A/B tests.\n- Compare A/B test results.\n- Finish an A/B test.\n\n### Creating an A/B test\n\nIn the following step by step, you will learn how to set up a new A/B test. Notice that, before proceeding any further, you must already have a [production workspace](https://developers.vtex.com/vtex-developer-docs/docs/vtex-io-documentation-creating-a-production-workspace) containing the changes you want to evaluate.\n\n1. Access the VTEX Admin.\n2. Go to **Others > AB Tester**.\n3. Click on **Create new AB test**.\n4. Fill out the presented fields as in the following:\n - **Workspace Name -** Enter the name of the production workspace containing the changes you want to examine via the A/B test.\n - **Traffic Proportion -** Enter the desired traffic proportion to be destined for the **master** workspace during the first hours of the A/B test. This value must be any whole number between 0 and 10000. For example, to set 90% of the traffic to the master workspace, enter 9000.\n - **Amount of Time -** Enter the amount of time (in hours) during which the specified **Traffic Proportion** will be maintained. After this period, the traffic proportions of the test will be automatically updated by the A/B testing system. Enter `0` if you prefer the A/B testing system to take care of your website traffic distribution from the start.\n >ℹ️ The A/B testing automatically balances traffic every 3 minutes according to the conversion or revenue rates.\n - **Test Type -** Enter what the A/B test must evaluate: revenue or conversion.\n5. Click on **Save**.\n\nOnce you save your changes, the A/B test will start immediately, splitting your website traffic according to your preferences.\n\n### Comparing results\n\nAfter creating your A/B test, the **AB Tester** app will provide a table containing some metrics that will help you evaluate and interpret the test status. This table contains the following information:\n\n* **Conversion** - Conversion rate percentage that each workspace presented during the test.\n* **Conversion (last 24hrs)** - Conversion rate percentage that each workspace presented during the test's last 24 hours.\n* **N. of Sessions** - Total number of sessions of each workspace since the beginning of the test.\n* **N. of Sessions (last 24hrs)** - Number of sessions for each workspace during the test's last 24 hours.\n\n### Finishing an A/B Test\n\nAlthough automatic, an A/B test will not end by itself. Take the following steps to terminate an A/B test:\n\n1. Access the VTEX Admin.\n2. Go to **Others > AB Tester** and scroll the horizontal bar until you see a Kebab menu.\n3. Click on the Kebab menu and click on **Finish A/B Test**.\n\n---- \n\n## Related Resources\n\n- [Running native A/B tests](https://developers.vtex.com/vtex-developer-docs/docs/vtex-io-documentation-running-native-ab-testing)\n\n\n----\n\n## Contributors ✨\n\nThanks goes to these wonderful people:\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n\n<table>\n <tr>\n <td align=\"center\"><a href=\"https://github.com/tomymehdi\"><img src=\"https://avatars.githubusercontent.com/u/774112?v=4\" width=\"100px;\" alt=\"\"/><br /><sub><b>Tomás Alfredo Mehdi</b></sub></a><br /><a href=\"https://github.com/vtex-apps/admin-ab-tester/commits?author=tomymehdi\" title=\"Code\">💻</a></td>\n </tr>\n</table>\n\n<!-- markdownlint-enable -->\n<!-- prettier-ignore-end -->\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_admin-ab-tester_991cce6e
[ { "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 admin-ab-tester/graphql/schema.graphql from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype Query {\n getTests: GetTestsResponse\n getData(key: String!): String\n @cacheControl(scope: PUBLIC, maxAge: MEDIUM)\n}\n\ntype Mutation {\n initialize(workspace: String!, proportion: Int!, hours: Int!, type: String): CreateTestResponse\n finishTest(workspace: String!): FinishTestResponse\n saveData(key: String!, value: String!): String\n}\n\n```" } ]
code_admin-ab-tester_cdcbf5f0
[ { "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 admin-ab-tester/node/service.json from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"memory\": 256,\n \"ttl\": 10,\n \"timeout\": 5,\n \"minReplicas\": 2,\n \"maxReplicas\": 4,\n \"workers\": 1\n}\n\n```" } ]
code_admin-ab-tester_ab521e2f
[ { "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 admin-ab-tester/node/utils.ts from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { AuthenticationError, ForbiddenError, UserInputError } from '@vtex/api'\nimport { AxiosError } from 'axios'\n\nexport const BUCKET_NAME = 'product-translation'\nexport const ALL_TRANSLATIONS_FILES = 'all-translations'\n\nexport const statusToError = (e: AxiosError) => {\n if (!e.response) {\n throw e\n }\n\n const {\n response: { status },\n } = e\n\n switch (status) {\n case 401: {\n throw new AuthenticationError(e)\n }\n\n case 403: {\n throw new ForbiddenError(e)\n }\n\n case 400: {\n throw new UserInputError(e)\n }\n\n default:\n throw new TypeError(e.message)\n }\n}\n\n\n\n\n```" } ]
code_admin-ab-tester_d97a679e
[ { "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 admin-ab-tester/node/package.json from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"dependencies\": {\n \"co-body\": \"^6.0.0\",\n \"moment\": \"^2.29.4\"\n },\n \"devDependencies\": {\n \"@types/co-body\": \"^0.0.3\",\n \"@types/node\": \"12.x\",\n \"@vtex/api\": \"6.45.15\",\n \"eslint\": \"^7.16.0\",\n \"eslint-config-vtex\": \"^12.9.3\",\n \"prettier\": \"^1.18.2\",\n \"typescript\": \"3.9.7\"\n },\n \"resolutions\": {\n \"**/**/lodash\": \"^4.17.19\"\n },\n \"scripts\": {\n \"lint\": \"tsc --noEmit --pretty\"\n },\n \"version\": \"1.0.14\"\n}\n\n```" } ]
code_admin-ab-tester_bf1919c5
[ { "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 admin-ab-tester/node/index.ts from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { LRUCache, Service, ParamsContext } from '@vtex/api'\n\nimport { Clients } from './clients'\nimport { resolvers } from './resolvers'\n\nconst memoryCache = new LRUCache<string, any>({ max: 5000 })\n\nmetrics.trackCache('status', memoryCache)\n\nexport default new Service<Clients, State, ParamsContext>({\n clients: {\n implementation: Clients,\n options: {\n default: {\n retries: 2,\n timeout: 10000,\n },\n },\n },\n graphql: {\n resolvers,\n },\n})\n\n```" } ]
code_admin-ab-tester_0b710608
[ { "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 admin-ab-tester/react/ABTest.tsx from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { FC } from 'react'\nimport Main from './components/Main'\nimport './styles.global.css'\nimport { ABTestProvider } from './context/index'\n\nconst ABTest: FC = () => {\n return (\n <ABTestProvider>\n <Main />\n </ABTestProvider>\n )\n}\n\nexport default ABTest\n\n```" } ]
code_admin-ab-tester_fb57ce9f
[ { "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 admin-ab-tester/react/package.json from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"vtex.admin-example\",\n \"version\": \"1.0.14\",\n \"scripts\": {\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^11.12.1\",\n \"@types/react\": \"^16.8.10\",\n \"@types/react-intl\": \"^2.3.17\",\n \"apollo-client\": \"^2.4.7\",\n \"graphql\": \"^14.0.2\",\n \"prop-types\": \"^15.7.2\",\n \"react\": \"^16.8.6\",\n \"react-dom\": \"^16.8.6\",\n \"react-intl\": \"^2.7.2\",\n \"typescript\": \"3.9.7\"\n }\n}\n\n```" } ]
code_admin-ab-tester_1d45b71a
[ { "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 admin-ab-tester/react/styles.global.css from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\nhtml,\nbody,\n#render-container,\n#render-provider,\n.render-container,\n.render-provider {\n height: 100%;\n}\n\n```" } ]
code_admin-ab-tester_24b1ad08
[ { "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 admin-ab-tester/react/utils.tsx from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport {\n Button,\n} from 'vtex.styleguide'\nimport { FormattedMessage } from 'react-intl'\n\nimport { useABTestContext } from './context/'\n\nexport const checkWorkspaceName = (name: string) => {\n if (name === \"\") return false\n const noSpecialChars = new RegExp(\n '^.*[-!$%^&*()_+|~=`{}[\\\\]:\";\\'<>?,./]+.*$'\n );\n const noMayusc = new RegExp('[A-Z]');\n if (!noSpecialChars.test(name) && !noMayusc.test(name)) {\n return true;\n } else {\n return false;\n }\n};\n\nexport const formatData = (data: any) => {\n const flattenData: any = [];\n\n const keys = Object.keys(data[0]);\n\n keys.forEach((key) => {\n const aux: any = {};\n const masterKeys = ['ConversionA', 'ConversionALast24Hours', 'WorkspaceASessions', 'WorkspaceASessionsLast24Hours']\n data.forEach((item: any) => {\n if (key !== '__typename' && key !== 'Finish' && key !== '[[Prototype]]' && key !== 'WorkspaceA' && key !== 'WorkspaceB') {\n if (masterKeys.includes(key)) {\n aux[item.WorkspaceA] = item[key]\n aux[item.WorkspaceB] = null\n } else {\n aux[item.WorkspaceA] = null\n aux[item.WorkspaceB] = item[key]\n }\n }\n if (key === 'Finish') (aux[item.WorkspaceB] = { type: 'finish', value: item[key] })\n if (key === 'proportion') (aux[item.WorkspaceB] = { type: 'proportion', value: item[key] })\n if (key !== '__typename' && key !== \"WorkspaceB\" && key !== \"WorkspaceA\") aux.Value = { type: 'key', value: key }\n });\n flattenData.push(aux);\n });\n\n const toUnify = [\n 'ConversionA',\n 'ConversionB',\n 'ConversionALast24Hours',\n 'ConversionBLast24Hours',\n 'WorkspaceASessions',\n 'WorkspaceBSessions',\n 'WorkspaceASessionsLast24Hours',\n 'WorkspaceBSessionsLast24Hours'\n ]\n\n const formattedData: any = flattenData.filter((item: any) => {\n return !toUnify.includes(item?.Value?.value) && Object.keys(item).length !== 0\n });\n\n const newData = formattedData.slice(0, -1)\n\n for (let i = 0; i < toUnify.length; i = i + 2) {\n merge(flattenData.find((item: any) => item.Value?.value === toUnify[i]), flattenData.find((item: any) => item.Value?.value === toUnify[i + 1]))\n }\n\n function merge(obj1: any, obj2: any) {\n const answer: any = {}\n for (let key in obj1) {\n if (answer[key] === undefined || answer[key] === null)\n answer[key] = obj1[key];\n }\n for (let key in obj2) {\n if (answer[key] === undefined || answer[key] === null)\n answer[key] = obj2[key];\n }\n if (obj1?.Value) {\n switch (obj1.Value?.value) {\n case 'ConversionA' || 'ConversionB': {\n answer.Value.value = 'Conversion'\n newData.push(answer)\n break\n }\n case 'ConversionALast24Hours' || 'ConversionBLast24Hours': {\n answer.Value.value = 'ConversionLast24Hours'\n newData.push(answer)\n break\n }\n case 'WorkspaceASessions' || 'WorkspaceBSessions': {\n answer.Value.value = 'WorkspaceSessions'\n newData.push(answer)\n break\n }\n case 'WorkspaceASessionsLast24Hours' || 'WorkspaceBSessionsLast24Hours': {\n answer.Value.value = 'workspacesessionslast24hours'\n newData.push(answer)\n break\n }\n }\n }\n return answer\n }\n newData.push(formattedData[formattedData.length - 1])\n\n return newData\n}\n\n\n\nexport const getPropertiesForSchema = (tests: any) => {\n const { finishTest } = useABTestContext()\n\n const properties: any = {};\n properties.Value = {\n name: {\n title: '',\n width: 600\n },\n }\n tests.length && Object.keys(tests[0]).forEach((item) => {\n properties[item] = {\n title: item, width: item !== \"Value\" ? 250 : 300, cellRenderer: ({ cellData }: { cellData: any }) => {\n return (\n <>\n {\n cellData?.type === 'finish' ? <Button onClick={() => finishTest(cellData.value)}><FormattedMessage id={`admin/admin.app.abtest.table.label.finishLabel`} /> </Button> : cellData?.type === 'key' ? <span className=\"b c-muted-2\"><FormattedMessage id={`admin/admin.app.abtest.table.label.${cellData.value.toLowerCase()}`} /></span> : cellData?.type === 'proportion' ? <p>%{cellData.value}</p> : cellData\n }\n </>\n )\n },\n }\n }\n\n );\n\n return properties\n}\n\n```" } ]
code_admin-ab-tester_6e257570
[ { "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 admin-ab-tester/public/metadata/messages/es-AR.json from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"AB Tester\",\n \"headline\": \"Crea, lista y finaliza los AB test.\",\n \"overview\": \"AB Tester te permite ejecutar diferentes versiones de tu tienda para probar ideas y mejorar la experiencia de usuario.\",\n \"features\": [\n \"Listar AB test\",\n \"Finalizar AB test\",\n \"Crear AB tests\"\n ],\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```" } ]
code_admin-ab-tester_a2e5ee8a
[ { "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 admin-ab-tester/public/metadata/messages/pt-BR.json from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"AB Tester\",\n \"headline\": \"Crie, liste e finalize testes AB.\",\n \"overview\": \"O AB Tester permite que você execute diferentes versões de sua loja para testar ideias e melhorar a experiência do usuário.\",\n \"features\": [\n \"Obter teste AB atual\",\n \"Terminar um teste AB\",\n \"Criar um teste AB\"\n ],\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```" } ]
code_admin-ab-tester_78e8827d
[ { "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 admin-ab-tester/public/metadata/messages/en-US.json from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"AB Tester\",\n \"headline\": \"Create, list and finish AB tests.\",\n \"overview\": \"AB Tester allows you to run different versions of your store to test ideas and improve the user experience.\",\n \"features\": [\n \"Get current AB Test\",\n \"Finish an AB Test\",\n \"Create a AB Test\"\n ],\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```" } ]
code_admin-ab-tester_2b62df37
[ { "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 admin-ab-tester/graphql/types/createTest.graphql from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype CreateTestResponse{\n status: String,\n data: String\n}\n\n```" } ]
code_admin-ab-tester_8aa3d92e
[ { "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 admin-ab-tester/graphql/types/finishTest.graphql from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype FinishTestResponse{\n status: String,\n data: String\n}\n\n```" } ]
code_admin-ab-tester_b66ae252
[ { "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 admin-ab-tester/graphql/types/getTests.graphql from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype GetTestsResponse{\n data: [DataResponse]\n status: Int\n error: String\n}\n\ntype DataResponse {\n ABTestBeginning: String\n WorkspaceA: String\n WorkspaceB: String\n Winner: String\n ConversionA: Float\n ConversionALast24Hours: Float\n ConversionB: Float\n ConversionBLast24Hours: Float\n WorkspaceASessions: Int\n WorkspaceBSessions: Int\n WorkspaceASessionsLast24Hours: Int\n WorkspaceBSessionsLast24Hours: Int\n hours: Int\n proportion: Int\n type: String\n Finish: String\n}\n\n```" } ]
code_admin-ab-tester_bab577ba
[ { "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 admin-ab-tester/node/clients/abtest.ts from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { InstanceOptions, IOContext } from '@vtex/api'\nimport { ExternalClient } from '@vtex/api'\nexport default class ABtest extends ExternalClient {\n constructor(context: IOContext, options?: InstanceOptions) {\n super(`http://app.io.vtex.com/vtex.ab-tester/v0`, context, {\n ...options,\n })\n }\n\n public async getTests() {\n try {\n const res = await this.http.getRaw(`/${this.context.account}/master/_v/private/abtesting/status`, {\n headers: {\n Authorization: `Bearer ${this.context.adminUserAuthToken}`,\n },\n })\n return res\n } catch (err) {\n return { data: err }\n }\n\n }\n\n public async initialize(workspace: string, proportion: number, hours: number, type: string) {\n const payload = {\n \"InitializingWorkspaces\": workspace,\n \"Proportion\": proportion,\n \"Hours\": hours,\n \"Type\": type\n }\n return await this.http.postRaw(`/${this.context.account}/master/_v/private/abtesting/initialize`, payload, {\n headers: {\n Authorization: `Bearer ${this.context.adminUserAuthToken}`,\n },\n })\n }\n\n public async finishTest(workspace: string) {\n return await this.http.delete(`/${this.context.account}/master/_v/private/abtesting/finish/${workspace}`, {\n headers: {\n Authorization: `Bearer ${this.context.adminUserAuthToken}`,\n },\n })\n }\n}\n\n```" } ]
code_admin-ab-tester_e1a5391e
[ { "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 admin-ab-tester/node/clients/index.ts from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { IOClients } from '@vtex/api'\n\nimport ABtest from './abtest'\n\nexport class Clients extends IOClients {\n public get abtest() {\n return this.getOrSet('abtest', ABtest)\n }\n}\n\n```" } ]
code_admin-ab-tester_59099bee
[ { "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 admin-ab-tester/node/typings/global.d.ts from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { RecorderState, ServiceContext } from '@vtex/api'\n\ndeclare global {\n type Context = ServiceContext<IOClients, State>\n\n interface State extends RecorderState {\n code: number\n }\n\n interface WorkspaceMetadata {\n name: string;\n weight: number;\n production: boolean;\n }\n\n interface ABTest {\n ABTestBeginning: string\n Winner: string\n WorkspaceB: string\n ConversionA: number\n ConversionALast24Hours: number\n ConversionB: number\n ConversionBLast24Hours: number\n WorkspaceBSessions: number\n WorkspaceBSessionsLast24Hours: number\n hours: number\n proportion: number\n type: string\n Finish: string\n }\n}\n\n\n\n```" } ]
code_admin-ab-tester_a4769e67
[ { "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 admin-ab-tester/node/resolvers/index.ts from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n queries as abtestQueries,\n mutations as abtestMutations\n} from './abtest'\nimport { queries as vbaseQueries, mutations as vbaseMutations } from './vbase'\n\nexport const resolvers = {\n Query: {\n ...abtestQueries,\n ...vbaseQueries,\n },\n Mutation: {\n ...abtestMutations,\n ...vbaseMutations,\n },\n}\n\n```" } ]
code_admin-ab-tester_94b7c8bb
[ { "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 admin-ab-tester/node/resolvers/abtest/index.ts from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport moment from 'moment'\n\nexport const queries = {\n getTests: async (_: unknown, __: unknown, { vtex: { logger }, clients: { abtest, vbase } }: Context\n ): Promise<any> => {\n const { data }: any = await abtest.getTests()\n logger.info({\n message: 'admin-ab-tester',\n action: 'list',\n data: data,\n })\n if (data.length) {\n for await (let element of data) {\n try {\n const extraData = await vbase.getJSON<string>('abtesterData', element.WorkspaceB)\n const parsedExtraData = JSON.parse(extraData.replace(/'/g, '\"'));\n Object.entries(parsedExtraData).forEach(\n ([key, value]) => element[key] = value\n );\n } catch (err) {\n continue\n }\n }\n data.forEach((item: ABTest) => {\n item.ABTestBeginning = moment(item.ABTestBeginning).format(\"DD/MM/YYYY\")\n item.Finish = item.WorkspaceB\n });\n return { status: 201, data: data, error: \"\" }\n } else {\n return { status: 404, data: [\"\"], error: data?.response?.data?.message }\n }\n\n }\n}\n\nexport const mutations = {\n initialize: async (\n _: unknown,\n { workspace, proportion, hours, type }: {\n workspace: string, proportion: number, hours: number, type: string\n },\n ctx: Context\n ): Promise<string> => {\n ctx.vtex.logger.info({\n message: 'admin-ab-tester',\n action: 'initialize'\n })\n return await ctx.clients.abtest.initialize(workspace, proportion, hours, type)\n },\n finishTest: async (\n _: unknown,\n { workspace }: { workspace: string },\n ctx: Context\n ): Promise<string> => {\n ctx.vtex.logger.info({\n message: 'admin-ab-tester',\n action: 'finish'\n })\n return await ctx.clients.abtest.finishTest(workspace)\n },\n}\n\n```" } ]
code_admin-ab-tester_a737e0c9
[ { "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 admin-ab-tester/node/resolvers/vbase/index.ts from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const queries = {\n getData: async (\n _: unknown,\n { key }: { key: string },\n ctx: Context\n ): Promise<any> => {\n const aux = await ctx.clients.vbase.getJSON<{ key: string }>(\n 'abtesterData',\n key\n )\n\n return aux\n },\n}\n\nexport const mutations = {\n saveData: async (\n _: unknown,\n {\n key,\n value,\n }: {\n key: string\n value: string\n },\n ctx: Context\n ): Promise<void> => {\n await ctx.clients.vbase.saveJSON('abtesterData', key, value)\n },\n}\n\n```" } ]
code_admin-ab-tester_14974831
[ { "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 admin-ab-tester/react/context/index.tsx from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { useState, createContext, useEffect, useContext } from 'react'\nimport { useMutation, useLazyQuery } from 'react-apollo'\nimport { useIntl } from 'react-intl'\n\nimport getTestsGQL from './../graphql/getTests.gql'\nimport createTestMutation from './../graphql/createTest.gql'\nimport finishTestMutation from './../graphql/finishTest.gql'\nimport saveDataGQL from './../graphql/saveData.gql'\nimport { formatData } from \"./../utils\"\n\nexport const ABTestContext = createContext({} as ABTestContextInterface)\n\nexport const useABTestContext = () => useContext(ABTestContext)\n\nexport function ABTestProvider({ children }: ContextChildren) {\n const intl = useIntl()\n const [saveData] = useMutation(saveDataGQL)\n const [getTestsQuery, { data: dataGetTests, loading: loadingGetTests, refetch: refetchGetTests }] = useLazyQuery(getTestsGQL)\n\n const [tests, setTests] = useState<ABTest[]>([])\n const [loading, setLoading] = useState(false)\n const [error, setError] = useState(\"\")\n const [success, setSuccess] = useState(\"\")\n const [emptyMessage, setEmptyMessage] = useState(\"\")\n\n const [testToCreate, setTestToCreate] = useState<NewTest>({\n name: \"\",\n proportion: 0,\n hours: 0,\n type: \"\"\n })\n\n const [createTest,\n {\n loading: loadingCreate,\n error: errorCreate,\n data: dataCreate,\n }] = useMutation(createTestMutation)\n\n const [finishTestGQL,\n {\n loading: loadingFinish,\n error: errorFinish,\n data: dataFinish,\n }] = useMutation(finishTestMutation)\n\n\n const [modalOpen, setModalOpen] = useState({\n isOpen: false,\n type: \"CREATE\"\n })\n\n const handleNewModal = (isOpen: boolean, type: string) => {\n setModalOpen({\n isOpen: isOpen,\n type: type\n })\n }\n\n const clearGeneralState = () => {\n setError(\"\")\n setSuccess(\"\")\n setLoading(false)\n }\n\n\n useEffect(() => {\n getTestsQuery()\n }, [])\n\n useEffect(() => {\n loadingGetTests && setLoading(true)\n if (dataGetTests) {\n if (dataGetTests.getTests?.status === 201) {\n setTests(formatData(dataGetTests.getTests?.data))\n setLoading(false)\n } else {\n setLoading(false)\n setTests([])\n setEmptyMessage(dataGetTests.getTests?.error)\n }\n }\n }, [dataGetTests])\n\n\n const createNewTest = (newTest: NewTest) => {\n newTest.proportion = (10000 - newTest.proportion) / 100\n createTest({ variables: { workspace: newTest.name, proportion: Number(newTest.proportion), hours: Number(newTest.hours), type: newTest.type } })\n setTestToCreate(newTest)\n }\n\n const finishTest = (workspace: string) => {\n finishTestGQL({ variables: { workspace: workspace } })\n }\n\n useEffect(() => {\n loadingCreate && setLoading(true)\n if (errorCreate) {\n setError(errorCreate.graphQLErrors[0].extensions?.exception?.response?.data)\n }\n if (dataCreate) {\n setLoading(false);\n refetchGetTests()\n setSuccess(intl.formatMessage({ id: 'admin/admin.app.abtest.form.createTest.success' }))\n handleNewModal(false, \"CREATE\")\n //if the test is successfully created we save the data in vbase to show it in the table\n saveData({ variables: { key: testToCreate.name, value: `\"{'proportion':${testToCreate.proportion},'hours':${testToCreate.hours},'type': '${testToCreate.type}'}\"` } })\n }\n }, [loadingCreate, errorCreate, dataCreate])\n\n useEffect(() => {\n loadingFinish && setLoading(true)\n if (errorFinish) {\n setError(errorFinish.graphQLErrors[0].extensions?.exception?.response?.data)\n }\n if (dataFinish) {\n setLoading(false);\n refetchGetTests()\n setSuccess(intl.formatMessage({ id: 'admin/admin.app.abtest.form.finishTest.success' }))\n }\n }, [loadingFinish, errorFinish, dataFinish])\n\n return (\n <ABTestContext.Provider\n value={{\n tests,\n handleNewModal,\n modalOpen,\n createNewTest,\n finishTest,\n error,\n loading,\n success,\n setError,\n clearGeneralState,\n emptyMessage\n }}\n >\n {children}\n </ABTestContext.Provider>\n )\n}\n\n```" } ]
code_admin-ab-tester_a453690f
[ { "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 admin-ab-tester/react/typings/storefront.d.ts from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ReactNode } from 'react'\n\ndeclare global {\n interface ContextChildren {\n children: ReactNode\n }\n interface ABTest {\n [x: string]: any;\n ABTestBeginning: string\n Winner: string\n WorkspaceA: string\n WorkspaceB: string\n ConversionA: number\n ConversionALast24Hours: number\n ConversionB: number\n ConversionBLast24Hours: number\n WorkspaceASessions: number\n WorkspaceBSessions: number\n WorkspaceASessionsLast24Hours: number\n WorkspaceBSessionsLast24Hours: number\n }\n interface ABTestContextInterface {\n tests: ABTest[] | undefined\n handleNewModal: (isOpen: boolean, type: \"CREATE\" | \"DELETE\") => void\n modalOpen: Modal\n createNewTest: (test: NewTest) => void\n finishTest: (workspace: string) => void\n loading: boolean\n error: string\n success: string\n setError: (error: string) => void\n clearGeneralState: () => void\n emptyMessage: string\n }\n interface GeneralState {\n loading: boolean,\n error: string,\n success: string\n }\n interface Modal {\n isOpen: boolean,\n type: string\n }\n interface EventInterface {\n target: {\n value: string\n name: string\n }\n }\n interface NewTest {\n name: string\n proportion: number\n hours: number\n type: string\n }\n interface RowHeader {\n rowData: ABTest\n }\n}\n\n```" } ]
code_admin-ab-tester_647cbd05
[ { "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 admin-ab-tester/react/components/Main.tsx from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { FC, useEffect } from 'react'\nimport { FormattedMessage } from 'react-intl'\nimport { Layout, PageBlock, PageHeader } from 'vtex.styleguide'\nimport ABTable from './Table/Table'\nimport { useABTestContext } from '../context';\n\nconst Main: FC = () => {\n return (\n <Layout\n pageHeader={\n <PageHeader\n title={<FormattedMessage id=\"admin/admin.app.abtest.title\" />}\n />\n }\n >\n <PageBlock variation=\"full\">\n <ABTable />\n </PageBlock>\n </Layout>\n )\n}\n\nexport default Main\n\n```" } ]
code_admin-ab-tester_24450062
[ { "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 admin-ab-tester/react/graphql/getTests.gql from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nquery getTests{\n getTests{\n data {\n ABTestBeginning\n WorkspaceA\n WorkspaceB\n Winner\n ConversionA\n ConversionALast24Hours\n ConversionB\n ConversionBLast24Hours\n WorkspaceASessions\n WorkspaceBSessions\n WorkspaceASessionsLast24Hours\n WorkspaceBSessionsLast24Hours\n hours\n proportion\n type\n Finish\n }\n status\n error\n }\n}\n\n```" } ]
code_admin-ab-tester_6ffa667b
[ { "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 admin-ab-tester/react/graphql/createTest.gql from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nmutation createTest($workspace: String!, $proportion: Int!, $hours: Int!, $type: String){\n initialize(workspace:$workspace, proportion:$proportion, hours: $hours, type: $type){\n status, data\n }\n}\n\n```" } ]
code_admin-ab-tester_4cbdd6e0
[ { "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 admin-ab-tester/react/graphql/saveData.gql from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nmutation saveData($key: String!, $value: String!){\n saveData(key: $key, value: $value)\n}\n```" } ]
code_admin-ab-tester_c9fee1b2
[ { "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 admin-ab-tester/react/graphql/finishTest.gql from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nmutation finishTest($workspace: String!){\n finishTest(workspace:$workspace){\n status, data\n }\n}\n\n```" } ]
code_admin-ab-tester_c5af4092
[ { "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 admin-ab-tester/react/graphql/getData.gql from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nquery getData($key: String!){\n getData(key: $key)\n}\n```" } ]
code_admin-ab-tester_c63d82c8
[ { "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 admin-ab-tester/react/components/Table/Table.tsx from the admin-ab-tester VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { useState } from 'react'\nimport { FormattedMessage, useIntl } from 'react-intl'\nimport {\n Table,\n Alert,\n Modal,\n Input,\n Dropdown,\n Button,\n} from 'vtex.styleguide'\n\nimport { useABTestContext } from '../../context'\n\nimport { checkWorkspaceName, getPropertiesForSchema } from \"./../../utils\"\n\nconst ABTestTable = () => {\n const { tests, handleNewModal, modalOpen, createNewTest, error, setError, success, clearGeneralState, loading, emptyMessage } = useABTestContext()\n\n const [newTest, setNewTest] = useState<NewTest>({\n name: \"\",\n proportion: 0,\n hours: 0,\n type: \"\"\n })\n\n const isValid = () => {\n if (checkWorkspaceName(newTest.name) && newTest.proportion && newTest.hours && newTest.type) {\n return true\n }\n }\n\n const intl = useIntl()\n\n const defaultSchema = {\n properties: getPropertiesForSchema(tests)\n }\n\n\n const selectOptions = [\n { value: 'revenue', label: 'Revenue' },\n { value: 'conversion', label: 'Conversion' },\n ]\n\n function handleInput(key: string, value: string) {\n if (key === \"name\") {\n !checkWorkspaceName(value) ? setError(intl.formatMessage({ id: 'admin/admin.app.abtest.form.label.invalidWorkspaceName' })) : setError(\"\")\n }\n setNewTest((prevState: any) => ({ ...prevState, [key]: value }))\n }\n\n var proportionTableIndex = 3;\n\n\n if(tests && tests.length > 0) {\n var firstWorkspaceProportion;\n var amountOfABTests = Object.entries(tests[proportionTableIndex]).length - 2\n var [keys] = Object.entries(tests[proportionTableIndex])\n\n for (const [key, value] of Object.entries(tests[proportionTableIndex])) {\n if(key == 'master' || key == 'Value'){} else {\n if (!firstWorkspaceProportion) {\n firstWorkspaceProportion = tests[proportionTableIndex][key].value\n }\n tests[proportionTableIndex][key] = { type: 'proportion', value: (firstWorkspaceProportion / amountOfABTests).toFixed(2) }\n }\n }\n tests[proportionTableIndex].master = { type: 'proportion', value: (100 - firstWorkspaceProportion).toFixed(2) }\n }\n\n return (\n <>\n <div className='mv4'>\n {success &&\n <Alert type={'success'} onClose={() => clearGeneralState()}>\n {success}\n </Alert>\n }\n {error &&\n <Alert type={'error'} onClose={() => clearGeneralState()}>\n {error}\n </Alert>\n }\n </div>\n <Table\n fullWidth\n schema={defaultSchema}\n items={tests}\n loading={loading}\n emptyStateLabel={emptyMessage}\n toolbar={{\n newLine: {\n label: intl.formatMessage({\n id: 'admin/admin.app.abtest.form.label.createTestAB',\n }),\n handleCallback: () => handleNewModal(true, \"CREATE\"),\n },\n }}\n />\n <Modal centered isOpen={modalOpen.isOpen && modalOpen.type === \"CREATE\"} onClose={() => handleNewModal(false, \"CREATE\")}>\n <div className=\"dark-gray\">\n <p className=\"f3 fw3\"><FormattedMessage id=\"admin/admin.app.abtest.form.label.createTestAB\" /></p>\n <div\n style={{\n display: 'flex',\n }}\n >\n <div\n className={'pr4 pb4'}\n style={{\n flex: '1 0 45%',\n }}\n >\n <Input\n dataAttributes={{\n 'hj-white-list': true,\n test: 'workspace-input',\n }}\n errorMessage={error}\n label={intl.formatMessage({\n id: 'admin/admin.app.abtest.table.label.workspaceName',\n })}\n type=\"text\"\n onChange={(ev: EventInterface): void => {\n handleInput(\"name\", ev.target.value)\n }}\n />\n </div>\n <div\n className={'pr4 pb4'}\n style={{\n flex: '1 0 45%',\n }}\n >\n <Input\n dataAttributes={{\n 'hj-white-list': true,\n test: 'workspace-input',\n }}\n label={intl.formatMessage({\n id: 'admin/admin.app.abtest.form.label.proportion',\n })}\n type=\"number\" min=\"0\" max=\"100\"\n onChange={(ev: EventInterface): void => {\n handleInput(\"proportion\", ((100 - parseInt(ev.target.value)) * 100).toString())\n }}\n />\n </div>\n </div>\n <div\n style={{\n display: 'flex',\n }}\n >\n <div\n className={'pr4 pb4'}\n style={{\n flex: '1 0 45%',\n }}\n >\n <Input\n dataAttributes={{\n 'hj-white-list': true,\n test: 'workspace-input',\n }}\n label={intl.formatMessage({\n id: 'admin/admin.app.abtest.form.label.hours',\n })}\n type=\"number\"\n onChange={(ev: EventInterface): void => {\n handleInput(\"hours\", ev.target.value)\n }}\n />\n </div>\n <div\n className={'pr4 pb4'}\n style={{\n flex: '1 0 45%',\n }}\n >\n <Dropdown\n label={intl.formatMessage({\n id: 'admin/admin.app.abtest.form.label.type',\n })}\n options={selectOptions}\n value={newTest.type}\n onChange={(ev: EventInterface): void => {\n handleInput(\"type\", ev.target.value)\n }}\n />\n </div>\n </div>\n <div className={'mv4'}>\n <Button disabled={!isValid()} variation=\"primary\" onClick={() => createNewTest(newTest)}>\n <FormattedMessage id=\"admin/admin.app.abtest.form.saveButton\" />\n </Button>\n </div>\n </div>\n </Modal>\n </>\n )\n}\n\nexport default ABTestTable\n\n```" } ]
code_store-on-localhost_5067f8d5
[ { "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 store-on-localhost/critical/index.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport critical from 'critical'\nimport { resolve } from 'path'\n\nconst dest = resolve(__dirname, '../build/static/css/critical.css')\nconst src = 'https://storetheme.vtex.com'\n\ncritical.generate({\n // Inline the generated critical-path CSS\n // - true generates HTML\n // - false generates CSS\n inline: false,\n\n // Your base directory\n // base: 'build/',\n\n // HTML source\n // html: '<html>...</html>',\n\n // HTML source file\n src,\n\n // Your CSS Files (optional)\n // css: ['../build/static/css/critical.css'],\n\n // Viewport width\n width: 1300,\n\n // Viewport height\n height: 900,\n\n // Target for final HTML output.\n // use some CSS file when the inline option is not set\n dest,\n\n // Minify critical-path CSS when inlining\n minify: true,\n\n // Extract inlined styles from referenced stylesheets\n // extract: true,\n\n // Complete Timeout for Operation\n timeout: 30000,\n\n // Prefix for asset directory\n // pathPrefix: '/MySubfolderDocrot',\n\n // ignore CSS rules\n // ignore: ['font-face',/some-regexp/],\n\n // overwrite default options\n // ignoreOptions: {}\n\n penthouse: {\n renderWaitTime: 5000,\n blockJSRequests: false,\n }\n})\n```" } ]
code_store-on-localhost_158b3ddc
[ { "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 store-on-localhost/server/typings.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n Request as ExpressRequest,\n Response as ExpressResponse,\n} from 'express'\n\nexport interface Response extends ExpressResponse { \n startTime: (name: string, desc: string) => void\n endTime: (name: string) => void\n}\n\nexport interface Request extends ExpressRequest {}\n```" } ]
code_store-on-localhost_a94937fc
[ { "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 store-on-localhost/server/index.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport compression from 'compression'\nimport path from 'path'\nimport serverTiming from 'server-timing'\nimport express from 'express'\nimport bodyParser from 'body-parser'\nimport morgan from 'morgan'\n\nimport { proxy } from './middlewares/proxy'\nimport { render } from './middlewares/renderer'\n\n\n// we'll talk about this in a minute:\nconst PORT = 8001\n\n// initialize the application and create the routes\nconst app = express()\nconst router = express.Router()\n\napp.use(morgan('dev'))\napp.use(bodyParser.json())\n\n// root (/) should always serve our server rendered page\nrouter.use('^/$', render)\n\nrouter.use('/_v/:scope/graphql/v1', proxy)\n\n// other static resources should just be served as they are\nrouter.use(\n express.static(\n path.resolve(__dirname, '../build'),\n { maxAge: '30d' },\n )\n)\n\n// tell the app to use the above rules\napp.use(compression())\napp.use(serverTiming({\n total: true,\n enabled: true,\n autoEnd: true,\n}))\napp.use(router)\n\n// start the app\napp.listen(PORT, (error) => {\n if (error) {\n console.error(error)\n process.exit(1)\n }\n console.log(`Server is listening on http://localhost:${PORT} 🦄`)\n})\n```" } ]
code_store-on-localhost_78d7920d
[ { "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 store-on-localhost/src/index.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport './index.css'\n\nimport React from 'react'\nimport ReactDOM from 'react-dom'\n\nimport { App, createOrHydrateApolloClient } from './App'\n\nconst client = createOrHydrateApolloClient()\n\nconst rootElement = document.getElementById('root')\n\nif ((window as any).__APOLLO_CACHE__) {\n console.log('hydating react ...')\n ReactDOM.hydrate(<App client={client}/>, rootElement)\n} else {\n ReactDOM.render(<App client={client}/>, rootElement)\n}\n\n```" } ]
code_store-on-localhost_db3010b6
[ { "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 store-on-localhost/src/App.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport './App.css'\n\nimport { InMemoryCache, NormalizedCacheObject } from 'apollo-cache-inmemory'\nimport { ApolloClient } from 'apollo-client'\nimport { ApolloLink } from 'apollo-link'\nimport { createHttpLink } from 'apollo-link-http'\nimport { canUseDOM } from 'exenv'\nimport React from 'react'\nimport { ApolloProvider } from 'react-apollo'\nimport { IntlProvider } from 'react-intl'\n\nimport HomeWrapper from './monobloco/HomeWrapper'\nimport StoreWrapper from './monobloco/StoreWrapper'\nimport staticRuntime from './runtime.json'\nimport { RenderContextProvider } from './vtex.render-runtime'\n\nconst runtime = {\n ...staticRuntime,\n getSettings: () => {},\n prefetchDefaultPages: () => {},\n addNavigationRouteModifier: () => {},\n}\n\ninterface Props {\n client: ApolloClient<NormalizedCacheObject>\n}\n\nexport const createOrHydrateApolloClient = () => {\n const httpLink = createHttpLink({\n fetch: window.fetch,\n credentials: 'include',\n useGETForQueries: false,\n uri: 'http://localhost:8001/_v/private/graphql/v1',\n includeExtensions: true\n })\n \n const inMemory = new InMemoryCache({\n addTypename: true,\n })\n\n if (canUseDOM && (window as any).__APOLLO_CACHE__) {\n console.log('Restoring apollo cache...')\n inMemory.restore((window as any).__APOLLO_CACHE__)\n }\n \n const client = new ApolloClient({\n link: ApolloLink.from([httpLink]),\n cache: inMemory,\n ssrMode: !canUseDOM,\n resolvers: {}\n })\n\n return client\n}\n\nexport const App = ({ client }: Props) => (\n <ApolloProvider client={client}>\n <IntlProvider messages={runtime.messages} locale=\"en\">\n <RenderContextProvider runtime={runtime}>\n <StoreWrapper>\n <HomeWrapper />\n </StoreWrapper>\n </RenderContextProvider> \n </IntlProvider>\n </ApolloProvider>\n)\n\n```" } ]
code_store-on-localhost_8a6158ed
[ { "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 store-on-localhost/src/App.css from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.App {\n text-align: center;\n}\n\n.App-logo {\n height: 40vmin;\n pointer-events: none;\n}\n\n@media (prefers-reduced-motion: no-preference) {\n .App-logo {\n animation: App-logo-spin infinite 20s linear;\n }\n}\n\n.App-header {\n background-color: #282c34;\n min-height: 100vh;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n font-size: calc(10px + 2vmin);\n color: white;\n}\n\n.App-link {\n color: #61dafb;\n}\n\n@keyframes App-logo-spin {\n from {\n transform: rotate(0deg);\n }\n to {\n transform: rotate(360deg);\n }\n}\n\n```" } ]
code_store-on-localhost_627d7aa0
[ { "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 store-on-localhost/src/index.css from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\nbody {\n margin: 0;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',\n 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',\n sans-serif;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n\ncode {\n font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',\n monospace;\n}\n\n```" } ]
code_store-on-localhost_1ae7d539
[ { "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 store-on-localhost/src/contextLink.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ApolloLink, NextLink, Operation } from 'apollo-link'\n\nexport const contextLink = new ApolloLink((operation: Operation, forward?: NextLink) => {\n return forward ? forward(operation) : null\n})\n```" } ]
code_store-on-localhost_c96d1ab3
[ { "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 store-on-localhost/src/global.d.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare global {\n}\n\ninterface Window extends Window, GlobalThis {\n pixelManagerEvents: any[]\n Element: any\n browserHistory: any\n __RUNTIME__: any\n __RENDER_8_SESSION__: any\n hrtime: any\n rendered: any\n __RENDER_8_COMPONENTS__: any\n __STATE__: any\n __hasPortals__: any\n self: any\n top: any\n __provideRuntime: any\n __RENDER_8_HOT__: any\n flags: any\n __hostname__: any\n ReactApollo: any\n ReactIntl: any\n ReactIntlLocaleData: any\n}\n```" } ]
code_store-on-localhost_ba58f086
[ { "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 store-on-localhost/server/middlewares/renderer.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { Request, Response } from '../typings'\nimport { readFile } from 'fs-extra'\nimport fetch from 'node-fetch'\nimport path from 'path'\nimport React from 'react'\nimport { renderToStringWithData } from '@apollo/react-ssr'\n\nimport { App, createOrHydrateApolloClient } from '../../src/App'\n\nglobal.window = global\nglobal.fetch = fetch\n\nconst filePath = path.resolve(__dirname, '../../build/index.html')\n\n\nconst renderServerSide = async (res: Response, htmlTemplate: string) => {\n const client = createOrHydrateApolloClient()\n \n res.startTime('renderToStringWithData', 'RenderToStringWithData')\n const renderedHTML = await renderToStringWithData(<App client={client}/>)\n res.endTime('renderToStringWithData')\n\n res.startTime('extractApolloClient', 'Apollo Client Extraction')\n const extracted = client.extract()\n res.endTime('extractApolloClient')\n\n return htmlTemplate\n .replace('<div id=\"root\"></div>', `<div id=\"root\">${renderedHTML}</div>`)\n .replace('<script id=\"apolloCache\"></script>', `<script id=\"apolloCache\">window.__APOLLO_CACHE__=${JSON.stringify(extracted)}</script>`)\n}\n\nconst renderClientSide = (htmlTemplate: string) => htmlTemplate\n\nexport const render = async (req: Request, res: Response) => {\n try {\n const { __disableSSR: disableSSR } = req.query\n\n res.startTime('htmlTemplate', 'Read HTML Template')\n const htmlTemplate = await readFile(filePath, { encoding: 'utf8' })\n res.endTime('htmlTemplate')\n\n let html: string = ''\n if (disableSSR != null) {\n res.startTime('renderClientSide', 'Client Side Rending')\n html = renderClientSide(htmlTemplate)\n res.endTime('renderClientSide')\n } else {\n res.startTime('serverSideRendering', 'Render Server Side')\n html = await renderServerSide(res, htmlTemplate)\n res.endTime('serverSideRendering')\n }\n \n res.send(html)\n } catch (err) {\n if (err) {\n console.error('err', err);\n return res.status(404).end()\n }\n }\n}\n```" } ]
code_store-on-localhost_89a7eb8a
[ { "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 store-on-localhost/server/middlewares/proxy.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport axios, { AxiosRequestConfig } from 'axios'\nimport { join } from 'path'\nimport LRU from 'lru-cache'\nimport crypto from 'crypto'\n\nimport { Request, Response } from '../typings'\n\ninterface Cached {\n data: any\n headers: Record<string, string>\n status: number\n}\n\nconst HOST = 'storetheme.vtex.com'\nconst PROTOCOL = 'https'\nconst CACHE = new LRU<string, Cached>({\n max: 1e3\n})\n\nconst http = axios.create({\n baseURL: `${PROTOCOL}://${HOST}`,\n timeout: 5e3,\n})\n\nconst delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))\n\nconst awaitForOperationName = async (operationName: string) => {\n \n let amount = 0\n if (operationName === 'pwaData') {\n amount = 0\n } else if (operationName === 'orderForm') {\n amount = 0\n } else if (operationName === 'orderFormCheckout') {\n amount = 0\n }\n\n console.log(`[${operationName}]: Awaiting ${amount}ms`)\n await delay(amount)\n}\n\nconst toMD5 = (input: string) => crypto.createHash('md5').update(input).digest('hex')\n\nconst optionsToCacheKey = (config: AxiosRequestConfig): string => [\n `url:${config.url}`,\n `data:${toMD5(JSON.stringify(config.data))}`,\n `headers:${toMD5(JSON.stringify(config.headers))}`\n].join('--')\n\nexport const proxy = async (req: Request, res: Response) => {\n try {\n const body = req.body\n const operationName = body?.operationName\n \n await awaitForOperationName(operationName)\n \n const options: AxiosRequestConfig = {\n method: 'POST',\n url: join(req.baseUrl, req.url),\n headers: {\n ...req.headers,\n host: HOST,\n },\n data: body,\n validateStatus: () => true\n }\n \n const key = optionsToCacheKey(options)\n const isCached = CACHE.has(key)\n\n if (!isCached) {\n console.log('[MISS]', options.data?.operationName)\n const { headers, status, data } = await http.request(options)\n\n if (!isCached && status === 200) {\n CACHE.set(key, {\n headers,\n status,\n data,\n })\n }\n } else {\n console.log('[HIT]', options.data?.operationName)\n }\n\n const { headers, status, data } = CACHE.get(key)\n \n Object.keys(headers).forEach(header => {\n res.set(header, headers[header])\n })\n\n res.status(status)\n res.send(data)\n \n } catch (err) {\n console.error(err)\n res.status(500)\n res.send(err)\n }\n}\n```" } ]
code_store-on-localhost_952e9bd6
[ { "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 store-on-localhost/src/monobloco/StoreWrapper.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { Fragment, useEffect } from 'react'\nimport Helmet from 'react-helmet'\nimport PropTypes from 'prop-types'\n\nimport PixelContext from './components/new/PixelContext/PixelContext'\nimport ToastProvider from './components/new/Styleguide/ToastProvider'\nimport PWAContext from './components/new/StoreResources/PWAContext'\nimport OrderQueue from './components/new/OrderManager/OrderQueue'\nimport OrderItems from './components/new/OrderItems/OrderItems'\nimport OrderManagerForm from './components/new/OrderManager/OrderForm'\nimport UserDataPixel from './components/UserDataPixel'\nimport PageViewPixel from './components/PageViewPixel'\nimport OrderFormProvider from './components/OrderFormProvider'\nimport NetworkStatusToast from './components/NetworkStatusToast'\nimport WrapperContainer from './components/WrapperContainer'\n\nimport { normalizeNavigation } from './utils/navigation'\nimport { useRuntime } from '../vtex.render-runtime'\n// import { canUseDOM } from 'exenv'\n\nconst { OrderQueueProvider } = OrderQueue\nconst { PixelProvider } = PixelContext\nconst { PWAProvider } = PWAContext\nconst { OrderFormProvider: OrderFormProviderCheckout } = OrderManagerForm\nconst { OrderItemsProvider } = OrderItems\n\nconst APP_LOCATOR = 'vtex.store'\nconst CONTENT_TYPE = 'text/html; charset=utf-8'\nconst META_ROBOTS = 'index, follow'\nconst MOBILE_SCALING = 'width=device-width, initial-scale=1'\n\nconst systemToCanonical = ({ canonicalPath }) => {\n const canonicalHost =\n window.__hostname__ || (window.location && window.location.hostname)\n return {\n canonicalPath,\n canonicalHost,\n }\n}\n\nconst StoreWrapper = ({ children }) => {\n const {\n amp,\n culture: { country, locale, currency },\n route,\n route: { metaTags, title: pageTitle },\n getSettings,\n rootPath = '',\n prefetchDefaultPages,\n addNavigationRouteModifier,\n } = useRuntime()\n // const isStorefrontIframe =\n // canUseDOM && window.top !== window.self && window.top.__provideRuntime\n\n // const supportsServiceWorker = canUseDOM && 'serviceWorker' in navigator\n\n useEffect(() => {\n prefetchDefaultPages([\n 'store.custom',\n 'store.product',\n 'store.search',\n 'store.search#brand',\n 'store.search#category',\n 'store.search#configurable',\n 'store.search#custom',\n 'store.search#department',\n 'store.search#subcategory',\n 'store.search#subcategory-terms',\n ])\n }, [prefetchDefaultPages])\n\n useEffect(() => {\n addNavigationRouteModifier(normalizeNavigation)\n }, [addNavigationRouteModifier])\n\n const settings = getSettings(APP_LOCATOR) || {}\n const {\n titleTag,\n metaTagDescription,\n metaTagRobots,\n storeName,\n faviconLinks,\n } = settings\n\n const { canonicalHost, canonicalPath } = systemToCanonical(route)\n const description = (metaTags && metaTags.description) || metaTagDescription\n const title = pageTitle || titleTag\n\n // const [queryMatch] = route.path.match(/\\?.*/) || ['?']\n\n const canonicalLink =\n canonicalHost &&\n canonicalPath &&\n `https://${canonicalHost}${rootPath}${canonicalPath}`\n\n return (\n <Fragment>\n <Helmet\n title={title}\n meta={[\n // viewport meta tag is already handled in render-server for AMP pages\n !amp && { name: 'viewport', content: MOBILE_SCALING },\n { name: 'description', content: description },\n { name: 'copyright', content: storeName },\n { name: 'author', content: storeName },\n { name: 'country', content: country },\n { name: 'language', content: locale },\n { name: 'currency', content: currency },\n { name: 'robots', content: metaTagRobots || META_ROBOTS },\n { httpEquiv: 'Content-Type', content: CONTENT_TYPE },\n ]\n .filter(Boolean)\n .filter(meta => meta.content && meta.content.length > 0)}\n // script={[\n // supportsServiceWorker && {\n // type: 'text/javascript',\n // src: `${rootPath}/pwa/workers/register.js${queryMatch}&scope=${encodeURIComponent(\n // rootPath\n // )}`,\n // defer: true,\n // },\n // ].filter(Boolean)}\n link={[\n ...(faviconLinks || []),\n ...(!amp && canonicalLink\n ? [\n {\n rel: 'canonical',\n href: encodeURI(canonicalLink),\n },\n ]\n : []),\n ].filter(Boolean)}\n />\n <PixelProvider currency={currency}>\n <PWAProvider rootPath={rootPath}>\n <PageViewPixel title={title} />\n <UserDataPixel />\n <ToastProvider positioning=\"window\">\n <NetworkStatusToast />\n <OrderFormProvider>\n <OrderQueueProvider>\n <OrderFormProviderCheckout>\n <OrderItemsProvider>\n <WrapperContainer className=\"vtex-store__template bg-base\">\n {children}\n </WrapperContainer>\n </OrderItemsProvider> \n </OrderFormProviderCheckout>\n </OrderQueueProvider>\n </OrderFormProvider>\n </ToastProvider> \n </PWAProvider>\n </PixelProvider>\n </Fragment>\n )\n}\n\nStoreWrapper.propTypes = {\n children: PropTypes.element,\n}\n\nexport default StoreWrapper\n\n```" } ]
code_store-on-localhost_803ab6e8
[ { "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 store-on-localhost/src/monobloco/HomeWrapper.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { useMemo, Fragment } from 'react'\nimport PropTypes from 'prop-types'\nimport { useRuntime } from '../vtex.render-runtime'\nimport { canUseDOM } from 'exenv'\n// import SearchAction from 'vtex.structured-data/SearchAction'\nimport useDataPixel from './hooks/useDataPixel'\nimport Header from './components/new/header'\nimport Carousel from './components/new/Carousel/Carousel'\nimport Row from './components/new/FlexLayout/Row'\nimport Col from './components/new/FlexLayout/Col'\nimport StoreImage from './components/new/StoreImage/Image'\nimport RichText from './components/new/RichText'\nimport Shelf from './components/new/Shelf/Shelf'\nimport InfoCard from './components/new/StoreComponents/InfoCard'\nimport Newsletter from './components/new/StoreComponents/Newsletter'\nimport Footer from './components/new/Footer/Footer'\n\nconst Deals = () => {\n return (\n <div>\n <Row blockClass=\"deals\">\n <Col>\n <StoreImage src=\"https://storecomponents.vteximg.com.br/arquivos/box.png\" maxHeight=\"24px\" />\n <RichText text=\"Free shipping\" blockClass=\"deals\" />\n </Col>\n <Col>\n <StoreImage src=\"https://storecomponents.vteximg.com.br/arquivos/delivery-fast.png\" maxHeight=\"24px\" />\n <RichText text=\"One day delivery\" blockClass=\"deals\" />\n </Col>\n <Col>\n <StoreImage src=\"https://storecomponents.vteximg.com.br/arquivos/store.png\" maxHeight=\"24px\" />\n <RichText text=\"Pick up in store\" blockClass=\"deals\" />\n </Col>\n <Col>\n <StoreImage src=\"https://storecomponents.vteximg.com.br/arquivos/coupon.png\" maxHeight=\"24px\" />\n <RichText text=\"Exclusive deals\" blockClass=\"deals\" />\n </Col>\n </Row>\n </div>\n )\n}\n\nconst FixedHome = () => {\n return <div>\n <Header />\n <Carousel autoplay={false} banners={\n [{\n \"image\": \"https://storecomponents.vteximg.com.br/arquivos/banner-principal.png\",\n \"mobileImage\": \"https://storecomponents.vteximg.com.br/arquivos/banner-principal-mobile.jpg\"\n },\n {\n \"image\": \"https://storecomponents.vteximg.com.br/arquivos/banner.jpg\",\n \"mobileImage\": \"https://storecomponents.vteximg.com.br/arquivos/banner-principal-mobile.jpg\"\n }]\n }\n height={720}\n showArrows\n showDots\n />\n <Deals />\n <Shelf orderBy=\"OrderByTopSaleDESC\" paginationDotsVisibility=\"desktopOnly\" skusFilter=\"FIRST_AVAILABLE\" productList={{\n \"maxItems\": 10,\n \"itemsPerPage\": 5,\n \"minItemsPerPage\": 1,\n \"scroll\": \"BY_PAGE\",\n \"arrows\": true,\n \"titleText\": \"Top sellers\"\n }} />\n <InfoCard id=\"info-card-home\" isFullModeStyle={false} textPosition=\"left\" imageUrl=\"https://storecomponents.vteximg.com.br/arquivos/banner-infocard2.png\" headline=\"Clearance Sale\" callToActionText=\"DISCOVER\" callToActionUrl=\"/sale/d/\" blockClass=\"info-card-home\" textAlignment=\"center\" />\n <RichText text=\"**This is an example store built using the VTEX platform.\\nWant to know more?**\" blockClass=\"question\" />\n <RichText text=\"\\n**Reach us at**\\nwww.vtex.com.br\" blockClass=\"link\" />\n <Newsletter />\n <Footer /> \n </div>\n}\n\nconst HomeWrapper = ({ children }) => {\n const { account, route } = useRuntime()\n\n const pixelEvents = useMemo(() => {\n if (!canUseDOM) {\n return null\n }\n\n return [\n {\n event: 'pageInfo',\n eventType: 'homeView',\n accountName: account,\n pageTitle: document.title,\n pageUrl: window.location.href,\n pageCategory: 'Home',\n },\n ]\n }, [account])\n\n useDataPixel(pixelEvents, route.routeId)\n\n return (\n <Fragment>\n <FixedHome />\n </Fragment>\n )\n}\n\nHomeWrapper.propTypes = {\n children: PropTypes.element,\n}\n\nexport default HomeWrapper\n\n```" } ]
code_store-on-localhost_4cc436cb
[ { "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 store-on-localhost/src/vtex.render-runtime/index.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport 'apollo-cache-inmemory'\nimport 'apollo-client'\nimport 'apollo-link-http'\nimport 'apollo-link-persisted-queries'\nimport 'apollo-upload-client'\nimport 'apollo-utilities'\nimport 'classnames'\nimport * as EventEmitter from 'eventemitter3'\nimport { canUseDOM } from 'exenv'\nimport 'graphql'\nimport { createBrowserHistory as createHistory } from 'history'\nimport queryString from 'query-string'\nimport React, { ReactElement } from 'react'\nimport { getDataFromTree } from 'react-apollo'\nimport { hydrate, render as renderDOM } from 'react-dom'\nimport { Helmet } from 'react-helmet'\nimport NoSSR, { useSSR } from './components/NoSSR'\nimport { isEmpty } from 'ramda'\nimport Loading from './components/Loading'\nimport { LoadingContextProvider } from './components/LoadingContext'\n\nimport { ChildBlock, useChildBlock } from './components/ChildBlock'\nimport ExtensionContainer from './components/ExtensionContainer'\nimport ExtensionPoint from './components/ExtensionPoint'\nimport LayoutContainer from './components/LayoutContainer'\nimport LegacyExtensionContainer from './components/LegacyExtensionContainer'\nimport Link from './components/Link'\nimport {\n RenderContext,\n useRuntime,\n withRuntimeContext,\n RenderContextProvider,\n} from './components/RenderContext'\nimport RenderProvider from './components/RenderProvider'\nimport { getVTEXImgHost } from './utils/assets'\nimport PageCacheControl from './utils/cacheControl'\nimport { getState } from './utils/client'\nimport { buildCacheLocator } from './utils/client'\nimport { ensureContainer, getContainer, getMarkups } from './utils/dom'\nimport { registerEmitter } from './utils/events'\nimport { getBaseURI } from './utils/host'\nimport registerComponent from './utils/registerComponent'\nimport { withSession } from './utils/session'\nimport { TreePathContext, useTreePath } from './utils/treePath'\nimport {\n isStyleWritable,\n optimizeSrcForVtexImg,\n optimizeStyleForVtexImg,\n} from './utils/vteximg'\nimport withHMR from './utils/withHMR'\nimport { generateExtensions } from './utils/blocks'\n\nlet emitter: EventEmitter | null = null\n\nconst renderExtension = (\n extensionName: string,\n destination: HTMLElement,\n props = {}\n) => {\n if (emitter) {\n emitter.emit('renderExtensionLoader.addOrUpdateExtension', {\n destination,\n extensionName,\n props,\n })\n } else {\n throw new Error(`ExtensionPortal can't be rendered before RenderProvider`)\n }\n}\n\nfunction renderToStringWithData(\n component: ReactElement<any>,\n renderFn: (root: ReactElement) => string,\n skipQuery = false\n): Promise<any> {\n const getDataFn = (): Promise<string | void> => {\n if (skipQuery) return Promise.resolve()\n return getDataFromTree(component)\n }\n\n const startGetDataFromTree = window.hrtime()\n return getDataFn().then(() => {\n const endGetDataFromTree = window.hrtime(startGetDataFromTree)\n\n const startRenderToString = window.hrtime()\n const markup = renderFn(component)\n const endRenderToString = window.hrtime(startRenderToString)\n return {\n markup,\n renderTimeMetric: {\n getDataFromTree: endGetDataFromTree,\n renderToString: endRenderToString,\n },\n }\n })\n}\n\n// Either renders the root component to a DOM element or returns a {name, markup} promise.\nconst render = async (\n name: string,\n runtime: any,\n element?: HTMLElement\n): Promise<any> => {\n const {\n customRouting,\n disableSSR,\n disableSSQ,\n page,\n pages,\n extensions,\n } = runtime\n\n const cacheControl = canUseDOM ? undefined : new PageCacheControl()\n const baseURI = getBaseURI(runtime)\n registerEmitter(runtime, baseURI)\n emitter = runtime.emitter\n\n const isPage =\n !!pages[name] && !!pages[name].path && !!extensions[name].component\n const created = !element && ensureContainer(page)\n const elem = element || getContainer()\n const history = canUseDOM && isPage && !customRouting ? createHistory() : null\n\n const root = (\n <RenderProvider\n history={history}\n cacheControl={cacheControl}\n baseURI={baseURI}\n root={name}\n runtime={runtime}\n >\n {!isPage ? <ExtensionPoint id={name} /> : null}\n </RenderProvider>\n )\n\n if (canUseDOM) {\n const renderFn = disableSSR || created ? renderDOM : hydrate\n\n return (renderFn(root, elem) as unknown) as Element\n }\n\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n // const { renderToStaticMarkup, renderToString } = require('react-dom/server')\n const { renderToString } = require('react-dom/server')\n\n const commonRenderResult = {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n maxAge: cacheControl!.maxAge,\n page,\n }\n\n // if (runtime.amp) {\n // return import(\n // /* webpackMode: \"weak\" */\n // '../AMP'\n // ).then(({ setupAMP }) => {\n // const { ampRoot, getExtraRenderedData } = setupAMP(\n // root,\n // renderToStaticMarkup,\n // runtime\n // )\n // return renderToStringWithData(\n // ampRoot,\n // renderToStaticMarkup,\n // disableSSQ\n // ).then(({ markup, renderTimeMetric }) => ({\n // ...commonRenderResult,\n // markups: getMarkups(name, markup),\n // renderTimeMetric,\n // ...getExtraRenderedData(),\n // }))\n // })\n // }\n\n return renderToStringWithData(root, renderToString, disableSSQ).then(\n ({ markup, renderTimeMetric }) => ({\n ...commonRenderResult,\n markups: getMarkups(name, markup),\n renderTimeMetric,\n })\n )\n}\n\nfunction validateRootComponent(rootName: string, extensions: any) {\n if (!extensions[rootName]) {\n throw new Error(`Missing extension point for page ${rootName}`)\n }\n\n if (!extensions[rootName].component) {\n throw new Error(`Missing component for extension point ${rootName}`)\n }\n}\n\nfunction setLazyCookie(setCookie: string) {\n if (setCookie) {\n document.cookie = setCookie\n }\n}\n\nfunction start() {\n try {\n if (\n window.__RUNTIME__.blocksTree &&\n !isEmpty(window.__RUNTIME__.blocksTree)\n ) {\n window.__RUNTIME__.hasNewExtensions = true\n window.__RUNTIME__.extensions = generateExtensions(\n window.__RUNTIME__.blocksTree,\n // eslint-disable-next-line\n window.__RUNTIME__.blocks!,\n // eslint-disable-next-line\n window.__RUNTIME__.contentMap!,\n window.__RUNTIME__.pages[window.__RUNTIME__.page]\n )\n }\n\n if (canUseDOM && window.location.search) {\n const browserQuery = queryString.parse(window.location.search)\n window.__RUNTIME__.query = {\n ...browserQuery,\n ...(window.__RUNTIME__.query || {}),\n }\n }\n\n const runtime = window.__RUNTIME__\n const rootName = runtime.page\n validateRootComponent(rootName, runtime.extensions)\n\n const ReactCreateElement = React.createElement\n const vtexImgHost = getVTEXImgHost(runtime.account)\n React.createElement = function patchedCreateElement(type: any, props: any) {\n if (type === 'a' && props) {\n if (props.target && !props.href) {\n props.target = undefined\n }\n // Follow Google's security recommendations concerning target blank\n // https://developers.google.com/web/tools/lighthouse/audits/noopener\n const rel = props.rel ? props.rel.split(' ') : []\n if (\n props.target === '_blank' &&\n !(rel.indexOf('noopener') !== -1 || rel.indexOf('noreferrer') !== -1)\n ) {\n props.rel = rel.concat('noopener').join(' ')\n }\n }\n\n if (type === 'img') {\n props.src = optimizeSrcForVtexImg(vtexImgHost, props.src)\n if (\n typeof props.src === 'string' &&\n props.src.startsWith(vtexImgHost)\n ) {\n props.crossOrigin = props.crossOrigin || 'anonymous'\n }\n }\n\n if (props && props.style && isStyleWritable(props)) {\n props.style = optimizeStyleForVtexImg(vtexImgHost, props.style)\n }\n // This rule was introduced in a eslint-config update.\n // Should be fixed in a future PR\n //eslint-disable-next-line prefer-rest-params\n return ReactCreateElement.apply(React, arguments)\n }\n\n const maybeRenderPromise = render(rootName, runtime)\n if (!canUseDOM) {\n // Expose render promise to global context.\n window.rendered = (maybeRenderPromise as Promise<\n AsyncGeneratorFunction\n >).then(({ markups, maxAge, page, renderTimeMetric, ...rendered }: any) => ({\n extensions: markups.reduce(\n (acc, { name, markup }) => {(acc[name] = markup); return acc},\n {}\n ),\n head: Helmet.rewind(),\n maxAge,\n renderMetrics: { [page]: renderTimeMetric },\n state: getState(runtime),\n ...rendered,\n }))\n } else {\n setLazyCookie(runtime.workspaceCookie)\n console.log(\n 'Welcome to Render! Want to look under the hood? https://careers.vtex.com'\n )\n }\n } catch (error) {\n console.error('Unexpected error rendering:', error)\n if (!canUseDOM) {\n window.rendered = { error }\n }\n }\n}\n\nconst RenderContextConsumer = RenderContext.Consumer\nconst TreePathContextConsumer = TreePathContext.Consumer\n\nexport {\n ExtensionContainer,\n /** Block is the preferred nomenclature now, ExtensionPoint is kept for\n * backwards compatibility\n */\n ExtensionPoint as Block,\n ExtensionPoint,\n LayoutContainer,\n LegacyExtensionContainer,\n Helmet,\n Link,\n NoSSR,\n useSSR,\n RenderContextConsumer,\n RenderContextProvider,\n TreePathContextConsumer,\n canUseDOM,\n render,\n start,\n withHMR,\n RenderProvider,\n registerComponent,\n withRuntimeContext,\n ChildBlock,\n useChildBlock,\n useRuntime,\n useTreePath,\n withSession,\n Loading,\n LoadingContextProvider,\n buildCacheLocator,\n renderExtension,\n // These unstable APIs should be deprecated shortly\n ChildBlock as Unstable__ChildBlock,\n useChildBlock as useChildBlock__unstable,\n}\n\n```" } ]
code_store-on-localhost_e8e19eb4
[ { "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 store-on-localhost/src/monobloco/utils/navigation.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport { contains, path as ramdaPath, zip, flatten } from 'ramda'\nimport queryString from 'query-string'\n\nconst SPEC_FILTER = 'specificationFilter'\nconst MAP_CATEGORY_CHAR = 'c'\nconst MAP_VALUES_SEP = ','\nconst PATH_SEPARATOR = '/'\n\nconst isLegacySearchFormat = (pathSegments, map) => {\n if (!map) {\n return false\n }\n return (\n map.includes(SPEC_FILTER) ||\n map.split(MAP_VALUES_SEP).length === pathSegments.length\n )\n}\n\nconst categoriesInSequence = mapValues => {\n let count = 0\n for (const value of mapValues) {\n if (value !== MAP_CATEGORY_CHAR) {\n return count\n }\n count++\n }\n return count\n}\n\nconst queryMapComparator = (tuple1, tuple2) => {\n const [, specFilterVal1] = tuple1 && tuple1[0].split(`${SPEC_FILTER}_`)\n const [, specFilterVal2] = tuple2 && tuple2[0].split(`${SPEC_FILTER}_`)\n const facetName1 = tuple1[1]\n const facetName2 = tuple2[1]\n\n const considerSpecificationFilter =\n specFilterVal1 &&\n specFilterVal2 &&\n !isNaN(Number(specFilterVal1)) &&\n !isNaN(Number(specFilterVal2))\n\n return considerSpecificationFilter\n ? Number(specFilterVal1) -\n Number(specFilterVal2) +\n facetName1.localeCompare(facetName2)\n : facetName1.localeCompare(facetName2)\n}\n\nconst normalizeQueryMap = (pathSegments, mapSegments) => {\n const categoryTreeDepth = categoriesInSequence(mapSegments)\n const zippedMapQuery = zip(mapSegments, pathSegments)\n\n const sorted =\n zippedMapQuery &&\n zippedMapQuery.slice(categoryTreeDepth).sort(queryMapComparator)\n\n const assembledSortedQuery = zippedMapQuery\n .slice(0, categoryTreeDepth)\n .concat(sorted)\n\n const sortedMap = assembledSortedQuery\n .map(value => (Array.isArray(value) ? value[0] : value))\n .join(',')\n const sortedPathSegments = assembledSortedQuery.map(tuple => tuple[1])\n\n return {\n map: sortedMap,\n pathSegments: sortedPathSegments,\n }\n}\n\nconst normalizeSearchNavigation = (pathSegments, map, segmentsToIgnore) => {\n const normalizedSegments = pathSegments.map(segment =>\n segmentsToIgnore.includes(segment) ? segment : segment.toLowerCase()\n )\n return { pathSegments: normalizedSegments, map }\n}\n\nconst getIgnoredSegments = ignore => {\n return ignore\n ? flatten(\n Object.values(ignore).map(routeModifier =>\n routeModifier.path.split(PATH_SEPARATOR)\n )\n )\n : []\n}\n\nconst normalizeLegacySearchNavigation = (pathSegments, queryMap, query) => {\n if (queryMap.map) {\n const mapValues = queryMap.map.split(MAP_VALUES_SEP)\n let convertedSegments = zip(pathSegments, mapValues).map(\n ([pathSegment, mapValue]) =>\n contains(SPEC_FILTER, mapValue)\n ? pathSegment\n : pathSegment.toLowerCase()\n )\n\n const {\n pathSegments: sortedPathSegments,\n map: sortedMap,\n } = normalizeQueryMap(\n queryMap.query ? queryMap.query.split('/').slice(1) : convertedSegments,\n mapValues\n )\n\n queryMap.map = sortedMap\n if (queryMap.query) {\n queryMap.query = `/${sortedPathSegments.join('/')}`\n } else {\n convertedSegments = sortedPathSegments\n }\n\n const normalizedQuery = queryString.stringify(queryMap, {\n encode: false,\n })\n\n return { pathSegments: convertedSegments, query: normalizedQuery }\n }\n return { pathSegments: pathSegments, query: query }\n}\n\nexport const normalizeNavigation = navigation => {\n if (ramdaPath(['__RUNTIME__', 'route', 'domain'], window) !== 'store') {\n return navigation\n }\n\n const { path, query, options } = navigation\n const parsedQuery = query ? queryString.parse(query) : {}\n const { map } = parsedQuery\n\n const pathSegments = path.startsWith(PATH_SEPARATOR)\n ? path.split(PATH_SEPARATOR).slice(1)\n : path.split(PATH_SEPARATOR)\n\n const segmentsToIgnore = getIgnoredSegments(options)\n\n const normalizedNavigation =\n parsedQuery.query || isLegacySearchFormat(pathSegments, map)\n ? normalizeLegacySearchNavigation(pathSegments, parsedQuery, query)\n : normalizeSearchNavigation(pathSegments, query, segmentsToIgnore)\n\n navigation.path = path.startsWith('/')\n ? '/' + normalizedNavigation.pathSegments.join('/')\n : normalizedNavigation.pathSegments.join('/')\n navigation.query = normalizedNavigation.query\n return navigation\n}\n\n```" } ]
code_store-on-localhost_944a6abf
[ { "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 store-on-localhost/src/monobloco/components/UserDataPixel.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { useEffect, FC } from 'react'\nimport {usePixel} from './new/PixelContext/PixelContext'\n\nconst fields = ['firstName', 'lastName', 'document', 'id', 'email', 'phone', 'isAuthenticated'] as const\n\ninterface SessionResponse {\n response: {\n namespaces: {\n profile?: {\n firstName?: {\n value: string\n }\n lastName?: {\n value: string\n }\n document?: {\n value: string\n }\n id?: {\n value: string\n }\n email?: {\n value: string\n }\n phone?: {\n value: string\n }\n isAuthenticated?: {\n value: string\n }\n }\n }\n }\n}\n\nconst getSessionPromiseFromWindow: any = () =>\n !(window as any).__RENDER_8_SESSION__ || !(window as any).__RENDER_8_SESSION__.sessionPromise\n ? Promise.resolve(null)\n : (window as any).__RENDER_8_SESSION__.sessionPromise\n\nconst toBoolean = (value: string) => value.toLowerCase() === 'true'\n\nfunction getUserData(profileFields: SessionResponse['response']['namespaces']['profile']) {\n if (!profileFields) {\n return {}\n }\n\n return fields.reduce<Record<string, string | boolean>>(\n (acc, key) => {\n const value = profileFields[key]?.value\n\n if (value) {\n acc[key] = key === 'isAuthenticated'\n ? toBoolean(value)\n : value\n }\n\n return acc\n },\n {}\n )\n}\n\nconst UserDataPixel: FC = () => {\n const { push } = usePixel()\n\n useEffect(() => {\n getSessionPromiseFromWindow().then((data: SessionResponse) => {\n const profileFields = data?.response?.namespaces?.profile\n\n if (!profileFields) {\n return\n }\n\n const userData = getUserData(profileFields)\n\n push({\n event: 'userData',\n ...userData,\n } as any)\n })\n }, [push])\n\n return null\n}\n\nexport default UserDataPixel\n\n```" } ]
code_store-on-localhost_a36cf1a4
[ { "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 store-on-localhost/src/monobloco/components/OrderFormProvider.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport { loader } from 'graphql.macro'\nimport { useMutation, useQuery } from 'react-apollo'\nimport { canUseDOM } from 'exenv'\n\nimport OrderFormContext from './new/StoreResources/OrderFormContext'\n\nconst addToCartMutation = loader('./new/StoreResources/mutations/addToCart.gql')\nconst updateItemsMutation = loader('./new/StoreResources/mutations/updateItems.gql')\nconst updateOrderFormProfileMutation = loader('./new/StoreResources/mutations/updateOrderFormProfile.gql')\nconst updateOrderFormShippingMutation = loader('./new/StoreResources/mutations/updateOrderFormShipping.gql')\nconst updateOrderFormCheckinMutation = loader('./new/StoreResources/mutations/updateOrderFormCheckin.gql')\nconst orderForm = loader('./new/StoreResources/queries/orderForm.gql')\n\nconst { Provider } = OrderFormContext\n\nlet value = {}\n\nconst OrderFormProvider = ({ children }) => {\n const { data, error } = useQuery(orderForm, { ssr: false })\n const addItem = useMutation(addToCartMutation)\n const updateOrderForm = useMutation(updateItemsMutation)\n const updateOrderFormProfile = useMutation(updateOrderFormProfileMutation)\n const updateOrderFormShipping = useMutation(updateOrderFormShippingMutation)\n const updateOrderFormCheckin = useMutation(updateOrderFormCheckinMutation)\n\n if (error) {\n throw error\n }\n\n value = {\n message: data?.message,\n orderFormContext: {\n updateToastMessage: () => console.log('updateToastMessage'),\n updateAndRefetchOrderForm: () => console.log('updateAndRefetchOrderForm'),\n updateOrderForm,\n addItem,\n updateOrderFormProfile,\n updateOrderFormShipping,\n updateOrderFormCheckin,\n }\n }\n\n return <Provider value={value}>{children}</Provider>\n\n}\n\nexport default OrderFormProvider\n\n\n// class OrderFormProvider extends Component {\n// state = {\n// orderFormContext: {\n// message: { isSuccess: null, text: null },\n// loading: true,\n// orderForm: {},\n// refetch: () => {},\n// addItem: this.props.addItem,\n// updateToastMessage: this.handleMessageUpdate,\n// updateOrderForm: this.props.updateOrderForm,\n// updateAndRefetchOrderForm: this.handleUpdateAndRefetchOrderForm,\n// updateOrderFormProfile: this.props.updateOrderFormProfile,\n// updateOrderFormShipping: this.props.updateOrderFormShipping,\n// updateOrderFormCheckin: this.props.updateOrderFormCheckin,\n// },\n// }\n\n// static getDerivedStateFromProps(props, state) {\n// if (!props.data.loading && !props.data.error) {\n// const orderFormContext = props.data\n\n// orderFormContext.message = state.orderFormContext.message\n\n// return {\n// orderFormContext,\n// }\n// }\n\n// return state\n// }\n\n// handleUpdateAndRefetchOrderForm = vars => {\n// return this.props.updateOrderForm(vars).then(() => {\n// return this.props.data.refetch()\n// })\n// }\n\n// handleMessageUpdate = message => {\n// const context = this.state.orderFormContext\n// context.message = message\n\n// this.setState({ orderFormContext: context })\n// }\n\n// render() {\n// const state = this.state\n\n// state.orderFormContext.updateToastMessage = this.handleMessageUpdate\n// state.orderFormContext.updateAndRefetchOrderForm = this.handleUpdateAndRefetchOrderForm\n// state.orderFormContext.updateOrderForm = this.props.updateOrderForm\n// state.orderFormContext.addItem = this.props.addItem\n// state.orderFormContext.updateOrderFormProfile = this.props.updateOrderFormProfile\n// state.orderFormContext.updateOrderFormShipping = this.props.updateOrderFormShipping\n// state.orderFormContext.updateOrderFormCheckin = this.props.updateOrderFormCheckin\n\n// return <Provider value={this.state}>{this.props.children}</Provider>\n// }\n// }\n\n// const options = {\n// options: () => ({\n// ssr: false,\n// }),\n// }\n\n// export default compose(\n// graphql(orderForm, options),\n// graphql(addToCart, { name: 'addItem' }),\n// graphql(updateItems, { name: 'updateOrderForm' }),\n// graphql(updateOrderFormProfile, { name: 'updateOrderFormProfile' }),\n// graphql(updateOrderFormShipping, { name: 'updateOrderFormShipping' }),\n// graphql(updateOrderFormCheckin, { name: 'updateOrderFormCheckin' })\n// )(OrderFormProvider)\n```" } ]
code_store-on-localhost_e8c9a2ad
[ { "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 store-on-localhost/src/monobloco/components/WrapperContainer.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\n\nconst WrapperContainer = ({ children, className }) => (\n <div className={className}>\n <div className=\"flex flex-column min-vh-100 w-100\">{children}</div>\n </div>\n)\n\nexport default WrapperContainer\n\n```" } ]
code_store-on-localhost_ed6c8591
[ { "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 store-on-localhost/src/monobloco/components/NetworkStatusToast.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport { path, pathOr } from 'ramda'\nimport { useCallback, useContext, useEffect, useMemo, useState } from 'react'\nimport { injectIntl } from 'react-intl'\nimport ToastContext from '../components/new/Styleguide/ToastContext'\nimport { useRuntime } from '../../vtex.render-runtime'\n\nfunction NetworkStatusToast({ intl }) {\n const runtime = useRuntime()\n const [offline, setOffline] = useState(false)\n // Useful to dismissable toast flow.\n const [showingOffline, setShowingOffline] = useState(false)\n const { showToast, hideToast, toastState } = useContext(ToastContext)\n\n const toastConfig = useMemo(\n () => ({\n message: intl.formatMessage({\n id: 'store/store.network-status.offline',\n }),\n dismissable: pathOr(false, ['hints', 'mobile'], runtime),\n duration: Infinity,\n }),\n [intl, runtime]\n )\n\n const updateStatus = useCallback(() => {\n if (navigator) {\n setOffline(!pathOr(true, ['onLine'], navigator))\n }\n }, [])\n\n useEffect(() => {\n if (window) {\n window.addEventListener('online', updateStatus)\n window.addEventListener('offline', updateStatus)\n }\n updateStatus()\n return function cleanUp() {\n if (window) {\n window.removeEventListener('online', updateStatus)\n window.removeEventListener('offline', updateStatus)\n }\n }\n }, [updateStatus])\n\n useEffect(() => {\n if (offline && !toastState.currentToast) {\n if (!showingOffline) {\n showToast(toastConfig)\n }\n setShowingOffline(!showingOffline)\n } else if (\n !offline &&\n toastState.isToastVisible &&\n path(['currentToast', 'message'], toastState) === toastConfig.message\n ) {\n hideToast()\n setShowingOffline(false)\n }\n }, [offline, toastState, toastConfig, showingOffline, showToast, hideToast])\n\n return null\n}\n\nexport default injectIntl(NetworkStatusToast)\n\n```" } ]
code_store-on-localhost_e8f9b035
[ { "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 store-on-localhost/src/monobloco/components/PageViewPixel.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\n/* eslint-disable react-hooks/exhaustive-deps */\nimport { canUseDOM } from 'exenv'\nimport { useMemo } from 'react'\n\nimport { useRuntime } from '../../vtex.render-runtime'\nimport useDataPixel from '../hooks/useDataPixel'\n\ninterface UsePageViewArgs {\n title?: string\n cacheKey?: string\n skip?: boolean\n}\n\nexport const usePageView = ({ title, cacheKey, skip }: UsePageViewArgs = {}) => {\n const { route, account } = useRuntime()\n const pixelCacheKey = cacheKey || route.routeId\n\n const eventData = useMemo(() => {\n if (!canUseDOM || skip) {\n return null\n }\n\n return {\n event: 'pageView',\n pageTitle: title || document.title,\n pageUrl: window.location.href,\n referrer:\n document.referrer.indexOf(window.location.origin) === 0\n ? undefined\n : document.referrer,\n accountName: account,\n routeId: route && route.routeId ? route.routeId : '',\n }\n }, [account, title, canUseDOM, pixelCacheKey])\n\n useDataPixel(skip ? null : eventData, pixelCacheKey)\n}\n\n// Those pages already use the hook above (`usePageView`)\n// They need to handle the pageView event because they set the page title async\nconst SKIP_PAGES = ['store.search', 'store.product']\n\n/** When you navigate to a new page, the route object will remain the one from the previous route.\n * So we save the ref on the first mount. After that, we wait for the first time route changes to send a page view with the correct title.\n * A possible better implementation for the future, is add a loading state in the route object.\n */\nconst PageViewPixel = ({ title }: Partial<UsePageViewArgs>) => {\n const { route } = useRuntime()\n\n const skip = route && SKIP_PAGES.some(routeId => route.routeId.indexOf(routeId) === 0)\n usePageView({ title, skip })\n\n return null\n}\n\nexport default PageViewPixel\n\n```" } ]
code_store-on-localhost_fb03da49
[ { "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 store-on-localhost/src/monobloco/hooks/useDataPixel.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { useEffect, useRef } from 'react'\nimport {usePixel} from '../components/new/PixelContext/PixelContext'\nimport { isEmpty } from 'ramda'\n\ntype Data = unknown[] | unknown\n\nconst useDataPixel = (data: Data, pageIdentifier: string = '', isLoading = false) => {\n const { push } = usePixel()\n const previousIdRef = useRef<string|null>(null)\n\n const previousId = previousIdRef.current\n\n useEffect(() => {\n if (pageIdentifier && !isLoading && previousId !== pageIdentifier) {\n if (!data || isEmpty(data)) {\n return\n }\n if (Array.isArray(data)) {\n data.forEach(push)\n } else {\n push(data as any)\n }\n\n previousIdRef.current = pageIdentifier\n }\n }, [data, isLoading, pageIdentifier, previousId, push])\n}\n\nexport default useDataPixel\n\n```" } ]
code_store-on-localhost_b1e65275
[ { "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 store-on-localhost/src/monobloco/components/new/FormatCurrency/formatCurrency.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { WrappedComponentProps } from 'react-intl'\n\ninterface FormatCurrencyParams extends WrappedComponentProps {\n value: number\n culture: {\n currency: string\n customCurrencyDecimalDigits?: number | null\n customCurrencySymbol?: string | null\n }\n}\n\nexport default function formatCurrency({\n intl,\n culture,\n value,\n}: FormatCurrencyParams) {\n\n return intl.formatNumber(value, {\n style: 'currency',\n currency: culture.currency,\n ...(culture.customCurrencyDecimalDigits != null\n ? { minimumFractionDigits: culture.customCurrencyDecimalDigits }\n : {}),\n })\n}\n\n```" } ]
code_store-on-localhost_b49d7495
[ { "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 store-on-localhost/src/monobloco/components/new/FormatCurrency/FormattedCurrency.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { FC, Fragment } from 'react'\nimport { useRuntime } from '../../../../vtex.render-runtime'\nimport { injectIntl, WrappedComponentProps } from 'react-intl'\n\nconst FormattedCurrency: FC<FormattedCurrencyProps & WrappedComponentProps> = ({\n value,\n intl,\n}) => {\n const { culture } = useRuntime()\n\n const number = intl.formatNumber(value, {\n style: 'currency',\n currency: culture.currency,\n ...(culture.customCurrencyDecimalDigits != null\n ? { minimumFractionDigits: culture.customCurrencyDecimalDigits }\n : {}),\n })\n\n return (\n <Fragment>\n {number}\n </Fragment>\n )\n}\n\ninterface FormattedCurrencyProps {\n value: number\n}\n\nexport default injectIntl(FormattedCurrency)\n\n```" } ]
code_store-on-localhost_bb63e9f8
[ { "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 store-on-localhost/src/monobloco/components/new/StackLayout/index.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { defineMessages } from 'react-intl'\nimport useCssHandles from '../CssHandles/useCssHandles'\nimport applyModifiers from '../CssHandles/applyModifiers'\n\nconst CSS_HANDLES = ['stackContainer', 'stackItem'] as const\n\ninterface Props {\n zIndexOffset?: number\n blockClass?: string\n}\n\nconst StackLayout: StorefrontFunctionComponent<Props> = ({\n children,\n zIndexOffset = 0,\n blockClass,\n}) => {\n const handles = useCssHandles(CSS_HANDLES,{blockClass})\n return (\n <div className={`${handles.stackContainer} relative`}>\n {React.Children.toArray(children).map((child, idx) => {\n\n // This allows the user customize the stackItem via CSS, via the blockClass of each child\n const childBlockClass = (child as any)?.props?.blockProps?.blockClass || ''\n let stackItemBlockClass = ''\n if (childBlockClass) {\n stackItemBlockClass = applyModifiers(handles.stackItem, childBlockClass)\n }\n\n if (idx === 0) {\n return (\n <div\n key={idx}\n className={`${applyModifiers(handles.stackItem, 'first')} ${stackItemBlockClass}`}\n style={{ zIndex: zIndexOffset + 1 }}\n >\n {child}\n </div>\n )\n }\n\n return (\n <div\n key={idx}\n className={`${handles.stackItem} absolute top-0 left-0 w-auto h-auto ${stackItemBlockClass}`}\n style={{ zIndex: zIndexOffset + idx + 1 }}\n >\n {child}\n </div>\n )\n })}\n </div>\n )\n}\n\nconst messages = defineMessages({\n title: {\n defaultMessage: '',\n id: 'admin/editor.stack-layout.title',\n },\n description: {\n defaultMessage: '',\n id: 'admin/editor.stack-layout.description',\n },\n})\n\nStackLayout.schema = {\n title: messages.title.id,\n description: messages.description.id,\n}\n\nexport default StackLayout\n\n```" } ]
code_store-on-localhost_bbab0ca8
[ { "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 store-on-localhost/src/monobloco/components/new/Drawer/styles.css from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.hiddenBody {\n overflow: hidden;\n position: fixed;\n bottom: 0;\n left: 0;\n}\n\n```" } ]
code_store-on-localhost_1ff7b933
[ { "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 store-on-localhost/src/monobloco/components/new/Drawer/Drawer.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { ReactElement, Suspense, useReducer } from 'react'\nimport { defineMessages } from 'react-intl'\n\nimport IconClose from '../StoreIcons/IconClose'\nimport IconMenu from '../StoreIcons/IconMenu'\nimport useCssHandles from '../CssHandles/useCssHandles'\n\nimport Overlay from './Overlay'\nimport Portal from './Portal'\nimport useLockScroll from './modules/useLockScroll'\n\nconst Swipable = React.lazy(() => import('./Swipable'))\n\ninterface MenuState {\n isOpen: boolean\n hasBeenOpened: boolean\n}\n\ninterface MenuAction {\n type: 'open' | 'close'\n}\n\nconst initialMenuState: MenuState = {\n isOpen: false,\n hasBeenOpened: false,\n}\n\nfunction menuReducer(state: MenuState, action: MenuAction) {\n switch (action.type) {\n case 'open':\n return {\n ...state,\n isOpen: true,\n hasBeenOpened: true,\n }\n case 'close':\n return {\n ...state,\n isOpen: false,\n }\n default:\n return state\n }\n}\n\nconst useMenuState = () => {\n const [state, dispatch] = useReducer(menuReducer, initialMenuState)\n const setLockScroll = useLockScroll()\n\n const setMenuOpen = (value: boolean) => {\n dispatch({ type: value ? 'open' : 'close' })\n setLockScroll(value)\n }\n\n const openMenu = () => setMenuOpen(true)\n const closeMenu = () => setMenuOpen(false)\n\n return {\n state,\n openMenu,\n closeMenu,\n }\n}\n\nconst CSS_HANDLES = [\n 'openIconContainer',\n 'drawer',\n 'closeIconContainer',\n 'childrenContainer',\n 'closeIconButton',\n]\n\nconst Drawer: any = ({\n width,\n customIcon,\n maxWidth = 450,\n isFullWidth,\n slideDirection = 'horizontal',\n children,\n}) => {\n const { state: menuState, openMenu, closeMenu } = useMenuState()\n const { isOpen: isMenuOpen, hasBeenOpened: hasMenuBeenOpened } = menuState\n const handles = useCssHandles(CSS_HANDLES)\n\n const direction =\n slideDirection === 'horizontal' || slideDirection === 'leftToRight'\n ? 'left'\n : 'right'\n\n const swipeHandler = direction === 'left' ? 'onSwipeLeft' : 'onSwipeRight'\n\n return (\n <>\n <div\n className={`pa4 pointer ${handles.openIconContainer}`}\n onClick={openMenu}\n aria-hidden\n >\n {customIcon || <IconMenu size={20} />}\n </div>\n <Portal>\n <Overlay visible={isMenuOpen} onClick={closeMenu} />\n <Suspense fallback={<React.Fragment />}>\n <Swipable\n {...{\n [swipeHandler]: closeMenu,\n }}\n enabled={isMenuOpen}\n position={isMenuOpen ? 'center' : direction}\n allowOutsideDrag\n className={`${handles.drawer} ${\n direction === 'right' ? 'right-0' : 'left-0'\n } fixed top-0 bottom-0 bg-base z-999 flex flex-column`}\n style={{\n width: width || (isFullWidth ? '100%' : '85%'),\n maxWidth,\n minWidth: 280,\n pointerEvents: isMenuOpen ? 'auto' : 'none',\n }}\n >\n <div\n style={{\n WebkitOverflowScrolling: 'touch',\n overflowY: 'scroll',\n }}\n >\n <div className={`flex ${handles.closeIconContainer}`}>\n <button\n className={`${handles.closeIconButton} pa4 pointer bg-transparent transparent bn pointer`}\n onClick={closeMenu}\n >\n <IconClose size={30} type=\"line\" />\n </button>\n </div>\n <div className={`${handles.childrenContainer} flex flex-grow-1`}>\n {hasMenuBeenOpened && children}\n </div>\n </div>\n </Swipable>\n </Suspense>\n </Portal>\n </>\n )\n}\n\nconst messages = defineMessages({\n title: {\n defaultMessage: '',\n id: 'admin/editor.drawer.title',\n },\n})\n\nDrawer.getSchema = () => {\n return {\n title: messages.title.id,\n }\n}\n\nexport default Drawer as any\n\n```" } ]