{"version":3,"file":"Context.cjs","names":["ApiClient","CentraEvents","createContext","isPlainObject","useState","useCallback","cookies","useMemo","useContext"],"sources":["../src/Context.tsx"],"sourcesContent":["import type * as CheckoutApi from '@noaignite/centra-types'\nimport { isPlainObject } from '@noaignite/utils'\nimport type Cookies from 'js-cookie'\nimport cookies from 'js-cookie'\nimport { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react'\nimport { ApiClient } from './ApiClient'\nimport { CentraEvents } from './internal/CentraEvents'\n\nconst defaultApiClient = ApiClient.default\nconst centraEvents = CentraEvents.default\n\n/**\n * The prop types that CentraProvider accepts\n */\nexport interface ProviderProps {\n  /**\n   * Centra API URL\n   */\n  apiUrl?: string\n  /**\n   * The api client to use instead of the default one\n   */\n  apiClient?: ApiClient\n  children: React.ReactNode\n  /**\n   * Disables automatic client side fetching of the Centra selection\n   */\n  disableInit?: boolean\n  /**\n   * Sets the initial selection.\n   * The `initialSelection` is ignore after the initial render\n   */\n  initialSelection?: CheckoutApi.SuccessResponse<CheckoutApi.SelectionResponse>\n  /**\n   * Used when submitting payment using the POST /payment Centra api call\n   */\n  paymentFailedPage:\n    | string\n    | ((selection: CheckoutApi.SuccessResponse<CheckoutApi.SelectionResponse>) => string)\n  /**\n   * Used when submitting payment using the POST /payment Centra api call\n   */\n  paymentReturnPage:\n    | string\n    | ((selection: CheckoutApi.SuccessResponse<CheckoutApi.SelectionResponse>) => string)\n  /**\n   * Receipt page to redirect to when Centra payment succeeds directly\n   */\n  receiptPage: string\n  /**\n   *  When the cookie used to store the Centra checkout token will expire, days as a number or a Date\n   *  @defaultValue `365`\n   */\n  tokenExpires?: number | Date\n  /**\n   * The name of the cookie used to store the Centra checkout token\n   * @defaultValue `centra-checkout-token`\n   */\n  tokenName?: string\n  tokenCookieOptions?: Cookies.CookieAttributes\n}\n\nexport interface ContextMethods {\n  /**\n   * @param item - The Centra item id\n   */\n  addItem?: (\n    item: string,\n    quantity?: number,\n  ) => Promise<CheckoutApi.Response<CheckoutApi.SelectionResponse>>\n  /**\n   * @param item - The Centra item id\n   * @param data - Bundle data\n   */\n  addBundleItem?: (\n    item: string,\n    data?: Record<string, unknown>,\n  ) => Promise<CheckoutApi.Response<CheckoutApi.SelectionResponse>>\n  /**\n   * @param giftCertificate - The `giftCertificate` value of the gift certificate to add\n   */\n  addGiftCertificate?: (\n    giftCertificate: string,\n  ) => Promise<CheckoutApi.Response<CheckoutApi.SelectionResponse>>\n\n  addBackInStockSubscription?: (\n    data: Record<string, unknown>,\n  ) => Promise<CheckoutApi.Response<CheckoutApi.SelectionResponse>>\n  /**\n   * @param giftCertificate - The `giftCertificate` value of the gift certificate to add\n   * @param amount - Custom gift certificate amount\n   */\n  addCustomGiftCertificate?: (\n    giftCertificate: string,\n    amount: string,\n  ) => Promise<CheckoutApi.Response<CheckoutApi.SelectionResponse>>\n\n  addNewsletterSubscription?: (\n    data: Record<string, unknown>,\n  ) => Promise<CheckoutApi.Response<CheckoutApi.SelectionResponse>>\n  /**\n   * @param voucher - The id of the voucher to add\n   */\n  addVoucher?: (voucher: string) => Promise<CheckoutApi.Response<CheckoutApi.SelectionResponse>>\n  /**\n   * @param line - The line id of the item to decrease\n   */\n  decreaseCartItem?: (line: string) => Promise<CheckoutApi.Response<CheckoutApi.SelectionResponse>>\n  /**\n   * @param line - The line id of the item to increase\n   */\n  increaseCartItem?: (line: string) => Promise<CheckoutApi.Response<CheckoutApi.SelectionResponse>>\n  /**\n   * @param selectionData - Initial selection data\n   */\n  init?: (selectionData?: CheckoutApi.Response<CheckoutApi.SelectionResponse>) => Promise<void>\n  loginCustomer?: (\n    email: string,\n    password: string,\n  ) => Promise<CheckoutApi.Response<CheckoutApi.SelectionResponse>>\n  logoutCustomer?: () => Promise<CheckoutApi.Response<CheckoutApi.SelectionResponse>>\n  /**\n   * @param data - All data to register to customer. See {@link https://docs.centra.com/swagger-ui/?api=CheckoutAPI#/6.%20customer%20handling/post_register | Centra docs} for more details.\n   */\n  registerCustomer?: (\n    data: Record<string, unknown>,\n  ) => Promise<CheckoutApi.Response<CheckoutApi.SelectionResponse>>\n  /**\n   * @param line - The line id of the item to increase\n   */\n  removeCartItem?: (line: string) => Promise<CheckoutApi.Response<CheckoutApi.SelectionResponse>>\n  /**\n   * @param voucher - The id of the voucher to add\n   */\n  removeVoucher?: (voucher: string) => Promise<CheckoutApi.Response<CheckoutApi.SelectionResponse>>\n  /**\n   * @param i - The `i` query parameter provided by Centra when landing on the password reset page\n   * @param id - The `id` query parameter provided by Centra when landing on the password reset page\n   */\n  resetCustomerPassword?: (\n    i: string,\n    id: string,\n    newPassword: string,\n  ) => Promise<CheckoutApi.Response<CheckoutApi.SelectionResponse>>\n  resetSelection?: () => Promise<void>\n  /**\n   * @param linkUri - URI of the password reset page. Should not be a full url e.g. `account/password-reset`. Domain is set in CheckoutApi.\n   */\n  sendCustomerResetPasswordEmail?: (\n    email: string,\n    linkUri: string,\n  ) => Promise<CheckoutApi.Response<CheckoutApi.SelectionResponse>>\n  submitPayment?: (\n    data: Record<string, unknown>,\n  ) => Promise<CheckoutApi.Response<CheckoutApi.Payment>>\n  updateCartItemQuantity?: (\n    line: string,\n    quantity: number,\n  ) => Promise<CheckoutApi.Response<CheckoutApi.SelectionResponse>>\n  updateCartItemSize?: (\n    cartItem: CheckoutApi.SelectionItem,\n    item: string,\n  ) => Promise<CheckoutApi.Response<CheckoutApi.SelectionResponse>>\n  updateCountry?: (\n    country: string,\n    data: { language: string },\n  ) => Promise<CheckoutApi.Response<CheckoutApi.SelectionResponse>>\n  updateCustomer?: (\n    data: Record<string, unknown>,\n  ) => Promise<CheckoutApi.Response<CheckoutApi.SelectionResponse>>\n  updateCustomerAddress?: (\n    data: Record<string, unknown>,\n  ) => Promise<CheckoutApi.Response<CheckoutApi.SelectionResponse>>\n  updateCustomerEmail?: (\n    email: string,\n  ) => Promise<CheckoutApi.Response<CheckoutApi.SelectionResponse>>\n  updateCustomerPassword?: (\n    password: string,\n    newPassword: string,\n  ) => Promise<CheckoutApi.Response<CheckoutApi.SelectionResponse>>\n  updateLanguage?: (\n    language: string,\n  ) => Promise<CheckoutApi.Response<CheckoutApi.SelectionResponse>>\n  updatePaymentFields?: (\n    data: Record<string, unknown>,\n  ) => Promise<CheckoutApi.Response<CheckoutApi.SelectionResponse>>\n  updatePaymentMethod?: (\n    paymentMethod: string,\n  ) => Promise<CheckoutApi.Response<CheckoutApi.SelectionResponse>>\n  updateShippingMethod?: (\n    shippingMethod: string,\n  ) => Promise<CheckoutApi.Response<CheckoutApi.SelectionResponse>>\n  updateCampaignSite?: (uri: string) => Promise<CheckoutApi.Response<CheckoutApi.SelectionResponse>>\n}\n\nexport type ContextProperties = CheckoutApi.SuccessResponse<CheckoutApi.SelectionResponse> & {\n  apiUrl?: string\n  apiClient?: ApiClient\n}\n\nexport const SELECTION_INITIAL_VALUE: CheckoutApi.SelectionResponse = {\n  countries: [],\n  languages: [],\n  location: {},\n  paymentFields: {},\n  paymentMethods: [],\n  selection: {\n    address: {},\n    discounts: {},\n    items: [],\n    totals: {},\n  },\n  shippingMethods: [],\n}\n\nexport const CentraHandlersContext = createContext<ContextMethods | null>(null)\nexport const CentraSelectionContext = createContext<ContextProperties | null>(null)\n\n/**\n * Perform `callback` when `Promise` contains a `CheckoutApi.SelectionResponse`\n *\n * @param promise -  Promise that may contain `selection` response\n * @param callback -  Callback that should be called with the `promise` if the results of the `promise` contains a `CheckoutApi.SelectionResponse`\n */\nconst onSelectionResponse = async <\n  TPromise extends Promise<CheckoutApi.SuccessResponse<CheckoutApi.SelectionResponse>>,\n  TCallback extends (promise: TPromise) => TPromise,\n>(\n  promise: Promise<unknown>,\n  callback: TCallback,\n): Promise<CheckoutApi.SuccessResponse<CheckoutApi.SelectionResponse>> => {\n  const results = await promise\n\n  if (isPlainObject(results) && 'selection' in results && Boolean(results.selection)) {\n    return callback(\n      // We have to cast it to `TPromise`, because there's not a way to create async type predicates without already passing the `Promise` as argument to a function.\n      promise as TPromise,\n    )\n  }\n\n  // casting here, to conform for the already exposed interface.\n  // Update this to something more pessimistic?\n  return results as TPromise\n}\n\n/**\n * React Context provider that is required to use the `useCentra` and `useCentraHandlers` hooks.\n * Provides state management and related handlers of the users current Centra selection via the Checkout API.\n * The handlers could be used for adding products to the selection and making purchases, for example.\n */\nexport function CentraProvider(props: ProviderProps) {\n  const {\n    apiClient: apiClientProp,\n    apiUrl,\n    children,\n    disableInit = false,\n    initialSelection,\n    paymentFailedPage,\n    paymentReturnPage,\n    receiptPage,\n    tokenExpires = 365,\n    tokenName = 'centra-checkout-token',\n    tokenCookieOptions = null,\n  } = props\n\n  const apiClient = apiClientProp ?? defaultApiClient\n\n  const [selection, setSelection] = useState<\n    CheckoutApi.SuccessResponse<CheckoutApi.SelectionResponse>\n  >(initialSelection ?? SELECTION_INITIAL_VALUE)\n\n  const centraCheckoutScript = 'selection' in selection && selection.selection?.centraCheckoutScript\n\n  // set api client url\n  if (apiUrl) {\n    apiClient.baseUrl = apiUrl\n  }\n\n  // set api token if available\n  if (initialSelection?.token) {\n    apiClient.headers.set('api-token', initialSelection.token)\n  }\n\n  const selectionApiCall = useCallback(\n    async (\n      apiCall:\n        | Promise<CheckoutApi.SuccessResponse<CheckoutApi.SelectionResponse>>\n        | (() => Promise<CheckoutApi.SuccessResponse<CheckoutApi.SelectionResponse>>),\n    ) => {\n      window.CentraCheckout?.suspend()\n\n      const response = typeof apiCall === 'function' ? await apiCall() : await apiCall\n\n      setSelection(response)\n\n      window.CentraCheckout?.resume()\n\n      return response\n    },\n    [],\n  )\n\n  const centraCheckoutCallback = useCallback(\n    async (event: GlobalEventHandlersEventMap['centra_checkout_callback']) => {\n      const response = (await apiClient.request(\n        'PUT',\n        `payment-fields`,\n        event.detail,\n      )) as CheckoutApi.Response<CheckoutApi.SelectionResponse>\n\n      if ('selection' in response && response.selection) {\n        setSelection(response)\n      }\n\n      window.CentraCheckout?.resume(event.detail.additionalFields?.suspendIgnore)\n\n      centraEvents.dispatch('centra_checkout_callback', response)\n    },\n    [apiClient],\n  )\n\n  const init = useCallback<NonNullable<ContextMethods['init']>>(\n    async (selectionData) => {\n      let response\n\n      const apiToken = cookies.get(tokenName)\n      if (apiToken) {\n        apiClient.headers.set('api-token', apiToken)\n      }\n\n      if (!selectionData) {\n        response = (await apiClient.request(\n          'GET',\n          'selection',\n        )) as CheckoutApi.Response<CheckoutApi.SelectionResponse>\n      } else {\n        response = selectionData\n      }\n\n      if ('selection' in response && response.selection) {\n        setSelection(response)\n\n        if (response.token && response.token !== apiToken) {\n          apiClient.headers.set('api-token', response.token)\n          cookies.set(tokenName, response.token, {\n            expires: tokenExpires,\n            ...tokenCookieOptions,\n          })\n        }\n      }\n    },\n    [tokenName, apiClient, tokenExpires, tokenCookieOptions],\n  )\n\n  /* HANDLER METHODS */\n\n  const addItem = useCallback<NonNullable<ContextMethods['addItem']>>(\n    (item, quantity = 1) =>\n      onSelectionResponse(\n        apiClient.request('POST', `items/${item}/quantity/${quantity}`),\n        selectionApiCall,\n      ),\n    [apiClient, selectionApiCall],\n  )\n\n  const addBundleItem = useCallback<NonNullable<ContextMethods['addBundleItem']>>(\n    (item, data) =>\n      onSelectionResponse(\n        apiClient.request('POST', `items/bundles/${item}`, data),\n        selectionApiCall,\n      ),\n    [apiClient, selectionApiCall],\n  )\n\n  const addGiftCertificate = useCallback<NonNullable<ContextMethods['addGiftCertificate']>>(\n    (giftCertificate) =>\n      onSelectionResponse(\n        apiClient.request('POST', `items/gift-certificates/${giftCertificate}`),\n        selectionApiCall,\n      ),\n    [apiClient, selectionApiCall],\n  )\n\n  const addCustomGiftCertificate = useCallback<\n    NonNullable<ContextMethods['addCustomGiftCertificate']>\n  >(\n    (giftCertificate, amount) =>\n      onSelectionResponse(\n        apiClient.request('POST', `items/gift-certificates/${giftCertificate}/amount/${amount}`),\n        selectionApiCall,\n      ),\n    [apiClient, selectionApiCall],\n  )\n\n  const increaseCartItem = useCallback<NonNullable<ContextMethods['increaseCartItem']>>(\n    (line) =>\n      onSelectionResponse(apiClient.request('POST', `lines/${line}/quantity/1`), selectionApiCall),\n    [apiClient, selectionApiCall],\n  )\n\n  const decreaseCartItem = useCallback<NonNullable<ContextMethods['decreaseCartItem']>>(\n    (line) =>\n      onSelectionResponse(\n        apiClient.request('DELETE', `lines/${line}/quantity/1`),\n        selectionApiCall,\n      ),\n    [apiClient, selectionApiCall],\n  )\n\n  const removeCartItem = useCallback<NonNullable<ContextMethods['removeCartItem']>>(\n    (line) => onSelectionResponse(apiClient.request('DELETE', `lines/${line}`), selectionApiCall),\n    [apiClient, selectionApiCall],\n  )\n\n  const updateCartItemQuantity = useCallback<NonNullable<ContextMethods['updateCartItemQuantity']>>(\n    (line, quantity) =>\n      onSelectionResponse(\n        apiClient.request('PUT', `lines/${line}/quantity/${quantity}`),\n        selectionApiCall,\n      ),\n    [apiClient, selectionApiCall],\n  )\n\n  const updateCartItemSize = useCallback<NonNullable<ContextMethods['updateCartItemSize']>>(\n    (cartItem, item) =>\n      selectionApiCall(async () => {\n        await apiClient.request('DELETE', `lines/${cartItem.line}`)\n\n        const response = (await apiClient.request(\n          'POST',\n          `items/${item}/quantity/${cartItem.quantity}`,\n        )) as Promise<CheckoutApi.Response<CheckoutApi.SelectionResponse>>\n\n        return response\n      }),\n    [apiClient, selectionApiCall],\n  )\n\n  const addVoucher = useCallback<NonNullable<ContextMethods['addVoucher']>>(\n    (voucher) =>\n      onSelectionResponse(apiClient.request('POST', 'vouchers', { voucher }), selectionApiCall),\n    [apiClient, selectionApiCall],\n  )\n\n  const removeVoucher = useCallback<NonNullable<ContextMethods['removeVoucher']>>(\n    (voucher) =>\n      onSelectionResponse(apiClient.request('DELETE', `vouchers/${voucher}`), selectionApiCall),\n    [apiClient, selectionApiCall],\n  )\n\n  const updateCountry = useCallback<NonNullable<ContextMethods['updateCountry']>>(\n    (country, data) =>\n      onSelectionResponse(apiClient.request('PUT', `countries/${country}`, data), selectionApiCall),\n    [apiClient, selectionApiCall],\n  )\n\n  const updateLanguage = useCallback<NonNullable<ContextMethods['updateLanguage']>>(\n    (language) =>\n      onSelectionResponse(apiClient.request('PUT', `languages/${language}`), selectionApiCall),\n    [apiClient, selectionApiCall],\n  )\n\n  const updateShippingMethod = useCallback<NonNullable<ContextMethods['updateShippingMethod']>>(\n    (shippingMethod) =>\n      onSelectionResponse(\n        apiClient.request('PUT', `shipping-methods/${shippingMethod}`),\n        selectionApiCall,\n      ),\n    [apiClient, selectionApiCall],\n  )\n\n  const updatePaymentMethod = useCallback<NonNullable<ContextMethods['updatePaymentMethod']>>(\n    (paymentMethod) =>\n      onSelectionResponse(\n        apiClient.request('PUT', `payment-methods/${paymentMethod}`),\n        selectionApiCall,\n      ),\n    [apiClient, selectionApiCall],\n  )\n\n  const updatePaymentFields = useCallback<NonNullable<ContextMethods['updatePaymentFields']>>(\n    async (data) =>\n      onSelectionResponse(apiClient.request('PUT', `payment-fields`, data), selectionApiCall),\n    [apiClient, selectionApiCall],\n  )\n\n  const submitPayment = useCallback<NonNullable<ContextMethods['submitPayment']>>(\n    async (data) => {\n      const response = (await apiClient.request('POST', 'payment', {\n        paymentReturnPage:\n          typeof paymentReturnPage === 'function'\n            ? paymentReturnPage(selection)\n            : paymentReturnPage,\n        paymentFailedPage:\n          typeof paymentFailedPage === 'function'\n            ? paymentFailedPage(selection)\n            : paymentFailedPage,\n        ...data,\n      })) as CheckoutApi.Response<CheckoutApi.Payment>\n\n      if ('errors' in response) {\n        throw new Error(\n          Object.entries(response.errors)\n            .map((key, value) => `${key}: ${value}`)\n            .join(','),\n        )\n      }\n\n      // handle redirecting here\n      switch (response.action) {\n        case 'redirect':\n          if (response.url) {\n            window.location.href = response.url\n          }\n          break\n        case 'success':\n          // according to Centra docs – if action === 'success', user should be forwarded directly to the receipt page\n          window.location.href = `${receiptPage}/${response.token}`\n          break\n        case 'javascript':\n          if (response.code) {\n            const script = document.createElement('script')\n            const text = document.createTextNode(response.code)\n            script.appendChild(text)\n            document.body.appendChild(script)\n          }\n          break\n        default:\n          return response\n      }\n      return response\n    },\n    [apiClient, paymentFailedPage, paymentReturnPage, receiptPage, selection],\n  )\n\n  const addBackInStockSubscription = useCallback<\n    NonNullable<ContextMethods['addBackInStockSubscription']>\n  >(\n    (data) =>\n      onSelectionResponse(\n        apiClient.request('POST', 'back-in-stock-subscription', data),\n        selectionApiCall,\n      ),\n    [apiClient, selectionApiCall],\n  )\n\n  const addNewsletterSubscription = useCallback<\n    NonNullable<ContextMethods['addNewsletterSubscription']>\n  >(\n    (data) =>\n      onSelectionResponse(\n        apiClient.request('POST', 'newsletter-subscription', data),\n        selectionApiCall,\n      ),\n    [apiClient, selectionApiCall],\n  )\n\n  const loginCustomer = useCallback<NonNullable<ContextMethods['loginCustomer']>>(\n    (email, password) =>\n      onSelectionResponse(\n        apiClient.request('POST', `login/${email}`, { password }),\n        selectionApiCall,\n      ),\n    [apiClient, selectionApiCall],\n  )\n\n  const logoutCustomer = useCallback<NonNullable<ContextMethods['logoutCustomer']>>(\n    () => onSelectionResponse(apiClient.request('POST', `logout`), selectionApiCall),\n    [apiClient, selectionApiCall],\n  )\n\n  const registerCustomer = useCallback<NonNullable<ContextMethods['registerCustomer']>>(\n    (data) => onSelectionResponse(apiClient.request('POST', `register`, data), selectionApiCall),\n    [apiClient, selectionApiCall],\n  )\n\n  const resetCustomerPassword = useCallback<NonNullable<ContextMethods['resetCustomerPassword']>>(\n    (i, id, newPassword) =>\n      onSelectionResponse(\n        apiClient.request('POST', `password-reset`, { i, id, newPassword }),\n        selectionApiCall,\n      ),\n    [apiClient, selectionApiCall],\n  )\n\n  /** Resets the selection. Useful if you need a fresh `api-token` (when a user exits a campaign site, for example). */\n  const resetSelection = useCallback<NonNullable<ContextMethods['resetSelection']>>(() => {\n    apiClient.headers.delete('api-token')\n    cookies.remove(tokenName)\n\n    return init()\n  }, [apiClient.headers, init, tokenName])\n\n  const sendCustomerResetPasswordEmail = useCallback<\n    NonNullable<ContextMethods['sendCustomerResetPasswordEmail']>\n  >(\n    (email, linkUri) =>\n      onSelectionResponse(\n        apiClient.request('POST', `password-reset-email/${email}`, { linkUri }),\n        selectionApiCall,\n      ),\n    [apiClient, selectionApiCall],\n  )\n\n  const updateCustomer = useCallback<NonNullable<ContextMethods['updateCustomer']>>(\n    (data) =>\n      onSelectionResponse(apiClient.request('PUT', `customer/update`, data), selectionApiCall),\n    [apiClient, selectionApiCall],\n  )\n\n  const updateCustomerAddress = useCallback<NonNullable<ContextMethods['updateCustomerAddress']>>(\n    (data) => onSelectionResponse(apiClient.request('PUT', `address`, data), selectionApiCall),\n    [apiClient, selectionApiCall],\n  )\n\n  const updateCustomerEmail = useCallback<NonNullable<ContextMethods['updateCustomerEmail']>>(\n    (newEmail) =>\n      onSelectionResponse(apiClient.request('PUT', `email`, { newEmail }), selectionApiCall),\n    [apiClient, selectionApiCall],\n  )\n\n  const updateCustomerPassword = useCallback<NonNullable<ContextMethods['updateCustomerPassword']>>(\n    (password, newPassword) =>\n      onSelectionResponse(\n        apiClient.request('PUT', `password`, { password, newPassword }),\n        selectionApiCall,\n      ),\n    [apiClient, selectionApiCall],\n  )\n\n  const updateCampaignSite = useCallback<NonNullable<ContextMethods['updateCampaignSite']>>(\n    (uri) =>\n      onSelectionResponse(apiClient.request('PUT', `campaign-site`, { uri }), selectionApiCall),\n    [apiClient, selectionApiCall],\n  )\n\n  /* EFFECTS */\n\n  useEffect(() => {\n    if (!disableInit) {\n      void init()\n    }\n\n    // always add event listener for centra_checkout_callback in case it is used\n    document.addEventListener('centra_checkout_callback', centraCheckoutCallback)\n\n    return () => {\n      document.removeEventListener('centra_checkout_callback', centraCheckoutCallback)\n    }\n  }, [disableInit, init, centraCheckoutCallback])\n\n  // run centra checkout script if it is available in the selection\n  useEffect(() => {\n    let script: HTMLScriptElement | null = null\n    if (centraCheckoutScript) {\n      script = document.createElement('script')\n      script.innerHTML = centraCheckoutScript\n      script.id = 'centra-checkout-script'\n      document.head.appendChild(script)\n    }\n\n    return () => {\n      if (script) {\n        document.head.removeChild(script)\n      }\n    }\n  }, [centraCheckoutScript])\n\n  const centraHandlersContext = useMemo<ContextMethods>(\n    (): ContextMethods => ({\n      addItem,\n      addBundleItem,\n      addGiftCertificate,\n      addBackInStockSubscription,\n      addCustomGiftCertificate,\n      addNewsletterSubscription,\n      addVoucher,\n      decreaseCartItem,\n      increaseCartItem,\n      init,\n      loginCustomer,\n      logoutCustomer,\n      registerCustomer,\n      removeCartItem,\n      removeVoucher,\n      resetCustomerPassword,\n      resetSelection,\n      sendCustomerResetPasswordEmail,\n      submitPayment,\n      updateCartItemQuantity,\n      updateCartItemSize,\n      updateCountry,\n      updateCustomer,\n      updateCustomerAddress,\n      updateCustomerEmail,\n      updateCustomerPassword,\n      updateLanguage,\n      updatePaymentFields,\n      updatePaymentMethod,\n      updateShippingMethod,\n      updateCampaignSite,\n    }),\n    [\n      addItem,\n      addBundleItem,\n      addGiftCertificate,\n      addBackInStockSubscription,\n      addCustomGiftCertificate,\n      addNewsletterSubscription,\n      addVoucher,\n      decreaseCartItem,\n      increaseCartItem,\n      init,\n      loginCustomer,\n      logoutCustomer,\n      registerCustomer,\n      removeCartItem,\n      removeVoucher,\n      resetCustomerPassword,\n      resetSelection,\n      sendCustomerResetPasswordEmail,\n      submitPayment,\n      updateCartItemQuantity,\n      updateCartItemSize,\n      updateCountry,\n      updateCustomer,\n      updateCustomerAddress,\n      updateCustomerEmail,\n      updateCustomerPassword,\n      updateLanguage,\n      updatePaymentFields,\n      updatePaymentMethod,\n      updateShippingMethod,\n      updateCampaignSite,\n    ],\n  )\n\n  const centraContext = useMemo(\n    (): ContextProperties => ({\n      ...selection,\n      apiUrl,\n      apiClient,\n    }),\n    [selection, apiUrl, apiClient],\n  )\n\n  return (\n    <CentraHandlersContext.Provider value={centraHandlersContext}>\n      <CentraSelectionContext.Provider value={centraContext}>\n        {children}\n      </CentraSelectionContext.Provider>\n    </CentraHandlersContext.Provider>\n  )\n}\n\n/**\n * This hook returns the centra selection\n */\nexport function useCentraSelection() {\n  const context = useContext(CentraSelectionContext)\n\n  if (context === null) {\n    throw new Error(\n      [\n        '@noaignite/react-centra-checkout: `useCentraSelection` may only be',\n        'used inside the `CentraProvider` react tree, please declare it at a',\n        'higher level.',\n      ].join(' '),\n    )\n  }\n\n  return context\n}\n\n/**\n * This hook returns update handlers\n */\nexport function useCentraHandlers() {\n  const context = useContext(CentraHandlersContext)\n\n  if (context === null) {\n    throw new Error(\n      [\n        '@noaignite/react-centra-checkout: `useCentraHandlers` may only be',\n        'used inside the `CentraProvider` react tree, please declare it at a',\n        'higher level.',\n      ].join(' '),\n    )\n  }\n\n  return context\n}\n\n/**\n * Returns the latest order receipt given a selection token\n */\nexport function useCentraReceipt(\n  token: string,\n): CheckoutApi.Response<CheckoutApi.OrderCompleteResponse> {\n  const [result, setResult] = useState<CheckoutApi.Response<CheckoutApi.OrderCompleteResponse>>({})\n  const { apiUrl } = useCentraSelection()\n\n  if (!token) {\n    console.error('@noaignite/react-centra-checkout: useReceipt requires a selection id')\n  }\n\n  useEffect(() => {\n    // create a new ApiClient in order to temporarily use a different token\n    const tempApiClient = new ApiClient(apiUrl)\n    tempApiClient.headers.set('api-token', token)\n\n    void (\n      tempApiClient.request('GET', 'receipt') as Promise<\n        CheckoutApi.Response<CheckoutApi.OrderCompleteResponse>\n      >\n    ).then((response) => {\n      setResult(response)\n    })\n  }, [apiUrl, token])\n\n  return result\n}\n\n/**\n * Returns the latest orders for the currently logged in user\n * @param from - Display orders from this index. Defaults to 0.\n * @param size - Display this many orders. Defaults lists all orders.\n */\nexport function useCentraOrders(\n  from?: number,\n  size?: number,\n  apiClient = defaultApiClient,\n): CheckoutApi.Response<CheckoutApi.OrdersResponse> {\n  const [result, setResult] = useState<CheckoutApi.Response<CheckoutApi.OrdersResponse>>({})\n\n  useEffect(() => {\n    // fetch orders\n    void (\n      apiClient.request('POST', 'orders', {\n        ...(from && { from }),\n        ...(size && { size }),\n      }) as Promise<CheckoutApi.Response<CheckoutApi.OrdersResponse>>\n    ).then((response) => {\n      setResult(response)\n    })\n  }, [apiClient, from, size])\n\n  return result\n}\n\nexport function useCentraEvents() {\n  return CentraEvents.default\n}\n"],"mappings":";;;;;;;;;;AAQA,MAAM,mBAAmBA,kBAAAA,UAAU;AACnC,MAAM,eAAeC,8BAAAA,aAAa;AA+LlC,MAAa,0BAAyD;CACpE,WAAW,CAAC;CACZ,WAAW,CAAC;CACZ,UAAU,CAAC;CACX,eAAe,CAAC;CAChB,gBAAgB,CAAC;CACjB,WAAW;EACT,SAAS,CAAC;EACV,WAAW,CAAC;EACZ,OAAO,CAAC;EACR,QAAQ,CAAC;CACX;CACA,iBAAiB,CAAC;AACpB;AAEA,MAAa,yBAAA,GAAwBC,MAAAA,cAAAA,CAAqC,IAAI;AAC9E,MAAa,0BAAA,GAAyBA,MAAAA,cAAAA,CAAwC,IAAI;;;;;;;AAQlF,MAAM,sBAAsB,OAI1B,SACA,aACwE;CACxE,MAAM,UAAU,MAAM;CAEtB,KAAA,GAAIC,iBAAAA,cAAAA,CAAc,OAAO,KAAK,eAAe,WAAW,QAAQ,QAAQ,SAAS,GAC/E,OAAO,SAEL,OACF;CAKF,OAAO;AACT;;;;;;AAOA,SAAgB,eAAe,OAAsB;CACnD,MAAM,EACJ,WAAW,eACX,QACA,UACA,cAAc,OACd,kBACA,mBACA,mBACA,aACA,eAAe,KACf,YAAY,yBACZ,qBAAqB,SACnB;CAEJ,MAAM,YAAY,iBAAiB;CAEnC,MAAM,CAAC,WAAW,iBAAA,GAAgBC,MAAAA,SAAAA,CAEhC,oBAAoB,uBAAuB;CAE7C,MAAM,uBAAuB,eAAe,aAAa,UAAU,WAAW;CAG9E,IAAI,QACF,UAAU,UAAU;CAItB,IAAI,kBAAkB,OACpB,UAAU,QAAQ,IAAI,aAAa,iBAAiB,KAAK;CAG3D,MAAM,oBAAA,GAAmBC,MAAAA,YAAAA,CACvB,OACE,YAGG;EACH,OAAO,gBAAgB,QAAQ;EAE/B,MAAM,WAAW,OAAO,YAAY,aAAa,MAAM,QAAQ,IAAI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