[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 checkout-coupon/react/__tests__/Coupon.test.tsx from the checkout-coupon VTEX app.

[Assistant]
Here's the implementation:

```tsx
import { render, fireEvent, wait } from '@vtex/test-tools/react'
import React, { useState } from 'react'

import Coupon from '../Coupon'

const {
  OrderCoupon: { OrderCouponProvider },
} = jest.requireMock('vtex.order-coupon')

describe('<Coupon />', () => {
  it('should show input after clicking to apply promotion code', () => {
    const { getByText, getByRole } = render(
      <OrderCouponProvider coupon="" insertCoupon={jest.fn()}>
        <Coupon />
      </OrderCouponProvider>
    )

    const button = getByText(/apply promo code/i)

    fireEvent.click(button)

    const couponInput = getByRole('textbox')

    expect(couponInput).toBeInTheDocument()
  })

  it('should show coupon tag if coupon already applied', () => {
    const { getByText } = render(
      <OrderCouponProvider coupon="testcoupon" insertCoupon={jest.fn()}>
        <Coupon />
      </OrderCouponProvider>
    )

    expect(getByText('testcoupon')).toBeInTheDocument()
  })

  it('should focus on the input after clicking on apply promo code button', () => {
    const { getByRole, getByText } = render(
      <OrderCouponProvider coupon="" insertCoupon={jest.fn()}>
        <Coupon />
      </OrderCouponProvider>
    )

    const addPromoButton = getByText(/apply promo code/i)

    fireEvent.click(addPromoButton)

    const couponInput = getByRole('textbox')

    expect(document.activeElement).toBe(couponInput)
  })

  it('should be able to submit the coupon code', async () => {
    const Component: React.FC = () => {
      const [coupon, setCoupon] = useState('')

      const insertCoupon = (newCoupon: string) => {
        setCoupon(newCoupon)

        return Promise.resolve({ success: true, errorKey: '' })
      }

      return (
        <OrderCouponProvider coupon={coupon} insertCoupon={insertCoupon}>
          <Coupon />
        </OrderCouponProvider>
      )
    }

    const { getByRole, getByText } = render(<Component />)

    const addPromoButton = getByText(/apply promo code/i)

    fireEvent.click(addPromoButton)

    const couponInput = getByRole('textbox')

    fireEvent.change(couponInput, { target: { value: 'freeshipping' } })

    const submitCouponButton = getByRole('button')

    fireEvent.click(submitCouponButton)

    await wait(() => expect(getByText('freeshipping')).toBeInTheDocument())
  })

  it('should remove coupon after clicking on coupon tag', () => {
    const Component: React.FC = () => {
      const [coupon, setCoupon] = useState('freeshipping')

      const insertCoupon = (newCoupon: string) => {
        setCoupon(newCoupon)

        return Promise.resolve({ success: true, errorKey: '' })
      }

      return (
        <OrderCouponProvider coupon={coupon} insertCoupon={insertCoupon}>
          <Coupon />
        </OrderCouponProvider>
      )
    }

    const { getByText, getByRole } = render(<Component />)

    const couponTag = getByText('freeshipping')

    expect(couponTag).toBeInTheDocument()

    fireEvent.click(couponTag)

    const couponInput = getByRole('textbox')

    expect(couponInput).toBeInTheDocument()
    expect(couponInput).toHaveValue('')
  })

  it.each`
    couponName          | errorKey            | messageRegex
    ${'expired coupon'} | ${'couponExpired'}  | ${/this promo code has expired/i}
    ${'invalid coupon'} | ${'couponNotFound'} | ${/invalid promo code/i}
  `(
    'should handle $errorKey error when submitting the coupon',
    async ({
      couponName,
      errorKey,
      messageRegex,
    }: {
      couponName: string
      errorKey: string
      messageRegex: RegExp
    }) => {
      const Component: React.FC = () => {
        const [coupon, setCoupon] = useState('')

        const insertCoupon = (newCoupon: string) => {
          if (newCoupon === couponName) {
            return Promise.resolve({ success: false, errorKey })
          }

          setCoupon(newCoupon)

          return Promise.resolve({ success: true, errorKey: '' })
        }

        return (
          <OrderCouponProvider coupon={coupon} insertCoupon={insertCoupon}>
            <Coupon />
          </OrderCouponProvider>
        )
      }

      const { getByRole, getByText } = render(<Component />)

      const addPromoButton = getByText(/apply promo code/i)

      fireEvent.click(addPromoButton)

      const couponInput = getByRole('textbox')

      fireEvent.change(couponInput, { target: { value: couponName } })

      const applyButton = getByRole('button')

      fireEvent.click(applyButton)

      await wait(() => expect(getByText(messageRegex)).toBeInTheDocument())
    }
  )
})

```


[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 sidecar-pixel/docs/README.md from the sidecar-pixel VTEX app.

[Assistant]
Here's the implementation:

```markdown
# Sidecar

> getsidecar.com first party app

## Setup

Open a terminal and type:

```
vtex install vtex.sidecar-pixel@1.x
```

Open your admin in the Apps section:

https://YOURSTORENAME.myvtex.com/admin/apps/

Click in Sidecar and fill your Site Domain and Site 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 sidecar-pixel/react/package.json from the sidecar-pixel VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "devDependencies": {
    "@types/graphql": "^14.2.2",
    "@types/jest": "^24.0.15",
    "@types/node": "^12.6.4",
    "eslint": "5",
    "eslint-config-vtex-react": "^4.1.0",
    "prettier": "^1.18.2",
    "typescript": "3.5.2"
  }
}

```


[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 sidecar-pixel/react/index.ts from the sidecar-pixel VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { canUseDOM } from 'vtex.render-runtime'
import { PixelMessage, OrderPlacedData } from './typings/events'

let added = false
function handleMessages(e: PixelMessage) {
  switch (e.data.eventName) {
    case 'vtex:pageView': {
      const { pageUrl } = e.data
      const isOrderPlaced = pageUrl.indexOf('checkout/orderPlaced') !== -1
      if (!isOrderPlaced && added === false) {
        addTrackingLib()
      }
      break
    }
    case 'vtex:orderPlaced': {
      const order = e.data
      addMetrics(order)
      addTrackingLib()
      break
    }
    default:
      break
  }
}

function addTrackingLib() {
  const a = document.createElement('script')
  a.async = true
  a.setAttribute('data-id', encodeURI(window.__sidecar_id))
  a.setAttribute('data-domain', encodeURI(window.__sidecar_domain))
  a.setAttribute('data-other', JSON.stringify({}))
  a.id = '_SCJS_'
  a.src = 'https://d3v27wwd40f0xu.cloudfront.net/js/tracking/sidecar.js'
  const r =
    document.getElementsByTagName('script')[0] ||
    document.getElementsByTagName('body')[0]
  r.parentNode!.insertBefore(a, r)
}

function addMetrics(order: OrderPlacedData) {
  window.sidecar = window.sidecar || {}

  type Promo = { name: string; amount: number }
  const promosMap = order.transactionProducts.reduce<Record<string, Promo>>(
    (promos, product) => {
      product.priceTags.forEach(priceTag => {
        // Not a discount, priceTag is increasing the price
        if (priceTag.value > 0) {
          return
        }

        if (!promos[priceTag.identifier]) {
          promos[priceTag.identifier] = {
            name: priceTag.identifier,
            amount: priceTag.value * -1,
          }
        }

        promos[priceTag.identifier].amount += priceTag.value * -1
      })

      return promos
    },
    {}
  )

  window.sidecar.transactions = {
    add: true,
    data: {
      order_id: order.transactionId,
      subtotal: order.transactionSubtotal,
      tax: order.transactionTax,
      shipping: order.transactionShipping,
      discounts: order.transactionDiscounts,
      total: order.transactionTotal,
      zipcode: order.visitorAddressPostalCode,
    },
    items: order.transactionProducts.map(product => ({
      product_id: product.sku,
      unit_price: product.price,
      quantity: product.quantity,
    })),
    discounts: Object.values(promosMap),
  }
}

if (canUseDOM) {
  window.addEventListener('message', handleMessages)
}

```


[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 sidecar-pixel/store/interfaces.json from the sidecar-pixel VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "pixel.sidecar": {
    "component": "index"
  }
}

```


[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 sidecar-pixel/react/typings/events.d.ts from the sidecar-pixel VTEX app.

[Assistant]
Here's the implementation:

```typescript
export interface PixelMessage extends MessageEvent {
  data: OrderPlacedData | PageViewData
}

export interface EventData {
  event: string
  eventName: string
  currency: string
}

export interface PageViewData extends EventData {
  event: 'pageView'
  eventName: 'vtex:pageView'
  pageTitle: string
  pageUrl: string
  referrer: string
}

export interface OrderPlacedData extends Order, EventData {
  event: 'orderPlaced'
  eventName: 'vtex:orderPlaced'
}

export interface Order {
  currency: string
  accountName: string
  orderGroup: string
  salesChannel: string
  coupon: string
  visitorCountry: string
  visitorState: string
  visitorType: string
  visitorContactInfo: string[]
  visitorAddressState: string
  visitorAddressCountry: string
  visitorAddressPostalCode: string
  transactionId: string
  transactionDate: string
  transactionAffiliation: string
  transactionTotal: number
  transactionSubtotal: number
  transactionDiscounts: number
  transactionShipping: number
  transactionTax: number
  transactionCurrency: string
  transactionPaymentType: PaymentType[]
  transactionShippingMethod: ShippingMethod[]
  transactionProducts: ProductOrder[]
  transactionPayment: {
    id: string
  }
}

interface PaymentType {
  group: string
  paymentSystemName: string
  installments: number
  value: number
}

interface ShippingMethod {
  itemId: string
  selectedSla: string
}

interface ProductOrder {
  id: string
  name: string
  sku: string
  skuRefId: string
  skuName: string
  brand: string
  brandId: string
  seller: string
  sellerId: string
  category: string
  categoryId: string
  categoryTree: string[]
  categoryIdTree: string[]
  priceTags: PriceTag[]
  originalPrice: number
  price: number
  sellingPrice: number
  tax: number
  quantity: number
  components: any[]
  measurementUnit: string
  unitMultiplier: number
}

interface PriceTag {
  identifier: string
  isPercentual: boolean
  value: number
}

```


[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 sidecar-pixel/react/typings/vtex.render-runtime.d.ts from the sidecar-pixel VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.render-runtime' {
  export const canUseDOM: 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 sidecar-pixel/react/typings/global.d.ts from the sidecar-pixel VTEX app.

[Assistant]
Here's the implementation:

```typescript
interface Window extends Window {
  __sidecar_domain: string
  __sidecar_id: string
  sidecar: any
}

```


[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 example-payment-authorization-app/docs/README.md from the example-payment-authorization-app VTEX app.

[Assistant]
Here's the implementation:

```markdown
# Payment app

The *Payment* app adds a verification step to the checkout process, responsible for allowing or forbidding an order placement.

To implement this feature in your store, you'll need to develop your own *Payment app*, but don't worry! This repository provides the necessary structure for that, and the following step by step will guide you.

## Step by step

> ℹ Please, keep in mind that in this step by step you'll be using the [VTEX IO](https://developers.vtex.com/vtex-developer-docs/docs/what-is-vtex-io) development platform.

### Step 1: Setting up the basic development environment

1. Using the terminal, [install the VTEX IO CLI](https://vtex.io/docs/recipes/development/vtex-io-cli-installation-and-command-reference/) (Command Line Interface) known as **Toolbelt** .
2. Using the terminal and the Toolbelt, log in to your VTEX account by running the following command:

```shell
vtex login {account}
```

> ⚠ Remember to replace the values between the curly brackets according to your scenario

Once you run this command, a window will open in your browser asking for your credentials.

3. Once you provide your credentials, run the following command in the terminal to create a [Development workspace](https://vtex.io/docs/recipes/development/creating-a-development-workspace/) and to start developing your *Payment* app.

```shell
vtex use {examplename}
```

> ⚠ Replace `{examplename}` with a name of your choosing. This name will be given to the workspace in which you will develop.

> ℹ If you're used to working with GitHub, think of workspaces as branches.

### Step 2: Editing the Payment app

1. Using your terminal, clone the *Payment* app boilerplate repository to your local files by running:

```shell
git clone https://github.com/vtex-apps/example-payment-authorization-app
```

2. Then, using any code editor of your choice, open the boilerplate repository's directory.
3. Open the `manifest.json` file and update its metadata, according to your scenario. It's essential that you update the following fields:

- `vendor` - The app owner. That is, the VTEX account responsible for the app development, maintenance, and distribution.
- `name` - The app name. It should concisely express the app's purpose. They must be comprised of lowercase letters separated by hyphens. Special characters, such as `*` and `@`, and numbers at the beginning of the name are not recommended.

4. Open the `pages/pages.json` file and replace `{example-payment-auth-app}` with the app `name` set in step 3.
5. Using your terminal, go to the app's directory and run the following command:

```shell
vtex link
```

> ℹ Once you [link the app](https://vtex.io/docs/recipes/development/linking-an-app/), your computer's local files will sync to our cloud development environment. This means that any change done locally in the code you are working on will be sent to the cloud and then reflected in the workspace in which you are working.

### Step 3: Running the *Payment* app

1. Using your browser, go to `http://{workspace}--{account}.myvtex.com/checkout?workspace={workspace}`.

> ⚠ Remember to replace the values between the curly brackets according to your scenario

2. Open the *browser Developer tools* and run the following command:

```javascript
window.transactionAppName = '{app-name}'
```

Now, if you go through the *checkout process*, you'll notice an additional verification step (set in our *Payment* app) after the *Order confirmation*.

### Step 4: Deploying the *Payment* app

> ℹ Before deploying your app, we recommend that you perform tests and check if everything is as expected. For that, go to `http://{workspace}--{store}.myvtex.com`. Add products to your store's cart and go to the shopping cart page. Open your browser DevTools and run the following command to get the `orderFormId` value: `vtexjs.checkout.orderFormId`. Now, inject the `orderFormId` value in `vtexcommercestable`, using:
`http://{workspace}--{account}.myvtex.com/checkout?workspace={workspace}&orderFormId={orderFormId}`.

Once you're happy with the changes, follow our documentation on [making your new app version publicly available](https://vtex.io/docs/recipes/development/making-your-new-app-version-publicly-available/) to run your app on master.

## Modus Operandi

After developing and implementing the *Payment* app, your store will profit from having an additional verification step in its checkout process.

To make the best use of the *Payment* app, this section discusses the following topics:

- Understanding the checkout response.
- Handling the order payload.
- Injecting external scripts.

### Understanding the checkout response

After the order placement, there's a validation step to check whether the transaction is approved or not.

If the transaction is approved, the checkout UI redirects to the *Order Placed* page. Otherwise, it shows a warning pop-up.

In our *Payment* app, this validation is performed through the `transactionValidation.vtex` event, which, when triggered, sends the payment status to the checkout UI according to the following [method](https://github.com/vtex-apps/payment-authorization-app-example/blob/3e5742c87a2771998009cff4fecacb092bb3362b/react/index.js#L22):

```javascript
respondTransaction = (status) => {
    window.$(window).trigger('transactionValidation.vtex', [status])
}
```

Notice that the `respondTransaction` function receives the `status` boolean value, which resolves (`status == true`) or rejects (`status == false`) an order placement.

Hence, whenever the `transactionValidation.vtex` event occurs, the Checkout UI checks the payment status and is redirected according to the `status` value provided to the `respondTransaction` function

### Handling the order payload

The `appPayload` is what the *Payment* app receives as `props` and it consists of a serialized JSON of the order payload.

Thus, to access this information, just run the following command:

```javascript
const { appPayload } = this.props // This appPayload is a serialized JSON (as string).
```

The expected response is a JSON object consisting of the data needed for the Payment app to allow or deny an order placement. Thus, depending on the payment processes implemented in your store, the `appPayload` fields may vary.

Take the following example:

```json
{
    "timeToCancel": 300,
    "transactionApproveLink": "https://..."
}
```

### Injecting external scripts

To run external scripts on your *Payment* app, you need to inject the following script on the head of the checkout `html`.

To do so, you have to do a DOM injection. For that, you should do:

```javascript
const head = document.getElementsByTagName('head')[0]

const js = document.createElement('script')
js.id = {{script-id}}
js.src = {{script-src}}
js.async = true;
js.defer = true;
js.onload = {{callback-onload}}

head.appendChild(js)
```

There is an example for the script injection [here](https://github.com/vtex-apps/payment-authorization-app-example/blob/3e5742c87a2771998009cff4fecacb092bb3362b/react/index.js#L41)

> ℹ Keep in mind that if the external `js` script handles DOM manipulation, then you should use React's [`ref`](https://reactjs.org/docs/refs-and-the-dom.html) to create a `div` container and hand it over to the library. There's also an [example](https://github.com/vtex-apps/payment-authorization-app-example/blob/3e5742c87a2771998009cff4fecacb092bb3362b/react/index.js#L11) for doing so in this repo.

```


[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 example-payment-authorization-app/pages/pages.json from the example-payment-authorization-app VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "extensions": {
    "checkout/transactions/example-payment-auth-app": {
      "component": "index"
    }
  }
}

```


[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 example-payment-authorization-app/react/index.tsx from the example-payment-authorization-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { Component, Fragment } from 'react'
import styles from './index.css'

interface InjectScriptProps {
  id: string
  src: string
  onLoad: (this: GlobalEventHandlers, ev: Event) => void
}

type Props = {
  appPayload: string
}

type State = {
  scriptLoaded: boolean
  loading: boolean
}

class ExampleTransactionAuthApp extends Component<Props, State> {
  divContainer: React.RefObject<HTMLDivElement>

  constructor(props: Props) {
    super(props)
    this.state = {
      scriptLoaded: false,
      loading: false,
    }

    this.divContainer = React.createRef()
  }

  componentWillMount = () => {
    this.injectScript({
      id: 'google-recaptcha-v2',
      src: 'https://recaptcha.net/recaptcha/api.js?render=explicit',
      onLoad: this.handleOnLoad
    })
  }

  componentDidMount() {
    // In case you want to remove payment loading in order to show an UI.
    window.$(window).trigger('removePaymentLoading.vtex')
  }

  respondTransaction = (status: boolean) => {
    window.$(window).trigger('transactionValidation.vtex', [status])
  }

  handleOnLoad = () => {
    this.setState({ scriptLoaded: true })
    grecaptcha.ready(() => {
      if (this.divContainer.current) {
        grecaptcha.render(this.divContainer.current, {
          sitekey: '------>REPATCHA_V2_SITE_KEY<------', //Replace with site key
          theme: 'dark',
          callback: this.onVerify,
        })
      }
    })
  }

  onVerify = () => {
    const parsedPayload = JSON.parse(this.props.appPayload)
    this.setState({ loading: true })

    fetch(parsedPayload.approvePaymentUrl).then(() => {
      this.respondTransaction(true)
    })
  }

  cancelTransaction = () => {
    const parsedPayload = JSON.parse(this.props.appPayload)
    this.setState({ loading: true })

    fetch(parsedPayload.denyPaymentUrl).then(() => {
      this.respondTransaction(false)
    })
  }

  confirmTransation = () => {
    const parsedPayload = JSON.parse(this.props.appPayload)
    this.setState({ loading: true })

    fetch(parsedPayload.approvePaymentUrl).then(() => {
      this.respondTransaction(true)
    })
  }

  injectScript = ({ id, src, onLoad }: InjectScriptProps) => {
    if (document.getElementById(id)) {
      return
    }

    const head = document.getElementsByTagName('head')[0]

    const js = document.createElement('script')
    js.id = id
    js.src = src
    js.async = true
    js.defer = true
    js.onload = onLoad

    head.appendChild(js)
  }

  render() {
    const { scriptLoaded, loading } = this.state

    return (
      <div className={styles.wrapper}>
        {scriptLoaded && !loading ? (
          <Fragment>
            <div className="g-recaptcha" ref={this.divContainer}></div>
            <button
              id="payment-app-confirm"
              className={styles.buttonSuccess}
              onClick={this.confirmTransation}>
              Confirmar
            </button>
          </Fragment>
        ) : (
          <h2>Carregando...</h2>
        )}

        {!loading && (
          <button
            id="payment-app-cancel"
            className={styles.buttonDanger}
            onClick={this.cancelTransaction}>
            Cancelar
          </button>
        )}
      </div>
    )
  }
}

export default ExampleTransactionAuthApp

```


[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 example-payment-authorization-app/react/index.css from the example-payment-authorization-app VTEX app.

[Assistant]
Here's the implementation:

```css
.wrapper {
  align-items: center;
  background: white;
  display: flex;
  flex-direction: column;
  height: 500px;
  justify-content: center;
  left: 0;
  margin-left: auto;
  margin-right: auto;
  position: absolute;
  right: 0;
  width: 500px;
  top: 0;
  box-shadow: 0px 0px 26px 0px rgba(0, 0, 0, 0.42);
  z-index: 999;
}

.buttonDanger {
  color: #fff;
  background-color: #d9534f;
  border-color: #d43f3a;
}

.buttonSuccess {
  color: #fff;
  background-color: #8bc34a;
  border-color: #8bc34a;
}

.appPayload {
  width: 100%;
  word-break: break-word;
}

```


[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 example-payment-authorization-app/react/package.json from the example-payment-authorization-app VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "name": "yes-no-app",
  "version": "1.1.0",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "react": "16.8.6",
    "react-dom": "16.8.6"
  },
  "devDependencies": {
    "@types/grecaptcha": "^3.0.4",
    "@types/node": "12.6.2",
    "@types/react": "16.8.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 example-payment-authorization-app/react/typings/global.d.ts from the example-payment-authorization-app VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module '*.css' {
  interface IClassNames {
    [className: string]: string
  }
  const classNames: IClassNames
  export = classNames
}

interface Window {
  vtexjs: VTEXJS
  $: any // JQuery types
}
```


[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 device-detector/docs/README.md from the device-detector VTEX app.

[Assistant]
Here's the implementation:

```markdown
# Device Detector

Use this app's HOC or hook to find out current device's viewport size.

### Usage

#### useDevice

Returns an object with the format of `DeviceInfo` defined as:
```js
interface DeviceInfo {
  device: Device
  isMobile: boolean
}

enum Device {
  phone = 'phone',
  tablet = 'tablet',
  desktop = 'desktop',
}
```

```js
import { useDevice } from 'vtex.device-detector'
const MyComponent = props => {
  const { isMobile } = useDevice()
  if (isMobile) {
    // is phone or tablet!
  }
  return ...
}
```

or

```js
import { useDevice } from 'vtex.device-detector'
const MyComponent = props => {
  const { device } = useDevice()
  if (device === 'tablet') {
    //is tablet!
  }
  return ...
}
```

#### withDevice

It is a HOC, it injects two props (`isMobile` and `device`) into your component's props:

```js
type WithDeviceProps = Props & {
  isMobile: boolean
  device: Device
}
enum Device {
  phone = 'phone',
  tablet = 'tablet',
  desktop = 'desktop',
}
```

```js
import { withDevice } from 'vtex.device-detector'
const MyComponent = props => {
  if (props.isMobile) {
    // is phone or tablet!
  }
  return ...
}

export default withDevice(MyComponent)
```

or

```js
import { useDevice } from 'vtex.device-detector'
const MyComponent = props => {
  if (props.device === 'tablet') {
    //is tablet!
  }
  return ...
}

export default withDevice(MyComponent)
```

```


[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 device-detector/react/DeviceDetector.tsx from the device-detector VTEX app.

[Assistant]
Here's the implementation:

```tsx
import type { FC } from 'react'
import type { RenderContext } from 'vtex.render-runtime'

import useDevice from './useDevice'

type Device = RenderContext.RenderContext['deviceInfo']['type']

export interface DeviceInfo {
  device: Device
  isMobile: boolean
}

interface Props {
  children?: (deviceInfo: DeviceInfo) => React.ReactElement
}

const DeviceDetector: FC<Props> = ({ children }) => {
  const { device, isMobile } = useDevice()

  if (!children) {
    return null
  }

  return children({ device, isMobile })
}

export default DeviceDetector

```


[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 device-detector/react/useDevice.tsx from the device-detector VTEX app.

[Assistant]
Here's the implementation:

```tsx
import { useRuntime } from 'vtex.render-runtime'
import type { RenderContext } from 'vtex.render-runtime'

type Device = RenderContext.RenderContext['deviceInfo']['type']

export interface DeviceInfo {
  device: Device
  isMobile: boolean
}

const useDevice = () => {
  const { deviceInfo, hints } = useRuntime()

  if (!deviceInfo) {
    /** Fallback code to support transition to device info coming
     * from render-runtime. Should be removed in the near future */

    return {
      device: (hints.phone
        ? 'phone'
        : hints.tablet
        ? 'tablet'
        : 'desktop') as Device,
      isMobile: hints.mobile,
    }
  }

  const { type: device, isMobile } = deviceInfo

  return { device, isMobile }
}

export default useDevice

```


[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 device-detector/react/package.json from the device-detector VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "scripts": {
    "test": "vtex-test-tools test",
    "lint": "tsc --noEmit && eslint --ext ts,tsx ."
  },
  "dependencies": {
    "@vtex/tsconfig": "^0.5.6",
    "react": "^16.8.3",
    "react-dom": "^16.8.3"
  },
  "devDependencies": {
    "@types/jest": "^24.0.11",
    "@types/node": "^11.13.0",
    "@types/react": "^16.8.10",
    "@types/react-intl": "^2.3.17",
    "@vtex/test-tools": "^3.3.2",
    "apollo-client": "^2.5.1",
    "typescript": "3.9.7",
    "vtex.render-runtime": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.126.4/public/@types/vtex.render-runtime"
  },
  "version": "0.2.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 device-detector/react/withDevice.tsx from the device-detector VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import type { ComponentType } from 'react'

import useDevice from './useDevice'

function withDevice<P>(Component: ComponentType<P>) {
  const WithDeviceHOC = ({ ...props }: P) => {
    const { isMobile, device } = useDevice()

    return <Component device={device} isMobile={isMobile} {...props} />
  }

  return WithDeviceHOC
}

export default withDevice

```


[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 device-detector/store/interfaces.json from the device-detector VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "base-store-component": {
    "component": "Example"
  }
}
```


[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 partytown/utils/build.js from the partytown VTEX app.

[Assistant]
Here's the implementation:

```javascript
/* eslint-disable no-await-in-loop */
const fs = require('fs')

const Mustache = require('mustache')
const { minify } = require('html-minifier')

function writeFile() {
  const headBuffer = fs.readFileSync('./src/head.html')
  const partytowBuffer = fs.readFileSync('./public/~partytown/partytown.js')
  const manifest = JSON.parse(fs.readFileSync('./manifest.json'))

  fs.writeFileSync(
    './pixel/head.html',
    `${Mustache.render(headBuffer.toString(), {
      version: manifest.version,
    })}<script>${partytowBuffer.toString()}</script>`
  )
}

function minifyFile() {
  const headBuffer = fs.readFileSync('./pixel/head.html')

  fs.writeFileSync(
    './pixel/head.html',
    minify(headBuffer.toString(), { minifyJS: true, collapseWhitespace: false })
  )
}

async function build() {
  writeFile()
  minifyFile()
}

build()

```


[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 partytown/docs/README.md from the partytown VTEX app.

[Assistant]
Here's the implementation:

```markdown
📢 Use this project, [contribute](https://github.com/vtex-apps/CHANGEME) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).

# Partytown

<!-- DOCS-IGNORE:start -->
<!-- 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 -->
<!-- DOCS-IGNORE:end -->

Partytown is app to manage your third party scripts.

> ℹ **Partytown is currently in closed beta**. Which means it's still not a final version and may have flaws. We recommend always testing all scripts while implementing this guide.

> ℹ  If you are using `experimentalLazyLoad` we recommend to disable it for `vtex.partytown` and any other pixel you want to run in partytown.

## Usage
### Installing partytown

Install the `vtex.partytown` on your new workspace by running `vtex install vtex.partytown@0.x`

### Migrating your pixel app to the partytown format

1. Open the `pixel/head.html` file

2. Add the `type="text/partytown"` attribute to each individual `<script>` tag
```diff
- <script>...</script>
+ <script type="text/partytown">...</script>
```

3. (Optional) If you want to access some global variables added to the `window` by the pixel apps, you need to declare it. Go to the `https://{{myworkspace}}--{{myaccount}}.myvtex.com/admin/apps` URL, select the `partytown` app and then add the name of the variables you want to access in the `Forward` field.

![image](https://user-images.githubusercontent.com/40380674/169821502-4148db94-4a1a-493f-95ee-aaf5e243ebec.png)

## Known Issues

### Uncaught TypeError: Cannot convert undefined or null to object

```
Uncaught TypeError: Cannot convert undefined or null to object
    at Function.getPrototypeOf (<anonymous>)
    at readOwnImplementation (partytown-sandbox-sw.js?v=0.7.4:492:38)
    at partytown-sandbox-sw.js?v=0.7.4:478:75
    at Array.map (<anonymous>)
    at readImplementations (partytown-sandbox-sw.js?v=0.7.4:478:19)
    at readMainPlatform (partytown-sandbox-sw.js?v=0.7.4:450:27)
    at partytown-sandbox-sw.js?v=0.7.4:542:56
    at worker.onmessage (partytown-sandbox-sw.js?v=0.7.4:552:69)
```

VTEX uses the [history npm lib](https://www.npmjs.com/package/history). Partytown doesn't have support for this lib, that's why this error is thrown.
Even with this error, partytown will work correctly as long as your script does not use the History API.

## Debug
To make sure that partytown is able to run scripts, install partytown in a development workspace and observe if the following message is printed in the browser console.

```
Partytown was able to run this script. If you are having problems running your script, it is possible that there is a compatibility issue between your script and partytown.
```

## Development

Modify the `src/head.html` file and run the `yar run build` command.

<!-- TODO: Documentation -->

```


[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 partytown/react/package.json from the partytown VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "scripts": {
    "test": "vtex-test-tools test"
  },
  "devDependencies": {
    "@apollo/react-testing": "^3.1.3",
    "@types/graphql": "^14.5.0",
    "@types/jest": "^25.1.5",
    "@types/node": "^13.11.0",
    "@types/react": "^16.9.31",
    "@types/react-intl": "^3.0.0",
    "@vtex/test-tools": "^3.1.0",
    "apollo-cache-inmemory": "^1.6.5",
    "apollo-client": "^2.6.8",
    "graphql": "^14.5.4",
    "react-intl": "^3.11.0",
    "typescript": "3.9.7",
    "vtex.pixel-interfaces": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.pixel-interfaces@1.1.1/public/_types/react",
    "vtex.render-runtime": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.124.3/public/@types/vtex.render-runtime"
  },
  "version": "0.0.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 partytown/store/interfaces.json from the partytown VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "pixel.partytown": {
    "component": "index"
  }
}

```


[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 partytown/public/~partytown/partytown-sw.js from the partytown VTEX app.

[Assistant]
Here's the implementation:

```javascript
/* Partytown 0.7.4 - MIT builder.io */
const e = new Map(),
  t = (e, t) => ({ F: e.F, p: t }),
  r = (e, t) =>
    new Response(e, {
      headers: {
        'content-type': t || 'text/html',
        'Cache-Control': 'no-store',
      },
    })
;(self.oninstall = () => self.skipWaiting()),
  (self.onactivate = () => self.clients.claim()),
  (self.onmessage = t => {
    const r = t.data,
      n = e.get(r.F)
    n && (e.delete(r.F), clearTimeout(n[1]), n[0](r))
  }),
  (self.onfetch = n => {
    const s = n.request,
      i = new URL(s.url).pathname
    i.endsWith('sw.html')
      ? n.respondWith(
          r(
            '<!DOCTYPE html><html><head><meta charset="utf-8"><script type="module">/* Partytown 0.7.4 - MIT builder.io */\n(e=>{const t=()=>{},r=e=>e.length,n=e=>{var t,r,n;try{const r=null===(t=null==e?void 0:e.constructor)||void 0===t?void 0:t.name;if(r)return r}catch(e){}try{const t=null===(n=null===(r=null==e?void 0:e.__zone_symbol__originalInstance)||void 0===r?void 0:r.constructor)||void 0===n?void 0:n.name;if(t)return t}catch(e){}return""},s=(e,t)=>e.startsWith(t),i=e=>!(s(e,"webkit")||s(e,"toJSON")||s(e,"constructor")||s(e,"toString")||s(e,"_")),o=e=>11===e.nodeType&&e.host?"#s":e.nodeName,a=()=>Math.round(Math.random()*Number.MAX_SAFE_INTEGER).toString(36),l={Anchor:"a",DList:"dl",Image:"img",OList:"ol",Paragraph:"p",Quote:"q",TableCaption:"caption",TableCell:"td",TableCol:"colgroup",TableRow:"tr",TableSection:"tbody",UList:"ul"},c={Graphics:"g",SVG:"svg"},u=Symbol(),h=Symbol(),d=new Map,p=new Map,m={},g=new WeakMap,f=(e,t)=>{if(e)return(t=g.get(e))||(t=e[u])||v(e,t=a()),t},y=(e,t,r,n,s)=>{if((r=m[e])&&r.U){if(e===t)return r.U;if(n=r.U.document,"d"===(s=t.split(".").pop()))return n;if("e"===s)return n.documentElement;if("h"===s)return n.head;if("b"===s)return n.body}return d.get(t)},v=(e,t,r)=>{e&&(d.set(t,e),e[u]=t,e[h]=r=Date.now(),r>w+5e3&&(d.forEach(((e,t)=>{e[h]<w&&e.nodeType&&!e.isConnected&&d.delete(t)})),w=r))};let w=0;const $=e.parent,S=document.implementation.createHTMLDocument(),b=$.partytown||{},E=(b.lib||"/~partytown/")+"",T=(e,t,r)=>{const n=((e,t)=>{return r=e,n={value:t},Object.defineProperty(r,"name",{...n,configurable:!0});var r,n})(class extends m[e].U.HTMLElement{},r[0]);return"connectedCallback,disconnectedCallback,attributeChangedCallback,adoptedCallback".split(",").map((r=>n.prototype[r]=function(...n){t.postMessage([15,e,f(this),r,n])})),n.observedAttributes=r[1],n},C=(e,t,r,i,a)=>void 0!==t&&(i=typeof t)?"string"===i||"number"===i||"boolean"===i||null==t?[0,t]:"function"===i?[6]:(r=r||new Set)&&Array.isArray(t)?r.has(t)?[1,[]]:r.add(t)&&[1,t.map((t=>C(e,t,r)))]:"object"===i?x(t)?[14,{name:t.name,message:t.message,stack:t.stack}]:""===(a=n(t))?[2,{}]:"Window"===a?[3,[e,e]]:"HTMLCollection"===a||"NodeList"===a?[7,Array.from(t).map((t=>C(e,t,r)[1]))]:a.endsWith("Event")?[5,I(e,t,r)]:"CSSRuleList"===a?[12,Array.from(t).map(M)]:s(a,"CSS")&&a.endsWith("Rule")?[11,M(t)]:"CSSStyleDeclaration"===a?[13,I(e,t,r)]:"Attr"===a?[10,[t.name,t.value]]:t.nodeType?[3,[e,f(t),o(t)]]:[2,I(e,t,r,!0,!0)]:void 0:t,I=(e,t,r,s,o,a,l,c)=>{if(a={},!r.has(t))for(l in r.add(t),t)i(l)&&(c="path"===l&&n(t).endsWith("Event")?t.composedPath():t[l],(s||"function"!=typeof c)&&(o||""!==c)&&(a[l]=C(e,c,r)));return a},M=e=>{let t,r={};for(t in e)U.includes(t)&&(r[t]=String(e[t]));return r},x=t=>t instanceof e.top.Error,N=(t,r,n,s)=>r?(n=r[0],s=r[1],0===n?s:4===n?L(t,s):1===n?s.map((e=>N(t,e))):3===n?y(s[0],s[1]):5===n?R(A(t,s)):2===n?A(t,s):8===n?s:9===n?new e[r[2]](s):void 0):void 0,L=(e,{V:t,w:r,L:n},s)=>((s=p.get(n))||(s=function(...s){e.postMessage([9,{V:t,w:r,L:n,R:C(t,this),b:C(t,s)}])},p.set(n,s)),s),R=e=>new("detail"in e?CustomEvent:Event)(e.type,e),A=(e,t,r,n)=>{for(n in r={},t)r[n]=N(e,t[n]);return r},U="cssText,selectorText,href,media,namespaceURI,prefix,name,conditionText".split(","),P=async(e,t)=>{let n,s,i,o,a,l,c={F:t.F},u=r(t.Q),h=0;for(;h<u;h++)try{l=h===u-1,n=t.Q[h],s=n.V,i=n.a,!m[s]&&s.startsWith("f_")&&await new Promise((e=>{let t=0,r=()=>{m[s]||t++>1e3?e():requestAnimationFrame(r)};r()})),1===i[0]&&i[1]in m[s].U?v(new m[s].U[i[1]](...N(e,i[2])),n.w):(o=y(s,n.w),o?(a=j(e,s,o,i,l,n.r),n.d&&("string"==typeof n.d?v(a,n.d):m[n.d.V]={V:n.d.V,U:{document:a}}),"object"==typeof(d=a)&&d&&d.then&&(a=await a,l&&(c.z=!0)),l&&(c.M=C(s,a))):c.p=n.w+" not found")}catch(e){l?c.p=String(e.stack||e):console.error(e)}var d;return c},j=(e,t,s,i,o,a)=>{let l,c,u,h,d,p=0,m=r(i);for(;p<m;p++){c=i[p],l=i[p+1],u=i[p-1];try{if(!Array.isArray(l))if("string"==typeof c||"number"==typeof c){if(p+1===m&&a)return d={},a.map((e=>d[e]=s[e])),d;s=s[c]}else{if(0===l)return void(s[u]=N(e,c));if("function"==typeof s[u]&&(h=N(e,c),"define"===u&&"CustomElementRegistry"===n(s)&&(h[1]=T(t,e,h[1])),"insertRule"===u&&h[1]>r(s.cssRules)&&(h[1]=r(s.cssRules)),s=s[u].apply(s,h),"play"===u))return Promise.resolve()}}catch(e){if(o)throw e;console.debug(e)}}return s},O=(e,t)=>{let n,s,i,o=t.V,a=t.U,l=a.document;l&&l.body?(n=l.querySelector(\'script[type="text/partytown"]:not([data-ptid]):not([data-pterror]):not([async]):not([defer])\'),n||(n=l.querySelector(\'script[type="text/partytown"]:not([data-ptid]):not([data-pterror])\')),n?(n.dataset.ptid=s=f(n,o),i={V:o,w:s},n.src?(i.S=n.src,i.H=n.dataset.ptsrc||n.src):i.j=n.innerHTML,e.postMessage([7,i])):(t.x||(t.x=1,((e,t,n)=>{let s,i,o=n._ptf,a=(n.partytown||{}).forward||[],l=(r,n)=>e.postMessage([10,{V:t,q:r,b:C(t,Array.from(n))}]);if(n._ptf=void 0,a.map((e=>{i=n,e.split(".").map(((e,t,n)=>{i=i[n[t]]=t+1<r(n)?i[n[t]]||("push"===n[t+1]?[]:{}):(...e)=>l(n,e)}))})),o)for(s=0;s<r(o);s+=2)l(o[s],o[s+1])})(e,o,a),l.dispatchEvent(new CustomEvent("pt0"))),e.postMessage([8,o]))):requestAnimationFrame((()=>O(e,t)))},k=(e,t,r)=>{if(!g.has(r)){g.set(r,t);const n=r.document,s=r.history,i=g.get(r.parent);let o=!1;const a=[],l=e=>{o?e():a.push(e)},c=()=>{e.postMessage([5,{V:t,J:i,S:n.baseURI,T:n.visibilityState}]),setTimeout((()=>{o=!0,a.forEach((e=>{e()}))}))},u=s.pushState.bind(s),h=s.replaceState.bind(s),d=(r,s,i,o)=>()=>{setTimeout((()=>{e.postMessage([13,{V:t,type:r,state:s,url:n.baseURI,newUrl:i,oldUrl:o}])}))};s.pushState=(e,t,r)=>{u(e,t,r),l(d(0,e,null==r?void 0:r.toString()))},s.replaceState=(e,t,r)=>{h(e,t,r),l(d(1,e,null==r?void 0:r.toString()))},r.addEventListener("popstate",(e=>{l(d(2,e.state))})),r.addEventListener("hashchange",(e=>{l(d(3,{},e.newURL,e.oldURL))})),r.addEventListener("ptupdate",(()=>{O(e,m[t])})),n.addEventListener("visibilitychange",(()=>e.postMessage([14,t,n.visibilityState]))),m[t]={V:t,U:r},"complete"===n.readyState?c():r.addEventListener("load",c)}},H=()=>{const e=S.createElement("i"),t=S.createTextNode(""),r=S.createComment(""),n=S.createDocumentFragment(),s=S.createElement("p").attachShadow({mode:"open"}),i=J($,"IntersectionObserver"),o=J($,"MutationObserver"),a=J($,"ResizeObserver"),l=$.performance,c=$.screen,u=[[$.history],[l],[l.navigation],[l.timing],[c],[c.orientation],[$.visualViewport],[i,12],[o,12],[a,12],[t],[r],[n],[s],[e],[e.attributes],[e.classList],[e.dataset],[e.style],[S],[S.doctype]],h=[F("Window",$),F("Node",t)],d={i:JSON.stringify(b,((e,t)=>("function"==typeof t&&(t=String(t)).startsWith(e+"(")&&(t="function "+t),t))),v:B(u,h),C:new URL(E,$.location)+"",I:origin,D:q("localStorage"),O:q("sessionStorage")};return G(d.v,$,"IntersectionObserverEntry"),d},V=()=>{const e=Object.getOwnPropertyNames($).map((e=>((e,t,r,n)=>{if(r=t.match(/^(HTML|SVG)(.+)Element$/))return n=r[2],"S"==t[0]?e.createElementNS("http://www.w3.org/2000/svg",c[n]||n.slice(0,2).toLowerCase()+n.slice(2)):e.createElement(l[n]||n)})(S,e))).filter((e=>e)).map((e=>[e]));return B(e,[])},D=new Set(["Object"]),B=(e,t)=>(e.filter((e=>e[0])).map((e=>{const t=e[0],r=e[1],s=n(t);return[s,$[s].prototype,t,r]})).map((([e,r,n,s])=>W(D,t,e,r,n,s))),t),F=(e,t,r)=>{let n=[],s=[e,"Object",n];for(r in t)_(n,t,r);return s},W=(e,t,r,s,i,a)=>{if(!e.has(r)){e.add(r);const l=Object.getPrototypeOf(s),c=n(l),u=[],h=Object.getOwnPropertyDescriptors(s);W(e,t,c,l,i,a);for(const e in h)_(u,i,e);t.push([r,c,u,a,o(i)])}},_=(e,t,r,s,o,a)=>{try{i(r)&&isNaN(r[0])&&"all"!==r&&("function"==(o=typeof(s=t[r]))?(String(s).includes("[native")||Object.getPrototypeOf(t)[r])&&e.push([r,5]):"object"===o&&null!=s?"Object"!==(a=n(s))&&self[a]&&e.push([r,s.nodeType||a]):"symbol"!==o&&(r.toUpperCase()===r?e.push([r,6,s]):e.push([r,6])))}catch(e){console.warn(e)}},q=e=>{let t,n=[],s=0,i=r($[e]);for(;s<i;s++)t=$[e].key(s),n.push([t,$[e].getItem(t)]);return n},J=(e,r)=>void 0!==e[r]?new e[r](t):0,G=(e,t,r)=>{void 0!==t[r]&&e.push([r,"Object",Object.keys(t[r].prototype).map((e=>[e,6])),12])};let Z;(t=>{const r=e.navigator.serviceWorker;return r.getRegistration().then((e=>(r.addEventListener("message",(t=>{return r=t.data,n=t=>e.active&&e.active.postMessage(t),P(Z,r).then(n);var r,n})),(e,t)=>{0===t[0]?e.postMessage([1,H()]):2===t[0]?e.postMessage([3,V()]):((e,t,r)=>{4===t[0]?k(e,a(),$):(r=m[t[1]])&&(7===t[0]?requestAnimationFrame((()=>O(e,r))):6===t[0]&&((e,t,r,n,s)=>{(s=t.U.document.querySelector(`[data-ptid="${r}"]`))&&(n?s.dataset.pterror=n:s.type+="-x",delete s.dataset.ptid),O(e,t)})(e,r,t[2],t[3]))})(e,t)})))})().then((e=>{e&&(Z=new Worker(URL.createObjectURL(new Blob([\'/* Partytown 0.7.4 - MIT builder.io */\\n(e=>{const t=Symbol(),r=Symbol(),n=Symbol(),i=Symbol(),s=Symbol(),o=Symbol(),a=Symbol(),l=Symbol(),c=new Map,$={},d=new WeakMap,u=[],h={},p=new Map,g=new Map,m={},f=new Map,w=new Map,y="about:blank",v=e=>e.split(","),S=e=>{if(e=h.C+e,new URL(e).origin!=location.origin)throw"Invalid "+e;return e},I=v("clientWidth,clientHeight,clientTop,clientLeft,innerWidth,innerHeight,offsetWidth,offsetHeight,offsetTop,offsetLeft,outerWidth,outerHeight,pageXOffset,pageYOffset,scrollWidth,scrollHeight,scrollTop,scrollLeft"),b=v("childElementCount,children,firstElementChild,lastElementChild,nextElementSibling,previousElementSibling"),M=v("insertBefore,remove,removeChild,replaceChild"),T=v("className,width,height,hidden,innerHTML,innerText,textContent"),E=v("setAttribute,setAttributeNS,setProperty"),N=v("addEventListener,dispatchEvent,removeEventListener"),x=N.concat(E,v("add,observe,remove,unobserve")),L=/^[A-Z_]([A-Z0-9-]*[A-Z0-9])?$/,C=()=>{},R=e=>e.length,H=e=>{var t,r,n;try{const r=null===(t=null==e?void 0:e.constructor)||void 0===t?void 0:t.name;if(r)return r}catch(e){}try{const t=null===(n=null===(r=null==e?void 0:e.__zone_symbol__originalInstance)||void 0===r?void 0:r.constructor)||void 0===n?void 0:n.name;if(t)return t}catch(e){}return""},W=[],P=()=>Math.round(Math.random()*Number.MAX_SAFE_INTEGER).toString(36),A="text/partytown",O=(e,t,r)=>Object.defineProperty(e,t,{...r,configurable:!0}),j=(e,t)=>O(e,"name",{value:t}),k=(e,t,r)=>O(e.prototype,t,r),D=(e,t)=>Object.defineProperties(e.prototype,t),U=(e,t,r)=>k(e,t,{value:r,writable:!0}),_=(e,t)=>t in e[o],B=(e,t)=>e[o][t],F=(e,t,r)=>e[o][t]=r,V=(e,t,r,n,i)=>(!(i=c.get(t))&&r&&m[e]&&(i=m[e].k(r,t,n),c.set(t,i)),i),z=(e,t)=>U(e,"nodeType",t),X=(e,t)=>t.map((t=>k(e,t,{get(){let e=q(this,t),r=w.get(e);return r||(r=de(this,[t]),w.set(e,r)),r}}))),q=(e,n,i)=>[e[t],e[r],n,...(i||W).map((e=>String(e&&e[t]?e[r]:e)))].join("."),G=(e,t)=>v(t).map((t=>k(e,t,{get(){return _(this,t)||F(this,t,de(this,[t])),B(this,t)},set(e){B(this,t)!==e&&ue(this,[t],e),F(this,t,e)}}))),J=e=>I.map((t=>k(e,t,{get(){const e=f.get(q(this,t));if("number"==typeof e)return e;const r=de(this,[t],I);return r&&"object"==typeof r?(Object.entries(r).map((([e,t])=>f.set(q(this,e),t))),r[t]):r}}))),Z=(e,t)=>t.map((t=>{e.prototype[t]=function(...e){let r=q(this,t,e),n=f.get(r);return n||(n=he(this,[t],e),f.set(r,n)),n}})),Y=(e,n,i,s,o)=>{return void 0!==i&&(o=typeof i)?"string"===o||"boolean"===o||"number"===o||null==i?[0,i]:"function"===o?[4,{V:e,w:n,L:(a=i,(l=d.get(a))||(d.set(a,l=P()),$[l]=a),l)}]:(s=s||new Set)&&Array.isArray(i)?s.has(i)?[1,[]]:s.add(i)&&[1,i.map((t=>Y(e,n,t,s)))]:"object"===o?i[r]?[3,[i[t],i[r]]]:i instanceof Event?[5,Q(e,n,i,!1,s)]:K&&i instanceof TrustedHTML?[0,i.toString()]:i instanceof ArrayBuffer?[8,i]:ArrayBuffer.isView(i)?[9,i.buffer,H(i)]:[2,Q(e,n,i,!0,s)]:void 0:i;var a,l},K="undefined"!=typeof TrustedHTML,Q=(e,t,r,n,i,s,o,a)=>{if(s={},!i.has(r))for(o in i.add(r),r)a=r[o],(n||"function"!=typeof a)&&(s[o]=Y(e,t,a,i));return s},ee=(e,n)=>e?Y(e[t],e[r],n):[0,n],te=(e,t,r,n,i,s,o,a)=>{if(n){if(i=n[0],s=n[1],0===i||11===i||12===i)return s;if(4===i)return ne(r,s);if(6===i)return e&&r.length>0?(...t)=>he(m[e].U,r,t,1):C;if(3===i)return re(s);if(7===i)return new se(s.map(re));if(10===i)return new oe(s);if(1===i)return s.map((n=>te(e,t,r,n)));if(14===i)return new ie(s);for(a in o={},s)o[a]=te(e,t,[...r,a],s[a]);if(13===i)return new m[e].U.CSSStyleDeclaration(e,t,r,o);if(5===i){if("message"===o.type&&o.origin){let e,t=JSON.stringify(o.data),r=u.find((e=>e.m===t));r&&(e=m[r.V],e&&(o.source=e.U,o.origin=e.E.origin))}return new Proxy(new Event(o.type,o),{get:(e,t)=>t in o?o[t]:"function"==typeof e[String(t)]?C:e[String(t)]})}if(2===i)return o}},re=([e,t,r])=>t===e&&m[e]?m[e].U:V(e,t,r),ne=(e,{V:t,w:r,G:n,L:i})=>($[i]||d.set($[i]=function(...i){const s=V(t,r,n);return he(s,e,i)},i),$[i]);class ie extends Error{constructor(e){super(e.message),this.name=e.name,this.message=e.message,this.stack=e.stack}}class se{constructor(e){(this._=e).map(((e,t)=>this[t]=e))}entries(){return this._.entries()}forEach(e,t){this._.map(e,t)}item(e){return this[e]}keys(){return this._.keys()}get length(){return R(this._)}values(){return this._.values()}[Symbol.iterator](){return this._[Symbol.iterator]()}}const oe=class{constructor(e){this.name=e[0],this.value=e[1]}get nodeName(){return this.name}get nodeType(){return 2}},ae=(e,t,r)=>console.warn(`Partytown unable to ${e} cross-origin ${t}: `+r.E),le=[],ce=(e,n,i,o,a,l)=>{if(e[s]){if(le.push({V:e[t],w:e[r],a:[...e[s],...n],d:o,r:a}),3===i)h.K([12,{F:P(),Q:[...le]}],l?[l instanceof ArrayBuffer?l:l.buffer]:void 0),le.length=0;else if(1===i)return $e(!0);h.c=setTimeout($e,20)}},$e=e=>{if(clearTimeout(h.c),R(le)){const t=le[R(le)-1],r={F:P(),Q:[...le]};if(le.length=0,e){const e=((e,t)=>{const r=new XMLHttpRequest;return r.open("POST",S("proxytown"),!1),r.send(JSON.stringify(t)),JSON.parse(r.responseText)})(0,r),n=e.z,i=te(t.V,t.w,t.a,e.M);if(e.p){if(n)return Promise.reject(e.p);throw new Error(e.p)}return n?Promise.resolve(i):i}h.K([12,r])}},de=(e,t,r,n)=>h.i.get&&(n=h.i.get(ge(e,t)))!==a?n:n=ce(e,t,1,void 0,r),ue=(e,t,r,n)=>{if(h.i.set){if((n=h.i.set({value:r,prevent:l,...ge(e,t)}))===l)return;n!==a&&(r=n)}T.some((e=>t.includes(e)))&&(f.clear(),t[t.length-1]),t=[...t,ee(e,r),0],ce(e,t,2)},he=(e,t,r,n,i,s,o,l)=>h.i.apply&&(o=h.i.apply({args:r,...ge(e,t)}))!==a?o:(l=t[R(t)-1],t=[...t,ee(e,r)],n=n||(x.includes(l)?2:1),"setAttribute"===l&&_(e,r[0])?F(e,r[0],r[1]):M.includes(l)?(f.clear(),w.clear()):E.includes(l)&&(n=2,f.clear()),o=ce(e,t,n,i,void 0,s)),pe=(e,t,r)=>{ce(e,[1,t,ee(e,r)],1)},ge=(e,r)=>({name:r.join("."),continue:a,nodeName:e[n],constructor:H(e),instance:e,window:m[e[t]].U}),me=(e,t,r,n,i)=>{let s,o,a=t=>((t=r.get(e.origin))||r.set(e.origin,t=[]),t),l=e=>a().findIndex((t=>t[fe]===e)),c={getItem:e=>(s=l(e),s>-1?a()[s][we]:null),setItem(r,o){s=l(r),s>-1?a()[s][we]=o:a().push([r,o]),n?he(e,[t,"setItem"],[r,o],2):ae("set",t,i)},removeItem(r){s=l(r),s>-1&&a().splice(s,1),n?he(e,[t,"removeItem"],[r],2):ae("remove",t,i)},key:e=>(o=a()[e],o?o[fe]:null),clear(){a().length=0,n?he(e,[t,"clear"],W,2):ae("clear",t,i)},get length(){return a().length}};e[t]=new Proxy(c,{get:(e,t)=>Reflect.has(e,t)?Reflect.get(e,t):e.getItem(t),set:(e,t,r)=>(e.setItem(t,r),!0),has:(e,t)=>!!Reflect.has(e,t)||"string"==typeof t&&null!==e.getItem(t),deleteProperty:(e,t)=>(e.removeItem(t),!0)})},fe=0,we=1,ye=(e,t,r)=>{e[r]=j(class extends t{constructor(e,t,r,i){return super(e,t,r,i||{}),new Proxy(this,{get:(e,t)=>e[t]?e[t]:(e[t]||"string"!=typeof t||e[n][t]||(e[n][t]=de(e,[t])),e[n][t]),set:(e,t,r)=>(e[n][t]=r,ue(e,[t],r),f.clear(),!0)})}setProperty(...e){this[n][e[0]]=e[1],he(this,["setProperty"],e,2),e[0],f.clear()}getPropertyValue(e){return this[e]}removeProperty(e){let t=this[n][e];return he(this,["removeProperty"],[e],2),f.clear(),this[n][e]=void 0,t}},r)},ve=(e,t)=>{e[t]=j(class{constructor(e){this.ownerNode=e}get cssRules(){const e=this.ownerNode;return new Proxy({},{get(t,r){const n=String(r);return"item"===n?t=>Ie(e,t):"length"===n?Se(e).length:isNaN(n)?t[r]:Ie(e,n)}})}insertRule(e,t){const r=Se(this.ownerNode);return(t=void 0===t?0:t)>=0&&t<=r.length&&(he(this.ownerNode,["sheet","insertRule"],[e,t],2),r.splice(t,0,0)),this.ownerNode,f.clear(),t}deleteRule(e){he(this.ownerNode,["sheet","deleteRule"],[e],2),Se(this.ownerNode).splice(e,1),this.ownerNode,f.clear()}get type(){return"text/css"}},t);const r={sheet:{get(){return new e[t](this)}}};D(e.HTMLStyleElement,r)},Se=(e,t)=>((t=B(e,2))||(t=de(e,["sheet","cssRules"]),F(e,2,t)),t),Ie=(e,t,r)=>(0===(r=Se(e))[t]&&(r[t]=de(e,["sheet","cssRules",parseInt(t,10)])),r[t]),be="0.7.4",Me=(e,t,r,n,i)=>{try{e.l=t,Te(e,r)}catch(e){console.error(r,e),i=String(e.stack||e)}return e.l="",i},Te=(e,t,r)=>{e.N=1,t=`with(this){${t.replace(/\\\\bthis\\\\b/g,"(thi$(this)?window:this)").replace(/\\\\/\\\\/# so/g,"//Xso")}\\\\n;function thi$(t){return t===this}};${(h.i.globalFns||[]).filter((e=>/[a-zA-Z_$][0-9a-zA-Z_$]*/.test(e))).map((e=>`(typeof ${e}==\\\'function\\\'&&(this.${e}=${e}))`)).join(";")};`+(r?"\\\\n//# sourceURL="+r:""),e.A||(t=t.replace(/.postMessage\\\\(/g,`.postMessage(\\\'${e.V}\\\',`)),new Function(t).call(e.U),e.N=0},Ee=(e,t,r)=>{(r=B(e,t))&&setTimeout((()=>r.map((e=>e({type:t})))))},Ne=(e,t,r,n,i,s)=>{for(n=e.E;!n.host&&(n=(e=m[e.J]).E,e.V!==e.J););return i=new URL(t||"",n),r&&h.i.resolveUrl&&(s=h.i.resolveUrl(i,n,r))?s:i},xe=(e,t,r)=>Ne(e,t,r)+"",Le=()=>`<script src="${S("partytown.js?v="+be)}"><\\\\/script>`,Ce=e=>class{constructor(){this.s="",this.l=[],this.e=[],this.style={}}get src(){return this.s}set src(t){this.s=t,fetch(xe(e,t,"image"),{mode:"no-cors",credentials:"include",keepalive:!0}).then((e=>{e.ok||0===e.status?this.l.map((e=>e({type:"load"}))):this.e.map((e=>e({type:"error"})))}),(()=>this.e.forEach((e=>e({type:"error"})))))}addEventListener(e,t){"load"===e&&this.l.push(t),"error"===e&&this.e.push(t)}get onload(){return this.l[0]}set onload(e){this.l=[e]}get onerror(){return this.e[0]}set onerror(e){this.e=[e]}},Re={addEventListener:{value(...e){const t=e[0],r=B(this,t)||[];r.push(e[1]),F(this,t,r)}},async:{get:C,set:C},defer:{get:C,set:C},onload:{get(){let e=B(this,"load");return e&&e[0]||null},set(e){F(this,"load",e?[e]:null)}},onerror:{get(){let e=B(this,"error");return e&&e[0]||null},set(e){F(this,"error",e?[e]:null)}},getAttribute:{value(e){return"src"===e?this.src:he(this,["getAttribute"],[e])}},setAttribute:{value(e,t){He.includes(e)?this[e]=t:he(this,["setAttribute"],[e,t])}}},He=v("src,type"),We=(e,t)=>{const r={innerHTML:Pe,innerText:Pe,src:{get(){return B(this,4)||""},set(e){const r=xe(t,e,null),n=h.i;e=xe(t,e,"script"),F(this,4,e),ue(this,["src"],e),r!==e&&ue(this,["dataset","ptsrc"],r),this.type&&n.loadScriptsOnMainThread&&n.loadScriptsOnMainThread.some((t=>t===e))&&ue(this,["type"],"text/javascript")}},textContent:Pe,type:{get(){return de(this,["type"])},set(e){Ae(e)||(F(this,5,e),ue(this,["type"],e))}},...Re};D(e,r)},Pe={get(){const e=de(this,["type"]);return Ae(e)?B(this,3)||"":de(this,["innerHTML"])},set(e){F(this,3,e)}},Ae=e=>!e||"text/javascript"===e,Oe=(e,i,s)=>{const o=h.i,a=j(class extends s{appendChild(e){return this.insertBefore(e,null)}get href(){}set href(e){}insertBefore(e,s){var a,l;const c=e[t]=this[t],$=e[r],d=e[n],u="SCRIPT"===d,p="IFRAME"===d;if(u){const t=B(e,3),r=B(e,5);if(t){if(Ae(r)){const r=e.id;if(r&&(null===(l=null===(a=o.loadScriptsOnMainThread)||void 0===a?void 0:a.includes)||void 0===l?void 0:l.call(a,r)))ue(e,["type"],"text/javascript");else{const r=Me(i,$,t,0,""),n=r?"pterror":"ptid",s=r||$;ue(e,["type"],A+"-x"),ue(e,["dataset",n],s)}}ue(e,["innerHTML"],t)}}if(he(this,["insertBefore"],[e,s],2),p){const t=B(e,0);if(t&&t.startsWith("javascript:")){const e=t.split("javascript:")[1];Me(i,$,e,0,"")}((e,t)=>{let r,n,i=0,s=()=>{m[e]&&m[e].x&&!m[e].y?(r=B(t,1)?"error":"load",n=B(t,r),n&&n.map((e=>e({type:r})))):i++>2e3?(n=B(t,"error"),n&&n.map((e=>e({type:"error"})))):setTimeout(s,9)};s()})($,e)}return u&&($e(!0),h.K([7,c])),e}get nodeName(){return"#s"===this[n]?"#document-fragment":this[n]}get nodeType(){return 3}get ownerDocument(){return i.n}},"Node");X(a,v("childNodes,firstChild,isConnected,lastChild,nextSibling,parentElement,parentNode,previousSibling")),e.Node=a},je=v("AUDIO,CANVAS,VIDEO"),ke=v("Audio,MediaSource"),De=(e,r,n)=>{D(e,{body:{get:()=>r.e},cookie:{get(){return r.A?de(this,["cookie"]):(ae("get","cookie",r),"")},set(e){r.A&&ue(this,["cookie"],e)}},createElement:{value(e){if(e=e.toUpperCase(),!L.test(e))throw e+" not valid";const r="IFRAME"===e,n=this[t],i=(r?"f_":"")+P();he(this,["createElement"],[e],2,i);const s=V(n,i,e);if(r)et({V:i,J:n,S:y},!0).U.fetch=fetch,ue(s,["srcdoc"],Le());else if("SCRIPT"===e){const e=B(s,5);Ae(e)&&ue(s,["type"],A)}return s}},createElementNS:{value(e,r){const n=P(),i=V(this[t],n,r,e);return he(this,["createElementNS"],[e,r],2,n),i}},createTextNode:{value(e){const r=this[t],n=P(),i=V(r,n,"#text");return he(this,["createTextNode"],[e],2,n),i}},createEvent:{value:e=>new Event(e)},currentScript:{get(){return r.l?V(this[t],r.l,"SCRIPT"):null}},defaultView:{get:()=>n?null:r.U},documentElement:{get:()=>r.o},getElementsByTagName:{value(e){return"BODY"===(e=e.toUpperCase())?[r.e]:"HEAD"===e?[r.s]:he(this,["getElementsByTagName"],[e])}},head:{get:()=>r.s},images:{get(){return de(this,["images"])}},implementation:{get(){return{hasFeature:()=>!0,createHTMLDocument:e=>{const t=P();return he(this,["implementation","createHTMLDocument"],[e],1,{V:t}),et({V:t,J:t,S:r.E+"",T:"hidden"},!0,!0).n}}}},location:{get:()=>r.E,set(e){r.E.href=e+""}},nodeType:{value:9},parentNode:{value:null},parentElement:{value:null},readyState:{value:"complete"},visibilityState:{get:()=>r.T||"visible"}}),G(e,"compatMode,referrer,forms")},Ue=(e,t)=>{D(e,{parentElement:{get(){return this.parentNode}},parentNode:{get:()=>t.o}})},_e=(e,t)=>{D(e,{localName:{get(){return this[n].toLowerCase()}},namespaceURI:{get(){return this[i]||"http://www.w3.org/1999/xhtml"}},nodeType:{value:1},tagName:{get(){return this[n]}}}),X(e,b),G(e,"id"),J(t),Z(t,v("getClientRects,getBoundingClientRect"))},Be=(e,t)=>{const r={};v("hash,host,hostname,href,origin,pathname,port,protocol,search").map((e=>{r[e]={get(){let r,n=B(this,4);return"string"!=typeof n&&(r=de(this,["href"]),F(this,4,r),n=new URL(r)[e]),Ne(t,n,null)[e]},set(r){let n;if("href"===e)if((e=>{try{return new URL(e),!0}catch(e){return!1}})(r))n=new URL(r);else{const e=t.E.href;n=Ne(t,e,null),n.href=new URL(r+"",n.href)}else n=Ne(t,this.href,null),n[e]=r;F(this,4,n.href),ue(this,["href"],n.href)}}})),D(e,r)},Fe=(e,t)=>{const r={contentDocument:{get(){return qe(this).n}},contentWindow:{get(){return qe(this).U}},src:{get(){let e=B(this,0);return e&&e.startsWith("javascript:")?e:(e=qe(this).E.href,e.startsWith("about:")?"":e)},set(e){if(e)if(e.startsWith("javascript:"))F(this,0,e);else if(!e.startsWith("about:")){let t,r=new XMLHttpRequest,n=qe(this);n.E.href=e=xe(n,e,"iframe"),n.y=1,F(this,1,void 0),r.open("GET",e,!1),r.send(),t=r.status,t>199&&t<300?(ue(this,["srcdoc"],`<base href="${e}">`+r.responseText.replace(ze,((e,t)=>{const r=[];let n,i=!1;for(;n=Xe.exec(t);){let[e]=n;e.startsWith("type=")&&(i=!0,e=e.replace(/(application|text)\\\\/javascript/,A)),r.push(e)}return i||r.push(\\\'type="text/partytown"\\\'),`<script ${r.join(" ")}>`}))+Le()),$e(!0),h.K([7,n.V])):(F(this,1,t),n.y=0)}}},...Re};D(e,r)},Ve="((?:\\\\\\\\w|-)+(?:=(?:(?:\\\\\\\\w|-)+|\\\'[^\\\']*\\\'|\\\\"[^\\\\"]*\\\\")?)?)",ze=new RegExp(`<script\\\\\\\\s*((${Ve}\\\\\\\\s*)*)>`,"mg"),Xe=new RegExp(Ve,"mg"),qe=e=>{const n=e[r];return m[n]||et({V:n,J:e[t],S:de(e,["src"])||y},!0),m[n]},Ge=e=>{const t=(e,t)=>{const{a:r,b:n,c:i,d:s,e:o,f:a}=he(e,[t],W);return new DOMMatrixReadOnly([r,n,i,s,o,a])},r={...e,getCTM:{value:function(){return t(this,"getCTM")}},getScreenCTM:{value:function(){return t(this,"getScreenCTM")}}};D(e,r)},Je=(e,t)=>{e.NamedNodeMap=j(class extends t{constructor(e,t,r){return super(e,t,r),new Proxy(this,{get(e,t){const r=Ye[t];return r?r.bind(e,[t]):de(e,[t])},set(e,t,r){if(Ye[t])throw new Error("Can\\\'t set read-only property: "+String(t));return ue(e,[t],r),!0}})}},"NamedNodeMap")};function Ze(e,...t){return he(this,e,t,1)}const Ye={getNamedItem:Ze,getNamedItemNS:Ze,item:Ze,removeNamedItem:Ze,removeNamedItemNS:Ze,setNamedItem:Ze,setNamedItemNS:Ze},Ke=(a,l,c,$,d,f)=>{let w,I,M;const T=class{constructor(e,l,c,$,d){this[t]=e||a,this[r]=l||w||P(),this[s]=c||[],this[n]=$||I,this[i]=d||M,this[o]={},w=I=M=void 0}},E=new(j(class extends URL{assign(){}reload(){}replace(){}},"Location"))(c),x=E.origin===h.I||E.origin===y,L=l===a,C={},W=()=>{let e,t,r=[];for(e in m)t=m[e],t.J!==a||t.B||r.push(t);return r},A=j(class extends T{constructor(){super(a,a);let n,i,o=this,c=0,u=()=>{c||((h.u||(e.g=[de,ue,he,pe,D,P,t,r,s],h.t(S("partytown-media.js?v="+be)),h.u=e.f,delete e.f),h.u)(T,Y,C,o,ke),c=1)},m={},y=(e,t,r)=>{je.includes(e)&&u();const n=m[e]?m[e]:e.includes("-")?m.UNKNOWN:m.I;return w=t,I=e,M=r,new n};var N,R;if(o.Window=A,o.name=name+a,Oe(o,C,T),(e=>{e.NodeList=j(se,"NodeList")})(o),Je(o,T),ye(o,T,"CSSStyleDeclaration"),((e,t,r)=>{e[r]=j(class extends t{now(){return performance.now()}},r)})(o,T,"Performance"),((e,t)=>{const r="customElements",n=new Map;e.customElements={define(i,s,o){n.set(i,s),t[i.toUpperCase()]=s;const a=[s.name,s.observedAttributes];he(e,[r,"define"],[i,a,o])},get:t=>n.get(t)||he(e,[r,"get"],[t]),whenDefined:t=>n.has(t)?Promise.resolve():he(e,[r,"whenDefined"],[t]),upgrade:t=>he(e,[r,"upgrade"],[t])}})(o,m),h.v.map((([e,t,n,i,l])=>{const c=Qe[e]?q:"EventTarget"===t?Y:"Object"===t?T:o[t],$=o[e]=j(12===i?class extends T{constructor(...t){super(),pe(this,e,t)}}:o[e]||class extends c{},e);l&&(m[l]=$),n.map((([e,t,n])=>{e in $.prototype||e in c.prototype||("string"==typeof t?k($,e,{get(){if(!_(this,e)){const n=this[r],i=[...this[s],e],l=o[t];l&&F(this,e,new l(a,n,i))}return B(this,e)},set(t){F(this,e,t)}}):5===t?U($,e,(function(...t){return he(this,[e],t)})):t>0&&(void 0!==n?U($,e,n):k($,e,{get(){return de(this,[e])},set(t){return ue(this,[e],t)}})))}))})),v("atob,btoa,crypto,indexedDB,setTimeout,setInterval,clearTimeout,clearInterval").map((t=>{delete A.prototype[t],t in o||(n=e[t],null!=n&&(o[t]="function"!=typeof n||n.toString().startsWith("class")?n:n.bind(e)))})),Object.getOwnPropertyNames(e).map((t=>{t in o||(o[t]=e[t])})),ke.map((e=>O(o,e,{get:()=>(u(),o[e])}))),"trustedTypes"in e&&(o.trustedTypes=e.trustedTypes),_e(o.Element,o.HTMLElement),De(o.Document,C,f),N=o.DocumentFragment,z(N,11),X(N,b),Be(o.HTMLAnchorElement,C),R=o.HTMLFormElement,D(R,{}),G(R,"elements"),Fe(o.HTMLIFrameElement),We(o.HTMLScriptElement,C),Ge(o.SVGGraphicsElement),Ue(o.HTMLHeadElement,C),Ue(o.HTMLBodyElement,C),((e,t)=>{D(e,{parentElement:{value:null},parentNode:{get:()=>t.n}})})(o.HTMLHtmlElement,C),ve(o,"CSSStyleSheet"),z(o.Comment,8),z(o.DocumentType,10),Object.assign(C,{V:a,J:l,U:new Proxy(o,{get:(e,t)=>{var r;if("string"!=typeof t||isNaN(t))return(null===(r=h.i.mainWindowAccessors)||void 0===r?void 0:r.includes(t))?de(this,[t]):e[t];{let e=W()[t];return e?e.U:void 0}},has:()=>!0}),n:y("#document",a+".d"),o:y("HTML",a+".e"),s:y("HEAD",a+".h"),e:y("BODY",a+".b"),E:E,T:$,A:x,B:L,k:y}),o.requestAnimationFrame=e=>setTimeout((()=>e(performance.now())),9),o.cancelAnimationFrame=e=>clearTimeout(e),o.requestIdleCallback=(e,t)=>(t=Date.now(),setTimeout((()=>e({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-t))})),1)),o.cancelIdleCallback=e=>clearTimeout(e),me(o,"localStorage",p,x,C),me(o,"sessionStorage",g,x,C),x||(o.indexeddb=void 0),d)i={},o.history={pushState(e){i=e},replaceState(e){i=e},get state(){return i},length:0},o.indexeddb=void 0;else{const e=o.history.pushState.bind(o.history),t=o.history.replaceState.bind(o.history);o.history.pushState=(t,r,n)=>{!1!==C.$propagateHistoryChange$&&e(t,r,n)},o.history.replaceState=(e,r,n)=>{!1!==C.$propagateHistoryChange$&&t(e,r,n)}}o.Worker=void 0}addEventListener(...e){"load"===e[0]?C.N&&setTimeout((()=>e[1]({type:"load"}))):he(this,["addEventListener"],e,2)}get body(){return C.e}get document(){return C.n}get documentElement(){return C.o}fetch(e,t){return e="string"==typeof e||e instanceof URL?String(e):e.url,fetch(xe(C,e,"fetch"),t)}get frames(){return C.U}get frameElement(){return L?null:V(l,a,"IFRAME")}get globalThis(){return C.U}get head(){return C.s}get length(){return W().length}get location(){return E}set location(e){E.href=e+""}get Image(){return Ce(C)}get navigator(){return(e=>{let t,r={sendBeacon:(t,r)=>{try{return fetch(xe(e,t,null),{method:"POST",body:r,mode:"no-cors",keepalive:!0}),!0}catch(e){return console.error(e),!1}}};for(t in navigator)r[t]=navigator[t];return r})(C)}get origin(){return E.origin}set origin(e){}get parent(){for(let e in m)if(m[e].V===l)return m[e].U;return C.U}postMessage(...e){m[e[0]]&&(R(u)>50&&u.splice(0,5),u.push({V:e[0],m:JSON.stringify(e[1])}),e=e.slice(1)),he(this,["postMessage"],e,3)}get self(){return C.U}get top(){for(let e in m)if(m[e].B)return m[e].U;return C.U}get window(){return C.U}get XMLHttpRequest(){const e=XMLHttpRequest,t=String(e),r=j(class extends e{open(...e){e[1]=xe(C,e[1],"xhr"),super.open(...e)}set withCredentials(e){}toString(){return t}},H(e));return r.prototype.constructor.toString=()=>t,r}},"Window"),q=class extends T{constructor(e,t,r,n){return super(e,t,r,n),new Proxy(this,{get:(e,t)=>de(e,[t]),set:(e,t,r)=>(ue(e,[t],r),!0)})}},Y=class extends T{};return N.map((e=>Y.prototype[e]=function(...t){return he(this,[e],t,2)})),G(A,"devicePixelRatio"),J(A),Z(A,["getComputedStyle"]),new A,C},Qe={DOMStringMap:1,NamedNodeMap:1},et=({V:e,J:t,S:r,T:n},i,s)=>(m[e]||(m[e]=Ke(e,t,r,n,i,s)),h.K([7,e]),m[e]),tt=[],rt=t=>{const r=t.data,n=r[0],i=r[1];if(h.x)if(7===n)(async e=>{let t,r=e.V,n=e.w,i=V(r,n,"SCRIPT"),s=e.j,o=e.S,a=e.H,l="",c=m[r],$=["text/jscript","text/javascript","text/x-javascript","application/javascript","application/x-javascript","text/ecmascript","text/x-ecmascript","application/ecmascript"];if(o)try{if(o=Ne(c,o,"script")+"",F(i,4,o),t=await fetch(o),t.ok){let e=t.headers.get("content-type");$.some((t=>{var r,n,i;return null===(i=null===(r=null==e?void 0:e.toLowerCase)||void 0===r?void 0:(n=r.call(e)).includes)||void 0===i?void 0:i.call(n,t)}))&&(s=await t.text(),c.l=n,Te(c,s,a||o)),Ee(i,"load")}else l=t.statusText,Ee(i,"error")}catch(e){console.error(e),l=String(e.stack||e),Ee(i,"error")}else s&&(l=Me(c,n,s,0,l));c.l="",h.K([6,r,n,l])})(i);else if(9===n)(({V:e,w:t,L:r,R:n,b:i})=>{if($[r])try{$[r].apply(te(e,t,[],n),te(e,t,[],i))}catch(e){console.error(e)}})(i);else if(10===n)(({V:e,q:t,b:r})=>{try{let n=m[e].U,i=0,s=R(t);for(;i<s;i++)i+1<s?n=n[t[i]]:n[t[i]].apply(n,te(null,e,[],r))}catch(e){console.error(e)}})(i);else if(5===n)et(i);else if(8===n)m[i].x=1,m[i].y=0;else if(14===n)m[i].T=r[2];else if(13===n){const e=i.V,t=m[e];t.E.href=i.url,function(e,t,r){const n=t.U.history;switch(r.type){case 0:t.$propagateHistoryChange$=!1;try{n.pushState(r.state,"",r.newUrl)}catch(e){}t.$propagateHistoryChange$=!0;break;case 1:t.$propagateHistoryChange$=!1;try{n.replaceState(r.state,"",r.newUrl)}catch(e){}t.$propagateHistoryChange$=!0}}(i.V,t,i)}else 15===n&&((e,t,r,n,i)=>{const s=V(t,r);s&&"function"==typeof s[n]&&s[n].apply(s,i)})(...r);else 1===n?((t=>{const r=h.i=JSON.parse(t.i),n=t.I;h.t=importScripts.bind(e),h.v=t.v,h.C=t.C,h.I=n,h.K=postMessage.bind(e),h.P=t.P,p.set(n,t.D),g.set(n,t.O),e.importScripts=void 0,delete e.postMessage,delete e.WorkerGlobalScope,v("resolveUrl,get,set,apply").map((e=>{r[e]&&(r[e]=new Function("return "+r[e])())}))})(i),h.K([2])):3===n?(h.v=[...h.v,...i],h.x=1,h.K([4]),[...tt].map(rt),tt.length=0):tt.push(t)};e.onmessage=rt,postMessage([0])})(self);\\n\'],{type:"text/javascript"})),{name:"Partytown 🎉"}),Z.onmessage=t=>{const r=t.data;12===r[0]?P(Z,r[1]):e(Z,r)},$.addEventListener("pt1",(e=>k(Z,f(e.detail.frameElement),e.detail))))}))})(window);\n</script></head></html>'
          )
        )
      : i.endsWith('proxytown') &&
        n.respondWith(
          (n =>
            new Promise(async s => {
              const i = await n.clone().json(),
                o = await (r =>
                  new Promise(async n => {
                    const s = [
                      ...(await self.clients.matchAll()),
                    ].sort((e, t) =>
                      e.url > t.url ? -1 : e.url < t.url ? 1 : 0
                    )[0]
                    if (s) {
                      const i = [
                        n,
                        setTimeout(() => {
                          e.delete(r.F), n(t(r, 'Timeout'))
                        }, 1e4),
                      ]
                      e.set(r.F, i), s.postMessage(r)
                    } else n(t(r, 'NoParty'))
                  }))(i)
              s(r(JSON.stringify(o), 'application/json'))
            }))(s)
        )
  })

```