id
stringlengths
12
53
messages
listlengths
3
3
code_admin-graphql-ide_3c078621
[ { "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-graphql-ide/node/middlewares/graphqlProxy.ts from the admin-graphql-ide VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ForbiddenError } from '@vtex/api'\nimport bodyParser from 'co-body'\nimport { path, pick } from 'ramda'\n\nimport type { Clients } from '../clients'\n\nconst EMPTY_OBJECT = {}\n\nexport const ensureAdminUser = async (\n clients: Pick<Clients, 'sphinx' | 'vtexID'>,\n idToken: string | undefined\n) => {\n const { sphinx, vtexID } = clients\n\n if (!idToken) {\n throw new ForbiddenError('No VtexIdclientAutCookie provided')\n }\n\n const { user: email } =\n (await vtexID.getIdUser(idToken)) || (EMPTY_OBJECT as any)\n\n if (!email) {\n throw new ForbiddenError(\n 'User must have a valid email to use admin-graphql-ide'\n )\n }\n\n const isAdminUser = await sphinx.isAdmin(email)\n\n if (!isAdminUser) {\n throw new ForbiddenError('User must be admin to use admin-graphql-ide')\n }\n}\n\nexport async function graphqlProxy(ctx: Context) {\n const {\n clients: { graphqlServer },\n vtex: {\n route: {\n params: { appId: paramAppId },\n },\n },\n } = ctx\n\n const idToken = ctx.cookies.get('VtexIdclientAutCookie')\n\n await ensureAdminUser(ctx.clients, idToken)\n\n const body = await bodyParser(ctx.req)\n\n const appId = paramAppId as string\n\n const headersToSend = [\n 'accept',\n 'accept-language',\n 'authorization',\n 'content-length',\n 'content-type',\n 'cookie',\n 'rest-range',\n 'user-agent',\n 'vtexidclientautcookie',\n 'x-forwarded-host',\n ]\n\n const headers = pick(headersToSend, ctx.request.headers)\n\n ctx.body = await graphqlServer\n .proxyGraphiQL(body, appId, headers)\n .catch(path(['response', 'data']))\n ctx.status = 200\n}\n\n```" } ]
code_admin-graphql-ide_3ad05680
[ { "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-graphql-ide/node/resolvers/apps.ts from the admin-graphql-ide VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { AppMetaInfo, Apps } from '@vtex/api'\nimport { filter as filterP } from 'bluebird'\nimport { filter, pluck } from 'ramda'\n\nimport type { Query } from '../../typedql/schema'\n\nconst TARGET_APP_NAME = 'vtex.graphql-server'\nconst TARGET_APP_MAJOR = '1'\nconst SCHEMA_GRAPHQL = 'public/schema.graphql'\n\nconst filterGraphQLApps = (metaInfos: AppMetaInfo[]) =>\n filter(({ _resolvedDependencies }) => {\n const graphqlServerVersion = _resolvedDependencies[TARGET_APP_NAME]\n\n if (graphqlServerVersion) {\n const [major] = graphqlServerVersion.split('.')\n\n return major === TARGET_APP_MAJOR\n }\n\n return false\n }, metaInfos)\n\nconst filterAppWithSchema = (appsClient: Apps, metaInfos: AppMetaInfo[]) =>\n filterP(metaInfos, async ({ id }) => {\n try {\n const schema = await appsClient.getAppFile(id, SCHEMA_GRAPHQL)\n\n return !!schema\n } catch (_) {\n return false\n }\n })\n\nexport const apps = async (\n _: any,\n __: any,\n ctx: Context\n): Promise<Query['apps']> => {\n const {\n clients: { apps: appsClient },\n } = ctx\n\n const metaInfos = await appsClient.getAppsMetaInfos()\n\n const graphqlApps = filterGraphQLApps(metaInfos)\n const appsWithSchema = await filterAppWithSchema(appsClient, graphqlApps)\n\n return pluck('id', appsWithSchema)\n}\n\n```" } ]
code_admin-graphql-ide_2a61c5dd
[ { "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-graphql-ide/react/typings/vtex.render-runtime.d.ts from the admin-graphql-ide VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* Typings for `render-runtime` */\ndeclare module 'vtex.render-runtime' {\n import { Component, ComponentType, ReactElement } from 'react'\n\n export interface NavigationOptions {\n page: string\n params?: any\n }\n\n export interface RenderContextProps {\n runtime: {\n navigate: (options: NavigationOptions) => void\n }\n }\n\n export const ExtensionPoint: ReactElement\n export const Helmet: ComponentType<any>\n export const Link: ReactElement\n export const NoSSR: ComponentType<any>\n export const RenderContextConsumer: ReactElement\n export const canUseDOM: boolean\n export const withRuntimeContext: <TOriginalProps extends {}>(\n Component: ComponentType<TOriginalProps & RenderContextProps>\n ) => ComponentType<TOriginalProps>\n\n export const buildCacheLocator = (app: string, type: string, cacheId: string) => string\n\n interface RenderComponent<P = {}, S = {}> extends Component<P, S> {\n getCustomMessages?: (locale: string) => any\n schema: ComponentSchema\n getSchema?: (a: any, b: any?) => ComponentSchema\n uiSchema: UISchema\n }\n\n export interface ComponentsRegistry {\n [component: string]: RenderComponent<any, any>\n }\n\n export interface Window extends Window {\n __RENDER_7_COMPONENTS__: ComponentsRegistry\n }\n\n let global: Window\n}\n\n```" } ]
code_admin-graphql-ide_29c0c189
[ { "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-graphql-ide/react/typings/graphiql.d.ts from the admin-graphql-ide VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module 'graphiql' {\n const value: any\n export default value\n}\n\n```" } ]
code_admin-graphql-ide_8e0bd5f5
[ { "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-graphql-ide/react/typings/graphqlQueries.d.ts from the admin-graphql-ide VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*.graphql' {\n import { DocumentNode } from 'graphql'\n\n const value: DocumentNode\n export default value\n}\n\n```" } ]
code_admin-graphql-ide_052cb01d
[ { "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-graphql-ide/react/typings/vtex.styleguide.d.ts from the admin-graphql-ide VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.styleguide' {\n import { ComponentType } from 'react'\n\n export const Alert: ComponentType<any>\n export const Checkbox: ComponentType<any>\n export const Badge: ComponentType<any>\n export const Box: ComponentType<any>\n export const Button: ComponentType<any>\n export const Card: ComponentType<any>\n export const Dropdown: ComponentType<any>\n export const EmptyState: ComponentType<any>\n export const IconArrowBack: ComponentType<any>\n export const IconEdit: ComponentType<any>\n export const Input: ComponentType<any>\n export const Modal: ComponentType<any>\n export const PageHeader: ComponentType<any>\n export const Pagination: ComponentType<any>\n export const Radio: ComponentType<any>\n export const Spinner: ComponentType<any>\n export const Tab: ComponentType<any>\n export const Table: ComponentType<any>\n export const Tabs: ComponentType<any>\n export const Toggle: ComponentType<any>\n export const Layout: ComponentType<any>\n export const PageBlock: ComponentType<any>\n}\n\n```" } ]
code_admin-graphql-ide_7e38a0e9
[ { "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-graphql-ide/react/utils/storage.ts from the admin-graphql-ide VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nclass ScopedStorage implements Storage {\n private keys: Set<string>\n\n constructor(\n private namespace: string\n ) {\n this.keys = new Set<string>()\n }\n\n public get length(): number {\n return this.keys.size\n }\n\n public setItem = (key: string, value: string) => {\n const scopedKey = this.addScope(key)\n this.keys.add(scopedKey)\n window.localStorage.setItem(scopedKey, value)\n }\n\n public clear = () => {\n this.keys.forEach(window.localStorage.removeItem)\n }\n\n public removeItem = (key: string) => window.localStorage.removeItem(this.addScope(key))\n\n public key = (index: number ) => window.localStorage.key(index)\n\n public getItem = (key: string) => window.localStorage.getItem(this.addScope(key))\n\n private addScope = (key: string) => `${this.namespace}::${key}`\n}\n\nconst storage: Record<string, Storage> = {}\n\nexport const getOrCreateScopedStorage = (namespace: string) => {\n if (!storage[namespace]) {\n storage[namespace] = new ScopedStorage(namespace)\n }\n return storage[namespace]\n}\n```" } ]
code_admin-graphql-ide_7a159019
[ { "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-graphql-ide/react/components/Controller.tsx from the admin-graphql-ide VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport GraphiQL from 'graphiql'\nimport { buildClientSchema, GraphQLSchema, IntrospectionQuery, introspectionQuery } from 'graphql'\nimport { path } from 'ramda'\nimport React, { Fragment } from 'react'\nimport { defineMessages, InjectedIntlProps, injectIntl } from 'react-intl'\nimport { EXPERIMENTAL_Select, Spinner } from 'vtex.styleguide'\n\nimport { getOrCreateScopedStorage } from '../utils/storage'\nimport { ErrorState } from './ErrorState'\nimport { NoAppSelected } from './NoAppSelected'\n\ntype Fetcher = (params: any) => Promise<string>\n\nenum ViewState {\n ON_ERROR = 'error',\n ON_SELECT_APP = 'select',\n ON_GRAPHIQL = 'graphiql',\n ON_FETCHING_SCHEMA = 'fetch',\n}\n\ninterface State {\n error: boolean\n chosenAppId: string | undefined\n schema: GraphQLSchema | undefined\n fetcher: Fetcher | undefined\n mode: ViewState\n}\n\ninterface Props extends InjectedIntlProps {\n apps: string[]\n}\n\nconst fetcherForApp = (appId: string) => (params: any) => fetch(`/_v/private/admin-graphql-ide/v0/${appId}`, {\n body: JSON.stringify(params),\n headers: { 'Content-Type': 'application/json' },\n method: 'post',\n}).then(response => response.json())\n\nconst messages = defineMessages({\n appChooser: {\n id: 'admin/controller.app-picker',\n defaultMessage: \"Choose your app from the list below\"\n }\n})\n\nclass GraphiQLControllerComponent extends React.Component<Props, State> {\n constructor(props: Props) {\n super(props)\n this.state = {\n chosenAppId: undefined,\n error: false,\n fetcher: undefined,\n schema: undefined,\n mode: ViewState.ON_SELECT_APP\n }\n }\n\n public setState = (state: any, cb?: () => void) => {\n const { schema, chosenAppId, error, fetcher }: any = typeof state === 'function' ? state(this.state) : { ...this.state, ...state }\n let mode: ViewState\n if (error) {\n mode = ViewState.ON_ERROR\n } else if (!schema && fetcher && chosenAppId) {\n mode = ViewState.ON_FETCHING_SCHEMA\n } else if (schema && chosenAppId) {\n mode = ViewState.ON_GRAPHIQL\n } else {\n mode = ViewState.ON_SELECT_APP\n }\n\n super.setState({\n schema,\n chosenAppId,\n error,\n fetcher,\n mode,\n }, () => {\n if (mode === ViewState.ON_FETCHING_SCHEMA) {\n this.fetchSchema()\n }\n if (cb) {\n cb()\n }\n })\n }\n\n public render = () => (\n <Fragment>\n <div className=\"mb5 z-max\">\n <EXPERIMENTAL_Select\n label={this.props.intl.formatMessage(messages.appChooser)}\n options={this.props.apps.map(app => ({ value: app, label: app }))}\n multi={false}\n onChange={(chosen: { value?: string } | null) => this.setState(\n (oldState: State) => {\n const chosenAppId = chosen ? chosen.value : undefined\n return {\n ...oldState,\n chosenAppId,\n fetcher: chosenAppId ? fetcherForApp(chosenAppId) : undefined,\n schema: undefined,\n }\n }\n )}\n />\n </div>\n {\n this.state.mode === ViewState.ON_GRAPHIQL\n ? (\n <GraphiQL\n fetcher={this.state.fetcher}\n storage={getOrCreateScopedStorage(this.state.chosenAppId!)}\n schema={this.state.schema}\n />\n )\n : this.state.mode === ViewState.ON_SELECT_APP\n ? (\n <NoAppSelected />\n )\n : this.state.mode === ViewState.ON_FETCHING_SCHEMA\n ? (\n <Spinner />\n )\n : (\n <ErrorState\n onRetryClick={() => this.setState({ error: false })}\n />\n )\n }\n </Fragment>\n )\n\n private fetchSchema = async () => {\n try {\n const response = await this.state.fetcher!({ query: introspectionQuery })\n const schema = path(['data'], response) as IntrospectionQuery | undefined\n this.setState({\n schema: schema && buildClientSchema(schema),\n error: schema ? false : true,\n })\n }\n catch (_) {\n this.setState({ error: true })\n }\n }\n}\n\n\nexport const GraphiQLController = injectIntl(GraphiQLControllerComponent)\n```" } ]
code_admin-graphql-ide_6215ade6
[ { "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-graphql-ide/react/components/ErrorState.tsx from the admin-graphql-ide VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { FunctionComponent } from 'react'\nimport { FormattedMessage, injectIntl, InjectedIntlProps, defineMessages } from 'react-intl'\nimport { Button, EmptyState } from 'vtex.styleguide'\n\ninterface Props extends InjectedIntlProps {\n onRetryClick: () => void\n}\n\nconst messages = defineMessages({\n errorShortMessage: {\n id: 'admin/error.title',\n defaultMessage: 'Something bad happened'\n }\n})\n\nconst ErrorStateComponent: FunctionComponent<Props> = ({onRetryClick, intl}) => (\n <EmptyState title={intl.formatMessage(messages.errorShortMessage)}>\n <div className=\"pt5\">\n <Button variation=\"secondary\" size=\"small\" onClick={onRetryClick}>\n <span className=\"flex align-baseline\">\n <FormattedMessage id=\"admin/error.state\" defaultMessage=\"Try Again\" />\n </span>\n </Button>\n </div>\n </EmptyState>\n)\n\nexport const ErrorState = injectIntl(ErrorStateComponent)\n```" } ]
code_admin-graphql-ide_cd4582ff
[ { "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-graphql-ide/react/components/NoAppSelected.tsx from the admin-graphql-ide VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { FunctionComponent } from 'react'\nimport { defineMessages, FormattedMessage, InjectedIntlProps, injectIntl } from 'react-intl'\nimport { EmptyState } from 'vtex.styleguide'\n\nconst messages = defineMessages({\n title: {\n id: 'admin/no-app-selected.title',\n defaultMessage: 'Choose an App'\n }\n})\n\nconst NoAppSelectedComponent: FunctionComponent<InjectedIntlProps> = ({intl}) => (\n <EmptyState title={intl.formatMessage(messages.title)}>\n <p>\n <FormattedMessage \n id='admin/no-app-selected.state'\n defaultMessage=\"Please choose an App to start making queries to\"\n />\n </p>\n </EmptyState>\n)\n\nexport const NoAppSelected = injectIntl(NoAppSelectedComponent)\n```" } ]
code_admin-graphql-ide_d53f4100
[ { "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-graphql-ide/react/graphql/getApps.tsx from the admin-graphql-ide VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { FunctionComponent } from 'react'\nimport { Query as QueryComponent } from 'react-apollo'\n\nimport { Query } from '../../typedql/schema'\nimport getAppsQuery from './apps.graphql'\n\ntype Data = Pick<Query, 'apps'>\n\ninterface Props {\n children: (data: any) => React.ReactNode\n}\n\nexport const GetApps: FunctionComponent<Props> = ({children}) => (\n <QueryComponent<Data> query={getAppsQuery}>\n {({data, loading}) => {\n if (loading) {\n return null\n }\n return children!(data)\n }}\n </QueryComponent>\n)\n```" } ]
code_admin-graphql-ide_1620402f
[ { "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-graphql-ide/react/graphql/apps.graphql from the admin-graphql-ide VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nquery GetApps {\n apps @context(provider: \"vtex.admin-graphql-ide\")\n}\n```" } ]
code_landing-pages_6c5f779d
[ { "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 landing-pages/docs/README.md from the landing-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# VTEX Landing Pages\n\nThis app aggregates all landing pages served by VTEX IO.\n\nEach landing page has its own IO App:\n\n- [TETRIX](https://tetrix.vtex.com): https://github.com/vtex-apps/tetrix \n- [VTEX Code Cup](https://codecup.vtex.com): https://github.com/vtex-apps/code-cup \n- [VTEX IO](https://vtex.io): https://github.com/vtex-apps/io-landing \n- [VTEX IO Docs](https://vtex.io/docs): https://github.com/vtex-apps/docs-ui\n\n```" } ]
code_affirm-components_f96cb811
[ { "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 affirm-components/docs/README.md from the affirm-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n📢 Use this project, [contribute](https://github.com/vtex-apps/affirm-components) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).\n\n# Affirm Components\n\nThis app provides promotional messaging components related to the Affirm payment method.\n\n## Configuration\n\n1. Follow the install instructions for [Affirm Payment](https://github.com/vtex-apps/affirm-payment)\n2. Add `\"vtex.affirm-components\": \"0.x\"` to your store-theme dependencies.\n3. Place the desired Affirm component blocks in your `/store/` folder.\n\nThe available blocks are:\n\n- `\"product-teaser.product.affirm\"`: This block should be placed on the product page (PDP). It displays a promotional message such as `As low as \\$\\__/mo at _% APR` followed by a `Prequalify now` or `Learn More` link.\n- `\"product-teaser.summary.affirm\"`: Similar to the above but designed to be placed on product shelves.\n\n## Customization\n\nIn order to apply CSS customizations to this and other blocks, follow the instructions given in the recipe on [Using CSS Handles for store customization](https://vtex.io/docs/recipes/style/using-css-handles-for-store-customization).\n\n| CSS Handles |\n|----------------------|\n| `affirmPromo` |\n| `affirmPromoSummary` |\n\n```" } ]
code_affirm-components_5cb0339c
[ { "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 affirm-components/react/package.json from the affirm-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"affirm-components\",\n \"version\": \"0.0.9\",\n \"description\": \"\",\n \"scripts\": {\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n },\n \"author\": \"VTEX\",\n \"license\": \"UNLICENSED\",\n \"dependencies\": {\n \"apollo-cache\": \"^1.3.4\",\n \"apollo-client\": \"^2.6.8\",\n \"apollo-link\": \"^1.2.13\",\n \"apollo-utilities\": \"^1.3.3\",\n \"graphql\": \"^14.0.2\",\n \"ramda\": \"^0.27.0\",\n \"react\": \"^16.8.6\",\n \"react-apollo\": \"^3.1.3\",\n \"react-dom\": \"^16.8.5\"\n },\n \"devDependencies\": {\n \"@types/bootstrap\": \"^4.3.0\",\n \"@types/graphql\": \"^14.0.5\",\n \"@types/jquery\": \"^3.3.34\",\n \"@types/node\": \"^10.14.4\",\n \"@types/ramda\": \"^0.27.0\",\n \"@types/react\": \"^16.8.8\",\n \"@types/react-dom\": \"^16.8.3\",\n \"vtex.affirm-components\": \"https://betocheckout--sandboxusdev.myvtex.com/_v/private/typings/linked/v1/vtex.affirm-components@0.0.5+build1644630177/public/@types/vtex.affirm-components\",\n \"vtex.affirm-payment\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.affirm-payment@2.1.8-beta.0/public/@types/vtex.affirm-payment\",\n \"vtex.css-handles\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.css-handles@0.4.4/public/@types/vtex.css-handles\",\n \"vtex.product-context\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.product-context@0.10.0/public/@types/vtex.product-context\",\n \"vtex.product-summary-context\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.product-summary-context@0.9.0/public/@types/vtex.product-summary-context\",\n \"vtex.product-teaser-interfaces\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.product-teaser-interfaces@1.0.2/public/_types/react\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.132.3/public/@types/vtex.render-runtime\",\n \"vtex.store\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store@2.122.0/public/@types/vtex.store\"\n }\n}\n\n```" } ]
code_affirm-components_e6b5efc3
[ { "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 affirm-components/react/AffirmPromo.tsx from the affirm-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport AffirmPromo from './components/AffirmPromo'\n\nexport default AffirmPromo\n\n```" } ]
code_affirm-components_7b485bee
[ { "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 affirm-components/react/AffirmSummaryPromo.tsx from the affirm-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport AffirmSummaryPromo from './components/AffirmSummaryPromo'\n\nexport default AffirmSummaryPromo\n\n```" } ]
code_affirm-components_ea41495e
[ { "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 affirm-components/store/interfaces.json from the affirm-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"product-teaser.product.affirm\": {\n \"component\": \"AffirmPromo\"\n },\n \"product-teaser.summary.affirm\": {\n \"component\": \"AffirmSummaryPromo\"\n }\n}\n\n```" } ]
code_affirm-components_6270af3e
[ { "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 affirm-components/public/metadata/messages/es-AR.json from the affirm-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n\n{\n \"name\": \"Affirm\",\n \"headline\": \"Permita que sus clientes paguen en cuotas con Affirm.\",\n \"overview\": \"Affirm es una forma sencilla y transparente de que los clientes paguen sus compras en cuotas. Al utilizar Affirm, puede mostrar un precio de pago mensual para cada ítem, mostrando a sus clientes un plan de pago de su elección y que se ajuste a su presupuesto. Conecte esta aplicación a su tienda VTEX y podrá ofrecer a sus clientes una forma alternativa de pagar en cuotas.\",\n \"features\": [\n \"Muestre opciones de financiación para los clientes en la página del producto\",\n \"Permita que sus clientes paguen a través del método de pago Affirm\"\n ],\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://help-tickets.vtex.com/en/support?app=vtex.affirm-payment\"\n }\n}\n```" } ]
code_affirm-components_116c17fd
[ { "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 affirm-components/public/metadata/messages/pt-BR.json from the affirm-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n\n{\n \"name\": \"Affirm\",\n \"headline\": \"Disponibilize aos seus clientes a opção de pagar a prazo com o Affirm.\",\n \"overview\": \"O Affirm oferece uma maneira simples e transparente de pagar compras a prazo. Ao utilizar o Affirm, é possível exibir o preço a ser pago mensalmente para cada item, disponibilizando aos clientes um cronograma de acordo com o orçamento desejado. Conecte este aplicativo à sua loja VTEX e empodere seus clientes com uma forma alternativa de pagamento a prazo.\",\n \"features\": [\n \"Exibe opções de financiamento para os clientes na página do produto\",\n \"Permite que os clientes paguem através do meio de pagamento Affirm\"\n ],\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://help-tickets.vtex.com/en/support?app=vtex.affirm-payment\"\n }\n}\n```" } ]
code_affirm-components_8c7f85cd
[ { "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 affirm-components/public/metadata/messages/en-US.json from the affirm-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n\n{\n \"name\": \"Affirm\",\n \"headline\": \"Allow shoppers to pay over time with Affirm.\",\n \"overview\": \"Affirm is a simple and transparent way for customers to pay for purchases over time. By using Affirm, you can display a monthly payment price for each item — showing shoppers a budget friendly schedule of their choosing. Connect this app to your VTEX store and you'll be able to empower your customers with an alternative way to pay over time.\",\n \"features\": [\n \"Displays financing options for shoppers on the product page\",\n \"Allows shoppers to pay through the Affirm payment method\"\n ],\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://help-tickets.vtex.com/en/support?app=vtex.affirm-payment\"\n }\n}\n```" } ]
code_affirm-components_e1236e0b
[ { "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 affirm-components/react/typings/storefront.d.ts from the affirm-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { FunctionComponent } from 'react'\n\ndeclare global {\n interface StorefrontFunctionComponent<P = {}> extends FunctionComponent<P> {\n getSchema?(props: P): object\n schema?: object\n }\n\n interface StorefrontComponent<P = {}, S = {}> extends Component<P, S> {\n getSchema?(props: P): object\n schema: object\n }\n}\n\n```" } ]
code_affirm-components_2259e386
[ { "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 affirm-components/react/typings/vtex.product-context.d.ts from the affirm-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.product-context/useProduct' {\n import { Context } from 'react'\n\n interface ProductContext {\n product: any\n selectedItem: any\n }\n\n export default function useProduct(): ProductContext\n}\n\n```" } ]
code_affirm-components_4d6cb952
[ { "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 affirm-components/react/typings/global.d.ts from the affirm-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare const vtex: any\ninterface Window extends Window {\n affirm: any\n _affirm_config: any\n modalTriggered: boolean\n}\n\n```" } ]
code_affirm-components_c954ead0
[ { "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 affirm-components/react/typings/vtex.product-summary-context.d.ts from the affirm-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.product-summary-context/ProductSummaryContext' {\n import { Context } from 'react'\n\n interface ProductSummaryContext {\n product: any\n isLoading: boolean\n }\n\n export function useProductSummary(): ProductSummaryContext\n}\n\n```" } ]
code_affirm-components_9d55b0f4
[ { "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 affirm-components/react/typings/graphql.d.ts from the affirm-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*.graphql' {\n import { DocumentNode } from 'graphql'\n\n const value: DocumentNode\n export default value\n}\n\n```" } ]
code_affirm-components_f3ef6aca
[ { "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 affirm-components/react/components/AffirmPromo.tsx from the affirm-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { useProduct } from 'vtex.product-context'\nimport React, { useEffect } from 'react'\nimport { useQuery } from 'react-apollo'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport useScriptLoader from './hooks/useScriptLoader'\nimport Settings from '../graphql/Settings.graphql'\n\ninterface AffirmPromoProps {\n affirmSettings: AffirmSettings\n}\n\ninterface AffirmSettings {\n publicApiKey: string\n isLive: boolean\n}\n\nconst CSS_HANDLES = ['affirmPromo'] as const\n\nconst AffirmPromoDiv: StorefrontFunctionComponent<AffirmPromoProps> = ({\n affirmSettings,\n}) => {\n const { publicApiKey = '', isLive = false } = affirmSettings\n\n const [affirm, { error }] = useScriptLoader(\n isLive\n ? 'https://cdn1.affirm.com/js/v2/affirm.js'\n : 'https://cdn1-sandbox.affirm.com/js/v2/affirm.js',\n 'affirm'\n )\n const productContext = useProduct()\n const product = productContext?.product\n const selectedItem = productContext?.selectedItem\n const selectedQty = productContext?.selectedQuantity ?? 1\n\n const handles = useCssHandles(CSS_HANDLES)\n\n useEffect(() => {\n if (!affirm || error || !publicApiKey) return\n\n window._affirm_config = {\n public_api_key: publicApiKey,\n }\n\n affirm.ui.refresh()\n }, [affirm, error, publicApiKey])\n\n useEffect(() => {\n if (!affirm || error || !publicApiKey) return\n\n affirm.ui.refresh()\n }, [selectedItem, selectedQty])\n\n if (!product || !selectedItem || !affirm || error || !publicApiKey) {\n return null\n }\n\n const price = selectedItem.sellers[0].commertialOffer.Price\n\n return (\n <p\n className={`affirm-as-low-as ${handles.affirmPromo}`}\n data-page-type=\"product\"\n data-amount={price * selectedQty * 100}\n ></p>\n )\n}\n\nconst AffirmPromo: StorefrontFunctionComponent = () => {\n const { data: settingsData } = useQuery(Settings, { ssr: false })\n\n if (!settingsData?.affirmSettings) return null\n\n return <AffirmPromoDiv affirmSettings={settingsData.affirmSettings} />\n}\n\nexport default AffirmPromo\n\n```" } ]
code_affirm-components_442d493b
[ { "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 affirm-components/react/components/AffirmSummaryPromo.tsx from the affirm-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { useProductSummary } from 'vtex.product-summary-context/ProductSummaryContext'\nimport React, { useEffect } from 'react'\nimport { useQuery } from 'react-apollo'\nimport { path, prop } from 'ramda'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport useScriptLoader from './hooks/useScriptLoader'\nimport Settings from '../graphql/Settings.graphql'\n\ninterface AffirmPromoProps {\n affirmSettings: AffirmSettings\n}\n\ninterface AffirmSettings {\n publicApiKey: string\n isLive: boolean\n}\n\nconst CSS_HANDLES = ['affirmPromoSummary'] as const\n\nconst AffirmSummaryPromoDiv: StorefrontFunctionComponent<AffirmPromoProps> = ({\n affirmSettings,\n}) => {\n const { publicApiKey = '', isLive = false } = affirmSettings\n\n const [affirm, { error }] = useScriptLoader(\n isLive\n ? 'https://cdn1.affirm.com/js/v2/affirm.js'\n : 'https://cdn1-sandbox.affirm.com/js/v2/affirm.js',\n 'affirm'\n )\n\n useEffect(() => {\n if (!affirm || error || !publicApiKey || window._affirm_config) return\n\n window._affirm_config = {\n public_api_key: publicApiKey,\n }\n affirm.ui.refresh()\n }, [affirm, error, publicApiKey])\n\n const handles = useCssHandles(CSS_HANDLES)\n const { product, isLoading } = useProductSummary()\n const commertialOffer = path<any>(\n ['sku', 'seller', 'commertialOffer'],\n product\n )\n\n const price = prop('Price', commertialOffer)\n\n if (\n isLoading ||\n !affirm ||\n !product ||\n !commertialOffer ||\n error ||\n !publicApiKey\n )\n return null\n\n return (\n <p\n className={`affirm-as-low-as ${handles.affirmPromoSummary}`}\n data-page-type=\"category\"\n data-amount={price * 100}\n ></p>\n )\n}\n\nconst AffirmSummaryPromo: StorefrontFunctionComponent = () => {\n const { data: settingsData } = useQuery(Settings, { ssr: false })\n\n if (!settingsData?.affirmSettings) return null\n\n return <AffirmSummaryPromoDiv affirmSettings={settingsData.affirmSettings} />\n}\n\nexport default AffirmSummaryPromo\n\n```" } ]
code_affirm-components_45c209ae
[ { "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 affirm-components/react/graphql/Settings.graphql from the affirm-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nquery Settings {\n affirmSettings @context(provider: \"vtex.affirm-payment\"){\n isLive\n enableKatapult\n companyName\n publicApiKey\n }\n}\n\n```" } ]
code_affirm-components_1d41e9ad
[ { "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 affirm-components/react/components/hooks/useScriptLoader.tsx from the affirm-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { useCallback, useEffect, useState } from 'react'\n\nconst useScriptLoader = <T extends object = any>(\n url: string,\n libName: string,\n init?: T\n) => {\n const [x, setX] = useState<T>(init as any)\n const [error, setError] = useState<string>('')\n\n const reload = useCallback(() => {\n const script = document.createElement('script')\n setError('')\n\n script.src = url\n script.async = true\n\n script.onload = () => {\n setX((window as any)[libName])\n document.body.removeChild(script)\n }\n\n script.onerror = () => {\n setError(`<script src=\"${url}\" /> error.`)\n document.body.removeChild(script)\n }\n\n script.onabort = () => {\n setError(`<script src=\"${url}\" /> was aborted.`)\n document.body.removeChild(script)\n }\n\n document.body.appendChild(script)\n\n return () => {}\n }, [libName, url])\n\n useEffect(() => {\n return reload()\n }, [reload, url])\n\n const helper = {\n error,\n retry: reload,\n }\n const anwser: [typeof x, typeof helper] = [x, helper]\n return anwser\n}\n\nexport default useScriptLoader\n\n```" } ]
code_responsive-values_24887c7e
[ { "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 responsive-values/docs/README.md from the responsive-values VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# vtex.responsive-values\n\n<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->\n\n[![All Contributors](https://img.shields.io/badge/all_contributors-0-orange.svg?style=flat-square)](#contributors-)\n\n<!-- ALL-CONTRIBUTORS-BADGE:END -->\n\nUtility for using props that accept different values for different devices or media queries.\n\nFor example, a given prop could accept both just a number...\n\n```js\nprops: {\n quantity: 1,\n}\n```\n\n...or different values depending on the device or a media query:\n\n```js\nprops: {\n quantity: {\n mobile: 1,\n desktop: 2,\n '(min-width: 1500px)': 4,\n }\n}\n```\n\n...and the component, in turn, would use it like this:\n\n```js\nimport { useResponsiveValue } from 'vtex.responsive-values'\n\nconst MyComponent = ({ quantity }) => {\n const quantity = useResponsiveValue(quantity)\n\n return <span>{quantity}</span>\n}\n\n<MyComponent quantity={1} /> {/* always returns 1 */}\n\n<MyComponent quantity={{\n '(min-width: 1500px)': 4,\n desktop: 2,\n mobile: 1,\n}} /> {/* returns 1 on mobile devices, 2 on desktop */}\n```\n\nAlternately, if you want to apply it to multiple values at once, or even the entire `props` object, you can use the hook `useResponsiveValues` (notice the plural) hook.\n\n```tsx\nimport { useResponsiveValues } from 'vtex.responsive-values'\n\nconst MyComponent = props => {\n const { margin, padding } = useResponsiveValues(\n {\n margin: props.margin,\n padding: props.padding\n }\n )\n\n return (\n <section style={{ margin, padding }}>\n <span>{props.children}</span>\n </section>\n )\n}\n\n<MyComponent margin={4} padding={4} /> {/* always returns margin 4 / padding 4 */}\n\n<MyComponent\n margin={{\n desktop: 4,\n mobile: 2,\n }}\n padding={{\n desktop: 4,\n mobile: 2,\n }}\n/> {/* returns 1 on mobile devices, 2 on desktop */}\n```\n\nThere are some things to keep in mind when using media queries:\n\n- Media queries take precedence over devices. If one matches, any device-specific value is ignored.\n- Media queries are written following the [standard media query syntax](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries#Syntax).\n- The definiton order matters. If more than one media query is matched, the first matched one is used.\n\n## API\n\nProps that use this hook accept either a value by itself, or an object with the following options: `phone` and `tablet` separately (or just `mobile` for both), `desktop` and generic media queries.\n\nIf there is any missing device, it will fallback to the next largest one. For example, if only the values of `phone` and `desktop` are passed, `tablet` devices will receive the value from `desktop`. Media queries have no fallback behavior.\n\n## Contributors ✨\n\nThanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):\n\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n<!-- markdownlint-enable -->\n<!-- prettier-ignore-end -->\n\n<!-- ALL-CONTRIBUTORS-LIST:END -->\n\nThis project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!\n\n```" } ]
code_responsive-values_78665bef
[ { "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 responsive-values/react/ResponsiveValuesTypes.ts from the responsive-values VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/** The user is able to input `mobile` as a device (as opposed to `desktop`),\n * but the output will be converted to `phone` and `tablet` */\n\nexport type InputDevice = 'mobile' | 'phone' | 'tablet' | 'desktop'\nexport type OutputDevice = 'phone' | 'tablet' | 'desktop'\n\n// TODO: replace that `| string` with `MediaQueryString` when IO supports TS 4.1+\n// type MinMax = 'min' | 'max'\n// type Dimensions = 'width' | 'height'\n// type Units = 'rem' | 'px' | 'px' | '%'\n// type MediaQueryProperty = `${MinMax}-${Dimensions}`\n// export type MediaQueryString = `(${MediaQueryProperty}:${number}${Units})`\nexport type ResponsiveInput<T> = Record<InputDevice | string, T>\n\nexport type ResponsiveValue<T> = T | ResponsiveInput<T>\n\n// We can't know the values types beforehand, so we default them to unknown\nexport type ResponsiveValues = Record<string, ResponsiveValue<unknown>>\n\n// Gets the type of a value wrapped in ResponsiveValues\nexport type GetResponsiveValueType<\n T extends ResponsiveValue<unknown>\n> = T extends ResponsiveValue<infer U> ? U : never\n\n```" } ]
code_responsive-values_90e0503d
[ { "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 responsive-values/react/useResponsiveValues.ts from the responsive-values VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { useDevice } from 'vtex.device-detector'\n\nimport type {\n GetResponsiveValueType,\n ResponsiveValues,\n} from './ResponsiveValuesTypes'\nimport { normalizeResponsiveInputs } from './modules/normalizeResponsiveInput'\nimport {\n useMediaQueryList,\n findFirstMatchingQuery,\n} from './hooks/useMediaQueryList'\n\ntype UsedResponsiveValues<Input> = {\n [key in keyof Input]: GetResponsiveValueType<Input[key]>\n}\n\nconst useResponsiveValues = <Input extends ResponsiveValues>(\n input: Input\n): UsedResponsiveValues<Input> => {\n const { device } = useDevice()\n\n const { inputList, queryList } = normalizeResponsiveInputs(input)\n const { mediaQueries } = useMediaQueryList(queryList)\n\n const result = {} as UsedResponsiveValues<Input>\n\n inputList.forEach(([key, values]) => {\n if (Object.keys(values.queries).length > 0) {\n const matched = findFirstMatchingQuery(mediaQueries)\n\n if (matched) {\n result[key] = values.queries[matched] as GetResponsiveValueType<\n Input[typeof key]\n >\n\n return\n }\n }\n\n result[key] = values.devices[device] as GetResponsiveValueType<\n Input[typeof key]\n >\n })\n\n return result\n}\n\nexport default useResponsiveValues\n\n```" } ]
code_responsive-values_48e94c39
[ { "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 responsive-values/react/package.json from the responsive-values VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"scripts\": {\n \"lint\": \"tsc --noEmit && eslint --quiet --fix --ext ts,tsx .\",\n \"test\": \"vtex-test-tools test\"\n },\n \"dependencies\": {\n \"apollo-client\": \"^2.6.3\",\n \"react\": \"^16.8.6\",\n \"react-apollo\": \"^2.5.8\",\n \"react-dom\": \"^16.8.6\",\n \"react-intl\": \"3\"\n },\n \"devDependencies\": {\n \"@apollo/react-testing\": \"^4.0.0\",\n \"@testing-library/react-hooks\": \"^3.4.1\",\n \"@types/graphql\": \"^14.2.2\",\n \"@types/react\": \"^16.8.22\",\n \"@types/react-intl\": \"^2.3.18\",\n \"@vtex/test-tools\": \"^3.1.0\",\n \"typescript\": \"3.9.7\"\n },\n \"version\": \"0.4.2\"\n}\n\n```" } ]
code_responsive-values_1968a565
[ { "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 responsive-values/react/useResponsiveValue.ts from the responsive-values VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { useDevice } from 'vtex.device-detector'\n\nimport type { ResponsiveValue } from './ResponsiveValuesTypes'\nimport { normalizeResponsiveInput } from './modules/normalizeResponsiveInput'\nimport {\n useMediaQueryList,\n findFirstMatchingQuery,\n} from './hooks/useMediaQueryList'\n\nconst useResponsiveValue = <T>(input: ResponsiveValue<T>): T => {\n const { device } = useDevice()\n const { devices, queries } = normalizeResponsiveInput(input)\n const queryList = Object.keys(queries)\n const { mediaQueries } = useMediaQueryList(queryList)\n\n if (queryList.length > 0) {\n const matched = findFirstMatchingQuery(mediaQueries)\n\n if (matched) {\n return queries[matched]\n }\n }\n\n return devices[device]\n}\n\nexport default useResponsiveValue\n\n```" } ]
code_responsive-values_b6436e82
[ { "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 responsive-values/react/typings/vtex.device-detector.d.ts from the responsive-values VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.device-detector' {\n interface Device {\n device: 'phone' | 'tablet' | 'desktop'\n isMobile: boolean\n }\n\n export function useDevice(): Device\n}\n\n```" } ]
code_responsive-values_6460dca4
[ { "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 responsive-values/react/__tests__/normalizeResponsiveInput.test.tsx from the responsive-values VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport {\n isResponsiveInput,\n normalizeResponsiveInput,\n} from '../modules/normalizeResponsiveInput'\n\njest.spyOn(console, 'warn').mockImplementation()\n\nafterEach(() => {\n jest.clearAllMocks()\n})\n\ndescribe('isResponsiveInput', () => {\n it('returns false if passed null', () => {\n const value = null\n\n expect(isResponsiveInput(value)).toBe(false)\n })\n\n it('returns false if passed a non-object', () => {\n const value = 2\n\n expect(isResponsiveInput(value)).toBe(false)\n })\n\n it('returns true if passed an object with a single device', () => {\n const value = {\n desktop: 1,\n }\n\n expect(isResponsiveInput(value)).toBe(true)\n })\n\n it('returns true if passed an object with all devices', () => {\n const value = {\n desktop: 1,\n mobile: 1,\n tablet: 1,\n phone: 1,\n }\n\n expect(isResponsiveInput(value)).toBe(true)\n })\n\n it('returns true if media queries are passed (wrapped between parenthesis)', () => {\n const value = {\n tablet: 1,\n '(max-width: 100px)': 1,\n '(max-width: 300px)': 2,\n }\n\n expect(isResponsiveInput(value)).toBe(true)\n })\n\n it('returns false if passed an object with an extraneous key', () => {\n const value = {\n desktop: 1,\n mobile: 1,\n tablet: 1,\n phone: 1,\n oops: 0,\n 'max-width: 300px': 0,\n }\n\n expect(isResponsiveInput(value)).toBe(false)\n })\n})\n\ndescribe('responsiveValue', () => {\n it('complains if \"mobile\" is defined along with \"tablet\"', () => {\n const value = {\n tablet: 1,\n phone: 1,\n mobile: 2,\n desktop: 3,\n }\n\n const result = normalizeResponsiveInput(value)\n\n expect(console.warn).toBeCalled()\n\n expect(result).toStrictEqual({\n devices: { phone: 1, tablet: 1, desktop: 3 },\n queries: {},\n })\n })\n\n it('returns an object with equal keys if the input has all the parameters', () => {\n const value = {\n desktop: 1,\n tablet: 2,\n phone: 3,\n }\n\n expect(normalizeResponsiveInput(value)).toStrictEqual({\n devices: { desktop: 1, tablet: 2, phone: 3 },\n queries: {},\n })\n })\n\n describe('single values should populate the device object', () => {\n it('works with straight values', () => {\n const value = 1\n\n expect(normalizeResponsiveInput(value)).toStrictEqual({\n devices: { desktop: 1, tablet: 1, phone: 1 },\n queries: {},\n })\n })\n\n it('works with \"desktop\"', () => {\n const value = { desktop: 1 }\n\n expect(normalizeResponsiveInput(value)).toStrictEqual({\n devices: { desktop: 1, tablet: 1, phone: 1 },\n queries: {},\n })\n })\n\n it('works with \"mobile\"', () => {\n const value = { mobile: 1 }\n\n expect(normalizeResponsiveInput(value)).toStrictEqual({\n devices: { desktop: 1, tablet: 1, phone: 1 },\n queries: {},\n })\n })\n\n it('works with \"tablet\"', () => {\n const value = { tablet: 1 }\n\n expect(normalizeResponsiveInput(value)).toStrictEqual({\n devices: { desktop: 1, tablet: 1, phone: 1 },\n queries: {},\n })\n })\n\n it('works with \"phone\"', () => {\n const value = {\n phone: 1,\n }\n\n expect(normalizeResponsiveInput(value)).toStrictEqual({\n devices: { desktop: 1, tablet: 1, phone: 1 },\n queries: {},\n })\n })\n })\n\n describe('fallbacks', () => {\n it('tablet fallbacks to desktop instead of phone, when both are defined', () => {\n const value = {\n desktop: 1,\n phone: 2,\n }\n\n expect(normalizeResponsiveInput(value)).toStrictEqual({\n devices: { desktop: 1, tablet: 1, phone: 2 },\n queries: {},\n })\n })\n\n it('desktop fallbacks to tablet instead of phone, when both are defined', () => {\n const value = {\n tablet: 1,\n phone: 2,\n }\n\n expect(normalizeResponsiveInput(value)).toStrictEqual({\n devices: { desktop: 1, tablet: 1, phone: 2 },\n queries: {},\n })\n })\n\n it('phone fallbacks to tablet instead of desktop, when both are defined', () => {\n const value = {\n tablet: 1,\n desktop: 2,\n }\n\n expect(normalizeResponsiveInput(value)).toStrictEqual({\n devices: { desktop: 2, tablet: 1, phone: 1 },\n queries: {},\n })\n })\n\n it('tablet fallbacks to mobile,', () => {\n const value = {\n phone: 1,\n mobile: 2,\n desktop: 3,\n }\n\n expect(normalizeResponsiveInput(value)).toStrictEqual({\n devices: { desktop: 3, tablet: 2, phone: 1 },\n queries: {},\n })\n })\n\n it('phone and tablet should override mobile', () => {\n const value = {\n phone: 1,\n mobile: 2,\n tablet: 3,\n desktop: 4,\n }\n\n expect(normalizeResponsiveInput(value)).toStrictEqual({\n devices: {\n phone: 1,\n tablet: 3,\n desktop: 4,\n },\n queries: {},\n })\n })\n })\n\n describe('generic media queries', () => {\n it('adds media query values to queries dictionary', () => {\n const value = {\n '(max-width: 800px)': 1,\n '(max-width: 1200px)': 2,\n }\n\n expect(normalizeResponsiveInput(value)).toStrictEqual({\n devices: { desktop: undefined, tablet: undefined, phone: undefined },\n queries: {\n '(max-width: 800px)': 1,\n '(max-width: 1200px)': 2,\n },\n })\n })\n\n it('works together with devices', () => {\n const value = {\n phone: 3,\n '(max-width: 800px)': 1,\n '(max-width: 1200px)': 2,\n }\n\n expect(normalizeResponsiveInput(value)).toStrictEqual({\n devices: { desktop: 3, tablet: 3, phone: 3 },\n queries: {\n '(max-width: 800px)': 1,\n '(max-width: 1200px)': 2,\n },\n })\n })\n })\n})\n\n```" } ]
code_responsive-values_cfa088c0
[ { "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 responsive-values/react/__tests__/useMediaQueryList.test.tsx from the responsive-values VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { renderHook, act } from '@testing-library/react-hooks'\n\nimport {\n useMediaQueryList,\n clearMatchersCache,\n findFirstMatchingQuery,\n} from '../hooks/useMediaQueryList'\nimport { mockMatchMedia } from '../testUtils/mockMatchMedia'\n\ntype HookArgs = string[]\ntype HookReturnType = ReturnType<typeof useMediaQueryList>\n\nafterEach(clearMatchersCache)\n\ntest('returns a list of media queries and that match state', () => {\n const queries = [\n '(max-width: 800px)',\n '(max-width: 600px)',\n '(max-width: 1200px)',\n ]\n\n const matchedQueries = ['(max-width: 800px)', '(max-width: 600px)']\n\n mockMatchMedia({ matchedQueries })\n const { result } = renderHook<HookArgs, HookReturnType>(() =>\n useMediaQueryList(queries)\n )\n\n expect(result.current.mediaQueries).toMatchObject([\n ['(max-width: 800px)', true],\n ['(max-width: 600px)', true],\n ['(max-width: 1200px)', false],\n ])\n})\n\ntest('returns the first matched media query', () => {\n const queries = [\n '(max-width: 800px)',\n '(max-width: 600px)',\n '(max-width: 1200px)',\n ]\n\n const matchedQueries = ['(max-width: 800px)', '(max-width: 600px)']\n\n mockMatchMedia({ matchedQueries })\n const { result } = renderHook<HookArgs, HookReturnType>(() =>\n useMediaQueryList(queries)\n )\n\n const firstMatch = findFirstMatchingQuery(result.current.mediaQueries)\n\n expect(firstMatch).toMatch('(max-width: 800px)')\n})\n\ntest('returns undefined if not query matches', () => {\n const queries = [\n '(max-width: 800px)',\n '(max-width: 600px)',\n '(max-width: 1200px)',\n ]\n\n mockMatchMedia()\n const { result } = renderHook<HookArgs, HookReturnType>(() =>\n useMediaQueryList(queries)\n )\n\n const firstMatch = findFirstMatchingQuery(result.current.mediaQueries)\n\n expect(firstMatch).toBeUndefined()\n})\n\ntest('does nothing if no media queries are passed', () => {\n const queries: string[] = []\n\n mockMatchMedia()\n\n const { result } = renderHook<HookArgs, HookReturnType>(() =>\n useMediaQueryList(queries)\n )\n\n expect(result.current.mediaQueries).toHaveLength(0)\n})\n\ntest('updates the matched list after a media listener is triggered', () => {\n const queries = [\n '(max-width: 600px)',\n '(max-width: 800px)',\n '(min-width: 1200px)',\n ]\n\n const resizeWindow = mockMatchMedia({\n matchedQueries: ['(min-width: 1200px)'],\n })\n\n const { result } = renderHook<HookArgs, HookReturnType>(() =>\n useMediaQueryList(queries)\n )\n\n expect(result.current.mediaQueries).toMatchObject([\n ['(max-width: 600px)', false],\n ['(max-width: 800px)', false],\n ['(min-width: 1200px)', true],\n ])\n\n act(() => {\n resizeWindow({\n matchedQueries: ['(max-width: 600px)', '(max-width: 800px)'],\n })\n })\n\n expect(result.current.mediaQueries).toMatchObject([\n ['(max-width: 600px)', true],\n ['(max-width: 800px)', true],\n ['(min-width: 1200px)', false],\n ])\n})\n\ntest('returns an updated list of media queries after the hook params changes', () => {\n const initialQueries: string[] = []\n\n mockMatchMedia({\n matchedQueries: ['(max-width: 800px)'],\n })\n\n const { result, rerender } = renderHook<HookArgs, HookReturnType>(\n (hookArgs) => useMediaQueryList(hookArgs),\n { initialProps: initialQueries }\n )\n\n expect(result.current.mediaQueries).toMatchObject([])\n\n const rerenderQueries = ['(max-width: 600px)', '(max-width: 800px)']\n\n rerender(rerenderQueries)\n\n expect(result.current.mediaQueries).toMatchObject([\n ['(max-width: 600px)', false],\n ['(max-width: 800px)', true],\n ])\n})\n\n```" } ]
code_responsive-values_f0301317
[ { "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 responsive-values/react/__tests__/useResponsiveValue.test.tsx from the responsive-values VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { renderHook } from '@testing-library/react-hooks'\nimport { useDevice } from 'vtex.device-detector'\n\nimport { mockMatchMedia } from '../testUtils/mockMatchMedia'\nimport useResponsiveValue from '../useResponsiveValue'\nimport useResponsiveValues from '../useResponsiveValues'\n\nconst devices = ['desktop', 'tablet', 'phone']\n\njest.mock('vtex.device-detector', () => {\n return { useDevice: jest.fn() }\n})\n\nfunction switchDevice(device: string) {\n return (useDevice as jest.Mock).mockImplementation(() => ({ device }))\n}\n\ndescribe('useResponsiveValue', () => {\n devices.forEach((device) => {\n it(`returns a single value for the current device: ${device}`, () => {\n switchDevice(device)\n\n const input = {\n desktop: 1,\n phone: 2,\n tablet: 3,\n }\n\n const { result } = renderHook(() => useResponsiveValue(input))\n\n expect(result.current).toBe(input[device as keyof typeof input])\n })\n\n it('returns a single value if the input is also a single value', () => {\n switchDevice(device)\n\n const input = 1\n\n const { result } = renderHook(() => useResponsiveValue(input))\n\n expect(result.current).toBe(input)\n })\n })\n\n it(`returns a single value matching a specific media query`, () => {\n mockMatchMedia({ matchedQueries: ['(max-width: 1000px)'] })\n switchDevice('desktop')\n\n const input = {\n desktop: 1,\n '(max-width: 1000px)': 2,\n }\n\n const { result } = renderHook(() => useResponsiveValue(input))\n\n expect(result.current).toBe(2)\n })\n})\n\ndescribe('useResponsiveValues', () => {\n it('returns the correct values for different keys', () => {\n switchDevice('desktop')\n\n const input = {\n first: { desktop: 1, mobile: 2 },\n second: { desktop: '3', mobile: '4' },\n third: { desktop: 1, '(max-width: 1000px)': 2 },\n }\n\n const { result } = renderHook(() => useResponsiveValues(input))\n\n expect(result.current.first).toBe(1)\n expect(result.current.second).toBe('3')\n expect(result.current.third).toBe(2)\n })\n})\n\n```" } ]
code_responsive-values_2ca42f2a
[ { "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 responsive-values/react/hooks/useMediaQueryList.ts from the responsive-values VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { useLayoutEffect, useState } from 'react'\n\nconst BreakpointMatchers: Record<string, MediaQueryList> = {}\n\nexport function clearMatchersCache() {\n Object.keys(BreakpointMatchers).forEach(\n (key) => delete BreakpointMatchers[key]\n )\n}\n\nfunction getBreakpointMatcher(query: string): MediaQueryList | undefined {\n if (!BreakpointMatchers[query] && typeof window?.matchMedia === 'function') {\n // ugly side-effect to get a up-to-date initial value(>д<)\n BreakpointMatchers[query] = window.matchMedia(query)\n }\n\n return BreakpointMatchers[query]\n}\n\nexport function useMediaQueryList(queries: string[]) {\n const [matches, setMatches] = useState<Record<string, boolean>>(() => {\n const initial: Record<string, boolean> = {}\n\n queries.forEach((query) => {\n initial[query] = Boolean(getBreakpointMatcher(query)?.matches)\n })\n\n return initial\n })\n\n useLayoutEffect(\n function updateQueryListeners() {\n if (typeof window?.matchMedia !== 'function' || queries.length === 0) {\n return\n }\n\n const cancels = queries.map((query) => {\n let mounted = true\n const mediaQueryList = getBreakpointMatcher(query)\n\n if (matches[query] === undefined || matches[query] === null) {\n setMatches((curMatches) => ({\n ...curMatches,\n [query]: Boolean(mediaQueryList?.matches),\n }))\n }\n\n const listener = (e: MediaQueryListEvent) => {\n if (!mounted) return\n setMatches((curMatches) => ({ ...curMatches, [query]: e.matches }))\n }\n\n mediaQueryList?.addListener(listener)\n\n return () => {\n mounted = false\n mediaQueryList?.removeListener(listener)\n }\n })\n\n return () => {\n cancels.forEach((cancel) => cancel())\n }\n },\n // We disable this rule because it doesn't treat `JSON.stringify(queries)`\n // as an explicit dependency of `queries`.\n // We're also doing a JSON.stringify because we need to guarantee that it won't\n // re-run if the reference was changed but its content didn't.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [JSON.stringify(queries), setMatches]\n )\n\n return {\n mediaQueries: Object.entries(matches),\n }\n}\n\nexport const findFirstMatchingQuery = (\n queryMatches: Array<[string, boolean]>\n): undefined | string => {\n const matchedBreakpoint = queryMatches.find(([, matches]) => matches)\n\n if (!matchedBreakpoint) {\n return\n }\n\n const [query] = matchedBreakpoint\n\n return query\n}\n\n```" } ]
code_responsive-values_38dbd67f
[ { "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 responsive-values/react/modules/normalizeResponsiveInput.ts from the responsive-values VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/** The user is able to input `mobile` as a device (as opposed to `desktop`),\n * but the output will be converted to `phone` and `tablet` */\n\nimport type { InputDevice, OutputDevice } from '../ResponsiveValuesTypes'\n\nconst InputDevicesMap: Record<InputDevice, InputDevice> = {\n mobile: 'mobile',\n phone: 'phone',\n tablet: 'tablet',\n desktop: 'desktop',\n}\n\nexport type ResponsiveInput<T> = Record<InputDevice | string, T>\nexport type MaybeResponsiveInput<T> = T | ResponsiveInput<T>\n\nexport type NormalizedInput<T> = {\n devices: Record<OutputDevice, T>\n queries: Record<string, T>\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst isUndefined = (value: any) => typeof value === 'undefined'\n\n/** Returns the first value of the input that is not undefined,\n * given a sorted array of keys */\nconst fallbackOrder = <T>(\n input: ResponsiveInput<T>,\n devices: Array<keyof ResponsiveInput<T>>\n) => devices.map((key) => input[key]).find((value) => !isUndefined(value)) as T\n\n/** Checks if the input value is a ResponsiveInput type (an object with\n * one or more keys of Device type--e.g. `desktop`, `mobile`) */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const isResponsiveInput = <T>(value: any): value is ResponsiveInput<T> =>\n Boolean(\n value &&\n typeof value === 'object' &&\n Object.keys(value).every((key) => {\n return (\n key in InputDevicesMap ||\n (key.charAt(0) === '(' && key.charAt(key.length - 1) === ')')\n )\n })\n )\n\nconst showWarnings = <T>(value: ResponsiveInput<T>) => {\n if (isUndefined(value.mobile)) {\n return\n }\n\n const devices: string[] = []\n\n if (!isUndefined(value.phone)) {\n devices.push('\"phone\"')\n }\n\n if (!isUndefined(value.tablet)) {\n devices.push('\"tablet\"')\n }\n\n if (devices.length === 0) {\n return\n }\n\n const devicesLabel = devices.join(' and ')\n\n console.warn(\n `You are defining a \"mobile\" value along with ${devicesLabel} ${\n devices.length > 1 ? 'values' : 'value'\n } in the props of a component. Please use \"phone\" and \"tablet\" in this case.`\n )\n}\n\n/** Takes an input that might be a responsive object or not\n * (i.e. either \"prop: {mobile: 1, desktop:2}\" or just \"prop: 2\")\n * and returns an object of the values broken down into devices\n * (i.e. {phone: 1, tablet: 1, desktop: 2})\n *\n * TODO: this can return undefined if only media queries are defined\n * should we add undefined to the return type of our hooks?\n * it would make it a bit annoying to use, but probably safer\n */\nexport const normalizeResponsiveInput = <T>(\n input: MaybeResponsiveInput<T>\n): NormalizedInput<T> => {\n if (!isResponsiveInput(input)) {\n return {\n devices: { phone: input, tablet: input, desktop: input },\n queries: {},\n }\n }\n\n const { phone, tablet, mobile, desktop, ...queries } = input\n\n showWarnings(input)\n\n return {\n devices: {\n phone: fallbackOrder(input, ['phone', 'mobile', 'tablet', 'desktop']),\n tablet: fallbackOrder(input, ['tablet', 'mobile', 'desktop', 'phone']),\n desktop: fallbackOrder(input, ['desktop', 'tablet', 'phone', 'mobile']),\n },\n queries,\n }\n}\n\nexport const normalizeResponsiveInputs = <\n Input extends Record<string, MaybeResponsiveInput<unknown>>\n>(\n input: Input\n) => {\n const normalizedInputs: Array<[keyof Input, NormalizedInput<unknown>]> = []\n const queryList: Set<string> = new Set()\n\n Object.keys(input).forEach((key) => {\n const normalizedInput = normalizeResponsiveInput(input[key])\n\n Object.keys(normalizedInput.queries).forEach((query) =>\n queryList.add(query)\n )\n\n normalizedInputs.push([key as keyof Input, normalizedInput])\n })\n\n return {\n inputList: normalizedInputs,\n queryList: [...queryList],\n }\n}\n\n```" } ]
code_responsive-values_b318c1c3
[ { "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 responsive-values/react/testUtils/mockMatchMedia.ts from the responsive-values VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ntype MockMatchMedia = {\n matchedQueries?: string[]\n}\n\nexport function mockMatchMedia({ matchedQueries = [] }: MockMatchMedia = {}) {\n const mqls: Array<{ mql: MediaQueryList; listeners: any[] }> = []\n\n Object.defineProperty(window, 'matchMedia', {\n writable: true,\n value: jest.fn().mockImplementation((media: string) => {\n let _listeners: any[] = []\n\n const mql = {\n media,\n get matches() {\n return matchedQueries.includes(media)\n },\n onchange: () => {},\n addListener: jest.fn((fn) => _listeners.push(fn)),\n addEventListener: jest.fn((fn: any) => _listeners.push(fn)),\n removeListener: jest.fn(\n (fn) => (_listeners = _listeners.filter((f) => f !== fn))\n ),\n removeEventListener: jest.fn(\n (fn: any) => (_listeners = _listeners.filter((f) => f !== fn))\n ),\n dispatchEvent: (_: Event) => true,\n }\n\n mqls.push({\n mql,\n get listeners() {\n return _listeners\n },\n })\n\n return mql\n }),\n })\n\n return ({\n matchedQueries: newMatchedQueries,\n }: {\n matchedQueries: string[]\n }) => {\n matchedQueries = newMatchedQueries\n\n mqls.forEach(({ mql, listeners }) =>\n listeners.forEach((fn) => fn({ matches: mql.matches }))\n )\n }\n}\n\n```" } ]
code_salesforce-oauth-middleware_802640d9
[ { "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 salesforce-oauth-middleware/node/service.json from the salesforce-oauth-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"memory\": 4096,\n \"ttl\": 43200,\n \"timeout\": 60,\n \"minReplicas\": 10,\n \"maxReplicas\": 400,\n \"workers\": 1,\n \"routes\": {\n \"proxy\": {\n \"path\": \"/_v/private/oauth-proxy/authorizations/*path\",\n \"public\": true\n },\n \"access_token\": {\n \"path\": \"/_v/private/oauth-proxy/autheticated/access-token/\",\n \"public\": true\n },\n \"refresh_token\": {\n \"path\": \"/_v/private/oauth-proxy/autheticated/refresh-token/\",\n \"public\": true\n }\n }\n}\n\n```" } ]
code_salesforce-oauth-middleware_86778a03
[ { "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 salesforce-oauth-middleware/node/package.json from the salesforce-oauth-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"dependencies\": {\n \"co-body\": \"^6.0.0\",\n \"qs\": \"^6.11.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.12\",\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\": \"1.0.2\"\n}\n\n```" } ]
code_salesforce-oauth-middleware_bc16ffd8
[ { "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 salesforce-oauth-middleware/node/index.ts from the salesforce-oauth-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { ClientsConfig } from '@vtex/api'\nimport { Service } from '@vtex/api'\n\nimport { Clients } from './clients'\nimport { getAccessToken } from './handlers/getAccessToken'\nimport { proxyRequest } from './handlers/proxyRequest'\nimport { refreshAccessToken } from './handlers/refreshAccessToken'\nimport { checkUserAuth } from './middlewares/checkUserAuth'\nimport { getAppSettings } from './middlewares/getAppSettings'\nimport { prepare } from './middlewares/prepare'\n\nconst TIMEOUT_MS = 800\nconst FOUR_SECONDS_MS = 5 * TIMEOUT_MS\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: FOUR_SECONDS_MS,\n },\n },\n}\n\n// Export a service that defines route handlers and client options.\nexport default new Service({\n clients,\n routes: {\n // `status` is the route ID from service.json. It maps to an array of middlewares (or a single handler).\n proxy: [prepare, getAppSettings, proxyRequest],\n access_token: [prepare, checkUserAuth, getAppSettings, getAccessToken],\n refresh_token:[prepare, checkUserAuth, getAppSettings, refreshAccessToken]\n },\n})\n\n```" } ]
code_salesforce-oauth-middleware_5ac3b78a
[ { "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 salesforce-oauth-middleware/node/clients/vtexid.ts from the salesforce-oauth-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type {\n InstanceOptions,\n IOContext,\n IOResponse,\n RequestConfig,\n} from '@vtex/api'\nimport { ExternalClient } from '@vtex/api'\nimport { createTracing } from '../utils/'\nimport { statusToError } from '../utils/'\n\nexport default class VTEXID extends ExternalClient {\n constructor(context: IOContext, options?: InstanceOptions) {\n // TO-DO: Fix production URL with the correct one\n super('https://vtexid.vtex.com.br', context, options)\n }\n\n public async getUserFromVTEXID(): Promise<IOResponse<AuthUser>> {\n const metric = `${this.context.account}-VTEXID-User-GET`\n\n return this.get('/api/vtexid/pub/authenticated/user', {\n params: {\n account: this.context.account,\n authToken: this.context.storeUserAuthToken,\n },\n metric,\n tracing: createTracing(metric),\n })\n }\n\n protected get = <T = any>(url: string, config?: RequestConfig) =>\n this.http.getRaw<T>(url, config).catch(statusToError) as Promise<\n IOResponse<T>\n >\n}\n\n```" } ]
code_salesforce-oauth-middleware_c31be927
[ { "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 salesforce-oauth-middleware/node/clients/customVBase.ts from the salesforce-oauth-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { AxiosError } from 'axios'\nimport {\n inflightURL,\n InstanceOptions,\n IOResponse,\n RequestTracingConfig,\n} from '@vtex/api/lib/HttpClient'\nimport { InfraClient, IOContext } from '@vtex/api'\nimport { IgnoreNotFoundRequestConfig } from '@vtex/api/lib/HttpClient/middlewares/notFound'\nimport { Logger } from '@vtex/api/lib/service/logger/logger'\n\nconst appId = process.env.VTEX_APP_ID\nconst [runningAppName] = appId ? appId.split('@') : ['']\n\nconst routes = {\n Bucket: (bucket: string) => `/buckets/${runningAppName}/${bucket}`,\n File: (bucket: string, path: string) => `${routes.Bucket(bucket)}/files/${path}`,\n Files: (bucket: string) => `${routes.Bucket(bucket)}/files`,\n}\n\nexport class CustomVBase extends InfraClient {\n constructor (context: IOContext, options?: InstanceOptions) {\n super('vbase@2.x', { ...context, workspace: \"master\" }, options)\n if (runningAppName === '') {\n throw new Error(`Invalid path to access VBase. Variable VTEX_APP_ID is not available.`)\n }\n }\n\n public getJSON = <T>(bucket: string, path: string, nullIfNotFound?: boolean, conflictsResolver?: ConflictsResolver<T>, tracingConfig?: RequestTracingConfig) => {\n return this.getRawJSON<T>(bucket, path, nullIfNotFound, conflictsResolver, tracingConfig)\n .then(response => response.data)\n }\n\n public getRawJSON = <T>(bucket: string, path: string, nullIfNotFound?: boolean, conflictsResolver?: ConflictsResolver<T>, tracingConfig?: RequestTracingConfig) => {\n const headers = conflictsResolver? {'X-Vtex-Detect-Conflicts': true}: {}\n const inflightKey = inflightURL\n const metric = 'vbase-get-json'\n return this.http.getRaw<T>(routes.File(bucket, path), { headers, inflightKey, metric, nullIfNotFound, tracing: {\n requestSpanNameSuffix: metric,\n ...tracingConfig?.tracing,\n }} as IgnoreNotFoundRequestConfig)\n .catch(async (error: AxiosError<T>) => {\n const { response } = error\n if (response && response.status === 409 && conflictsResolver) {\n const conflictsMergedData = await conflictsResolver.resolve(this.context.logger)\n return { ...response, data: conflictsMergedData } as IOResponse<T>\n }\n throw error\n })\n }\n\n public saveJSON = <T>(bucket: string, path: string, data: T, tracingConfig?: RequestTracingConfig, ifMatch?: string) => {\n const headers: Headers = { 'Content-Type': 'application/json' }\n if (ifMatch) {\n headers['If-Match'] = ifMatch\n }\n const metric = 'vbase-save-json'\n return this.http.put(routes.File(bucket, path), data, {headers, metric, tracing: {\n requestSpanNameSuffix: metric,\n ...tracingConfig?.tracing,\n }})\n }\n}\n\ninterface Headers { [key: string]: string | number }\n\nexport interface ConflictsResolver<T>{\n resolve: (logger?: Logger) => T | Promise<T>\n}\n\n```" } ]
code_salesforce-oauth-middleware_50f10163
[ { "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 salesforce-oauth-middleware/node/clients/salesforceProxy.ts from the salesforce-oauth-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type {\n InstanceOptions,\n IOContext,\n IOResponse,\n RequestConfig,\n} from '@vtex/api'\nimport { ExternalClient } from '@vtex/api'\nimport { createTracing } from '../utils/'\nimport { statusToError } from '../utils/'\n\nexport default class SalesforceProxy extends ExternalClient {\n constructor(context: IOContext, options?: InstanceOptions) {\n // TO-DO: Fix production URL with the correct one\n super(\n context.production || (context as CustomIOContext).appSettings.configs.forceProduction\n ? (context as CustomIOContext).appSettings.production.endpoint\n : (context as CustomIOContext).appSettings.staging.endpoint,\n context,\n options\n )\n }\n\n public async proxyGet(path: string, params: {}): Promise<IOResponse<any>> {\n const metric = `${this.context.account}-Salesforce-OAuth-Proxy-GET`\n const host = this.getHost()\n return this.get(path, {\n params,\n headers: {\n 'host': host,\n 'x-forwarded-host': host\n },\n metric,\n tracing: createTracing(metric),\n })\n }\n\n public async proxyPost(path: string, body: any, params: {}): Promise<IOResponse<any>> {\n const metric = `${this.context.account}-Salesforce-OAuth-Proxy-POST`\n const host = this.getHost()\n return this.post(path, body, {\n params,\n headers: {\n 'host': host,\n 'x-forwarded-host': host\n },\n metric,\n tracing: createTracing(metric),\n })\n }\n\n public async refreshToken(refreshToken: string): Promise<IOResponse<any>> {\n const metric = `${this.context.account}-Salesforce-OAuth-RefreshToken-POST`\n const host = this.getHost()\n const env = this.context.production || (this.context as CustomIOContext).appSettings.configs.forceProduction ? \"production\" : \"staging\"\n const credentials = (this.context as CustomIOContext).appSettings[env].credentials\n\n return this.post('/services/oauth2/token', null, {\n params: {\n grant_type: \"refresh_token\",\n client_id: credentials.clientId,\n client_secret: credentials.clientSecret,\n refresh_token: refreshToken\n },\n headers: {\n 'host': host,\n 'x-forwarded-host': host\n },\n metric,\n tracing: createTracing(metric),\n })\n }\n\n protected getHost: () => string = () => {\n return new URL(this.options?.baseURL as string).hostname\n }\n\n protected get = <T = any>(url: string, config?: RequestConfig) =>\n this.http.getRaw<T>(url, config).catch(statusToError) as Promise<\n IOResponse<T>\n >\n\n protected put = <T = any>(url: string, data?: any, config?: RequestConfig) =>\n this.http.putRaw<T>(url, data, config).catch(statusToError) as Promise<\n IOResponse<T>\n >\n\n protected post = <T = any>(url: string, data?: any, config?: RequestConfig) =>\n this.http.post<T>(url, data, config).catch(statusToError) as Promise<\n IOResponse<T>\n >\n\n protected delete = <T = any>(url: string, config?: RequestConfig) =>\n this.http.delete<T>(url, config).catch(statusToError) as Promise<\n IOResponse<T>\n >\n}\n\n```" } ]
code_salesforce-oauth-middleware_8531ccc4
[ { "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 salesforce-oauth-middleware/node/clients/index.ts from the salesforce-oauth-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { IOClients } from '@vtex/api'\n\nimport SalesforceProxy from './salesforceProxy'\nimport VTEXID from './vtexid'\nimport { CustomVBase } from './customVBase'\n\n// Extend the default IOClients implementation with our own custom clients.\nexport class Clients extends IOClients {\n public get salesforceProxy() {\n return this.getOrSet('salesforceProxy', SalesforceProxy)\n }\n\n public get vtexid() {\n return this.getOrSet('vtexid', VTEXID)\n }\n\n public get customVBase() {\n return this.getOrSet('customVBase', CustomVBase)\n }\n}\n\n```" } ]
code_salesforce-oauth-middleware_493ffedd
[ { "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 salesforce-oauth-middleware/node/parsers/cleanErrorParser.ts from the salesforce-oauth-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { cleanError } from '@vtex/api'\n\nexport const cleanErrorParser = (\n customMessage: string,\n error: any\n) => {\n const cleanedError = cleanError(error)\n return {\n ...cleanedError,\n ...{\n customMessage,\n },\n }\n}\n\n```" } ]
code_salesforce-oauth-middleware_1b448ff6
[ { "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 salesforce-oauth-middleware/node/parsers/errorParses.ts from the salesforce-oauth-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport function errorParser(\n ctx: Context,\n error: any,\n message: string,\n method: string\n) {\n const {\n vtex: {\n route: { params },\n },\n state: { currentUser },\n req: { method: reqMethod },\n } = ctx\n\n const path = params?.path as string\n const requestMethod = reqMethod?.toLowerCase() as string\n\n let appMessage: string = ''\n let stackTrace: any = null\n\n if (error.isAxiosError) {\n appMessage = `${message} ${error.response?.status}`\n } else {\n appMessage = error.message || 'Unhandled exception'\n stackTrace = error.stack\n }\n\n return {\n appMessage,\n data: error.response?.data,\n message: error.message,\n path,\n method,\n requestMethod,\n stackTrace,\n status: error.response?.status,\n statusText: error.response?.statusText,\n currentUser,\n }\n}\n\n```" } ]
code_salesforce-oauth-middleware_98cc33c4
[ { "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 salesforce-oauth-middleware/node/typings/authetication.d.ts from the salesforce-oauth-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface AuthUser {\n userId: string\n user: string\n userType: string\n}\n\n```" } ]
code_salesforce-oauth-middleware_db50a4b4
[ { "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 salesforce-oauth-middleware/node/typings/session.d.ts from the salesforce-oauth-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface Session {\n namespaces?: {\n profile?: {\n id: {\n value: string\n }\n email: {\n value: string\n }\n }\n authentication?: {\n storeUserId: {\n value: string\n }\n storeUserEmail: {\n value: string\n }\n }\n }\n}\n\n```" } ]
code_salesforce-oauth-middleware_efd62f0e
[ { "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 salesforce-oauth-middleware/node/typings/proxy.d.ts from the salesforce-oauth-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface proxyResponse {\n data: any\n status: number\n}\n\n```" } ]
code_salesforce-oauth-middleware_752531af
[ { "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 salesforce-oauth-middleware/node/typings/appSettings.d.ts from the salesforce-oauth-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport interface AppSettings {\n production: {\n endpoint: string\n credentials: Credentials\n },\n staging: {\n endpoint: string\n credentials: Credentials\n },\n configs: {\n forceProduction: boolean\n }\n}\n\nexport interface Credentials {\n clientId: string\n clientSecret: string\n}\n\n```" } ]
code_salesforce-oauth-middleware_be7ece82
[ { "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 salesforce-oauth-middleware/node/typings/global.d.ts from the salesforce-oauth-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ServiceContext, RecorderState, ParamsContext } from '@vtex/api'\nimport type { IOContext } from '@vtex/api'\nimport { Clients } from '../clients'\nimport { AppSettings } from './appSettings'\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, ParamsContextm, CustomIOContext>\n\n interface State extends RecorderState {\n body: any\n salesforceAccessToken: string\n currentUser: CurrentUser\n }\n\n interface CustomIOContext extends IOContext {\n appSettings: AppSettings\n }\n\n interface CurrentUser {\n email: string\n userId: string\n }\n}\n\n```" } ]
code_salesforce-oauth-middleware_272053f3
[ { "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 salesforce-oauth-middleware/node/typings/salesforceAccessToken.d.ts from the salesforce-oauth-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface ISalesforceAccessTokenRes {\n sub: string\n user_id: string\n organization_id: string\n preferred_username: string\n nickname: string\n name: string\n email: string\n email_verified: boolean\n given_name: string\n family_name: string\n zoneinfo: string\n photos: {\n picture: string\n thumbnail: string\n }\n profile: string\n picture: string\n address: {\n country: string\n }\n urls: {\n enterprise: string\n metadata: string\n partner: string\n rest: string\n sobjects: string\n search: string\n query: string\n recent: string\n tooling_soap: string\n tooling_rest: string\n profile: string\n feeds: string\n groups: string\n users: string\n feed_items: string\n feed_elements: string\n custom_domain: string\n }\n active: boolean\n user_type: string\n language: string\n locale: string\n utcOffset: number\n updated_at: string\n}\n\ninterface ISalesforceAccessToken extends ISalesforceAccessTokenRes {\n end_date: Date\n}\n\ninterface ISalesforceRefreshToken {\n access_token: string\n id: string\n id_token?: string\n instance_url: string\n issued_at: string\n refresh_token?: string\n scope: string\n sfdc_community_id: string\n sfdc_community_url: string\n signature: string\n token_type: string\n}\n\n```" } ]
code_salesforce-oauth-middleware_debf4bea
[ { "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 salesforce-oauth-middleware/node/middlewares/prepare.ts from the salesforce-oauth-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ResolverError } from '@vtex/api'\nimport { form, json } from 'co-body'\n\nexport async function prepare(ctx: Context, next: () => Promise<any>) {\n const {\n method: reqMethod,\n query,\n req\n } = ctx\n\n let args: any;\n\n if (['POST'].includes(reqMethod) && (!ctx.request.type.includes('application/json') && !ctx.request.type.includes('application/x-www-form-urlencoded'))) {\n ctx.throw(406, 'Content type not allowed')\n }\n\n if (['POST'].includes(reqMethod) && ctx.request.type.includes('application/json')) {\n args = await json(req)\n }\n\n if (['POST'].includes(reqMethod) && ctx.request.type.includes('application/x-www-form-urlencoded')) {\n args = await form(req)\n }\n\n if (!reqMethod) {\n throw new ResolverError('Empty request method')\n }\n\n if (!['GET', 'POST'].includes(reqMethod)) {\n ctx.throw(405)\n }\n\n if (['POST'].includes(reqMethod) && args) {\n ctx.state.body = args\n }\n\n if(query && query.access_token) {\n ctx.state.salesforceAccessToken = query.access_token\n }\n\n await next()\n}\n\n```" } ]
code_salesforce-oauth-middleware_035836f2
[ { "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 salesforce-oauth-middleware/node/middlewares/checkUserAuth.ts from the salesforce-oauth-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { AuthenticationError } from '@vtex/api'\n\nimport { getCurrentUserFromSession } from '../utils/getCurrentUserFromSession'\nimport { getCurrentUserFromVTEXAuthCookie } from '../utils/getCurrentUserFromVTEXAuthCookie'\n\nfunction isLogged(user: CurrentUser | null) {\n return user?.email\n}\n\nexport async function checkUserAuth(ctx: Context, next: () => Promise<any>) {\n let currentUser: CurrentUser | null\n\n currentUser = await getCurrentUserFromSession(ctx)\n\n if (!isLogged(currentUser)) {\n currentUser = await getCurrentUserFromVTEXAuthCookie(ctx)\n }\n\n if (!isLogged(currentUser)) {\n throw new AuthenticationError('User not authenticated')\n }\n\n ctx.state.currentUser = currentUser as CurrentUser\n\n await next()\n}\n\n```" } ]
code_salesforce-oauth-middleware_2c777826
[ { "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 salesforce-oauth-middleware/node/middlewares/getAppSettings.ts from the salesforce-oauth-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ResolverError } from '@vtex/api'\n\nimport { appSettingsService } from \"../services/appSettingsService\";\nimport type { AppSettings } from '../typings/appSettings';\n\nexport async function getAppSettings(ctx: Context, next: () => Promise<any>) {\n const {\n clients: { apps}\n } = ctx\n\n const service = appSettingsService(ctx.vtex.account, ctx.vtex.workspace, apps)\n const appSettings: AppSettings = await service.getSettings()\n\n if (!appSettings) {\n throw new ResolverError('No app settings found')\n }\n\n if (!appSettings.staging.endpoint || !appSettings.production.endpoint ) {\n throw new ResolverError('Missing Staging or Production endpoint app config')\n }\n\n if (\n !appSettings.staging.credentials.clientId || !appSettings.staging.credentials.clientSecret\n || !appSettings.production.credentials.clientId || !appSettings.production.credentials.clientSecret\n ) {\n throw new ResolverError('Missing Staging or Production credentials app config')\n }\n\n ctx.vtex.appSettings = appSettings\n\n\n await next()\n}\n\n```" } ]
code_salesforce-oauth-middleware_14b45737
[ { "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 salesforce-oauth-middleware/node/utils/getCurrentUserFromSession.ts from the salesforce-oauth-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ResolverError } from '@vtex/api'\nimport { path } from 'ramda'\nimport { cleanErrorParser } from '../parsers/cleanErrorParser'\n\nexport async function getCurrentUserFromSession(\n ctx: Context\n): Promise<CurrentUser | null> {\n try {\n const {\n clients: { session },\n vtex: { logger }\n } = ctx\n\n const currentSession = await session.getSession(\n ctx.vtex.sessionToken as string,\n ['*']\n )\n const thisSession = currentSession.sessionData as Session\n\n if (!thisSession || !thisSession.namespaces) {\n const warn = cleanErrorParser(\"Error getting logged user info from session\", new ResolverError('Error fetching session data'))\n logger.warn(warn)\n return null\n }\n\n const idPath = ['namespaces', 'authentication', 'storeUserId', 'value']\n const emailPath = [\n 'namespaces',\n 'authentication',\n 'storeUserEmail',\n 'value',\n ]\n\n return {\n email: path(emailPath, thisSession) as string,\n userId: path(idPath, thisSession) as string,\n }\n } catch (error) {\n const {\n vtex: { logger },\n } = ctx\n\n const log = cleanErrorParser(\"Error getting logged user info from session\", error)\n logger.error(log)\n\n return null\n }\n}\n\n```" } ]
code_salesforce-oauth-middleware_eded9d9b
[ { "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 salesforce-oauth-middleware/node/utils/statusToError.ts from the salesforce-oauth-middleware 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 function statusToError<T>(e: AxiosError): T {\n if (!e.response) {\n throw e\n }\n\n const { response } = e\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { status } = response!\n\n if (status === 401) {\n throw new AuthenticationError(e)\n }\n if (status === 403) {\n throw new ForbiddenError(e)\n }\n if (status === 400) {\n throw new UserInputError(e)\n }\n\n throw e\n}\n\n```" } ]
code_salesforce-oauth-middleware_d4b2f7dc
[ { "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 salesforce-oauth-middleware/node/utils/constants.ts from the salesforce-oauth-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nconst DEFAULT_SETTINGS_CACHE_MAX_AGE_IN_MS = 5000\n\nexport {\n DEFAULT_SETTINGS_CACHE_MAX_AGE_IN_MS,\n}\n\n```" } ]
code_salesforce-oauth-middleware_d83b2bbd
[ { "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 salesforce-oauth-middleware/node/utils/getCurrentUserFromVTEXAuthCookie.ts from the salesforce-oauth-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ResolverError } from '@vtex/api'\nimport { cleanErrorParser } from '../parsers/cleanErrorParser'\n\nexport async function getCurrentUserFromVTEXAuthCookie(\n ctx: Context\n): Promise<CurrentUser | null> {\n try {\n const {\n clients: { vtexid },\n vtex: { logger }\n } = ctx\n\n const { data: currentAuthUser } = await vtexid.getUserFromVTEXID()\n\n if (!currentAuthUser || !currentAuthUser.user) {\n const warn = cleanErrorParser(\"Error getting logged user info from cookie\", new ResolverError('Error fetching VTEX ID user data'))\n logger.warn(warn)\n return null\n }\n\n return {\n email: currentAuthUser.user as string,\n userId: currentAuthUser.userId as string,\n }\n } catch (error) {\n const {\n vtex: { logger },\n } = ctx\n\n const log = cleanErrorParser(\"Error getting logged user info from cookie\", error)\n logger.error(log)\n\n return null\n }\n}\n\n```" } ]
code_salesforce-oauth-middleware_14a51ee6
[ { "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 salesforce-oauth-middleware/node/utils/index.ts from the salesforce-oauth-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { createTracing } from './createTracing'\nimport { statusToError } from './statusToError'\n\nexport { statusToError, createTracing }\n\n```" } ]
code_salesforce-oauth-middleware_599a7833
[ { "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 salesforce-oauth-middleware/node/utils/createTracing.ts from the salesforce-oauth-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { RequestTracingConfig } from '@vtex/api'\n\nexport const createTracing = (\n metric: string,\n tracingConfig?: RequestTracingConfig\n) => ({\n requestSpanNameSuffix: metric,\n ...tracingConfig?.tracing,\n})\n\n```" } ]
code_salesforce-oauth-middleware_e775988e
[ { "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 salesforce-oauth-middleware/node/handlers/proxyRequest.ts from the salesforce-oauth-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ResolverError } from '@vtex/api'\n\nimport { proxyGetHandler } from './proxyGetHandler'\nimport { proxyPostHandler } from './proxyPostHandler'\nimport { errorParser } from '../parsers/errorParses'\nimport SalesforceAccessToken from '../services/salesforceAccessToken'\nimport SalesforceRefreshToken from '../services/salesforceRefreshToken'\nimport { getUserInfo } from './getUserInfoHandler'\n\nexport async function proxyRequest(ctx: Context) {\n try {\n const {\n vtex: {\n logger,\n route: {\n params: { path },\n },\n },\n req: { method: reqMethod }\n } = ctx\n\n let proxyResponse: proxyResponse | any\n\n if (!reqMethod) {\n throw new ResolverError('Empty request method')\n }\n\n switch (reqMethod.toLocaleLowerCase()) {\n case 'get':\n proxyResponse = await proxyGetHandler(ctx)\n break\n case 'post':\n proxyResponse = await proxyPostHandler(ctx)\n break\n default:\n throw new Error(`Proxy request handler for ${reqMethod} not implementd`)\n }\n\n if (path.includes('services/oauth2/userinfo') && proxyResponse.data) {\n const salesforceAccessToken = new SalesforceAccessToken()\n const userEmail = proxyResponse.data?.email\n salesforceAccessToken.save(ctx, userEmail, proxyResponse.data)\n } else if (path.includes('services/oauth2/token')) {\n const salesforceRefreshToken = new SalesforceRefreshToken()\n const { data: { email } } = await getUserInfo(ctx, proxyResponse.access_token)\n\n if(!email)\n throw new ResolverError(\"No user email found\")\n\n salesforceRefreshToken.save(ctx, email, proxyResponse)\n\n }\n\n logger.info({\n message: 'Salesforce OAuth Provider request success',\n path,\n reqMethod,\n })\n\n ctx.set('Cache-Control', 'no-cache,no-store')\n ctx.status = proxyResponse.status || 200\n ctx.body = proxyResponse?.data || proxyResponse\n\n } catch (error) {\n const {\n vtex: { logger },\n } = ctx\n\n const log = errorParser(\n ctx,\n error,\n 'Request to Salesforce OAuth Provider failed with status',\n 'proxyRequest'\n )\n\n logger.error(log)\n\n ctx.status = log.status || 500\n ctx.set('Cache-Control', 'no-cache,no-store')\n ctx.body = {\n message: log.message,\n status: log.status\n }\n }\n}\n\n```" } ]
code_salesforce-oauth-middleware_258e7a36
[ { "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 salesforce-oauth-middleware/node/handlers/proxyGetHandler.ts from the salesforce-oauth-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport async function proxyGetHandler(ctx: Context) {\n const {\n clients: { salesforceProxy },\n vtex: {\n route: {\n params: { path },\n },\n },\n query\n } = ctx\n\n return salesforceProxy.proxyGet(path as string, query)\n}\n\n```" } ]
code_salesforce-oauth-middleware_8bed473d
[ { "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 salesforce-oauth-middleware/node/handlers/getAccessToken.ts from the salesforce-oauth-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { errorParser } from '../parsers/errorParses'\nimport SalesforceAccessToken from '../services/salesforceAccessToken'\n\nexport async function getAccessToken(ctx: Context) {\n try {\n const {\n vtex: { logger },\n state: { currentUser },\n } = ctx\n\n const salesforceAccessToken = new SalesforceAccessToken()\n const salesforceUserAccessToken = await salesforceAccessToken.get(\n ctx,\n currentUser.email\n )\n\n logger.info({\n message: 'Retrieve user access token success',\n currentUser,\n })\n\n ctx.set('Cache-Control', 'no-cache,no-store')\n ctx.status = 200\n ctx.body = salesforceUserAccessToken\n\n } catch (error) {\n const {\n vtex: { logger },\n } = ctx\n\n const log = errorParser(\n ctx,\n error,\n 'Retrieve user access token failed with status',\n 'getAccessToken'\n )\n\n logger.error(log)\n\n ctx.status = log.status || 500\n ctx.set('Cache-Control', 'no-cache,no-store')\n ctx.body = {\n appMessage: log.appMessage,\n method: log.method,\n status: log.status,\n statusText: log.statusText\n }\n }\n}\n\n```" } ]
code_salesforce-oauth-middleware_3daf061e
[ { "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 salesforce-oauth-middleware/node/handlers/proxyPostHandler.ts from the salesforce-oauth-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport qs from 'qs';\n\nexport async function proxyPostHandler(ctx: Context) {\n const {\n clients: { salesforceProxy },\n state: { body },\n vtex: {\n route: {\n params: { path },\n },\n },\n query\n } = ctx\n let reqBody = body\n\n if (ctx.request.type.includes('application/x-www-form-urlencoded')) {\n reqBody = qs.stringify(body)\n }\n\n return salesforceProxy.proxyPost(path as string, reqBody, query)\n}\n\n```" } ]
code_salesforce-oauth-middleware_74d2e450
[ { "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 salesforce-oauth-middleware/node/handlers/refreshAccessToken.ts from the salesforce-oauth-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ResolverError } from '@vtex/api'\nimport { errorParser } from '../parsers/errorParses'\nimport SalesforceAccessToken from '../services/salesforceAccessToken'\nimport SalesforceRefreshToken from '../services/salesforceRefreshToken'\n\nexport async function refreshAccessToken(ctx: Context) {\n try {\n const {\n clients: { salesforceProxy },\n state: { currentUser },\n } = ctx\n\n let refreshedData\n\n const salesforceRefreshToken = new SalesforceRefreshToken()\n const refreshTokenData: ISalesforceRefreshToken = await salesforceRefreshToken.get(\n ctx,\n currentUser.email\n )\n const salesforceAccessToken = new SalesforceAccessToken()\n const accessTokenData: ISalesforceAccessToken = await salesforceAccessToken.get(\n ctx,\n currentUser.email\n )\n\n const refreshToken = refreshTokenData.refresh_token\n\n if (!refreshToken) {\n throw new ResolverError(\"No refresh token found\")\n }\n\n const refreshAccessTokenRes: ISalesforceRefreshToken = await salesforceProxy.refreshToken(refreshToken)\n const refreshedAccessToken: string = refreshAccessTokenRes.access_token\n\n if(refreshedAccessToken) {\n refreshedData = await salesforceAccessToken.save(ctx, currentUser.email, accessTokenData, refreshedAccessToken)\n }\n\n ctx.set('Cache-Control', 'no-cache,no-store')\n ctx.status = 200\n ctx.body = refreshedData\n\n } catch (error) {\n const {\n vtex: { logger },\n } = ctx\n let body\n\n const log = errorParser(\n ctx,\n error,\n 'Refresh user access token failed with status',\n 'refreshAccessToken'\n )\n\n logger.error(log)\n\n if (log.status === 400) {\n body = error.response?.data\n } else {\n body = {\n appMessage: log.appMessage,\n method: log.method,\n status: log.status,\n statusText: log.statusText\n }\n }\n\n ctx.status = log.status || 500\n ctx.set('Cache-Control', 'no-cache,no-store')\n ctx.body = body\n }\n}\n\n```" } ]
code_salesforce-oauth-middleware_b64e18cc
[ { "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 salesforce-oauth-middleware/node/handlers/getUserInfoHandler.ts from the salesforce-oauth-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport async function getUserInfo(ctx: Context, accessToken: string) {\n const {\n clients: { salesforceProxy }\n } = ctx\n\n return salesforceProxy.proxyGet(\"/services/oauth2/userinfo\", { access_token: accessToken })\n}\n\n```" } ]
code_salesforce-oauth-middleware_2efaaa2d
[ { "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 salesforce-oauth-middleware/node/services/appSettingsService.ts from the salesforce-oauth-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { Apps } from '@vtex/api'\nimport { LRUCache } from '@vtex/api'\n\nimport type { AppSettings } from '../typings/appSettings'\nimport { DEFAULT_SETTINGS_CACHE_MAX_AGE_IN_MS } from '../utils/constants'\n\nexport const appSettingsService = (\n account: string,\n workspace: string,\n apps: Apps\n) => {\n const getSettings = async () => {\n const SettingsCache = new LRUCache<string, AppSettings>({ max: 5000 })\n const cacheKey = `${account}-${workspace}-${process.env.VTEX_APP_ID}`\n\n return (await SettingsCache.getOrSet(cacheKey, () =>\n apps.getAppSettings(process.env.VTEX_APP_ID as string).then((res) => {\n return {\n value: res,\n maxAge: DEFAULT_SETTINGS_CACHE_MAX_AGE_IN_MS,\n }\n })\n )) as AppSettings\n }\n\n return {\n getSettings,\n }\n}\n\n```" } ]
code_salesforce-oauth-middleware_acb7920c
[ { "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 salesforce-oauth-middleware/node/services/salesforceRefreshToken.ts from the salesforce-oauth-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { createHash } from 'crypto'\n\nexport default class SalesforceRefreshToken {\n constructor() {}\n\n public async get(\n ctx: Context,\n userEmail: string\n ): Promise<ISalesforceRefreshToken> {\n const {\n clients: { customVBase },\n } = ctx\n\n const normalizedFilePath = this.normalizedJSONFile(userEmail)\n\n return customVBase.getJSON<ISalesforceRefreshToken>(\n 'sf_refresh_token',\n normalizedFilePath\n )\n }\n\n public async save(\n ctx: Context,\n userEmail: string,\n res: ISalesforceRefreshToken\n ): Promise<ISalesforceRefreshToken> {\n const {\n clients: { customVBase }\n } = ctx\n\n const normalizedFilePath = this.normalizedJSONFile(userEmail)\n\n customVBase.saveJSON<ISalesforceRefreshToken>(\n 'sf_refresh_token',\n normalizedFilePath,\n res\n )\n\n return res\n }\n\n protected getTTL = (expirationInMinutes?: number) => {\n const ttl = new Date()\n\n ttl.setMinutes(ttl.getMinutes() + (expirationInMinutes || 1440))\n\n return ttl\n }\n\n protected normalizedJSONFile = (filePath: string) =>\n createHash('md5').update(filePath).digest('hex') + '.json'\n}\n\n```" } ]
code_salesforce-oauth-middleware_ace3c04d
[ { "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 salesforce-oauth-middleware/node/services/salesforceAccessToken.ts from the salesforce-oauth-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { createHash } from 'crypto'\n\nexport default class SalesforceAccessToken {\n constructor() {}\n\n public async get(\n ctx: Context,\n userEmail: string\n ): Promise<ISalesforceAccessToken> {\n const {\n clients: { customVBase },\n } = ctx\n\n const normalizedFilePath = this.normalizedJSONFile(userEmail)\n\n return customVBase.getJSON<ISalesforceAccessToken>(\n 'sf_token',\n normalizedFilePath\n )\n }\n\n public async save(\n ctx: Context,\n userEmail: string,\n res: ISalesforceAccessToken | ISalesforceAccessTokenRes,\n accessToken?: string\n ): Promise<ISalesforceAccessToken> {\n const {\n clients: { customVBase },\n state: { salesforceAccessToken }\n } = ctx\n\n const endDate = this.getTTL()\n const userInfo = {\n ...res,\n ...{\n access_token: accessToken ?? salesforceAccessToken,\n end_date: endDate,\n },\n }\n\n const normalizedFilePath = this.normalizedJSONFile(userEmail)\n\n customVBase.saveJSON<ISalesforceAccessToken>(\n 'sf_token',\n normalizedFilePath,\n userInfo\n )\n\n return userInfo\n }\n\n protected getTTL = (expirationInMinutes?: number) => {\n const ttl = new Date()\n\n ttl.setMinutes(ttl.getMinutes() + (expirationInMinutes || 1440))\n\n return ttl\n }\n\n protected normalizedJSONFile = (filePath: string) =>\n createHash('md5').update(filePath).digest('hex') + '.json'\n}\n\n```" } ]
code_order-shipping_55260ffc
[ { "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 order-shipping/docs/README.md from the order-shipping VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# Order Shipping\n\n> Centralizes all shipping related requests to the Checkout API.\n\nAny kind of shipping query or manipulation should be made through this component. This ensures that each interaction with the Checkout API happens in succession, avoiding concurrency issues.\n\n## Usage\n\nUse the hook `useOrderShipping` to get access to the API methods. Your component must be contained in a `OrderShippingProvider`, which in turn must be contained in a `OrderFormProvider` inside a `OrderQueueProvider`.\n\n```tsx\nimport { OrderFormProvider } from 'vtex.order-manager/OrderForm'\nimport { OrderQueueProvider } from 'vtex.order-manager/OrderQueue'\nimport {\n OrderShippingProvider,\n useOrderShipping,\n} from 'vtex.order-shipping/OrderShipping'\n\nconst MainComponent: FunctionComponent = () => (\n <OrderQueueProvider>\n <OrderFormProvider>\n <OrderShippingProvider>\n <MyComponent />\n </OrderShippingProvider>\n </OrderFormProvider>\n </OrderQueueProvider>\n)\n\nconst MyComponent: FunctionComponent = () => {\n const { insertAddress, selectDeliveryOption } = useOrderShipping()\n // ...\n}\n```\n\n## API\n\n### `insertAddress: (props: { addressId: string, addressType: string, city: string, country: string, state: string, street: string, postalCode: string, neighborhood: string, geocoordinates: number[], number: string, complement: string, receiverName: string, reference: string, addressQuery: string}) => void`\n\nSets the `selectedAddress` inside `shipping` property of the `orderForm`.\n\n#### Example\n\n```tsx\ninsertAddress({\n addressId: '1569522356557',\n addressType: 'residential',\n city: 'Rio de Janeiro',\n country: 'BRA',\n state: 'RJ',\n street: 'Rua General Polidoro',\n postalCode: '22230-060',\n neighborhood: 'Botafogo',\n geocoordinates: [],\n complement: '',\n number: '',\n receiverName: '',\n reference: '',\n addressQuery: '',\n})\n```\n\n### `selectDeliveryOption: ( deliveryOptionId: string ) => void`\n\nChanges the selected delivery option to be the one which has the given `deliveryOptionId`.\n\n#### Example\n\n```tsx\nselectDeliveryOption('PAC')\n```\n\n```" } ]
code_order-shipping_26ec1e61
[ { "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 order-shipping/react/OrderShipping.tsx from the order-shipping VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { useCallback } from 'react'\nimport { useMutation } from 'react-apollo'\nimport { OrderQueue, OrderForm } from 'vtex.order-manager'\nimport { Address as CheckoutAddress } from '@vtex/checkout-types'\nimport EstimateShippingMutation from 'vtex.checkout-resources/MutationEstimateShipping'\nimport SelectDeliveryOptionMutation from 'vtex.checkout-resources/MutationSelectDeliveryOption'\nimport SelectPickupOptionMutation from 'vtex.checkout-resources/MutationSelectPickupOption'\nimport UpdateSelectedAddressMutation from 'vtex.checkout-resources/MutationUpdateSelectedAddress'\n\nimport { useLogger } from './utils/logger'\nimport {\n createOrderShippingProvider,\n useOrderShipping,\n} from './components/createOrderShippingProvider'\n\nconst { useOrderQueue, useQueueStatus } = OrderQueue\n\nconst { useOrderForm } = OrderForm\n\nfunction useEstimateShipping() {\n const [estimateShipping] = useMutation(EstimateShippingMutation)\n\n return {\n estimateShipping: useCallback(\n async (address: CheckoutAddress) => {\n const {\n data: { estimateShipping: newOrderForm },\n } = await estimateShipping({\n variables: { addressInput: address },\n })\n\n return newOrderForm\n },\n [estimateShipping]\n ),\n }\n}\n\nfunction useSelectDeliveryOption() {\n const [selectDeliveryOption] = useMutation(SelectDeliveryOptionMutation)\n return {\n selectDeliveryOption: useCallback(\n async (deliveryOptionId: string) => {\n const {\n data: { selectDeliveryOption: newOrderForm },\n } = await selectDeliveryOption({\n variables: {\n deliveryOptionId,\n },\n })\n\n return newOrderForm\n },\n [selectDeliveryOption]\n ),\n }\n}\n\nfunction useSelectPickupOption() {\n const [selectPickupOption] = useMutation(SelectPickupOptionMutation)\n return {\n selectPickupOption: useCallback(\n async (pickupOptionId: string) => {\n const {\n data: { selectPickupOption: newOrderForm },\n } = await selectPickupOption({\n variables: {\n pickupOptionId,\n },\n })\n\n return newOrderForm\n },\n [selectPickupOption]\n ),\n }\n}\n\nfunction useUpdateSelectedAddress() {\n const [updateSelectedAddress] = useMutation(UpdateSelectedAddressMutation)\n return {\n updateSelectedAddress: useCallback(\n async (address: CheckoutAddress) => {\n const {\n data: { updateSelectedAddress: newOrderForm },\n } = await updateSelectedAddress({\n variables: {\n address,\n },\n })\n\n return newOrderForm\n },\n [updateSelectedAddress]\n ),\n }\n}\n\nconst { OrderShippingProvider } = createOrderShippingProvider({\n useOrderForm,\n useOrderQueue,\n useQueueStatus,\n useSelectPickupOption,\n useEstimateShipping,\n useSelectDeliveryOption,\n useLogger,\n useUpdateSelectedAddress,\n})\n\nexport { OrderShippingProvider, useOrderShipping }\nexport default { OrderShippingProvider, useOrderShipping }\n\n```" } ]
code_order-shipping_c394f24e
[ { "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 order-shipping/react/package.json from the order-shipping VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"scripts\": {\n \"test\": \"vtex-test-tools test\",\n \"lint\": \"tsc --noEmit && eslint --ext ts,tsx .\"\n },\n \"dependencies\": {\n \"@vtex/css-handles\": \"^1.0.0\",\n \"classnames\": \"^2.2.6\",\n \"ramda\": \"^0.26.1\",\n \"react\": \"^16.8.3\",\n \"react-apollo\": \"^3.1.3\",\n \"react-dom\": \"^16.8.3\"\n },\n \"devDependencies\": {\n \"@apollo/react-testing\": \"^3.1.3\",\n \"@testing-library/react-hooks\": \"^7.0.2\",\n \"@types/classnames\": \"^2.2.7\",\n \"@types/graphql\": \"^14.2.0\",\n \"@types/jest\": \"^24.0.11\",\n \"@types/node\": \"^11.13.0\",\n \"@types/prop-types\": \"^15.7.0\",\n \"@types/ramda\": \"^0.26.5\",\n \"@types/react\": \"^16.8.10\",\n \"@vtex/checkout-types\": \"^0.1.2\",\n \"@vtex/order-manager\": \"^0.5.4-beta.0\",\n \"@vtex/test-tools\": \"^3.1.0\",\n \"react-intl\": \"^4.3.1\",\n \"typescript\": \"3.9.7\",\n \"vtex.checkout-graphql\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.checkout-graphql@0.55.1/public/@types/vtex.checkout-graphql\",\n \"vtex.checkout-resources\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.checkout-resources@0.41.0/public/@types/vtex.checkout-resources\",\n \"vtex.order-manager\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.order-manager@0.9.0/public/@types/vtex.order-manager\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.126.5/public/@types/vtex.render-runtime\"\n },\n \"version\": \"0.8.0\"\n}\n\n```" } ]
code_order-shipping_3c59e4af
[ { "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 order-shipping/react/__fixtures__/OrderFormProvider.tsx from the order-shipping VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { createOrderFormProvider } from '@vtex/order-manager'\n\nimport { mockOrderForm } from './orderForm'\n\nfunction useToast() {\n return {\n showToast: () => {},\n toastState: {\n isToastVisible: false,\n },\n }\n}\n\nfunction useClearOrderFormMessages() {\n return () =>\n new Promise(resolve => {\n resolve(true)\n })\n}\n\nfunction useGetOrderForm(args: any): any {\n return new Promise(resolve => {\n resolve({\n ...args,\n })\n })\n}\n\nconst { OrderFormProvider } = createOrderFormProvider({\n useToast,\n useClearOrderFormMessages,\n useGetOrderForm,\n defaultOrderForm: mockOrderForm,\n})\n\nexport { OrderFormProvider }\n\n```" } ]
code_order-shipping_29097da7
[ { "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 order-shipping/react/__fixtures__/orderForm.ts from the order-shipping VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const mockOrderForm = {\n id: '123',\n loggedIn: false,\n paymentData: {\n installmentOptions: [\n {\n value: 100,\n paymentSystem: '1',\n installments: [],\n },\n ],\n isValid: true,\n payments: [],\n paymentSystems: [],\n availableAccounts: [],\n },\n items: [\n {\n additionalInfo: {\n brandName: 'Test Brand 0',\n },\n id: '1',\n uniqueId: '1',\n detailUrl: '/work-shirt/p',\n imageUrls: {\n at1x:\n 'http://storecomponents.vteximg.com.br/arquivos/ids/155476-55-55/Frame-4.jpg?v=636793808441900000',\n at2x:\n 'http://storecomponents.vteximg.com.br/arquivos/ids/155476-55-55/Frame-4.jpg?v=636793808441900000',\n at3x:\n 'http://storecomponents.vteximg.com.br/arquivos/ids/155476-55-55/Frame-4.jpg?v=636793808441900000',\n },\n listPrice: 2800000,\n measurementUnit: 'un',\n name: 'قميص العمل الأعلى',\n price: 2400000,\n productId: '1',\n quantity: 3,\n sellingPrice: 2400000,\n skuName: 'Test SKU 0',\n skuSpecifications: [],\n attachmentOfferings: [],\n bundleItems: [],\n\n attachments: [],\n offerings: [],\n priceTags: [],\n },\n {\n additionalInfo: {\n brandName: 'Test Brand 1',\n },\n id: '30',\n uniqueId: '30',\n detailUrl: '/long-sleeve-shirt/p',\n imageUrls: {\n at1x:\n 'http://storecomponents.vteximg.com.br/arquivos/ids/155487-55-55/Frame-7.jpg?v=636793837686400000',\n at2x:\n 'http://storecomponents.vteximg.com.br/arquivos/ids/155487-55-55/Frame-7.jpg?v=636793837686400000',\n at3x:\n 'http://storecomponents.vteximg.com.br/arquivos/ids/155487-55-55/Frame-7.jpg?v=636793837686400000',\n },\n listPrice: 945000,\n measurementUnit: 'un',\n name: '上品なサングラス',\n price: 945000,\n productId: '2000005',\n quantity: 1,\n sellingPrice: 945000,\n skuName: 'Test SKU 1',\n skuSpecifications: [],\n attachmentOfferings: [],\n bundleItems: [],\n isGift: false,\n attachments: [],\n offerings: [],\n priceTags: [],\n },\n {\n additionalInfo: {\n brandName: 'Test Brand 2',\n },\n id: '2000535',\n uniqueId: '2000535',\n detailUrl: '/classy--sunglasses/p',\n imageUrls: {\n at1x:\n 'http://storecomponents.vteximg.com.br/arquivos/ids/155469-55-55/Frame-8.jpg?v=636793757498800000',\n at2x:\n 'http://storecomponents.vteximg.com.br/arquivos/ids/155469-55-55/Frame-8.jpg?v=636793757498800000',\n at3x:\n 'http://storecomponents.vteximg.com.br/arquivos/ids/155469-55-55/Frame-8.jpg?v=636793757498800000',\n },\n listPrice: 400000,\n measurementUnit: 'un',\n name: 'กางเกงขาสั้น St Tropez',\n price: 360000,\n productId: '13',\n quantity: 4,\n sellingPrice: 360000,\n skuName: 'Test SKU 2',\n skuSpecifications: [],\n attachmentOfferings: [],\n bundleItems: [],\n isGift: false,\n attachments: [],\n offerings: [],\n priceTags: [],\n },\n ],\n marketingData: {},\n totalizers: [\n {\n id: 'Items',\n name: 'Items Total',\n value: 9585000,\n },\n ],\n shipping: {\n countries: ['BRA'],\n deliveryOptions: [\n { id: 'Motoboy', price: 500, estimate: '8d', isSelected: false },\n { id: 'PAC', price: 1000, estimate: '5d', isSelected: false },\n { id: 'Expressa', price: 1000, estimate: '7d', isSelected: true },\n ],\n selectedAddress: {\n addressId: '1569522356557',\n addressType: 'residential',\n city: 'Rio de Janeiro',\n complement: '',\n country: 'BRA',\n neighborhood: 'Flamengo',\n number: '',\n postalCode: '22280-001',\n receiverName: '',\n reference: '',\n state: 'RJ',\n street: '',\n geoCoordinates: [],\n },\n },\n messages: {\n couponMessages: [],\n generalMessages: [],\n },\n clientProfileData: {\n email: 'fulanodetal@vtex.com',\n firstName: 'Fulano',\n lastName: 'Di Tal',\n isValid: true,\n },\n canEditData: false,\n value: 9585000,\n}\n\n```" } ]
code_order-shipping_602a49c5
[ { "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 order-shipping/react/typings/storefront.d.ts from the order-shipping VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { FunctionComponent } from 'react'\n\ndeclare global {\n interface StorefrontFunctionComponent<P = {}> extends FunctionComponent<P> {\n getSchema?(props: P): object\n schema?: object\n }\n\n interface StorefrontComponent<P = {}, S = {}> extends Component<P, S> {\n getSchema?(props: P): object\n schema: object\n }\n}\n\n```" } ]
code_order-shipping_40dd5456
[ { "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 order-shipping/react/typings/vtex.checkout-resources.d.ts from the order-shipping VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.checkout-resources/MutationEstimateShipping' {\n export { default } from 'vtex.checkout-resources/react/MutationEstimateShipping'\n}\n\ndeclare module 'vtex.checkout-resources/MutationSelectDeliveryOption' {\n export { default } from 'vtex.checkout-resources/react/MutationSelectDeliveryOption'\n}\n\ndeclare module 'vtex.checkout-resources/MutationUpdateSelectedAddress' {\n export { default } from 'vtex.checkout-resources/react/MutationUpdateSelectedAddress'\n}\n\ndeclare module 'vtex.checkout-resources/MutationSelectPickupOption' {\n export { default } from 'vtex.checkout-resources/MutationSelectPickupOption'\n}\n\n```" } ]
code_order-shipping_1375556a
[ { "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 order-shipping/react/typings/vtex.render-runtime.d.ts from the order-shipping VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* Typings for `render-runtime` */\ndeclare module 'vtex.render-runtime' {\n import { Component, ComponentType, ReactElement, ReactType } from 'react'\n\n export interface NavigationOptions {\n page: string\n params?: any\n }\n\n export interface RenderContextProps {\n runtime: {\n navigate: (options: NavigationOptions) => void\n }\n }\n\n interface ExtensionPointProps {\n id: string\n [key: string]: any\n }\n\n export const ExtensionPoint: ComponentType<ExtensionPointProps>\n\n interface ChildBlockProps {\n id: string\n }\n\n export const ChildBlock: ComponentType<ChildBlockProps>\n export const useChildBlock = function({ id: string }): object {}\n\n export const Helmet: ReactElement\n export const Link: ReactType\n export const NoSSR: ReactElement\n export const RenderContextConsumer: ReactElement\n export const canUseDOM: boolean\n export const withRuntimeContext: <TOriginalProps extends {}>(\n Component: ComponentType<TOriginalProps & RenderContextProps>\n ) => ComponentType<TOriginalProps>\n}\n\n```" } ]
code_order-shipping_14586cd4
[ { "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 order-shipping/react/typings/css.d.ts from the order-shipping VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*.css' {\n const css: any\n export default css\n}\n\n```" } ]
code_order-shipping_892b9d74
[ { "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 order-shipping/react/typings/graphql.d.ts from the order-shipping VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*.graphql' {\n import { DocumentNode } from 'graphql'\n\n const value: DocumentNode\n export default value\n}\n\n```" } ]
code_order-shipping_ad0472f1
[ { "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 order-shipping/react/typings/vtex.styleguide.d.ts from the order-shipping VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.styleguide' {\n import { ComponentType } from 'react'\n\n export const Input: ComponentType<InputProps>\n\n interface InputProps {\n [key: string]: any\n }\n}\n\n```" } ]
code_order-shipping_56a6a2c2
[ { "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 order-shipping/react/utils/logger.ts from the order-shipping VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport interface LogParams {\n type: 'Error'\n level: 'Critical'\n event: unknown\n workflowType?: 'OrderShipping'\n workflowInstance: string\n}\n\nexport type LogFn = (params: LogParams) => void\n\nexport type UseLogger = () => { log: LogFn }\n\nconst log = ({\n type,\n level,\n event,\n workflowType,\n workflowInstance,\n}: LogParams) => {\n // eslint-disable-next-line no-console\n console.log({\n type,\n level,\n event,\n workflowInstance,\n workflowType: workflowType ?? 'OrderShipping',\n })\n}\n\nexport function useLogger() {\n return { log }\n}\n\n```" } ]
code_order-shipping_089e7a4c
[ { "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 order-shipping/react/components/createOrderShippingProvider.tsx from the order-shipping VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, {\n createContext,\n useContext,\n useCallback,\n useMemo,\n useState,\n FC,\n} from 'react'\nimport { OrderQueueContext } from '@vtex/order-manager'\nimport {\n OrderForm as CheckoutOrderForm,\n Address as CheckoutAddress,\n DeliveryOption,\n PickupOption,\n} from '@vtex/checkout-types'\n\nimport { UseLogger } from '../utils/logger'\n\nexport const QueueStatus = {\n PENDING: 'Pending',\n FULFILLED: 'Fulfilled',\n} as const\n\ninterface InsertAddressResult {\n success: boolean\n orderForm?: CheckoutOrderForm\n}\n\ninterface SelectShippingOptionResult {\n success: boolean\n orderForm?: CheckoutOrderForm\n}\n\ninterface SelectAddressResult {\n success: boolean\n}\n\ninterface ShippingContext {\n searchedAddress: CheckoutAddress | null\n countries: string[]\n canEditData: boolean\n selectedAddress?: CheckoutAddress\n updateSelectedAddress: (\n address: CheckoutAddress\n ) => Promise<SelectAddressResult>\n insertAddress: (address: CheckoutAddress) => Promise<InsertAddressResult>\n deliveryOptions: DeliveryOption[]\n pickupOptions: PickupOption[]\n selectDeliveryOption: (option: string) => Promise<SelectShippingOptionResult>\n selectPickupOption: (option: string) => Promise<SelectShippingOptionResult>\n}\n\nconst OrderShippingContext = createContext<ShippingContext | undefined>(\n undefined\n)\n\nconst TASK_CANCELLED = 'TASK_CANCELLED'\n\ntype ListenFunction = (event: any, callback: () => void) => () => void\ninterface QueueContext {\n enqueue: (task: () => Promise<CheckoutOrderForm>, id?: string) => any\n listen: ListenFunction\n isWaiting: (id: string) => boolean\n}\ndeclare type OrderFormUpdate<O> =\n | Partial<O>\n | ((prevOrderForm: O) => Partial<O>)\n\ninterface OrderContext<O extends CheckoutOrderForm> {\n loading: boolean\n setOrderForm: (nextValue: OrderFormUpdate<O>) => void\n error: any | undefined\n orderForm: O\n}\n\ntype UseEstimateShipping = () => {\n estimateShipping: (\n address: CheckoutAddress,\n orderFormId?: string\n ) => Promise<CheckoutOrderForm>\n}\n\ntype UseSelectDeliveryOption = () => {\n selectDeliveryOption: (\n deliveryOptionId: string,\n orderFormId?: string\n ) => Promise<CheckoutOrderForm>\n}\n\ntype UseSelectPickupOption = () => {\n selectPickupOption: (\n pickupOptionId: string,\n orderFormId?: string\n ) => Promise<CheckoutOrderForm>\n}\n\ntype UseUpdateSelectedAddress = () => {\n updateSelectedAddress: (\n address: CheckoutAddress,\n orderFormId?: string\n ) => Promise<CheckoutOrderForm>\n}\n\ninterface CreateOrderShippingProvider<O extends CheckoutOrderForm> {\n useLogger: UseLogger\n useOrderQueue: () => QueueContext\n useOrderForm: () => OrderContext<O>\n useQueueStatus: (listen: OrderQueueContext<O>['listen']) => any\n useEstimateShipping: UseEstimateShipping\n useSelectDeliveryOption: UseSelectDeliveryOption\n useSelectPickupOption: UseSelectPickupOption\n useUpdateSelectedAddress: UseUpdateSelectedAddress\n}\n\nexport function createOrderShippingProvider({\n useLogger,\n useOrderQueue,\n useOrderForm,\n useQueueStatus,\n useEstimateShipping,\n useSelectDeliveryOption,\n useSelectPickupOption,\n useUpdateSelectedAddress,\n}: CreateOrderShippingProvider<CheckoutOrderForm>) {\n const OrderShippingProvider: FC = ({ children }) => {\n const { enqueue, listen } = useOrderQueue()\n const { orderForm, setOrderForm } = useOrderForm()\n const { estimateShipping } = useEstimateShipping()\n const { selectDeliveryOption } = useSelectDeliveryOption()\n const { selectPickupOption } = useSelectPickupOption()\n const { updateSelectedAddress } = useUpdateSelectedAddress()\n const { log } = useLogger()\n const queueStatusRef = useQueueStatus(listen)\n const {\n canEditData,\n id,\n shipping: { countries, selectedAddress, deliveryOptions, pickupOptions },\n } = orderForm\n\n const [\n searchedAddress,\n setSearchedAddress,\n ] = useState<CheckoutAddress | null>(null)\n\n const handleInsertAddress = useCallback(\n async (address: CheckoutAddress) => {\n const task = async () => {\n const orderFormUpdate = await estimateShipping(address, id)\n\n return orderFormUpdate\n }\n\n try {\n const newOrderForm = await enqueue(task, 'insertAddress')\n\n if (queueStatusRef.current === QueueStatus.FULFILLED) {\n setOrderForm(newOrderForm)\n }\n\n setSearchedAddress(address)\n\n return { success: true, orderForm: newOrderForm as CheckoutOrderForm }\n } catch (error) {\n log({\n type: 'Error',\n level: 'Critical',\n event: {\n error,\n orderFormId: id,\n },\n workflowInstance: 'insert-address-error',\n })\n if (!error || error.code !== TASK_CANCELLED) {\n throw error\n }\n return { success: false }\n }\n },\n [estimateShipping, enqueue, queueStatusRef, setOrderForm, id, log]\n )\n\n const handleSelectDeliveryOption = useCallback(\n async (deliveryOptionId: string) => {\n const task = async () => {\n const updatedOrderForm = await selectDeliveryOption(\n deliveryOptionId,\n id\n )\n\n return updatedOrderForm\n }\n\n setOrderForm(prevOrderForm => ({\n ...prevOrderForm,\n shipping: {\n ...prevOrderForm.shipping,\n deliveryOptions: prevOrderForm.shipping.deliveryOptions?.map(\n deliveryOption => ({\n ...deliveryOption,\n isSelected: deliveryOption?.id === deliveryOptionId,\n })\n ),\n },\n }))\n\n enqueue(task, 'selectDeliveryOption').then(\n (newOrderForm: CheckoutOrderForm) => {\n if (queueStatusRef.current === QueueStatus.FULFILLED) {\n setOrderForm(newOrderForm)\n }\n }\n )\n\n return { success: true }\n },\n [queueStatusRef, selectDeliveryOption, enqueue, setOrderForm, id]\n )\n\n const handleSelectPickupOption = useCallback(\n async (pickupOptionId: string) => {\n const task = async () => {\n const updatedOrderForm = await selectPickupOption(pickupOptionId, id)\n\n return updatedOrderForm\n }\n\n setOrderForm(prevOrderForm => ({\n ...prevOrderForm,\n shipping: {\n ...prevOrderForm.shipping,\n pickupOptions: prevOrderForm.shipping.pickupOptions?.map(\n pickupOption => ({\n ...pickupOption,\n isSelected: pickupOption?.id === pickupOptionId,\n })\n ),\n },\n }))\n\n enqueue(task, 'selectPickupOption').then(\n (newOrderForm: CheckoutOrderForm) => {\n if (queueStatusRef.current === QueueStatus.FULFILLED) {\n setOrderForm(newOrderForm)\n }\n }\n )\n\n return { success: true }\n },\n [queueStatusRef, selectPickupOption, enqueue, setOrderForm, id]\n )\n\n const handleSelectAddress = useCallback(\n async (address: CheckoutAddress) => {\n const task = async () => {\n const newOrderForm = await updateSelectedAddress(address, id)\n\n return newOrderForm\n }\n\n try {\n const newOrderForm = await enqueue(task, 'selectAddress')\n\n if (queueStatusRef.current === QueueStatus.FULFILLED) {\n setOrderForm(newOrderForm)\n }\n\n return { success: true, orderForm: newOrderForm as CheckoutOrderForm }\n } catch (error) {\n log({\n type: 'Error',\n level: 'Critical',\n event: {\n error,\n orderFormId: id,\n },\n workflowInstance: 'selected-address-not-update',\n })\n if (!error || error.code !== TASK_CANCELLED) {\n throw error\n }\n return { success: false }\n }\n },\n [enqueue, queueStatusRef, updateSelectedAddress, setOrderForm, id, log]\n )\n\n const contextValue = useMemo(\n () => ({\n searchedAddress,\n canEditData,\n countries: countries as string[],\n selectedAddress: selectedAddress!,\n updateSelectedAddress: handleSelectAddress,\n insertAddress: handleInsertAddress,\n deliveryOptions: deliveryOptions as DeliveryOption[],\n pickupOptions: pickupOptions as PickupOption[],\n selectDeliveryOption: handleSelectDeliveryOption,\n selectPickupOption: handleSelectPickupOption,\n }),\n [\n searchedAddress,\n canEditData,\n countries,\n selectedAddress,\n handleSelectAddress,\n handleInsertAddress,\n deliveryOptions,\n pickupOptions,\n handleSelectDeliveryOption,\n handleSelectPickupOption,\n ]\n )\n\n return (\n <OrderShippingContext.Provider value={contextValue}>\n {children}\n </OrderShippingContext.Provider>\n )\n }\n\n return { OrderShippingProvider }\n}\n\nexport const useOrderShipping = () => {\n const context = useContext(OrderShippingContext)\n if (context === undefined) {\n throw new Error(\n 'useOrderShipping must be used within a OrderShippingProvider'\n )\n }\n\n return context\n}\n\nexport default { createOrderShippingProvider, useOrderShipping }\n\n```" } ]
code_order-shipping_2798f212
[ { "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 order-shipping/react/__tests__/createOrderShippingProvider.test.tsx from the order-shipping VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { FC } from 'react'\nimport {\n useOrderForm,\n useOrderQueue,\n useQueueStatus,\n OrderQueueProvider,\n} from '@vtex/order-manager'\nimport { renderHook, act } from '@testing-library/react-hooks'\n\nimport {\n createOrderShippingProvider,\n useOrderShipping,\n} from '../components/createOrderShippingProvider'\nimport { LogParams } from '../utils/logger'\nimport { OrderFormProvider } from '../__fixtures__/OrderFormProvider'\nimport { mockOrderForm } from '../__fixtures__/orderForm'\n\nconst mockLog = jest.fn()\n\nfunction useLogger() {\n const log = ({\n type,\n level,\n event,\n workflowType,\n workflowInstance,\n }: LogParams) => {\n mockLog({\n type,\n level,\n event,\n workflowType: workflowType ?? 'OrderProfileTest',\n workflowInstance,\n })\n }\n\n return { log }\n}\n\nconst mockUseSelectPickupOption = jest.fn().mockResolvedValue(true)\nconst mockUseEstimateShipping = jest.fn().mockResolvedValue(true)\nconst mockUseSelectDeliveryOption = jest.fn().mockResolvedValue(true)\nconst mockUseUpdateSelectedAddress = jest.fn().mockResolvedValue(true)\n\nconst createWrapperOrderProviders = () => {\n const useSelectPickupOption = () => ({\n selectPickupOption: mockUseSelectPickupOption,\n })\n\n const useEstimateShipping = () => ({\n estimateShipping: mockUseEstimateShipping,\n })\n\n const useUpdateSelectedAddress = () => ({\n updateSelectedAddress: mockUseUpdateSelectedAddress,\n })\n const useSelectDeliveryOption = () => ({\n selectDeliveryOption: mockUseSelectDeliveryOption,\n })\n\n const { OrderShippingProvider } = createOrderShippingProvider({\n useLogger,\n useOrderQueue,\n useOrderForm,\n useQueueStatus,\n useSelectPickupOption,\n useEstimateShipping,\n useUpdateSelectedAddress,\n useSelectDeliveryOption,\n })\n\n const Wrapper: FC = ({ children }) => {\n return (\n <OrderQueueProvider>\n <OrderFormProvider>\n <OrderShippingProvider>{children}</OrderShippingProvider>\n </OrderFormProvider>\n </OrderQueueProvider>\n )\n }\n\n return { Wrapper }\n}\n\nconst mockAddress = {\n addressId: '1569522356557',\n addressType: 'residential',\n city: 'Rio de Janeiro',\n complement: '',\n country: 'BRA',\n neighborhood: 'Flamengo',\n number: '',\n postalCode: '22250-040',\n receiverName: '',\n reference: '',\n state: 'RJ',\n street: '',\n geoCoordinates: [],\n}\n\ndescribe('OrderProfile', () => {\n it('should throw an error if theres no OrderShippingProvider on the tree', () => {\n const {\n result: { error },\n } = renderHook(() => useOrderShipping())\n\n expect(error).not.toBeNull()\n expect(error?.message).toEqual(\n 'useOrderShipping must be used within a OrderShippingProvider'\n )\n })\n\n it('should get the right values from the orderForm', () => {\n const { Wrapper } = createWrapperOrderProviders()\n\n const {\n result: { error, current },\n } = renderHook(() => useOrderShipping(), { wrapper: Wrapper })\n\n expect(error).toBeUndefined()\n expect(current.selectedAddress).toEqual(\n mockOrderForm.shipping.selectedAddress\n )\n expect(current.countries).toEqual(mockOrderForm.shipping.countries)\n expect(current.deliveryOptions).toEqual(\n mockOrderForm.shipping.deliveryOptions\n )\n })\n\n it('should call estimateShipping if insertAddress was executed', async () => {\n const { Wrapper } = createWrapperOrderProviders()\n\n const {\n result: {\n current: { insertAddress },\n },\n } = renderHook(() => useOrderShipping(), { wrapper: Wrapper })\n\n await act(async () => {\n const { success } = await insertAddress(mockAddress)\n\n expect(success).toBeTruthy()\n })\n expect(mockUseEstimateShipping).toHaveBeenCalledWith(\n mockAddress,\n mockOrderForm.id\n )\n expect(mockLog).not.toHaveBeenCalled()\n })\n\n it('should call selectedDeliveryOption query if selectDeliveryOption was executed', async () => {\n const { Wrapper } = createWrapperOrderProviders()\n\n const {\n result: {\n current: { selectDeliveryOption },\n },\n } = renderHook(() => useOrderShipping(), { wrapper: Wrapper })\n\n await act(async () => {\n const { success } = await selectDeliveryOption(\n mockOrderForm.shipping.deliveryOptions[1].id\n )\n\n expect(success).toBeTruthy()\n })\n expect(mockUseSelectDeliveryOption).toHaveBeenCalledWith(\n mockOrderForm.shipping.deliveryOptions[1].id,\n mockOrderForm.id\n )\n expect(mockLog).not.toHaveBeenCalled()\n })\n\n it('should call selectedPickupOption query if selectedPickupOption was executed', async () => {\n const { Wrapper } = createWrapperOrderProviders()\n\n const {\n result: {\n current: { selectPickupOption },\n },\n } = renderHook(() => useOrderShipping(), { wrapper: Wrapper })\n\n await act(async () => {\n const { success } = await selectPickupOption(\n mockOrderForm.shipping.deliveryOptions[1].id\n )\n\n expect(success).toBeTruthy()\n })\n expect(mockUseSelectPickupOption).toHaveBeenCalledWith(\n mockOrderForm.shipping.deliveryOptions[1].id,\n mockOrderForm.id\n )\n expect(mockLog).not.toHaveBeenCalled()\n })\n\n it('should call updateSelectedAddress if selectAddress was executed', async () => {\n const { Wrapper } = createWrapperOrderProviders()\n\n const {\n result: {\n current: { updateSelectedAddress },\n },\n } = renderHook(() => useOrderShipping(), { wrapper: Wrapper })\n\n await act(async () => {\n const { success } = await updateSelectedAddress(mockAddress)\n\n expect(success).toBeTruthy()\n })\n expect(mockUseUpdateSelectedAddress).toHaveBeenCalledWith(\n mockAddress,\n mockOrderForm.id\n )\n expect(mockLog).not.toHaveBeenCalled()\n })\n})\n\n```" } ]
code_order-shipping_ebbdc666
[ { "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 order-shipping/react/__tests__/OrderShipping.test.tsx from the order-shipping VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { FunctionComponent } from 'react'\nimport { act, render, fireEvent } from '@vtex/test-tools/react'\nimport EstimateShipping from 'vtex.checkout-resources/MutationEstimateShipping'\nimport SelectDeliveryOption from 'vtex.checkout-resources/MutationSelectDeliveryOption'\nimport { OrderForm, OrderQueue } from 'vtex.order-manager'\n\nimport { mockOrderForm } from '../__fixtures__/orderForm'\nimport { OrderShippingProvider, useOrderShipping } from '../OrderShipping'\n\nconst { OrderFormProvider, useOrderForm } = OrderForm\nconst { OrderQueueProvider } = OrderQueue\n\nconst mockedAddress = {\n addressId: '1569522356558',\n addressType: 'residential',\n city: 'Rio de Janeiro',\n complement: '',\n country: 'BRA',\n neighborhood: 'Botafogo',\n number: '',\n postalCode: '22230-005',\n receiverName: '',\n reference: '',\n state: 'RJ',\n street: '',\n geoCoordinates: [],\n}\n\nconst mockedDeliveryOptions = [\n { id: 'Motoboy', price: 500, estimate: '8d', isSelected: false },\n { id: 'PAC', price: 1000, estimate: '5d', isSelected: true },\n { id: 'Expressa', price: 1000, estimate: '7d', isSelected: false },\n]\n\nconst mockInsertAddressMutation = (\n args: CheckoutAddress,\n result: CheckoutAddress\n) => ({\n request: {\n query: EstimateShipping,\n variables: {\n addressInput: args,\n },\n },\n result: {\n data: {\n estimateShipping: {\n ...mockOrderForm,\n shipping: {\n selectedAddress: result,\n },\n },\n },\n },\n})\n\nconst mockSelectDeliveryOptionMutation = (\n args: string,\n result: DeliveryOption[]\n) => ({\n request: {\n query: SelectDeliveryOption,\n variables: {\n deliveryOptionId: args,\n },\n },\n result: {\n data: {\n selectDeliveryOption: {\n ...mockOrderForm,\n shipping: {\n deliveryOptions: result,\n },\n },\n },\n },\n})\n\ndescribe('OrderShipping', () => {\n it('should throw when useOrderShipping is used outside a OrderShippingProvider', () => {\n const oldConsoleError = console.error\n console.error = () => {}\n\n const Component: FunctionComponent = () => {\n useOrderShipping()\n return <div>foo</div>\n }\n\n expect(() => render(<Component />)).toThrow(\n 'useOrderShipping must be used within a OrderShippingProvider'\n )\n\n console.error = oldConsoleError\n })\n\n it('should change selectedAddress', async () => {\n const Component: FunctionComponent = () => {\n const {\n orderForm: {\n shipping: {\n selectedAddress: { postalCode },\n },\n },\n } = useOrderForm()\n const { insertAddress } = useOrderShipping()\n\n return (\n <div>\n {postalCode}\n <button onClick={() => insertAddress(mockedAddress)}>mutate</button>\n </div>\n )\n }\n\n const mockInsertAddress = mockInsertAddressMutation(\n mockedAddress,\n mockedAddress\n )\n\n const { getByText } = render(\n <OrderQueueProvider>\n <OrderFormProvider>\n <OrderShippingProvider>\n <Component />\n </OrderShippingProvider>\n </OrderFormProvider>\n </OrderQueueProvider>,\n { graphql: { mocks: [mockInsertAddress] } }\n )\n\n const button = getByText('mutate')\n\n expect(getByText('22280-001')).toBeTruthy()\n act(() => {\n fireEvent.click(button)\n })\n\n await act(() => new Promise(resolve => setTimeout(() => resolve())))\n\n expect(getByText('22230-005')).toBeTruthy()\n })\n\n it('should change the selected delivery option', async () => {\n const Component: FunctionComponent = () => {\n const {\n orderForm: {\n shipping: { deliveryOptions },\n },\n } = useOrderForm()\n const { selectDeliveryOption } = useOrderShipping()\n\n const { id } = deliveryOptions.find((option: DeliveryOption) => {\n return option.isSelected\n })\n\n return (\n <div>\n {id}\n <button onClick={() => selectDeliveryOption('PAC')}>mutate</button>\n </div>\n )\n }\n\n const mockSelectDeliveryOptions = mockSelectDeliveryOptionMutation(\n 'PAC',\n mockedDeliveryOptions\n )\n\n const { getByText } = render(\n <OrderQueueProvider>\n <OrderFormProvider>\n <OrderShippingProvider>\n <Component />\n </OrderShippingProvider>\n </OrderFormProvider>\n </OrderQueueProvider>,\n { graphql: { mocks: [mockSelectDeliveryOptions] } }\n )\n\n expect(getByText('Expressa')).toBeTruthy()\n\n const button = getByText('mutate')\n\n act(() => {\n fireEvent.click(button)\n })\n\n await act(() => new Promise(resolve => setTimeout(() => resolve())))\n\n expect(getByText('PAC')).toBeTruthy()\n })\n})\n\n```" } ]
code_vtex-scripts_e8845392
[ { "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 vtex-scripts/bin/vtex-scripts.js from the vtex-scripts VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n#!/usr/bin/env node\n'use strict'\n\nconst args = process.argv.slice(2)\n\nif (args.length === 0) {\n process.exit(1)\n}\n\nconst script = args[0]\n\nswitch (script) {\n case 'test':\n case 'build': {\n const executeScript = require(`../scripts/${script}`)\n\n try {\n executeScript(...args.slice(1))\n } catch (e) {\n console.log(`An error occurred while running the script \"${script}\".\\n`)\n console.log(\n 'If you think this is a bug in our tools, feel free to file a bug report at',\n 'https://www.github.com/vtex-apps/npm-storecomponents/issues\\n'\n )\n process.exit(1)\n }\n break\n }\n default:\n console.log(`Unknown script \"${script}\".`)\n break\n}\n\n```" } ]
code_vtex-scripts_b00c7bab
[ { "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 vtex-scripts/config/createJestConfig.js from the vtex-scripts VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n'use strict'\n\nconst fs = require('fs')\nconst path = require('path')\nconst paths = require('../utils/paths')\nconst overrides = require('../utils/overrides')\n\nmodule.exports = (resolve, rootDir, srcDirs) => {\n const setupTestsFile = fs.existsSync(paths.testsSetup)\n ? `<rootDir>/${paths.rawTestsSetup}`\n : undefined\n\n let config = {\n roots: srcDirs.map(d => `<rootDir>/${path.relative(rootDir || '', d)}`),\n setupTestFrameworkScriptFile: setupTestsFile,\n testEnvironment: 'node',\n testURL: 'http://localhost',\n transform: {\n '^.+\\\\.(js|jsx|mjs)$': resolve('config/jest/babelTransform.js'),\n '^.+\\\\.css$': resolve('config/jest/cssTransform.js'),\n '^.+\\\\.(graphql|gql)$': resolve('config/jest/graphqlTransform.js'),\n '^(?!.*\\\\.(js|jsx|mjs|css|json|graphql|gql)$)': resolve(\n 'config/jest/fileTransform.js'\n ),\n },\n // Consider the node_modules installed in `vtex-scripts`, on the rootPath\n // and inside every source directory folder\n moduleDirectories: [\n '<rootDir>/node_modules',\n ...srcDirs.map(\n d =>\n `<rootDir>/${path.relative(\n rootDir || '',\n path.join(d, 'node_modules')\n )}`\n ),\n path.join(__dirname, '..', 'node_modules'),\n ],\n transformIgnorePatterns: ['[/\\\\\\\\]node_modules[/\\\\\\\\].+\\\\.(js|jsx|mjs)$'],\n testPathIgnorePatterns: [\n '[/\\\\\\\\]node_modules[/\\\\\\\\]',\n '(.*)[/\\\\\\\\]helpers[/\\\\\\\\](.*)',\n ],\n snapshotSerializers: [require.resolve('enzyme-to-json/serializer')],\n }\n\n if (rootDir) config.rootDir = rootDir\n\n if (overrides.jest) {\n config = {\n ...config,\n ...overrides.jest,\n }\n }\n\n return config\n}\n\n```" } ]
code_vtex-scripts_d18b8de1
[ { "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 vtex-scripts/utils/overrides.js from the vtex-scripts VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n'use strict'\n\nconst paths = require('./paths')\n\nconst packageJson = require(paths.packageJsonPath)\n\nlet vtexScriptsOverrides = {}\n\nif (packageJson.vtexScriptsOverrides) {\n vtexScriptsOverrides = packageJson.vtexScriptsOverrides\n}\n\nmodule.exports = vtexScriptsOverrides\n\n```" } ]
code_vtex-scripts_a61dc870
[ { "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 vtex-scripts/utils/paths.js from the vtex-scripts VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n'use strict'\n\nconst fs = require('fs')\nconst path = require('path')\n\nconst appDirectory = fs.realpathSync(process.cwd())\nconst resolveAppPath = relative => path.resolve(appDirectory, relative)\n\nconst packageJsonPath = resolveAppPath('package.json')\n\nconst { vtexScriptsOverride } = require(packageJsonPath)\n\nmodule.exports = {\n appPath: resolveAppPath('.'),\n entryPath: resolveAppPath('src/index.js'),\n srcPath: resolveAppPath('src'),\n distPath: resolveAppPath('dist'),\n rawTestsSetup: 'src/setupTests.js',\n testsSetup: resolveAppPath('src/setupTests.js'),\n}\n\nif (vtexScriptsOverride) {\n const srcPath = vtexScriptsOverride.srcPath || 'src'\n const distPath = vtexScriptsOverride.distPath || 'dist'\n const setupTestsFilename =\n vtexScriptsOverride.setupTestsFilename || 'setupTests.js'\n\n module.exports = {\n appPath: resolveAppPath('.'),\n entryPath: resolveAppPath(path.join(srcPath, 'index.js')),\n srcPath: resolveAppPath(srcPath),\n distPath: resolveAppPath(distPath),\n rawTestsSetup: path.join(srcPath, setupTestsFilename),\n testsSetup: resolveAppPath(path.join(srcPath, setupTestsFilename)),\n }\n}\n\nmodule.exports.packageJsonPath = packageJsonPath\nmodule.exports.moduleName = path.basename(process.cwd())\nmodule.exports.srcDirs = [module.exports.srcPath]\n\n```" } ]
code_vtex-scripts_dde17af9
[ { "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 vtex-scripts/scripts/test.js from the vtex-scripts VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n#!/usr/bin/env node\n'use strict'\n\nprocess.env.BABEL_ENV = 'test'\nprocess.env.NODE_ENV = 'test'\n\nprocess.on('unhandledRejection', err => {\n throw err\n})\n\nconst jest = require('jest')\nconst path = require('path')\nconst paths = require('../utils/paths')\nconst createJestConfig = require('../config/createJestConfig')\n\nfunction startTest(...processArgs) {\n const args = processArgs ? processArgs.slice(0) : []\n\n const config = createJestConfig(\n relativePath => path.resolve(__dirname, '..', relativePath),\n paths.appPath,\n paths.srcDirs\n )\n\n args.push('--config', JSON.stringify(config))\n\n jest.run(args)\n}\n\nmodule.exports = startTest\n\n```" } ]
code_vtex-scripts_abc677d9
[ { "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 vtex-scripts/scripts/build.js from the vtex-scripts VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n#!/usr/bin/env node\n'use strict'\n\nprocess.env.BABEL_ENV = 'production'\nprocess.env.NODE_ENV = 'production'\n\nprocess.on('unhandledRejection', err => {\n throw err\n})\n\nconst printBuildError = require('react-dev-utils/printBuildError')\nconst formatWebpackMessages = require('react-dev-utils/formatWebpackMessages')\nconst chalk = require('chalk')\nconst fs = require('fs-extra')\nconst webpack = require('webpack')\nconst paths = require('../utils/paths')\nconst config = require('../config/webpack.config')\n\nfunction build() {\n console.log('Creating production build...\\n')\n\n const compiler = webpack(config)\n\n return new Promise((res, rej) => {\n compiler.run((err, stat) => {\n if (err) {\n return rej(err)\n }\n\n const messages = formatWebpackMessages(stat.toJson({}, true))\n\n if (messages.errors.length) {\n if (messages.errors.length > 1) {\n messages.errors.length = 1\n }\n return rej(new Error(messages.errors.join('\\n\\n')))\n }\n\n return res({\n stat,\n warnings: messages.warnings,\n })\n })\n })\n}\n\nfunction startBuild() {\n return new Promise(res => {\n res(fs.emptyDir(paths.distPath))\n })\n .then(() => build())\n .then(\n ({ warnings }) => {\n if (warnings.length) {\n console.log(chalk.yellow('Compiled with warnings'))\n console.log(warnings.join('\\n\\n'))\n } else {\n console.log(chalk.green('Compiled successfully.'))\n }\n },\n errors => {\n console.log(chalk.red('Failed to compile.\\n'))\n printBuildError(errors)\n process.exit(1)\n }\n )\n .catch(err => {\n if (err && err.message) {\n console.log(err.message)\n }\n process.exit(1)\n })\n}\n\nmodule.exports = startBuild\n\n```" } ]
code_vtex-scripts_5980751c
[ { "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 vtex-scripts/config/jest/fileTransform.js from the vtex-scripts VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n'use strict'\n\nconst path = require('path')\n\nmodule.exports = {\n process(src, filename) {\n const assetFilename = JSON.stringify(path.basename(filename))\n\n if (filename.match(/\\.svg$/)) {\n return `module.exports = {\n __esModule: true,\n default: ${assetFilename},\n ReactComponent: () => ${assetFilename},\n };`\n }\n\n return `module.exports = ${assetFilename};`\n },\n}\n\n```" } ]
code_vtex-scripts_0c9c7589
[ { "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 vtex-scripts/config/jest/cssTransform.js from the vtex-scripts VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n'use strict'\n\nmodule.exports = {\n process() {\n return 'module.exports = {};'\n },\n getCacheKey() {\n return 'cssTransform'\n },\n}\n\n```" } ]
code_vtex-scripts_f707523f
[ { "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 vtex-scripts/config/jest/graphqlTransform.js from the vtex-scripts VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n'use strict'\n\nconst loader = require('graphql-tag/loader')\n\nmodule.exports = {\n process(src) {\n return loader.call({ cacheable() {} }, src)\n },\n}\n\n```" } ]
code_vtex-scripts_b8425206
[ { "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 vtex-scripts/config/jest/babelTransform.js from the vtex-scripts VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n'use strict'\n\nconst babelJest = require('babel-jest')\n\nmodule.exports = babelJest.createTransformer({\n babelrc: false,\n presets: ['react', 'es2015'].map(preset =>\n require.resolve(`babel-preset-${preset}`)\n ),\n plugins: [\n 'transform-es2015-modules-commonjs',\n 'dynamic-import-node',\n 'transform-class-properties',\n ].map(plugin => require.resolve(`babel-plugin-${plugin}`)),\n})\n\n```" } ]