"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.euiMarkdownLinkValidator = euiMarkdownLinkValidator;
exports.mutateLinkToText = mutateLinkToText;
exports.validateUrl = validateUrl;
var _unistUtilVisit = _interopRequireDefault(require("unist-util-visit"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0 and the Server Side Public License, v 1; you may not use this file except
 * in compliance with, at your election, the Elastic License 2.0 or the Server
 * Side Public License, v 1.
 */

function euiMarkdownLinkValidator(options) {
  return function (ast) {
    (0, _unistUtilVisit.default)(ast, 'link', function (_node) {
      var node = _node;
      if (!validateUrl(node.url, options)) {
        mutateLinkToText(node);
      }
    });
  };
}
function mutateLinkToText(node) {
  var _node$children, _node$children$, _node$url;
  // this is an upsupported url, convert to a text node
  node.type = 'text';

  // and, if the link text matches the url there's only one value to show
  // otherwise render as the markdown syntax so both text & url remain, unlinked
  var linkText = ((_node$children = node.children) === null || _node$children === void 0 ? void 0 : (_node$children$ = _node$children[0]) === null || _node$children$ === void 0 ? void 0 : _node$children$.value) || '';
  var linkUrl = (_node$url = node.url) !== null && _node$url !== void 0 ? _node$url : '';
  if (linkText === linkUrl) {
    node.value = linkText;
  } else {
    node.value = "[".concat(linkText, "](").concat(node.url, ")");
  }
  delete node.children;
  delete node.title;
  delete node.url;
  return node;
}
function validateUrl(url, _ref) {
  var allowRelative = _ref.allowRelative,
    allowProtocols = _ref.allowProtocols;
  // relative captures both relative paths `/` and protocols `//`
  var isRelative = url.startsWith('/');
  if (isRelative) {
    return allowRelative;
  }
  try {
    var parsedUrl = new URL(url);
    return allowProtocols.indexOf(parsedUrl.protocol) !== -1;
  } catch (e) {
    // failed to parse input as url
    return false;
  }
}