'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var hooks = require('preact/hooks');
var errors = require('./errors.js');
var api = require('./api.js');
var subscription = require('./subscription.js');

/**
 * Returns the current array of `metafields` applied to the checkout.
 * You can optionally filter the list.
 * @arg {MetafieldsFilters} - filter the list of returned metafields
 * @deprecated `useMetafields` is deprecated. Use `useAppMetafields` with cart metafields instead.
 * @publicDocs
 */
function useMetafields(filters) {
  const metaFields = subscription.useSubscription(api.useApi().metafields);
  return hooks.useMemo(() => {
    if (filters) {
      const {
        namespace,
        key
      } = filters;
      if (!namespace) {
        throw new errors.CheckoutUIExtensionError('You must pass in a namespace with a key');
      }
      const filteredResults = metaFields.filter(metafield => metafield.namespace === namespace && (!key || metafield.key === key));
      return filteredResults;
    }
    return metaFields;
  }, [filters, metaFields]);
}

/**
 * Returns a function to mutate the `metafields` property of the checkout.
 * @publicDocs
 */
function useApplyMetafieldsChange() {
  const api$1 = api.useApi();
  if ('applyMetafieldChange' in api$1) {
    return api$1.applyMetafieldChange;
  }
  throw new errors.ExtensionHasNoMethodError('applyMetafieldChange', api$1.extension.target);
}

exports.useApplyMetafieldsChange = useApplyMetafieldsChange;
exports.useMetafields = useMetafields;
