robots-txt-builder.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. "use strict";
  2. var __assign = (this && this.__assign) || function () {
  3. __assign = Object.assign || function(t) {
  4. for (var s, i = 1, n = arguments.length; i < n; i++) {
  5. s = arguments[i];
  6. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  7. t[p] = s[p];
  8. }
  9. return t;
  10. };
  11. return __assign.apply(this, arguments);
  12. };
  13. exports.__esModule = true;
  14. exports.RobotsTxtBuilder = void 0;
  15. var array_js_1 = require("../utils/array.js");
  16. var RobotsTxtBuilder = /** @class */ (function () {
  17. function RobotsTxtBuilder() {
  18. }
  19. /**
  20. * Normalize robots.txt policies
  21. * @param policies
  22. * @returns
  23. */
  24. RobotsTxtBuilder.prototype.normalizePolicy = function (policies) {
  25. return policies.map(function (x) {
  26. var _a, _b;
  27. return (__assign(__assign({}, x), { allow: (0, array_js_1.toArray)((_a = x.allow) !== null && _a !== void 0 ? _a : []), disallow: (0, array_js_1.toArray)((_b = x.disallow) !== null && _b !== void 0 ? _b : []) }));
  28. });
  29. };
  30. /**
  31. * Add new policy
  32. * @param key
  33. * @param rules
  34. * @returns
  35. */
  36. RobotsTxtBuilder.prototype.addPolicies = function (key, rules) {
  37. return rules.reduce(function (prev, curr) { return "".concat(prev).concat(key, ": ").concat(curr, "\n"); }, '');
  38. };
  39. /**
  40. * Generates robots.txt content
  41. * @param config
  42. * @returns
  43. */
  44. RobotsTxtBuilder.prototype.generateRobotsTxt = function (config) {
  45. var _this = this;
  46. var _a = config.robotsTxtOptions, additionalSitemaps = _a.additionalSitemaps, policies = _a.policies;
  47. var normalizedPolices = this.normalizePolicy(policies);
  48. var content = '';
  49. normalizedPolices.forEach(function (x) {
  50. content += "# ".concat(x.userAgent, "\nUser-agent: ").concat(x.userAgent, "\n");
  51. if (x.allow) {
  52. content += "".concat(_this.addPolicies('Allow', x.allow));
  53. }
  54. if (x.disallow) {
  55. content += "".concat(_this.addPolicies('Disallow', x.disallow));
  56. }
  57. if (x.crawlDelay) {
  58. content += "Crawl-delay: ".concat(x.crawlDelay, "\n");
  59. }
  60. content += '\n';
  61. });
  62. // Append host
  63. content += "# Host\nHost: ".concat(config.siteUrl, "\n");
  64. if (additionalSitemaps && additionalSitemaps.length > 0) {
  65. content += "\n# Sitemaps\n";
  66. additionalSitemaps.forEach(function (x) {
  67. content += "Sitemap: ".concat(x, "\n");
  68. });
  69. }
  70. return content;
  71. };
  72. return RobotsTxtBuilder;
  73. }());
  74. exports.RobotsTxtBuilder = RobotsTxtBuilder;