link.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. "use strict";
  2. // markdown-it plugin for:
  3. // 1. adding target="_blank" to external links
  4. // 2. normalize internal links to end with `.html`
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. exports.linkPlugin = void 0;
  7. const url_1 = require("url");
  8. const indexRE = /(^|.*\/)index.md(#?.*)$/i;
  9. exports.linkPlugin = (md, externalAttrs) => {
  10. md.renderer.rules.link_open = (tokens, idx, options, env, self) => {
  11. const token = tokens[idx];
  12. const hrefIndex = token.attrIndex('href');
  13. if (hrefIndex >= 0) {
  14. const hrefAttr = token.attrs[hrefIndex];
  15. const url = hrefAttr[1];
  16. const isExternal = /^https?:/.test(url);
  17. if (isExternal) {
  18. Object.entries(externalAttrs).forEach(([key, val]) => {
  19. token.attrSet(key, val);
  20. });
  21. }
  22. else if (!url.startsWith('#')) {
  23. normalizeHref(hrefAttr);
  24. }
  25. }
  26. return self.renderToken(tokens, idx, options);
  27. };
  28. function normalizeHref(hrefAttr) {
  29. let url = hrefAttr[1];
  30. const indexMatch = url.match(indexRE);
  31. if (indexMatch) {
  32. const [, path, hash] = indexMatch;
  33. url = path + hash;
  34. }
  35. else {
  36. let cleanUrl = url.replace(/\#.*$/, '').replace(/\?.*$/, '');
  37. // .md -> .html
  38. if (cleanUrl.endsWith('.md')) {
  39. cleanUrl = cleanUrl.replace(/\.md$/, '.html');
  40. }
  41. // ./foo -> ./foo.html
  42. if (!cleanUrl.endsWith('.html') && !cleanUrl.endsWith('/')) {
  43. cleanUrl += '.html';
  44. }
  45. const parsed = new url_1.URL(url, 'http://a.com');
  46. url = cleanUrl + parsed.search + parsed.hash;
  47. }
  48. // ensure leading . for relative paths
  49. if (!url.startsWith('/') && !/^\.\//.test(url)) {
  50. url = './' + url;
  51. }
  52. // export it for existence check
  53. const data = md.__data;
  54. const links = data.links || (data.links = []);
  55. links.push(url.replace(/\.html$/, ''));
  56. // markdown-it encodes the uri
  57. hrefAttr[1] = decodeURI(url);
  58. }
  59. };
  60. //# sourceMappingURL=link.js.map