webpack-userscript
Version:
A Webpack plugin for userscript projects.
84 lines • 3.18 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.RenderHeaders = void 0;
const table_1 = require("table");
const const_1 = require("../const");
const feature_1 = require("./feature");
class RenderHeaders extends feature_1.Feature {
constructor() {
super(...arguments);
this.name = 'RenderHeaders';
}
apply({ hooks }) {
hooks.renderHeaders.tap(this.name, (headersMap) => this.render(this.mergeHeadersMap(headersMap), this.options));
if (this.options.proxyScript) {
hooks.renderProxyHeaders.tap(this.name, (headers) => this.render(headers, this.options));
}
}
mergeHeadersMap(headersMap) {
return Array.from(headersMap)
.map(([locale, headers]) => Object.fromEntries(Object.entries(headers).map(([tag, value]) => [
locale === const_1.DEFAULT_LOCALE_KEY ? tag : `${tag}:${locale}`,
value,
])))
.reduce((h1, h2) => (Object.assign(Object.assign({}, h1), h2)));
}
render(headers, { prefix = '// ==UserScript==\n', suffix = '// ==/UserScript==\n', pretty = false, tagOrder = [
'name',
'description',
'version',
'author',
'homepage',
'supportURL',
'include',
'exclude',
'match',
], } = {}) {
const orderRevMap = new Map(tagOrder.map((tag, index) => [tag, index]));
const rows = Object.entries(headers)
.sort(([tag1], [tag2]) => {
var _a, _b;
return ((_a = orderRevMap.get(this.getTagName(tag1))) !== null && _a !== void 0 ? _a : orderRevMap.size) -
((_b = orderRevMap.get(this.getTagName(tag2))) !== null && _b !== void 0 ? _b : orderRevMap.size) ||
(tag1 > tag2 ? 1 : tag1 < tag2 ? -1 : 0);
})
.flatMap(([tag, value]) => this.renderTag(tag, value));
const body = pretty
? (0, table_1.table)(rows, {
border: (0, table_1.getBorderCharacters)('void'),
columnDefault: {
paddingLeft: 0,
paddingRight: 1,
},
drawHorizontalLine: () => false,
})
.split('\n')
.map((line) => line.trim())
.join('\n')
: rows.map((cols) => cols.join(' ')).join('\n') + '\n';
return prefix + body + suffix;
}
renderTag(tag, value) {
if (Array.isArray(value)) {
return value.map((v) => [`// @${tag}`, v !== null && v !== void 0 ? v : '']);
}
if (typeof value === 'object') {
return Object.entries(value).map(([k, v]) => [
`// @${tag}`,
`${k} ${v !== null && v !== void 0 ? v : ''}`,
]);
}
if (typeof value === 'string') {
return [[`// @${tag}`, value]];
}
if (value === true) {
return [[`// @${tag}`, '']];
}
return [];
}
getTagName(tag) {
return tag.replace(/:.+$/, '');
}
}
exports.RenderHeaders = RenderHeaders;
//# sourceMappingURL=render-headers.js.map