@markdown-design/markdown-it-sanitize
Version:
A markdown-it plugin built on DOMPurify.
61 lines (60 loc) • 2.49 kB
JavaScript
;
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const DOMPurify = require("dompurify");
const transformKeys = /* @__PURE__ */ new Set(["code_inline", "text"]);
const transformer = (params) => {
const { content, md, env, encode } = params;
const outTokens = [];
const state = new md.inline.State(content, md, env, outTokens);
md.inline.tokenize(state);
if (!outTokens.some((token) => token.type === "html_inline")) return "";
const transformFn = encode ? encodeURIComponent : decodeURIComponent;
return outTokens.map((token) => {
const { content: content2, markup, type } = token;
const transformedContent = transformKeys.has(type) ? transformFn(content2) : content2;
return markup + transformedContent + markup;
}).join("");
};
const sanitize = (md, options = {}) => {
if (!md.options.html) return;
md.core.ruler.after("block", "sanitize_block", (state) => {
state.tokens.forEach((token) => {
const { type, content } = token;
if (type !== "html_block") return;
token.content = DOMPurify.sanitize(content, options);
});
});
md.core.ruler.before("inline", "sanitize_inline", (state) => {
state.tokens.forEach((token) => {
if (token.type !== "inline") return;
const content = transformer(__spreadProps(__spreadValues(__spreadValues({}, state), token), {
encode: true
}));
if (!content) return;
token.content = transformer(__spreadProps(__spreadValues({}, state), {
content: DOMPurify.sanitize(content, options),
encode: false
}));
});
});
};
exports.sanitize = sanitize;