[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of store-resources/react/queries/productSearch.gql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
query productSearch(
  $query: String
  $map: String
  $facetQuery: String
  $facetMap: String
  $orderBy: String
  $priceRange: String
  $from: Int
  $to: Int
  $withFacets: Boolean = true
) {
  products(
    query: $query
    map: $map
    orderBy: $orderBy
    priceRange: $priceRange
    from: $from
    to: $to
  ) @context(provider: "vtex.search-graphql") {
    cacheId
    productId
    description
    productName
    linkText
    brand
    link
    items {
      itemId
      name
      nameComplete
      complementName
      ean
      referenceId {
        Key
        Value
      }
      measurementUnit
      unitMultiplier
      images {
        cacheId
        imageId
        imageLabel
        imageTag
        imageUrl
        imageText
      }
      sellers {
        sellerId
        sellerName
        commertialOffer {
          discountHighlights {
            name
          }
          Price
          ListPrice
          Tax
          taxPercentage
          spotPrice
          PriceWithoutDiscount
          RewardValue
          PriceValidUntil
          AvailableQuantity
        }
      }
    }
    productClusters {
      id
      name
    }
  }
  facets(query: $facetQuery, map: $facetMap)
    @include(if: $withFacets)
    @context(provider: "vtex.search-graphql") {
    departments {
      quantity
      name
      link
      linkEncoded
      map
      selected
      value
    }
    brands {
      quantity
      name
      link
      linkEncoded
      map
      selected
      value
    }
    specificationFilters {
      name
      facets {
        quantity
        name
        link
        linkEncoded
        map
        selected
        value
      }
    }
    categoriesTrees {
      id
      quantity
      name
      link
      href
      linkEncoded
      map
      selected
      value
      children {
        id
        quantity
        name
        link
        href
        linkEncoded
        map
        selected
        value
        children {
          id
          quantity
          name
          link
          href
          linkEncoded
          map
          selected
          value
        }
      }
    }
    priceRanges {
      quantity
      name
      link
      linkEncoded
      slug
      map
    }
    recordsFiltered
    # Backwards compatibility with search-result v3
    Departments {
      Quantity
      Name
      Link
    }
    Brands {
      Quantity
      Name
      Link
    }
    SpecificationFilters {
      name
      facets {
        Quantity
        Name
        Link
      }
    }
    CategoriesTrees {
      Id
      Quantity
      Name
      Link
      href
      name
      Children {
        Id
        Quantity
        Name
        Link
        href
        name
        Children {
          Id
          Quantity
          Name
          Link
          href
          name
        }
      }
    }
    PriceRanges {
      Quantity
      Name
      Link
      Slug
    }
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of store-resources/react/queries/recommendationShelf.gql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
#import '../fragments/product.graphql'
#import '../fragments/item.graphql'
#import '../fragments/seller.graphql'
#import '../fragments/commertialOffer.graphql'
#import '../fragments/installment.graphql'

fragment RecommendationProductFragment on Product {
  ...ProductFragment
  items {
    ...ItemFragment
    sellers {
      ...SellerFragment
      commertialOffer {
        ...CommertialOfferFragment
        Installments {
          ...InstallmentFragment
        }
      }
    }
  }
}

query recommendation($input: RecommendationInput) {
  recommendation(input: $input)
    @context(provider: "vtex.recommendation-graphql") {
    products {
      ...RecommendationProductFragment
    }
    jwt
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of store-resources/react/queries/orderForm.gql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
query orderForm {
  orderForm @context(scope: "private") {
    cacheId
    sellers {
      id
      name
    }
    orderFormId
    userProfileId
    customData {
      customApps {
        id
        fields
      }
    }
    itemMetadata {
      items {
        id
        name
        assemblyOptions {
          id
          name
          composition {
            items {
              id
              seller
            }
          }
        }
      }
      priceTable {
        type
        values {
          id
          price
        }
      }
    }
    value
    totalizers {
      id
      name
      value
    }
    items {
      id
      productId
      name
      imageUrl
      detailUrl
      productRefId
      additionalInfo {
        brandName
      }
      canHaveAttachment
      productCategoryIds
      productCategories
      skuName
      quantity
      sellingPrice
      listPrice
      parentItemIndex
      parentAssemblyBinding
      cartIndex
      sellingPriceWithAssemblies
      assemblyOptions {
        added {
          item {
            name
            sellingPrice
            quantity
            sellingPriceWithAssemblies
            assemblyOptions {
              added {
                item {
                  name
                  sellingPrice
                  quantity
                  sellingPriceWithAssemblies
                }
                normalizedQuantity
                choiceType
                extraQuantity
              }
              removed {
                removedQuantity
                initialQuantity
                name
              }
              parentPrice
            }
          }
          normalizedQuantity
          choiceType
          extraQuantity
        }
        removed {
          removedQuantity
          initialQuantity
          name
        }
        parentPrice
      }
      seller
      priceDefinition {
        calculatedSellingPrice
        total
        sellingPrices {
          quantity
          value
        }
      }
    }
    shippingData {
      address {
        id
        neighborhood
        complement
        number
        street
        postalCode
        city
        reference
        addressName
        addressType
        geoCoordinates
        state
        receiverName
        country
      }
      availableAddresses {
        id
        neighborhood
        complement
        number
        street
        postalCode
        city
        reference
        addressName
        addressType
        geoCoordinates
        state
        receiverName
        country
      }
    }
    clientProfileData {
      email
      firstName
      lastName
    }
    storePreferencesData {
      countryCode
      currencyCode
      timeZone
    }
    checkedInPickupPointId
    isCheckedIn
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of store-resources/react/queries/pwaData.gql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
query pwaData {
  pwaSettings {
    disablePrompt
    promptOnCustomEvent
  }
  manifest {
    theme_color
  }
  iOSIcons {
    src
    type
    sizes
  }
  splashes {
    src
    type
    sizes
  }
}
```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of store-resources/react/queries/search.gql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
query search(
  $query: String
  $map: String
  $rest: String
  $orderBy: String
  $priceRange: String
  $from: Int
  $to: Int
  $withFacets: Boolean = true
) {
  search(
    query: $query
    map: $map
    rest: $rest
    orderBy: $orderBy
    priceRange: $priceRange
    from: $from
    to: $to
  ) @context(provider: "vtex.store-graphql") {
    titleTag
    metaTagDescription
    facets @include(if: $withFacets) {
      Departments {
        Quantity
        Name
        Link
      }
      Brands {
        Quantity
        Name
        Link
      }
      SpecificationFilters {
        name
        facets {
          Quantity
          Name
          Link
        }
      }
      CategoriesTrees {
        Id
        Quantity
        Name
        Link
        href
        name
        Children {
          Id
          Quantity
          Name
          Link
          href
          name
          Children {
            Id
            Quantity
            Name
            Link
            href
            name
          }
        }
      }
      PriceRanges {
        Quantity
        Name
        Link
        Slug
      }
    }
    products {
      cacheId
      categories
      categoryTree {
        name
        href
      }
      productId
      description
      productName
      linkText
      brand
      link
      items {
        itemId
        name
        nameComplete
        complementName
        ean
        referenceId {
          Key
          Value
        }
        measurementUnit
        unitMultiplier
        images {
          cacheId
          imageId
          imageLabel
          imageTag
          imageUrl
          imageText
        }
        sellers {
          sellerId
          sellerName
          commertialOffer {
            discountHighlights {
              name
            }
            Price
            ListPrice
            PriceWithoutDiscount
            RewardValue
            PriceValidUntil
            AvailableQuantity
          }
        }
      }
      productClusters {
        id
        name
      }
    }
    recordsFiltered
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of store-resources/react/queries/searchMetadata.gql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
query SearchMetadata($query: String, $map: String) {
  searchMetadata(query: $query, map: $map)
    @context(provider: "vtex.search-graphql") {
    titleTag
    metaTagDescription
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of store-resources/react/queries/itemsWithSimulation.gql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
query itemsWithSimulation($items: [ItemInput]) {
  itemsWithSimulation(items: $items) {
    itemId
    sellers {
      sellerId
      commertialOffer {
        AvailableQuantity
        Price
        ListPrice
        PriceValidUntil
        Installments {
        	Value
          InterestRate
          TotalValuePlusInterestRate
          NumberOfInstallments
      	}
      }
    }
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of store-resources/react/queries/facets.gql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
query facets(
  $query: String
  $map: String
  $hideUnavailableItems: Boolean = false
  $behavior: String = "Static"
) {
  facets(query: $query, map: $map, hideUnavailableItems: $hideUnavailableItems, behavior: $behavior)
    @context(provider: "vtex.search-graphql") {
    departments {
      quantity
      name
      link
      linkEncoded
      map
      selected
      value
    }
    brands {
      quantity
      name
      link
      linkEncoded
      map
      selected
      value
    }
    specificationFilters {
      name
      facets {
        quantity
        name
        link
        linkEncoded
        map
        selected
        value
      }
    }
    categoriesTrees {
      id
      quantity
      name
      link
      href
      linkEncoded
      map
      selected
      value
      children {
        id
        quantity
        name
        link
        href
        linkEncoded
        map
        selected
        value
        children {
          id
          quantity
          name
          link
          href
          linkEncoded
          map
          selected
          value
          children {
            id
            quantity
            name
            link
            href
            linkEncoded
            map
            selected
            value
            children {
              id
              quantity
              name
              link
              href
              linkEncoded
              map
              selected
              value
            }
          }
        }
      }
    }
    priceRanges {
      quantity
      name
      link
      linkEncoded
      slug
      map
    }
    queryArgs {
      query
      map
    }
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of store-resources/react/queries/sponsoredProducts.gql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
#import '../fragments/product.graphql'
#import '../fragments/item.graphql'
#import '../fragments/seller.graphql'
#import '../fragments/commertialOffer.graphql'
#import '../fragments/installment.graphql'

query sponsoredProducts(
  $fullText: String
  $selectedFacets: [SelectedFacetInput]
  $orderBy: String
  $from: Int
  $to: Int
  $hideUnavailableItems: Boolean = false
  $skusFilter: ItemsFilter = ALL_AVAILABLE
  $simulationBehavior: SimulationBehavior = default
  $installmentCriteria: InstallmentsCriteria = MAX_WITHOUT_INTEREST
  $productOriginVtex: Boolean = false
  $fuzzy: String
  $operator: Operator
  $searchState: String
  $excludedPaymentSystems: [String]
  $includedPaymentSystems: [String]
  $anonymousId: String
) {
  sponsoredProducts(
    fullText: $fullText
    selectedFacets: $selectedFacets
    orderBy: $orderBy
    from: $from
    to: $to
    hideUnavailableItems: $hideUnavailableItems
    simulationBehavior: $simulationBehavior
    productOriginVtex: $productOriginVtex
    fuzzy: $fuzzy
    operator: $operator
    searchState: $searchState
    anonymousId: $anonymousId
  ) @context(provider: "vtex.search-graphql") {
      ...ProductFragment
      advertisement {
        adId
        campaignId
        actionCost
        adRequestId
        adResponseId
      }
      items(filter: $skusFilter) {
        ...ItemFragment
        sellers {
          ...SellerFragment
          commertialOffer {
            ...CommertialOfferFragment
            Installments(
              criteria: $installmentCriteria
              excludedPaymentSystems: $excludedPaymentSystems
              includedPaymentSystems: $includedPaymentSystems
            ) {
              ...InstallmentFragment
            }
          }
        }
      }
      selectedProperties {
        key
        value
      }
      rule {
        id
      }
    }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of store-resources/react/queries/facetsV2.gql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
query facetsV2(
  $query: String
  $fullText: String
  $selectedFacets: [SelectedFacetInput]
  $hideUnavailableItems: Boolean = false
  $behavior: String = "Static"
  $categoryTreeBehavior: CategoryTreeBehavior = default
  $fuzzy: String
  $operator: Operator
  $searchState: String
  $from: Int
  $to: Int
  $initialAttributes: String
  $variant: String
) {
  facets(
    query: $query
    fullText: $fullText
    selectedFacets: $selectedFacets
    hideUnavailableItems: $hideUnavailableItems
    behavior: $behavior
    categoryTreeBehavior: $categoryTreeBehavior
    fuzzy: $fuzzy
    operator: $operator
    searchState: $searchState
    initialAttributes: $initialAttributes
    variant: $variant
  ) @context(provider: "vtex.search-graphql") {
    sampling
    breadcrumb {
      name
      href
    }
    facets {
      name
      type
      hidden
      quantity
      facets: values (from: $from, to: $to) {
        id
        quantity
        name
        key
        selected
        value
        link
        linkEncoded
        href
        range {
          from
          to
        }
        children {
          id
          quantity
          name
          key
          selected
          value
          link
          linkEncoded
          href
          children {
            id
            quantity
            name
            key
            selected
            value
            link
            linkEncoded
            href
            children {
              id
              quantity
              name
              key
              selected
              value
              link
              linkEncoded
              href
              children {
                id
                quantity
                name
                key
                selected
                value
                link
                linkEncoded
                href
              }
            }
          }
        }
      }
    }
    queryArgs {
      query
      selectedFacets {
        key
        value
      }
    }
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of store-resources/react/queries/session.gql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
query Session {
  getSession {
    id
    adminUserId
    impersonable
    adminUserEmail
    address {
      cacheId
      id
      addressId
      userId
      receiverName
      complement
      neighborhood
      country
      state
      number
      street
      geoCoordinates
      postalCode
      city
      reference
      addressName
      addressType
    }
    profile {
      id
      firstName
      lastName
      email
    }
    impersonate {
      profile {
        phone
        email
        lastName
        document
        firstName
      }
    }
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of store-resources/react/queries/address.gql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
query address {
  orderForm {
    pickupPointCheckedIn {
      friendlyName
    }
    cacheId
    orderFormId
    shippingData {
      address {
        id
        neighborhood
        complement
        number
        street
        postalCode
        city
        reference
        addressName
        addressType
        geoCoordinates
        state
        receiverName
        country
      }
      availableAddresses {
        id
        neighborhood
        complement
        number
        street
        postalCode
        city
        reference
        addressName
        addressType
        geoCoordinates
        state
        receiverName
        country
      }
    }
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of store-resources/react/queries/banners.gql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
query banners($fullText: String, $selectedFacets: [SelectedFacetInput]) {
  banners(fullText: $fullText, selectedFacets: $selectedFacets)
    @context(provider: "vtex.search-graphql") {
    banners {
      id
      name
      area
      html
    }
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of store-resources/react/queries/productSearchV2.gql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
#import '../fragments/product.graphql'
#import '../fragments/item.graphql'
#import '../fragments/seller.graphql'
#import '../fragments/commertialOffer.graphql'
#import '../fragments/installment.graphql'

query productSearchV2(
  $query: String
  $map: String
  $facetQuery: String
  $facetMap: String
  $category: String
  $collection: String
  $specificationFilters: [String]
  $orderBy: String
  $priceRange: String
  $from: Int
  $to: Int
  $withFacets: Boolean = true
  $hideUnavailableItems: Boolean = false
  $skusFilter: ItemsFilter = ALL_AVAILABLE
  $simulationBehavior: SimulationBehavior = default
  $installmentCriteria: InstallmentsCriteria = MAX_WITHOUT_INTEREST
) {
  productSearch(
    query: $query
    map: $map
    category: $category
    collection: $collection
    specificationFilters: $specificationFilters
    orderBy: $orderBy
    priceRange: $priceRange
    from: $from
    to: $to
    hideUnavailableItems: $hideUnavailableItems
    simulationBehavior: $simulationBehavior
  ) @context(provider: "vtex.search-graphql") {
    products {
      ...ProductFragment
      items(filter: $skusFilter) {
        ...ItemFragment
        sellers {
          ...SellerFragment
          commertialOffer {
            ...CommertialOfferFragment
            Installments(criteria: $installmentCriteria) {
              ...InstallmentFragment
            }
          }
        }
      }
    }
    recordsFiltered
    breadcrumb {
      name
      href
    }
  }
  facets(
    query: $facetQuery
    map: $facetMap
    hideUnavailableItems: $hideUnavailableItems
  ) @include(if: $withFacets) @context(provider: "vtex.search-graphql") {
    departments {
      quantity
      name
      link
      linkEncoded
      map
      selected
      value
    }
    brands {
      quantity
      name
      link
      linkEncoded
      map
      selected
      value
    }
    specificationFilters {
      name
      facets {
        quantity
        name
        link
        linkEncoded
        map
        selected
        value
      }
    }
    categoriesTrees {
      id
      quantity
      name
      link
      href
      linkEncoded
      map
      selected
      value
      children {
        id
        quantity
        name
        link
        href
        linkEncoded
        map
        selected
        value
        children {
          id
          quantity
          name
          link
          href
          linkEncoded
          map
          selected
          value
          children {
            id
            quantity
            name
            link
            href
            linkEncoded
            map
            selected
            value
            children {
              id
              quantity
              name
              link
              href
              linkEncoded
              map
              selected
              value
            }
          }
        }
      }
    }
    priceRanges {
      quantity
      name
      link
      linkEncoded
      slug
      map
    }
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of store-resources/react/queries/productSearchV3.gql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
#import '../fragments/product.graphql'
#import '../fragments/item.graphql'
#import '../fragments/seller.graphql'
#import '../fragments/commertialOffer.graphql'
#import '../fragments/installment.graphql'

query productSearchV3(
  $query: String
  $fullText: String
  $selectedFacets: [SelectedFacetInput]
  $orderBy: String
  $from: Int
  $to: Int
  $hideUnavailableItems: Boolean = false
  $skusFilter: ItemsFilter = ALL_AVAILABLE
  $simulationBehavior: SimulationBehavior = default
  $installmentCriteria: InstallmentsCriteria = MAX_WITHOUT_INTEREST
  $productOriginVtex: Boolean = false
  $fuzzy: String
  $operator: Operator
  $searchState: String
  $excludedPaymentSystems: [String]
  $includedPaymentSystems: [String]
  $variant: String
  $showSponsored: Boolean
  $advertisementOptions: AdvertisementOptions
  $origin: String
) {
  productSearch(
    query: $query
    fullText: $fullText
    selectedFacets: $selectedFacets
    orderBy: $orderBy
    from: $from
    to: $to
    hideUnavailableItems: $hideUnavailableItems
    simulationBehavior: $simulationBehavior
    productOriginVtex: $productOriginVtex
    fuzzy: $fuzzy
    operator: $operator
    searchState: $searchState
    variant: $variant
    showSponsored: $showSponsored
    advertisementOptions: $advertisementOptions
    origin: $origin
  ) @context(provider: "vtex.search-graphql") {
    products {
      ...ProductFragment
      advertisement {
        adId
        campaignId
        actionCost
        adRequestId
        adResponseId
      }
      items(filter: $skusFilter) {
        ...ItemFragment
        sellers {
          ...SellerFragment
          commertialOffer {
            ...CommertialOfferFragment
            Installments(
              criteria: $installmentCriteria
              excludedPaymentSystems: $excludedPaymentSystems
              includedPaymentSystems: $includedPaymentSystems
            ) {
              ...InstallmentFragment
            }
          }
        }
      }
      selectedProperties {
        key
        value
      }
      rule {
        id
      }
      deliveryPromisesBadges {
        typeName
        pickupId
        pickupName
      }
      specification
    }
    recordsFiltered
    correction {
      misspelled
    }
    breadcrumb {
      name
      href
    }
    fuzzy
    operator
    searchState
    redirect
    options {
      deliveryPromisesEnabled
    }
    searchId
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of store-resources/react/queries/productSuggestions.gql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
#import '../fragments/product.graphql'
#import '../fragments/item.graphql'
#import '../fragments/seller.graphql'
#import '../fragments/commertialOffer.graphql'
#import '../fragments/installment.graphql'

query productSuggestions(
  $fullText: String!
  $facetKey: String
  $facetValue: String
  $origin: String
  $productOriginVtex: Boolean = false
  $simulationBehavior: SimulationBehavior = default
  $hideUnavailableItems: Boolean = false
  $orderBy: String
  $count: Int
  $shippingOptions: [String]
  $variant: String
  $advertisementOptions: AdvertisementOptions
) {
  productSuggestions(
    fullText: $fullText
    facetKey: $facetKey
    facetValue: $facetValue
    origin: $origin
    productOriginVtex: $productOriginVtex
    simulationBehavior: $simulationBehavior
    hideUnavailableItems: $hideUnavailableItems
    orderBy: $orderBy
    count: $count
    shippingOptions: $shippingOptions
    variant: $variant
    advertisementOptions: $advertisementOptions
  ) @context(provider: "vtex.search-graphql") {
    count
    misspelled
    operator
    products {
      ...ProductFragment
      items {
        ...ItemFragment
        sellers {
          ...SellerFragment
          commertialOffer {
            ...CommertialOfferFragment
            Installments {
              ...InstallmentFragment
            }
          }
        }
      }
      selectedProperties {
        key
        value
      }
      rule {
        id
      }
      specification
    }
    searchId
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of store-resources/react/queries/searchMetadataV2.gql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
query SearchMetadataV2(
  $query: String
  $selectedFacets: [SelectedFacetInput]
  $fullText: String
) {
  searchMetadata(
    query: $query
    selectedFacets: $selectedFacets
    fullText: $fullText
  ) @context(provider: "vtex.search-graphql") {
    titleTag
    metaTagDescription
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of store-resources/react/queries/topSearches.gql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
query topSearches($searchState: String) {
  topSearches(searchState: $searchState)
    @context(provider: "vtex.search-graphql") {
    searches {
      term
    }
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of store-resources/react/queries/correction.gql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
query correction($fullText: String) {
  correction(fullText: $fullText) @context(provider: "vtex.search-graphql") {
    correction {
      text
      highlighted
      misspelled
      correction
    }
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of store-resources/react/queries/autocompleteSearchSuggestions.gql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
query autocompleteSearchSuggestions($fullText: String!, $searchState: String) {
  autocompleteSearchSuggestions(fullText: $fullText, searchState: $searchState)
    @context(provider: "vtex.search-graphql") {
    searches {
      term
      attributes {
        key
        value
        labelValue
      }
    }
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of store-resources/react/queries/UNSTABLE__productCategoryTree.gql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
query ProductCategoryTree($slug: String, $identifier: ProductUniqueIdentifier) {
  product(slug: $slug, identifier: $identifier)
    @context(provider: "vtex.search-graphql") {
    cacheId
    categoryTree {
      id
      name
      href
    }
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of store-resources/react/queries/products.gql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
#import '../fragments/product.graphql'
#import '../fragments/item.graphql'
#import '../fragments/seller.graphql'
#import '../fragments/commertialOffer.graphql'
#import '../fragments/installment.graphql'

query Products(
  $category: String
  $collection: String
  $specificationFilters: [String]
  $shippingOptions: [String]
  $orderBy: String
  $from: Int
  $to: Int
  $hideUnavailableItems: Boolean = false
  $skusFilter: ItemsFilter = ALL_AVAILABLE
  $installmentCriteria: InstallmentsCriteria = MAX_WITHOUT_INTEREST
  $variant: String
  $searchState: String
  $advertisementOptions: AdvertisementOptions
) {
  products(
    category: $category
    collection: $collection
    specificationFilters: $specificationFilters
    shippingOptions: $shippingOptions
    orderBy: $orderBy
    from: $from
    to: $to
    advertisementOptions: $advertisementOptions
    hideUnavailableItems: $hideUnavailableItems
    variant: $variant
    searchState: $searchState
  ) @context(provider: "vtex.search-graphql") {
    ...ProductFragment
    items(filter: $skusFilter) {
      ...ItemFragment
      sellers {
        ...SellerFragment
        commertialOffer {
          ...CommertialOfferFragment
          Installments(criteria: $installmentCriteria) {
            ...InstallmentFragment
          }
        }
      }
    }
    rule {
      id
    }
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of store-resources/react/queries/productPreview.gql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
fragment product on Product {
  cacheId
  productId
  productName
  linkText
  titleTag
  metaTagDescription
  categories
  categoryTree {
    name
    href
  }
  items {
    itemId
    name
    nameComplete
    complementName
    ean
    referenceId {
      Key
      Value
    }
    measurementUnit
    unitMultiplier
    images {
      imageId
      imageLabel
      imageTag
      imageUrl
      imageText
    }
    sellers {
      sellerId
      sellerName
      commertialOffer {
        Price
        ListPrice
        PriceWithoutDiscount
        RewardValue
        PriceValidUntil
        AvailableQuantity
      }
    }
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of product-list-context/docs/README.md from the product-list-context VTEX app.

[Assistant]
Here's the implementation:

```markdown
📢 Use this project, contribute to it or open issues to help evolve it using Store Discussion.
<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
[![All Contributors](https://img.shields.io/badge/all_contributors-0-orange.svg?style=flat-square)](#contributors-)
<!-- ALL-CONTRIBUTORS-BADGE:END -->

# Product List Context

The Product List Context is responsible for storing product data from an app and then providing it to specific store product components, such as the Shelf.

⚠ This app is not rendered and should only be used to provide product data to specific store blocks.

## Configuration

Add the `product-list-context` app to the app's dependencies list (in the `manifest.json`) from which you want fetch product data. For example:

```json
"dependencies": {
  "vtex.product-list-context": "0.x"
}
```

| Prop name | Type | Description | Default Value |
| --- | --- | --- | --- |
| `listName` | `string` | The list that you are providing the products (e.g. `Home Shelf` or `Search Result`) | `'List of products'` |

In the app's files, use the `ProductListProvider` to initialise the context. You'll need to wrap the file's rendered component with the provider in order for its children to have access to the context's data. For example:

```tsx
return (
  <div ref={ref} className={`${handles.container} pv4 pb9`}>
    <ProductListProvider listName="Shelf">
      <ProductList {...productListProps} />
    </ProductListProvider>
  </div>
)
```

The Product List Context state is comprised of a object with the following properties: `nextImpressions`: List of products that are going to be sent on the product impression event.
`sentIds`: Set of the IDs of the products that were already impressed or are marked to be impressed.

You can use two Hooks to handle the data contained in the Product List Context object: `useProductListState` and `useProductListDispatch`.

`useProductListState`: used to get the data stored in the context. In order to use it, you need to first import and then call the hook anywhere in any file under the component which is wrapped by ProductListProvider. For example:

```tsx
import { ProductListContext } from 'vtex.product-list-context'

//...

  const { useProductListState } = ProductListContext
  const { nextImpressions } = useProductListState()
```

`useProductListDispatch`: returns a dispatch function that is used to change the context state. Notice that you should only import and declare this hook if you wish to change data that's stored in the context.

```tsx
import { ProductListContext } from 'vtex.product-list-context'

//...

  const { useProductListDispatch } = ProductListContext
  const dispatch = useProductListDispatch()
```

Starting from the dispatch function, you can add new values to the `nextImpressions` array (`SEND_IMPRESSION`) or reset this array (`RESET_NEXT_IMPRESSIONS`). For example:

```tsx
const dispatch = useProductListDispatch()  useEffect(() => {
  if (inView) {
    dispatch({ type: 'SEND_IMPRESSION', args: { product: product }})
  }
}, [inView])
```

This app also contains `useProductImpression`, which is a hook that you can call when you want to send impression events of the products in the `nextImpressions` array. For example:

```tsx
import { useProductImpression } from 'vtex.product-list-context'

//...

  useProductImpression()
```

When calling this hook, the `product-list-context` will always check if there is anything in the `nextImpressions` array. If there is, and the array doesn't change for one second, all the products in it will be impressed and the array will be reseted.

## Contributors ✨

Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):

<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<!-- markdownlint-enable -->
<!-- prettier-ignore-end -->
<!-- ALL-CONTRIBUTORS-LIST:END -->

This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind are welcome!

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of product-list-context/react/ProductListContext.tsx from the product-list-context VTEX app.

[Assistant]
Here's the implementation:

```tsx
import type { FC } from 'react'
import React, { useReducer, useContext, createContext, useEffect } from 'react'

export interface Product {
  productId: string
  [key: string]: any
}
export interface State {
  nextImpressions: Array<{
    product: Product
    impressionIndex: number
    originalIndex: number
  }>
  sentIds: Map<string, { position: number }>
  listName?: string
}

interface SendImpressionAction {
  type: 'SEND_IMPRESSION'
  args: { product: Product; position?: number }
}

interface ResetNextImpressionsAction {
  type: 'RESET_NEXT_IMPRESSIONS'
}

interface SetListNameAction {
  type: 'SET_LIST_NAME'
  args: { listName: string }
}

type ReducerActions =
  | SendImpressionAction
  | ResetNextImpressionsAction
  | SetListNameAction

export type Dispatch = (action: ReducerActions) => void

const DEFAULT_STATE: State = {
  nextImpressions: [],
  sentIds: new Map<string, { position: number }>(),
}

const ProductListStateContext = createContext<State>(DEFAULT_STATE)
const ProductListDispatchContext = createContext<Dispatch>((action) => {
  console.error('error in dispatch ', action)
})

function productListReducer(state: State, action: ReducerActions): State {
  switch (action.type) {
    case 'SEND_IMPRESSION': {
      const { product, position: originalIndex = 0 } = action.args
      let { nextImpressions } = state

      // ignore already sent impressions
      if (state.sentIds.has(product.productId)) {
        return state
      }

      const position = state.sentIds.size + 1

      state.sentIds.set(product.productId, { position })

      const nextImpressionsFirstPosition =
        state.nextImpressions[0]?.impressionIndex ?? position

      nextImpressions = state.nextImpressions
        .concat({
          product,
          impressionIndex: position,
          originalIndex,
        })
        .sort(
          (
            { originalIndex: originalIndexA },
            { originalIndex: originalIndexB }
          ) => originalIndexA - originalIndexB
        )
        .map((impression, index) => ({
          ...impression,
          impressionIndex: nextImpressionsFirstPosition + index,
        }))

      return {
        ...state,
        nextImpressions,
      }
    }

    case 'RESET_NEXT_IMPRESSIONS': {
      return {
        ...state,
        nextImpressions: [],
      }
    }

    case 'SET_LIST_NAME': {
      // When setting a new list name, we should also reset `sentIds`, since
      // this indicates we're dealing with a brand new list.
      if (action.args.listName !== state.listName) {
        return {
          ...state,
          listName: action.args.listName,
          sentIds: new Map(),
        }
      }

      return state
    }

    default: {
      throw new Error(`Unhandled action type on product-list-context`)
    }
  }
}

const initialState: State = {
  nextImpressions: [],
  sentIds: new Map(),
}

interface ProviderProps {
  // Because of this prop you can't use the same context
  // to two different lists (if you want to differentiate both)
  listName: string
}

const ProductListProvider: FC<ProviderProps> = ({ children, listName }) => {
  const [state, dispatch] = useReducer(productListReducer, initialState)

  useEffect(() => {
    dispatch({ type: 'SET_LIST_NAME', args: { listName } })
  }, [listName])

  return (
    <ProductListStateContext.Provider value={state}>
      <ProductListDispatchContext.Provider value={dispatch}>
        {children}
      </ProductListDispatchContext.Provider>
    </ProductListStateContext.Provider>
  )
}

const useProductListState = () => useContext(ProductListStateContext)

const useProductListDispatch = () => useContext(ProductListDispatchContext)

export default {
  ProductListProvider,
  useProductListState,
  useProductListDispatch,
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of product-list-context/react/package.json from the product-list-context VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "scripts": {
    "test": "vtex-test-tools test"
  },
  "dependencies": {
    "apollo-client": "^2.6.3",
    "debounce": "^1.2.0",
    "react": "^16.8.6",
    "react-apollo": "^2.5.8",
    "react-dom": "^16.8.6",
    "react-intl": "^2.9.0"
  },
  "devDependencies": {
    "@types/debounce": "^1.2.0",
    "@types/graphql": "^14.2.2",
    "@types/react": "^16.8.22",
    "@types/react-intl": "^2.3.18",
    "@vtex/test-tools": "^3.4.3",
    "@vtex/tsconfig": "^0.2.0",
    "prop-types": "^15.7.2",
    "typescript": "3.9.7",
    "vtex.pixel-manager": "http://vtex.vteximg.com.br/_v/public/typings/v1/vtex.pixel-manager@1.1.4/public/@types/vtex.pixel-manager",
    "vtex.render-runtime": "http://vtex.vteximg.com.br/_v/public/typings/v1/vtex.render-runtime@8.88.0/public/@types/vtex.render-runtime"
  },
  "version": "0.4.1"
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of product-list-context/react/useProductImpression.tsx from the product-list-context VTEX app.

[Assistant]
Here's the implementation:

```tsx
import { useEffect, useCallback } from 'react'
import debounce from 'debounce'
import { PixelContext } from 'vtex.pixel-manager'

import type { Product, Dispatch } from './ProductListContext'
import productImpressionHooks from './ProductListContext'
import { parseToProductImpression } from './utils/parser'

const { useProductListDispatch, useProductListState } = productImpressionHooks

interface ImpressionParams {
  nextImpressions: Array<{ product: Product; impressionIndex: number }>
  push: any
  dispatch: Dispatch
  listName?: string
}

const sendImpressionEvents = (params: ImpressionParams) => {
  const { push, nextImpressions, dispatch, listName } = params

  if (!nextImpressions || nextImpressions.length <= 0) {
    return
  }

  const impressions = nextImpressions
    .filter(Boolean)
    .map(({ product, impressionIndex }, index) => ({
      product: parseToProductImpression(product),
      position: impressionIndex ?? index,
    }))

  push({
    event: 'productImpression',
    list: listName || 'List of products',
    impressions,
  })

  dispatch({ type: 'RESET_NEXT_IMPRESSIONS' })
}

const useProductImpression = (): void => {
  const { nextImpressions, listName } = useProductListState()
  const { push } = PixelContext.usePixel()
  const dispatch = useProductListDispatch()

  // we know what we're doing.
  // eslint-disable-next-line react-hooks/exhaustive-deps
  const debouncedSendImpressionEvents = useCallback(
    debounce(sendImpressionEvents, 1000, false),
    []
  )

  useEffect(() => {
    debouncedSendImpressionEvents({
      push,
      dispatch,
      listName,
      nextImpressions,
    })
  }, [nextImpressions, debouncedSendImpressionEvents, dispatch, push, listName])
}

export default useProductImpression

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of product-list-context/react/utils/parser.tsx from the product-list-context VTEX app.

[Assistant]
Here's the implementation:

```tsx
import type { Product } from '../ProductListContext'
import { changeImageUrlSize, toHttps } from './urlHelpers'

const defaultImage = { imageUrl: '', imageLabel: '' }
const defaultReference = { Value: '' }
const defaultSeller = { commertialOffer: { Price: 0, ListPrice: 0 } }

function findAvailableProduct(item: any) {
  return item.sellers.find(
    ({ commertialOffer = {} }: { commertialOffer: any }) =>
      commertialOffer.AvailableQuantity > 0
  )
}

export function parseToProductImpression(product: Product): Product {
  const parsedProduct = { ...product }
  const items = parsedProduct.items || []
  const sku = items.find(findAvailableProduct) || items[0]

  if (sku) {
    const [seller = defaultSeller] = sku?.sellers ?? []
    const [referenceId = defaultReference] = sku.referenceId ?? []
    const [image = defaultImage] = sku.images ?? []

    const resizedImage = changeImageUrlSize(toHttps(image.imageUrl), 500)
    const parsedImage = { ...image, imageUrl: resizedImage }

    parsedProduct.sku = {
      ...sku,
      seller,
      referenceId,
      image: parsedImage,
    }
  }

  return parsedProduct
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of product-list-context/react/utils/urlHelpers.tsx from the product-list-context VTEX app.

[Assistant]
Here's the implementation:

```tsx
export const DEFAULT_WIDTH = 'auto'
export const DEFAULT_HEIGHT = 'auto'
export const MAX_WIDTH = 3000
export const MAX_HEIGHT = 4000

/**
 * Having the url below as base for the LEGACY file manager,
 * https://storecomponents.vteximg.com.br/arquivos/ids/155472/Frame-3.jpg?v=636793763985400000
 * the following regex will match https://storecomponents.vteximg.com.br/arquivos/ids/155472
 *
 * Also matches urls with defined sizes like:
 * https://storecomponents.vteximg.com.br/arquivos/ids/155473-160-auto
 * @type {RegExp}
 *
 * On the new vtex.file-manager isn't necessary replace the URL, just add the param on the querystring, like:
 * "?width=WIDTH&height=HEIGHT&aspect=true"
 *
 */
const baseUrlRegex = /.+ids\/(\d+)/
const httpRegex = /http:\/\//
const legacyUrlPattern = '/arquivos/ids/'

export function toHttps(url: any) {
  return url.replace(httpRegex, 'https://')
}

export function cleanImageUrl(imageUrl: any) {
  const result = baseUrlRegex.exec(imageUrl)

  if (result && result.length > 0) {
    return result[0]
  }

  return undefined
}

function replaceLegacyFileManagerUrl(imageUrl: any, width: any, height: any) {
  const isLegacyUrl = imageUrl.includes(legacyUrlPattern)

  if (!isLegacyUrl) return imageUrl

  return `${cleanImageUrl(imageUrl)}-${width}-${height}`
}

export function changeImageUrlSize(
  imageUrl: any,
  width: number | string = DEFAULT_WIDTH,
  height: number | string = DEFAULT_HEIGHT
) {
  if (!imageUrl) return
  if (typeof width === 'number') width = Math.min(width, MAX_WIDTH)
  if (typeof height === 'number') height = Math.min(height, MAX_HEIGHT)

  const normalizedImageUrl = replaceLegacyFileManagerUrl(
    imageUrl,
    width,
    height
  )

  const queryStringSeparator = normalizedImageUrl.includes('?') ? '&' : '?'

  return `${normalizedImageUrl}${queryStringSeparator}width=${width}&height=${height}&aspect=true`
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of binding-selector/messages/pt.json from the binding-selector VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "admin/binding-selector.navigation.label": "Seletor de binding",
  "admin/binding-selector": "Seletor de binding",
  "admin/binding-selector.navigation.search.kws": "Seletor de binding",
  "admin/description": "As políticas de vendas serão atualizadas quando seus clientes mudarem os bindings de suas lojas.",
  "admin/label": "Atualizar política comercial",
  "admin/store": "Loja {index}: {address}",
  "admin/locale": "Região: {locale}",
  "admin/action": "Nomes das lojas personalizadas",
  "admin/modal": "Personalize os nomes da loja no idioma deste binding.",
  "admin/cancel": "Cancelar",
  "admin/save": "Salvar",
  "admin/hide-binding": "Visível",
  "admin/show-binding": "Oculto",
  "admin/advanced-settings": "Configurações avançadas",
  "admin/set-external-url": "Definir URL de redirecionamento externo",
  "admin/external-url-placeholder": "URL de redirecionamento externo",
  "admin/save-url": "Salvar URL",
  "admin/edit-url": "Editar URL",
  "admin/external-url-helper-text": "Por favor inclua https:// na URL",
  "admin/missing-labels": "Falta uma etiqueta",
  "admin/hide-label": "Ocultar",
  "store/challenge-bar.action-text": "Escolha visualizar conteúdo específico ou comprar online em outro país ou região.",
  "admin/editor.challenge-bar.title": "Barra de ações do desafio de binding",
  "admin/editor.challenge-bar.barText.title": "Chamada para ação",
  "admin/custom-flag.toggle": "Ícone de flag de binding personalizado",
  "admin/custom-flag.helpText": "É recomendável usar arquivos SVG com um tamanho de 24x24 px para manter a consistência",
  "admin/custom-flag.cta": "Editar flag",
  "admin/custom-flag.modal-title": "Carregar flag personalizada",
  "admin/custom-flag.modal-error": "Você carregou um {type} com um tamanho de {size} KB. Somente imagens de menos de 512 KB são permitidas",
  "admin/custom-flag.modal-dropzone-title": "Solte o arquivo aqui ou",
  "admin/custom-flag.modal-dropzone-cta": "selecione um arquivo",
  "admin/custom-flag.modal-dropzone-limit": "O tamanho máximo de arquivo é de {max_size} KB.",
  "admin/redirect-url.tooltip-label": "Este binding tem uma URL de redirecionamento externo"
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of binding-selector/messages/en.json from the binding-selector VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "admin/binding-selector.navigation.label": "Binding Selector",
  "admin/binding-selector": "Binding Selector",
  "admin/binding-selector.navigation.search.kws": "Binding Selector",
  "admin/description": "The sales policies will be updated when your customers change their store bindings.",
  "admin/label": "Update Trade Policy",
  "admin/store": "Store {index}: {address}",
  "admin/locale": "Locale: {locale}",
  "admin/action": "Custom store names",
  "admin/modal": "Customise the store names in this binding’s language.",
  "admin/cancel": "Cancel",
  "admin/save": "Save",
  "admin/hide-binding": "Visible",
  "admin/show-binding": "Hidden",
  "admin/advanced-settings": "Advanced Settings",
  "admin/set-external-url": "Set external redirect URL",
  "admin/external-url-placeholder": "External redirect URL",
  "admin/save-url": "Save URL",
  "admin/edit-url": "Edit URL",
  "admin/external-url-helper-text": "Please include https:// in the URL",
  "admin/missing-labels": "There is a missing label",
  "admin/hide-label": "Hide",
  "store/challenge-bar.action-text": "Choose to view specific content or buy online in another country or region.",
  "admin/editor.challenge-bar.title": "Binding challenge action bar",
  "admin/editor.challenge-bar.barText.title": "Call to action",
  "admin/custom-flag.toggle": "Custom binding flag icon",
  "admin/custom-flag.helpText": "SVG files, with a 24x24px size, is recommended to mantain consistency",
  "admin/custom-flag.cta": "Edit flag",
  "admin/custom-flag.modal-title": "Upload custom flag",
  "admin/custom-flag.modal-error": "You uploaded a/an {type} weighting {size} KB and only images of less than 512 KB are allowed",
  "admin/custom-flag.modal-dropzone-title": "Drop your file here or",
  "admin/custom-flag.modal-dropzone-cta": "choose a file",
  "admin/custom-flag.modal-dropzone-limit": "Maximum file size of {max_size} KB.",
  "admin/redirect-url.tooltip-label": "This binding has an external redirect URL"
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of binding-selector/messages/it.json from the binding-selector VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "admin/binding-selector.navigation.label": "Selettore di binding",
  "admin/binding-selector": "Selettore di binding",
  "admin/binding-selector.navigation.search.kws": "Selettore di binding",
  "admin/description": "Le politiche di vendita verranno aggiornate quando i tuoi clienti cambieranno i binding dei negozi.",
  "admin/label": "Aggiorna politica commerciale",
  "admin/store": "Negozio {index}: {address}",
  "admin/locale": "Regione: {locale}",
  "admin/action": "Personalizza i nomi del negozio",
  "admin/modal": "Personalizza i nomi del negozio nella lingua del binding.",
  "admin/cancel": "Annulla",
  "admin/save": "Salva",
  "admin/hide-binding": "Visibile",
  "admin/show-binding": "Nascosto",
  "admin/advanced-settings": "Impostazioni avanzate",
  "admin/set-external-url": "Imposta URL di reindirizzamento esterno",
  "admin/external-url-placeholder": "URL di reindirizzamento esterno",
  "admin/save-url": "Salva URL",
  "admin/edit-url": "Modifica URL",
  "admin/external-url-helper-text": "Si prega di includere https:// nell'URL",
  "admin/missing-labels": "Manca un'etichetta",
  "admin/hide-label": "Nascondi",
  "store/challenge-bar.action-text": "Scegli di visualizzare contenuti specifici o acquista online in un altro paese o regione.",
  "admin/editor.challenge-bar.title": "Barra delle azioni della sfida di binding",
  "admin/editor.challenge-bar.barText.title": "CTA (Call to Action)",
  "admin/custom-flag.toggle": "Personalizza l'icona del flag di binding",
  "admin/custom-flag.helpText": "É consigliabile utilizzare file SVG con una dimensione di 24x24 px per mantenere la consistenza.",
  "admin/custom-flag.cta": "Modifica flag",
  "admin/custom-flag.modal-title": "Carica flag personalizzato",
  "admin/custom-flag.modal-error": "Hai caricato un {type} con una dimensione di {size} KB. Sono consentite solamente immagini con una dimensione inferiore ai 512 KB.",
  "admin/custom-flag.modal-dropzone-title": "Trascina il tuo file qui o",
  "admin/custom-flag.modal-dropzone-cta": "scegli un file",
  "admin/custom-flag.modal-dropzone-limit": "La dimensione massima del file è di {max_size} KB.",
  "admin/redirect-url.tooltip-label": "Questo binding ha un URL di reindirizzamento esterno"
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of binding-selector/messages/context.json from the binding-selector VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "admin/binding-selector.navigation.label": "Binding Selector",
  "admin/binding-selector": "Binding Selector",
  "admin/binding-selector.navigation.search.kws": "Binding Selector",
  "admin/description": "The sales policies will be updated when your customers change their store bindings.",
  "admin/label": "Update Trade Policy",
  "admin/store": "Store {index}: {address}",
  "admin/locale": "Locale: {locale}",
  "admin/action": "Custom store names",
  "admin/modal": "Customise the store names in this binding’s language.",
  "admin/cancel": "Cancel",
  "admin/save": "Save",
  "admin/hide-binding": "Hide",
  "admin/show-binding": "Show",
  "admin/advanced-settings": "Advanced Settings",
  "admin/set-external-url": "Set external redirect URL",
  "admin/external-url-placeholder": "External redirect URL",
  "admin/save-url": "Save URL",
  "admin/edit-url": "Edit URL",
  "admin/external-url-helper-text": "Please include https:// in the URL",
  "admin/missing-labels": "There is a missing label",
  "admin/hide-label": "Hide",
  "store/challenge-bar.action-text": "Content for the challenge binding action bar",
  "admin/editor.challenge-bar.title": "Site editor challenge bar title",
  "admin/editor.challenge-bar.barText.title": "Challenge bar action-text title",
  "admin/custom-flag.toggle": "Custom binding flag toggle label",
  "admin/custom-flag.helpText": "Custom binding flag toggle help text",
  "admin/custom-flag.cta": "Custom binding flag button call to action",
  "admin/custom-flag.modal-title": "Custom binding flag modal title",
  "admin/custom-flag.modal-error": "Modal upload error",
  "admin/custom-flag.modal-dropzone-title": "First line of modal's text",
  "admin/custom-flag.modal-dropzone-cta": "Modal's call to action",
  "admin/custom-flag.modal-dropzone-limit": "Modal's file limit",
  "admin/redirect-url.tooltip-label": "Tooltip text describing the use of a redirect url"
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of binding-selector/messages/es.json from the binding-selector VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "admin/binding-selector.navigation.label": "Selector de binding",
  "admin/binding-selector": "Selector de binding",
  "admin/binding-selector.navigation.search.kws": "Selector de binding",
  "admin/description": "Las políticas comerciales se actualizarán cuando tus clientes cambien los bindings de su tienda.",
  "admin/label": "Actualizar política comercial",
  "admin/store": "Tienda {index}: {address}",
  "admin/locale": "Región: {locale}",
  "admin/action": "Nombres de tienda personalizados",
  "admin/modal": "Personalizar los nombres de las tiendas en el idioma del binding.",
  "admin/cancel": "Cancelar",
  "admin/save": "Guardar",
  "admin/hide-binding": "Visible",
  "admin/show-binding": "Oculto",
  "admin/advanced-settings": "Configuración avanzada",
  "admin/set-external-url": "Establecer URL de redirección externa",
  "admin/external-url-placeholder": "URL de redirección externa",
  "admin/save-url": "Guardar URL",
  "admin/edit-url": "Editar URL",
  "admin/external-url-helper-text": "Por favor, incluye https:// en la URL",
  "admin/missing-labels": "Falta una etiqueta",
  "admin/hide-label": "Ocultar",
  "store/challenge-bar.action-text": "Elige ver contenido específico o compra online en otro país o región.",
  "admin/editor.challenge-bar.title": "Barra de acciones del desafío de binding",
  "admin/editor.challenge-bar.barText.title": "CTA",
  "admin/custom-flag.toggle": "Ícono de flag de binding personalizado",
  "admin/custom-flag.helpText": "Se recomienda utilizar archivos SVG con un tamaño de 24x24 px para mantener uniformidad.",
  "admin/custom-flag.cta": "Editar flag",
  "admin/custom-flag.modal-title": "Cargar flag personalizado",
  "admin/custom-flag.modal-error": "Has cargado un {type} con un tamaño de {size} KB y solo se permiten imágenes de menos de 512 KB",
  "admin/custom-flag.modal-dropzone-title": "Arrastra el archivo aquí o",
  "admin/custom-flag.modal-dropzone-cta": "selecciona un archivo",
  "admin/custom-flag.modal-dropzone-limit": "El tamaño máximo de archivo es de {max_size} KB.",
  "admin/redirect-url.tooltip-label": "Este binding tiene una URL de redirección externa."
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of binding-selector/admin/navigation.json from the binding-selector VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "section": "accountSettings",
  "titleId": "admin/binding-selector.navigation.label",
  "path": "/admin/binding-selector",
  "searchKeyWordsHelpers": "admin/binding-selector.navigation.search.kws"
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of binding-selector/admin/routes.json from the binding-selector VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "admin.binding-selector": {
    "component": "BindingSelectorAdmin",
    "path": "/admin/app/binding-selector"
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of binding-selector/docs/README.md from the binding-selector VTEX app.

[Assistant]
Here's the implementation:

```markdown
# Binding Selector

##  ⚠ Maintenance ⚠
*Starting June 1st 2023, this application will no longer be maintained by VTEX.*

---

The Binding Selector APP, allows multi-language stores, specifically those with a single account-multiple binding architecture, to switch between their configured bindings.

The App takes the **Canonical** context of the current binding as well as the **Alternate href** addresses registered for the other bindings, and creates a drop-down menu component to display the possible options on the Store Front.

This allows customers to seamlesly switch between stores without returning to Home or leaving the site.

Example:
If a user arrives to the Spanish Site:
www.testperformancev.com/es/iphone-11-128gb-rojo/p -> Canonical
www.testperformancev.com/pt/iphone-11-128gb-vermelho/p -> Alternate

If a user switches or arrives to the Portuguese Site:
www.testperformancev.com/pt/iphone-11-128gb-vermelho/p -> Canonical
www.testperformancev.com/es/iphone-11-128gb-rojo/p -> Alternate

It has the possibility to update the Session and Cart's Sales Channel, this changes the prices and stock available for each store. It is up to the user to toggle this setting ON of OFF inside the App's settings.

The App is geared towards an improvement on Site Experience for the customer and it will have a direct impact on the store's conversion.

![bindingfunctionality](/docs/bindingfunctionality.gif)

## Configuration

The App consists on **two** main features an **Admin Interface** and a Store Block called **binding-selector** to be declared on the Store-Theme.

The Setup for the app is as follows:

1. on the CLI and run: `vtex install vtex.binding-selector@2.x`
2. declare the block as a peerDependency inside your store-theme manifest.json:

   ```
   "peerDependencies": {
    "vtex.binding-selector": "2.x"
   }
   ```

3. on the **store-theme** declare the block **binding-selector** where it is intended to be displayed, for example, inside the **header.json** declare the block as follows:

   ```
   "flex-layout.row#4-desktop": {
    "props": {
      "blockClass": "main-header",
      "horizontalAlign": "center",
      "verticalAlign": "center",
      "preventHorizontalStretch": true,
      "preventVerticalStretch": true,
      "fullWidth": true
    },
    "children": [
      "flex-layout.col#logo-desktop",
      "flex-layout.col#category-menu",
      "flex-layout.col#spacer",
      "search-bar",
      "binding-selector",
      "login",
      "minicart.v2"
    ]},
   "binding-selector": {
    "props": {
      "layout": "dropdown",
      "display": "combined"
    }
   }

   ```

4. Go to your account Admin Panel and under the Account Settings, there will be a new menu item called **Binding Selector**. Here you will have the following options:

   4.1 Possibility to toggle whether or not the app will change Sales Channels when switching bindings. When the store changes the Sales Channel, the prices of the store and the checkout will also change.

   4.2. Toggle each store individually to be displayed on the front end component.

   4.3 Modify each displayed option labels clicking on the **Custom Store Names** button. This process has to be done for each active or displayed site.

    **if there are no labels configured, the menu won't display any options!!**

   4.4 _Advanced Settings_

    4.4.1 External redirect URL
      - When set, user will redirect to the given URL when clicking the binding in the store

    4.4.2 Custom Flag
      - It's possible to customize the flags that represents the bindings. SVG files, with a 24x24px size, is recommended to mantain consistency.

![adminfunctionality](/docs/admininterface.gif)

### `binding-selector` block

Renders a component that allows the user to select a different binding for your store.

| Prop name | Type     | Description                                                                                | Default value |
| --------- | -------- | ---------------------------------------------------------------------------------------------- | ------------- |
| `layout`  | `string` | How the bindings are grouped. Possible values are: `dropdown` - `list` - `select`            | `dropdown`    |
| `display` | `string` | How the bindings are displayed in the group. Possible values are: `text` - `flag` - `combined`. Please keep in mind that the `select` layout cannot be paired with `flag` or `combined`, as the native HTML tag 'select' can only render text | `text`        |

### `current-binding` block

Renders a component that ONLY shows the current binding as a SVG flag. Useful to use it as modal-trigger

### `binding-challenge` block

Renders an action bar that automatically detects if the user's country is different from the binding locale its browsing.
The bar has a call to action text and is using the `binding-selector` selector.

## Customization

In order to apply CSS customizations in this and other blocks, follow the instructions given in the recipe on [Using CSS Handles for store customization](https://vtex.io/docs/recipes/style/using-css-handles-for-store-customization).

| CSS Handles         |
| ------------------- |
| `container`         |
| `relativeContainer` |
| `button`            |
| `buttonText`        |
| `list`              |
| `listElement`       |
| `active*`           |
| `currentBinding`    |
| `challengeBar`      |
| `actionCTA`         |
| `actionContainer`   |
| `listContainer`     |

_\*conditional class when dropdown is open_

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of binding-selector/graphql/schema.graphql from the binding-selector VTEX app.

[Assistant]
Here's the implementation:

```graphql
type Query {
  bindingInfo: [TranslatedInfoOutput]
    @cacheControl(scope: PUBLIC, maxAge: SHORT)
  isSalesChannelUpdate: Boolean @cacheControl(scope: PUBLIC, maxAge: SHORT)
}

type Mutation {
  updateSalesChannel(orderFormId: ID, salesChannel: String): PartialOrderForm

  saveBindingInfo(data: [BindingsInput]): [TranslatedInfoOutput]
  toggleSalesChannel(salesChannel: Boolean): Boolean
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of binding-selector/node/routes.ts from the binding-selector VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { method } from '@vtex/api'

import { viewerCountry } from './middlewares'

const routes = {
  viewerCountry: method({
    GET: [viewerCountry],
  }),
}

export { routes }

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of binding-selector/node/service.json from the binding-selector VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "stack": "nodejs",
  "memory": 1024,
  "ttl": 12,
  "timeout": 10,
  "minReplicas": 6,
  "maxReplicas": 20,
  "routes": {
    "viewerCountry": {
      "path": "/_v/binding-selector/viewer-country",
      "public": true
    }
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of binding-selector/node/utils.ts from the binding-selector VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { AuthenticationError, ForbiddenError, UserInputError } from '@vtex/api'
import type { AxiosError } from 'axios'

export const statusToError = (e: AxiosError) => {
  if (!e.response) {
    throw e
  }

  const {
    response: { status },
  } = e

  switch (status) {
    case 401: {
      throw new AuthenticationError(e)
    }

    case 403: {
      throw new ForbiddenError(e)
    }

    case 400: {
      throw new UserInputError(e)
    }

    default:
      break
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of binding-selector/node/package.json from the binding-selector VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "name": "vtex.binding-selector",
  "version": "2.1.7",
  "license": "UNLICENSED",
  "private": true,
  "scripts": {
    "test": "vtex-test-tools test"
  },
  "devDependencies": {
    "@vtex/test-tools": "vtex/test-tools",
    "@vtex/tsconfig": "^0.5.6",
    "axios": "^0.21.1",
    "typescript": "3.9.7",
    "vtex.checkout-graphql": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.checkout-graphql@0.65.1/public/@types/vtex.checkout-graphql",
    "vtex.country-flags": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.country-flags@0.1.1/public/@types/vtex.country-flags",
    "vtex.css-handles": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.css-handles@0.4.4/public/@types/vtex.css-handles",
    "vtex.device-detector": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.device-detector@0.2.6/public/@types/vtex.device-detector",
    "vtex.file-manager-graphql": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.file-manager-graphql@0.3.0/public/@types/vtex.file-manager-graphql",
    "vtex.order-items": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.order-items@0.13.1/public/@types/vtex.order-items",
    "vtex.render-runtime": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@7.45.0/public/@types/vtex.render-runtime",
    "vtex.rewriter": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.rewriter@1.56.1/public/@types/vtex.rewriter",
    "vtex.store-graphql": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store-graphql@2.149.2/public/@types/vtex.store-graphql",
    "vtex.styleguide": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.145.2/public/@types/vtex.styleguide",
    "vtex.tenant-graphql": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.tenant-graphql@0.1.2/public/@types/vtex.tenant-graphql"
  },
  "dependencies": {
    "@vtex/api": "6.45.6"
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of binding-selector/node/index.ts from the binding-selector VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type {
  ClientsConfig,
  ServiceContext,
  ParamsContext,
  RecorderState,
} from '@vtex/api'
import { LRUCache, Service } from '@vtex/api'

import { Clients } from './clients'
import { routes } from './routes'
import { queries, mutations } from './resolvers'

const TIMEOUT_MS = 10 * 1000

// The @vtex/api HttpClient respects Cache-Control headers and uses the provided cache.
const memoryCache = new LRUCache<string, any>({ max: 5000 })

metrics.trackCache('checkout', memoryCache)

// This is the configuration for clients available in `ctx.clients`.
const clients: ClientsConfig<Clients> = {
  implementation: Clients,
  options: {
    // All IO Clients will be initialized with these options, unless otherwise specified.
    default: {
      retries: 2,
      timeout: TIMEOUT_MS,
      memoryCache,
      concurrency: 10,
    },
  },
}

declare global {
  // We declare a global Context type just to avoid re-writing ServiceContext<Clients, State> in every handler and resolver
  type Context = ServiceContext<Clients>
}

// Export a service that defines route handlers and client options.
export default new Service<Clients, RecorderState, ParamsContext>({
  clients,
  routes,
  graphql: {
    resolvers: {
      Query: {
        ...queries,
      },
      Mutation: {
        ...mutations,
      },
    },
  },
})

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of binding-selector/react/CurrentBinding.tsx from the binding-selector VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import type { FC } from 'react'
import { useCssHandles } from 'vtex.css-handles'

import { useBinding } from './hooks/useBindings'
import Spinner from './components/Spinner'
import LabelOption from './components/LabelsFlags'

const CSS_HANDLES = ['currentBinding'] as const

interface Props {
  /* How we display the current binding */
  display: FlagDisplay
}

/**
 * @returns an icon or string showing which is
 * the current binding, useful as a modal-trigger
 */
const CurrentBinding: FC<Props> = ({ display = 'text' }) => {
  const {
    data: { currentBinding, bindingsError, loadingBindings },
  } = useBinding()

  const handles = useCssHandles(CSS_HANDLES)
  const noBinding = !loadingBindings && !currentBinding.id
  const hasError = !!bindingsError
  const flag = currentBinding.customFlagData

  if (hasError) {
    console.error('Error loading current Binding', {
      bindingsError,
    })

    return null
  }

  if (noBinding) {
    console.warn('No Binding assigned to the current Binding', {
      bindingsError,
    })

    return null
  }

  return (
    <div
      className={`${handles.currentBinding} flex items-center justify-center h-100 mh4`}
    >
      {loadingBindings ? (
        <Spinner />
      ) : (
        <LabelOption binding={currentBinding} display={display} flag={flag} />
      )}
    </div>
  )
}

export default CurrentBinding

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of binding-selector/react/BindingSelectorAdmin.tsx from the binding-selector VTEX app.

[Assistant]
Here's the implementation:

```tsx
import type { FC } from 'react'
import React from 'react'
import { FormattedMessage } from 'react-intl'
import { Layout, PageBlock, PageHeader } from 'vtex.styleguide'

import Selector from './components/admin/Selector'

import './styles.global.css'

const BindingSelectorAdmin: FC = () => {
  return (
    <Layout
      pageHeader={
        <PageHeader title={<FormattedMessage id="admin/binding-selector" />} />
      }
    >
      <PageBlock variation="full">
        <Selector />
      </PageBlock>
    </Layout>
  )
}

export default BindingSelectorAdmin

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of binding-selector/react/package.json from the binding-selector VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "name": "vtex.binding-selector",
  "version": "2.1.7",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "devDependencies": {
    "@types/node": "^11.12.1",
    "@types/react": "^16.8.10",
    "@types/react-intl": "^3.0.0",
    "prop-types": "^15.7.2",
    "react-intl": "^5.13.2",
    "typescript": "3.9.7",
    "vtex.checkout-graphql": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.checkout-graphql@0.65.1/public/@types/vtex.checkout-graphql",
    "vtex.country-flags": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.country-flags@0.1.1/public/@types/vtex.country-flags",
    "vtex.css-handles": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.css-handles@0.4.4/public/@types/vtex.css-handles",
    "vtex.device-detector": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.device-detector@0.2.6/public/@types/vtex.device-detector",
    "vtex.file-manager-graphql": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.file-manager-graphql@0.3.0/public/@types/vtex.file-manager-graphql",
    "vtex.order-items": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.order-items@0.13.1/public/@types/vtex.order-items",
    "vtex.render-runtime": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.132.3/public/@types/vtex.render-runtime",
    "vtex.rewriter": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.rewriter@1.56.1/public/@types/vtex.rewriter",
    "vtex.store-graphql": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store-graphql@2.149.2/public/@types/vtex.store-graphql",
    "vtex.styleguide": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.145.2/public/@types/vtex.styleguide",
    "vtex.tenant-graphql": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.tenant-graphql@0.1.2/public/@types/vtex.tenant-graphql"
  },
  "dependencies": {
    "@apollo/client": "^3.3.7",
    "apollo-client": "^2.6.10",
    "graphql": "^15.5.0",
    "react": "^17.0.1",
    "react-apollo": "^3.1.5",
    "react-dom": "^17.0.1",
    "react-markdown": "^4.0.4",
    "react-router-dom": "5.2.0"
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of binding-selector/react/styles.global.css from the binding-selector VTEX app.

[Assistant]
Here's the implementation:

```css
html,
body,
#render-container,
#render-provider,
.render-container,
.render-provider {
  height: 100%;
}

.flex-basis-33 {
  flex-basis: 33%;
}

.flex-basis-25 {
  flex-basis: 25%;
}

.flex-basis-50 {
  flex-basis: 50%;
}

.width-70 {
  width: 70%;
}

.z-9999 {
  z-index: 9999;
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of binding-selector/react/BindingChallenge.tsx from the binding-selector VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { useState, useEffect } from 'react'
import { ButtonWithIcon, IconClose } from 'vtex.styleguide'
import { FormattedMessage } from 'react-intl'
import { useDevice } from 'vtex.device-detector'
import { useCssHandles } from 'vtex.css-handles'

import { useBinding } from './hooks/useBindings'
import BindingSelectorBlock from './BindingSelectorBlock'

const close = <IconClose />

const CSS_HANDLES = ['challengeBar', 'actionCTA', 'actionContainer'] as const

interface Props {
  barText: string
}

const BindingChallenge = ({ barText }: Props) => {
  const [show, setDisplay] = useState(false)
  const [viewerCountry, setViewerCountry] = useState<string | null>(null)
  const handles = useCssHandles(CSS_HANDLES)
  const { device } = useDevice()

  const {
    data: { currentBinding, bindingsError, loadingBindings },
  } = useBinding()

  useEffect(() => {
    async function fetchViewerCountry() {
      try {
        const response = await fetch(`/_v/binding-selector/viewer-country`)
        const countryISO = await response.text()

        !countryISO || setViewerCountry(countryISO)
      } catch (e) {
        console.error(e)
      }
    }

    fetchViewerCountry()
  }, [])

  useEffect(() => {
    if (!viewerCountry || !currentBinding.defaultLocale) {
      return
    }

    if (localStorage.getItem('hasShownBindingBar') === 'true') {
      return
    }

    /* viewer country is ISO2
    so we compare the last 2 digits of the locale
    i.e es-ES === ES
    */
    const bindingLocale = currentBinding.defaultLocale
      ?.substr(3, 2)
      .toUpperCase()

    if (viewerCountry === bindingLocale) {
      return
    }

    setDisplay(true)
  }, [currentBinding, viewerCountry])

  const handleActionBar = () => {
    localStorage.setItem('hasShownBindingBar', 'true')
    setDisplay(false)
  }

  const text = barText || (
    <FormattedMessage id="store/challenge-bar.action-text" />
  )

  const shouldShowActionBar =
    show && !bindingsError && !loadingBindings && currentBinding.id

  if (!shouldShowActionBar) {
    return null
  }

  return (
    <div
      className={`${
        handles.challengeBar
      } flex items-center justify-center shadow-active w-100 bg-base pa4 tc ${
        device === 'phone' ? 'flex-column' : ''
      }`}
    >
      <span
        className={`${handles.actionCTA} t-small ${
          device === 'phone' ? 'pb3' : ''
        }`}
      >
        {text}
      </span>
      <div className={`${handles.actionContainer} flex`}>
        <span className="mh5 w-10" style={{ width: 180 }}>
          <BindingSelectorBlock layout="select" display="text" />
        </span>
        <span>
          <ButtonWithIcon
            size="small"
            icon={close}
            variation="tertiary"
            onClick={() => {
              handleActionBar()
            }}
          />
        </span>
      </div>
    </div>
  )
}

BindingChallenge.schema = {
  title: 'admin/editor.challenge-bar.title',
  type: 'object',
  properties: {
    barText: {
      title: 'admin/editor.challenge-bar.barText.title',
      type: 'string',
    },
  },
}

export default BindingChallenge

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of binding-selector/react/BindingSelectorBlock.tsx from the binding-selector VTEX app.

[Assistant]
Here's the implementation:

```tsx
import type { FC } from 'react'
import React, { useState, useEffect } from 'react'
import { useRuntime } from 'vtex.render-runtime'
import { useMutation, useLazyQuery, useQuery } from 'react-apollo'
import { useOrderItems } from 'vtex.order-items/OrderItems'

import BindingSelectorDropdown from './components/BindingSelectorDropdown'
import updateSalesChannelMutation from './graphql/updateSalesChannel.gql'
import alternateHrefsQuery from './graphql/alternateHrefs.gql'
import { createRedirectUrl, getMatchRoute, transformUserRouteId } from './utils'
import shouldUpdateSalesChannel from './graphql/isSalesChannelUpdate.gql'
import BindingSelectorList from './components/BindingSelectorList'
import BindingSelectorSelect from './components/BindingSelectorSelect'
import { useBinding } from './hooks/useBindings'
import getOrderForm from './graphql/getOrderForm.gql'

interface GetOrderFormResponse {
  orderForm: {
    salesChannel: string
    orderFormId: string
    items: Array<{ id: string }>
  }
}

interface Props {
  /* How the list of bindings is rendered */
  layout: 'dropwdown' | 'list' | 'select'
  /* How we display each binding */
  display: FlagDisplay
}

const BindingSelectorBlock: FC<Props> = ({
  layout = 'dropdown',
  display = 'text',
}) => {
  const {
    data: { currentBinding, bindingList, bindingsError, loadingBindings },
    actions: { setCurrentBindingInfo },
  } = useBinding()

  const [HasRunSyncEffect, setHasRunSyncEffect] = useState(false)
  const [salesChannel, setSalesChannel] = useState('')
  const {
    route: {
      pageContext: { id, type },
      queryString,
    },
  } = useRuntime()

  const { updateQuantity } = useOrderItems()

  const queryVariables = {
    id: type === 'route' ? transformUserRouteId(id) : id,
    type: type === 'route' ? 'userRoute' : type,
  }

  const [
    getAlternateHrefs,
    { data: hrefAltData },
  ] = useLazyQuery<QueryInternal>(alternateHrefsQuery, {
    variables: queryVariables,
  })

  const [updateSalesChannel] = useMutation<
    {
      updateSalesChannel: {
        orderFormId: string
        items: Array<{ quantity: number; uniqueId: string }>
      }
    },
    UpdateSalesChannelVariables
  >(updateSalesChannelMutation)

  /**
   * @todo We are using this query only because the order-manager doesn't
   * expose the salesChannel. If we make a PR to checkout-graphql to add it
   * we could dispose of this query to avoid waiting for the block to render
   */
  const {
    data: orderFormResponse,
    loading: loadingOrderForm,
    error: orderFormError,
  } = useQuery<GetOrderFormResponse>(getOrderForm, {
    ssr: false,
  })

  const [loadingRedirect, setLoadingRedirect] = useState<boolean>(false)

  const { data: toogleSalesChannel } = useQuery<SalesChannelResponse>(
    shouldUpdateSalesChannel,
    {
      ssr: false,
    }
  )

  /**
   * This effect handles the redirect after user selects a new binding.
   * We are handling it here because we couldn't get the hreflang inside the handleSelection method, since the callback from useLazyCallback returns void
   */
  useEffect(() => {
    const { canonicalBaseAddress } = currentBinding
    const { hostname, protocol, hash } = window.location
    let path = ''

    // eslint-disable-next-line vtex/prefer-early-return
    if (hrefAltData) {
      const { routes = [] } = hrefAltData.internal

      path = getMatchRoute({ routes, currentBindingId: currentBinding.id })

      const keepSalesChannel = !toogleSalesChannel?.isSalesChannelUpdate

      const { channel } = JSON.parse(atob(window.__RUNTIME__.segmentToken))

      const urlToRedirect = createRedirectUrl({
        canonicalBaseAddress,
        hostname,
        protocol,
        path,
        hash,
        pageType: id,
        keepSalesChannel,
        /**
         * We try to use the salesChannel set on state, but the first load
         * will not have it - we trust that segmentToken on runtime will be right.
         * See more details in the useEffect below.
         */
        salesChannel: salesChannel || channel,
      })

      console.info(`Redirecting to ${urlToRedirect}`)

      window.location.href = urlToRedirect
    }
  }, [hrefAltData, currentBinding, id, toogleSalesChannel, salesChannel])

  /**
   * This effect handles the synchronization between binding sales channel on page load and cart sales channel.
   * If different, it updates the cart sales channel to be the same as the one coming from the sales channel based on the binding url
   */
  useEffect(() => {
    const syncSalesChannel = async () => {
      const { data } = await updateSalesChannel({
        variables: {
          orderFormId: (orderFormResponse as GetOrderFormResponse).orderForm
            .orderFormId,
          salesChannel: currentBinding.salesChannel,
        },
      })

      const { items } = data?.updateSalesChannel ?? { items: [] }

      for (let i = 0; i < items.length; i++) {
        const { uniqueId, quantity } = items[i]

        // Trigger a re-render for cart component
        updateQuantity({
          uniqueId,
          quantity,
        })
      }
    }

    if (
      orderFormResponse?.orderForm.items.length &&
      currentBinding?.id &&
      toogleSalesChannel?.isSalesChannelUpdate
    ) {
      if (
        orderFormResponse.orderForm.salesChannel !==
          currentBinding.salesChannel &&
        !HasRunSyncEffect
      ) {
        syncSalesChannel()
      }

      setHasRunSyncEffect(true)
    }
  }, [
    currentBinding,
    toogleSalesChannel,
    updateSalesChannel,
    updateQuantity,
    HasRunSyncEffect,
    orderFormResponse,
  ])

  /**
   * This effect sets the target sales channel after the user changes binding
   * for the first time. This allows the user to change to a different binding multiple
   * times wihtout losing reference from the first one visited. It was necessary because
   * `window.__RUNTIME__.segmentToken` (for some weird reason) didn't keep sync'ed with the
   * sales channel in the session cookie.
   */
  useEffect(() => {
    if (queryString?.sc && !salesChannel) {
      setSalesChannel(queryString.sc)
    }
  }, [queryString, salesChannel])

  const handleSelection = async (
    selectedBinding: TranslationsAndSettings
  ): Promise<void> => {
    setLoadingRedirect(true)
    setCurrentBindingInfo(selectedBinding.id)

    if (selectedBinding.externalRedirectData?.redirectUrl) {
      window.location.href = selectedBinding.externalRedirectData.url

      return
    }

    if (toogleSalesChannel?.isSalesChannelUpdate) {
      try {
        await updateSalesChannel({
          variables: {
            orderFormId: (orderFormResponse as GetOrderFormResponse).orderForm
              .orderFormId,
            salesChannel: selectedBinding.salesChannel,
          },
        })
      } catch (e) {
        // How to handle when there is an error updating sales channel?
        console.error(e)
      }
    }

    getAlternateHrefs()
  }

  const isLoading =
    loadingBindings || loadingOrderForm || !currentBinding.id || loadingRedirect

  const noBinding = !loadingBindings && !loadingOrderForm && !currentBinding.id

  const hasError = !!orderFormError || !!bindingsError

  if (hasError) {
    console.error('Error loading Binding Selector', {
      orderFormError,
      bindingsError,
    })

    return null
  }

  if (noBinding) {
    console.warn('No Binding assigned to the current Binding')

    return null
  }

  if (layout === 'list') {
    return (
      <BindingSelectorList
        bindingList={bindingList}
        currentBinding={currentBinding}
        onSelectBinding={handleSelection}
        display={display}
        /* Don't want to check for loadingRedirect */
        isLoading={loadingBindings || loadingOrderForm || !currentBinding.id}
      />
    )
  }

  if (layout === 'select') {
    if (display === 'combined' || display === 'flag') {
      console.error(
        'Binding selector: Native HTML <select> tag cannot render flags as options, please choose a different layout'
      )
    }

    return (
      <BindingSelectorSelect
        bindingList={bindingList}
        currentBinding={currentBinding}
        onSelectBinding={handleSelection}
        isLoading={isLoading}
      />
    )
  }

  return (
    <BindingSelectorDropdown
      bindingInfo={bindingList}
      currentBinding={currentBinding}
      onSelectBinding={handleSelection}
      isLoading={isLoading}
      display={display}
    />
  )
}

export default BindingSelectorBlock

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of binding-selector/store/interfaces.json from the binding-selector VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "binding-selector": {
    "component": "BindingSelectorBlock"
  },
  "current-binding": {
    "component": "CurrentBinding"
  },
  "binding-challenge": {
    "component": "BindingChallenge"
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of binding-selector/public/metadata/messages/es-AR.json from the binding-selector VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "name": "Country Store Switcher",
  "headline": "Solución nativa para cambiar entre tiendas para los clientes en una arquitectura de una cuenta - multiples bindings.",
  "overview": "Esta App le permite a los usuarios cambiar entre las diferentes tiendas que tenga la cuenta.",
  "features": [
    "Cambia de una tienda a la otra sin barreras",
    "Posibilidad de cambiar Políticas Comerciales entre tiendas",
    "Toggle On/Off para los sitios que se desean mostrar",
    "Capacidad de tener redirects externos",
    "Configuración de etiquetas por idioma"
  ],
  "websiteURL": "https://vtex.com/",
  "support": {
    "url": "https://support.vtex.com/hc/requests"
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of binding-selector/public/metadata/messages/pt-BR.json from the binding-selector VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "name": "Country Store Switcher",
  "headline": "Solução nativa para navegação entre lojas em contas com arquitetura single account - multi-bindings.",
  "overview": "Esta applicação permite navegação entre diferentes lojas para contas com arquitetura single account - multiple bindings.",
  "features": [
    "Mudança simples de navegação entre lojas",
    "Permite alterar Sales Channel do carrinho ao navegar para outra loja",
    "Escolha de quais lojas serão listadas no seletor de loja",
    "Permite incluir URL externa para redirecionar usuários a lojas fora da VTEX",
    "Configuração dos nomes das lojas que serão listadas no seletor"
  ],
  "websiteURL": "https://vtex.com/",
  "support": {
    "url": "https://support.vtex.com/hc/requests"
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of binding-selector/public/metadata/messages/en-US.json from the binding-selector VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "name": "Country Store Switcher",
  "headline": "Native solution to switch between stores on a single account - multi-binding architecture.",
  "overview": "This app allows stores with a single account - multiple binding architecture to switch between their stores.",
  "features": [
    "Seamlessly switch between stores",
    "Possibility to change Sales Channels when switching stores",
    "Toggle On/Off the sites desired to be shown",
    "External redirect capability",
    "Configure labels by language"
  ],
  "websiteURL": "https://vtex.com/",
  "support": {
    "url": "https://support.vtex.com/hc/requests"
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of binding-selector/graphql/types/OrderForm.graphql from the binding-selector VTEX app.

[Assistant]
Here's the implementation:

```graphql
type PartialOrderForm {
  orderFormId: ID!
  salesChannel: String!
  items: [Item!]!
  canEditData: Boolean!
  loggedIn: Boolean!
  userProfileId: String
  value: Float!
  clientPreferencesData: ClientPreferencesData
  allowManualPrice: Boolean
}

type ClientPreferencesData {
  locale: String
  optinNewsletter: Boolean
}

input ClientPreferencesDataInput {
  optinNewsletter: Boolean
  locale: String
}

```