import _defineProperty from "@babel/runtime/helpers/defineProperty";
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
import { traverse } from '@atlaskit/adf-utils/traverse';
import { isResolvingMentionProvider } from '@atlaskit/mention/resource';
/**
 * Sanitises a document where some content should not be in the document (e.g. mention names).
 *
 * It is expected that these names we be resolved separately (e.g. when rendering
 * a node view).
 */
export function sanitizeNodeForPrivacy(json, providerFactory) {
  var mentionNames = new Map();
  var hasCacheableMentions = false;
  var sanitizedJSON = traverse(json, {
    mention: function mention(node) {
      if (node.attrs && node.attrs.text) {
        hasCacheableMentions = true;
        // Remove @ prefix
        var text = node.attrs.text;
        var name = text.startsWith('@') ? text.slice(1) : text;
        mentionNames.set(node.attrs.id, name);
      }
      return _objectSpread(_objectSpread({}, node), {}, {
        attrs: _objectSpread(_objectSpread({}, node.attrs), {}, {
          text: ''
        })
      });
    }
  });
  if (hasCacheableMentions && providerFactory) {
    var handler = function handler(_name, providerPromise) {
      if (providerPromise) {
        providerPromise.then(function (provider) {
          if (isResolvingMentionProvider(provider)) {
            mentionNames.forEach(function (name, id) {
              provider.cacheMentionName(id, name);
            });
            mentionNames.clear();
            providerFactory.unsubscribe('mentionProvider', handler);
          }
        });
      }
    };
    providerFactory.subscribe('mentionProvider', handler);
  }
  return sanitizedJSON;
}