You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
core/src/factories/sitemap.js

120 lines
2.4 KiB

This file contains invisible Unicode characters!

This file contains invisible Unicode characters that may be processed differently from what appears below. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to reveal hidden characters.

const { XMLParser, XMLBuilder, XMLValidator} = require('fast-xml-parser')
const dayjs = require('dayjs')
const assign = require('assign-deep')
/**
*
*
* @author Björn Hase <me@herr-hase.wtf>
* @license http://opensource.org/licenses/MIT The MIT License
* @link https://gitea.node001.net/HerrHase/siteomat-webpack-plugin.git
*
*/
class Sitemap {
/**
*
*
* @param {[type]} site
* @param {[type]} pages
*
*/
constructor(site) {
this._site = assign({
'sitemap': {
'use_permalinks': true
}
}, site)
this._urls = []
}
/**
* adding page to urls of sitemap, check if page is valid for sitemap
*
* @param {object} page
*
*/
addPage(page) {
if (this._isValid(page)) {
let path = page.permalink
console.log(this._site)
if (this._site.sitemap.use_permalinks === false) {
path = page.path
}
this._urls.push({
loc: 'https://' + this._site.domain + path,
lastmod: dayjs().format()
})
}
}
/**
* get xml as string
*
* @return {string}
*
*/
getXmlAsString() {
return this._createXml(this._urls)
}
/**
* check if robots has a noindex
*
* @param {object} page
* @return {boolean}
*
*/
_isValid(page) {
let result = true
if (page.meta && page.meta.robots && page.meta.robots.includes('noindex')) {
result = false
}
if (page.extensions !== 'html') {
result = false
}
return result
}
/**
* create xml with urls and return it as string
*
* @param {object} urls
* @return {string}
*
*/
_createXml(urls) {
// builder for XML
const builder = new XMLBuilder({
format: true,
processEntities: false,
ignoreAttributes: false,
attributeNamePrefix: '@'
})
const xmlString = builder.build({
'?xml': {
'@version': '1.0',
'@encoding': 'UTF-8'
},
'urlset': {
'@xmlns': 'http://www.sitemaps.org/schemas/sitemap/0.9',
'url': urls
}
})
return xmlString
}
}
module.exports = Sitemap