@humanonlyweb/writer 0.2.1 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/render.js CHANGED
@@ -1,56 +1,177 @@
1
1
  import { isUploadPlaceholder } from "./placeholder.js";
2
2
  import { NATIVE_TAGS, sanitize } from "./sanitize.js";
3
- import { resolveAttributes, sanitizeData, toNativeAttributes } from "comark/utils";
3
+ import { TREE_WALK_MAX_DEPTH, resolveAttributes, sanitizeData, toNativeAttributes } from "comark/utils";
4
4
  import { Fragment, h } from "vue";
5
5
  // src/render.ts
6
- const childrenOf = (node) => node.slice(2);
7
6
  const own = (map, key) => key !== void 0 && Object.hasOwn(map, key) ? map[key] : void 0;
8
7
  /** The prop a block declares to receive its raw node, as Comark's renderers name it. */
9
8
  const NODE_PROP = "__node";
10
- const declaresNode = (component) => typeof component === "object" && "props" in component && !!component.props && typeof component.props === "object" && "__node" in component.props;
9
+ const ASYNC_RESOLVED = "__asyncResolved";
10
+ function hasNodeProp(props) {
11
+ if (!props || typeof props !== "object") return false;
12
+ return Array.isArray(props) ? props.includes(NODE_PROP) : NODE_PROP in props;
13
+ }
14
+ function declaresNode(component) {
15
+ if (typeof component !== "object" || component === null) return false;
16
+ if ("props" in component && hasNodeProp(component.props)) return true;
17
+ if (ASYNC_RESOLVED in component) {
18
+ const resolved = Reflect.get(component, ASYNC_RESOLVED);
19
+ if (resolved && typeof resolved === "object" && "props" in resolved) return hasNodeProp(resolved.props);
20
+ }
21
+ return false;
22
+ }
11
23
  /** A named slot: `#title` in a block parses to `<template name="title">`. */
12
24
  function slotOf(node) {
13
25
  if (typeof node === "string" || node[0] !== "template") return void 0;
14
- const props = node[1];
15
- const name = typeof props.name === "string" ? props.name : Object.keys(props).find((k) => k.startsWith("v-slot:"))?.slice(7);
26
+ const [, props, ...children] = node;
27
+ let name = typeof props.name === "string" ? props.name : void 0;
28
+ if (!name) {
29
+ for (const k in props) if (Object.hasOwn(props, k) && k.startsWith("v-slot:")) {
30
+ name = k.slice(7);
31
+ break;
32
+ }
33
+ }
16
34
  return name ? {
17
35
  name,
18
- children: childrenOf(node)
36
+ children
19
37
  } : void 0;
20
38
  }
21
- /** The text of `nodes`, for accessible names. */
22
- function plainText(nodes) {
23
- return nodes.map((node) => typeof node === "string" ? node : node[0] === null ? "" : plainText(childrenOf(node))).join("");
39
+ /** The text of `nodes` from `startIndex`, for accessible names. */
40
+ function plainText(nodes, startIndex = 0, depth = 0) {
41
+ if (depth >= TREE_WALK_MAX_DEPTH) return "";
42
+ let out = "";
43
+ for (let i = startIndex; i < nodes.length; i++) {
44
+ const node = nodes[i];
45
+ if (typeof node === "string") out += node;
46
+ else if (node[0] !== null && node.length > 2) {
47
+ const [, , ...children] = node;
48
+ out += plainText(children, 0, depth + 1);
49
+ }
50
+ }
51
+ return out;
24
52
  }
25
53
  const isCheckbox = (node) => typeof node !== "string" && !!node && node[0] === "input" && node[1].type === "checkbox";
26
54
  /** A task list checkbox, named by the text that follows it: `- [x] Buy salt`. */
27
- function labelled(checkbox, rest) {
55
+ function labelled(checkbox, siblings, nextIndex) {
28
56
  if (checkbox[1]["aria-label"] !== void 0) return checkbox;
29
- const label = plainText(rest).trim();
30
- return label ? [
57
+ const label = plainText(siblings, nextIndex).trim();
58
+ if (!label) return checkbox;
59
+ const [, attrs, ...children] = checkbox;
60
+ return [
31
61
  "input",
32
62
  {
33
- ...checkbox[1],
63
+ ...attrs,
34
64
  "aria-label": label
35
65
  },
36
- ...childrenOf(checkbox)
37
- ] : checkbox;
66
+ ...children
67
+ ];
68
+ }
69
+ /** Safe deep clone of plain data objects (tolerates reactive proxies and non-cloneables). */
70
+ function cloneData(value, depth = 0) {
71
+ if (value === null || typeof value !== "object" || depth >= 16) return typeof value === "function" || typeof value === "symbol" ? void 0 : value;
72
+ if (Array.isArray(value)) return value.map((item) => cloneData(item, depth + 1));
73
+ if (value instanceof Date) return new Date(value.getTime());
74
+ return cloneRecord(value, depth);
75
+ }
76
+ function cloneRecord(value, depth = 0) {
77
+ const out = {};
78
+ for (const [key, item] of Object.entries(value)) {
79
+ const cloned = cloneData(item, depth + 1);
80
+ if (cloned !== void 0) out[key] = cloned;
81
+ }
82
+ return out;
83
+ }
84
+ function sanitizeRecord(value) {
85
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
86
+ const cloned = cloneRecord(value);
87
+ sanitizeData(cloned);
88
+ return cloned;
89
+ }
90
+ const preparedCache = /* @__PURE__ */ new WeakMap();
91
+ function cacheKey(blocks, security) {
92
+ const blockKeys = Object.keys(blocks).toSorted().join(",");
93
+ if (!security) return blockKeys;
94
+ return `${blockKeys}|${JSON.stringify(security)}`;
95
+ }
96
+ function prepareDocument(document, blocks, security) {
97
+ const key = cacheKey(blocks, security);
98
+ const cached = preparedCache.get(document);
99
+ if (cached && cached.key === key) return cached;
100
+ const isAllowed = (tag) => NATIVE_TAGS.has(tag) || Object.hasOwn(blocks, tag);
101
+ const entry = {
102
+ key,
103
+ nodes: sanitize(document.nodes ?? [], isAllowed, security),
104
+ frontmatter: sanitizeRecord(document.frontmatter),
105
+ meta: sanitizeRecord(document.meta)
106
+ };
107
+ preparedCache.set(document, entry);
108
+ return entry;
38
109
  }
39
- function renderNode(node, options, data, key, inPre) {
110
+ /** Fast path for nodes inside `<pre>` (e.g. hundreds of syntax-highlighted `<span>` tokens). */
111
+ function renderCodeNode(node, key, depth) {
40
112
  if (typeof node === "string") return node;
41
- if (node[0] === null) return null;
42
- const [tag, attributes] = node;
43
- const children = childrenOf(node).map((child, i, all) => isCheckbox(child) ? labelled(child, all.slice(i + 1)) : child);
113
+ if (node[0] === null || depth >= TREE_WALK_MAX_DEPTH) return null;
114
+ const [tag, attributes, ...children] = node;
115
+ const props = { key };
116
+ for (const k in attributes) {
117
+ if (!Object.hasOwn(attributes, k) || k === "$") continue;
118
+ props[k === "className" ? "class" : k] = attributes[k];
119
+ }
120
+ if (children.length === 0) return h(tag, props);
121
+ if (children.length === 1 && typeof children[0] === "string") return h(tag, props, children[0]);
122
+ const rendered = [];
123
+ for (let i = 0; i < children.length; i++) {
124
+ const child = renderCodeNode(children[i], i, depth + 1);
125
+ if (child !== null) rendered.push(child);
126
+ }
127
+ return h(tag, props, rendered);
128
+ }
129
+ function hasElementChild(children) {
130
+ for (let i = 0; i < children.length; i++) if (typeof children[i] !== "string") return true;
131
+ return false;
132
+ }
133
+ function hasNonMetaAttr(attributes) {
134
+ for (const k in attributes) if (Object.hasOwn(attributes, k) && k !== "$") return true;
135
+ return false;
136
+ }
137
+ function renderNode(node, options, data, key, depth) {
138
+ if (typeof node === "string") return node;
139
+ if (node[0] === null || depth >= TREE_WALK_MAX_DEPTH) return null;
140
+ const [tag, attributes, ...children] = node;
44
141
  const as = typeof attributes.as === "string" ? attributes.as : void 0;
45
- const component = inPre ? void 0 : own(options.blocks, as) ?? own(options.components, tag) ?? own(options.blocks, tag);
142
+ let component;
143
+ let blockName;
144
+ const asBlock = own(options.blocks, as);
145
+ if (asBlock) {
146
+ component = asBlock;
147
+ blockName = as;
148
+ } else {
149
+ const nativeOverride = own(options.components, tag);
150
+ if (nativeOverride) component = nativeOverride;
151
+ else {
152
+ const tagBlock = own(options.blocks, tag);
153
+ if (tagBlock) {
154
+ component = tagBlock;
155
+ blockName = tag;
156
+ }
157
+ }
158
+ }
46
159
  let props = {};
47
- for (const [k, value] of Object.entries(resolveAttributes(attributes, data, { parseJson: true }))) props[k === "className" ? "class" : k] = value;
160
+ const resolved = resolveAttributes(attributes, data, { parseJson: true });
161
+ for (const k in resolved) {
162
+ if (!Object.hasOwn(resolved, k)) continue;
163
+ props[k === "className" ? "class" : k] = resolved[k];
164
+ }
48
165
  if (!component) props = toNativeAttributes(tag, node, props);
49
- else if (declaresNode(component)) props[NODE_PROP] = node;
166
+ else if (blockName !== void 0 && options.nodeBlocks?.has(blockName) || declaresNode(component)) props[NODE_PROP] = node;
50
167
  if (tag === "img" && (!props.src || isUploadPlaceholder(props.src))) return null;
51
168
  if (tag === "a" && isUploadPlaceholder(props.href)) {
52
- const text = children.map((child, i) => renderNode(child, options, data, i, inPre));
53
- return h(Fragment, { key }, text.filter((child) => child !== null));
169
+ const text = [];
170
+ for (let i = 0; i < children.length; i++) {
171
+ const child = renderNode(children[i], options, data, i, depth + 1);
172
+ if (child !== null) text.push(child);
173
+ }
174
+ return h(Fragment, { key }, text);
54
175
  }
55
176
  if (tag === "img") {
56
177
  props.loading ??= "lazy";
@@ -58,40 +179,71 @@ function renderNode(node, options, data, key, inPre) {
58
179
  }
59
180
  if (as && component) delete props.as;
60
181
  props.key = key;
61
- const scope = Object.keys(attributes).some((k) => k !== "$") ? {
182
+ if (tag === "pre" && !component) {
183
+ if (children.length === 0) return h(tag, props);
184
+ const rendered = [];
185
+ for (let i = 0; i < children.length; i++) {
186
+ const child = renderCodeNode(children[i], i, depth + 1);
187
+ if (child !== null) rendered.push(child);
188
+ }
189
+ return h(tag, props, rendered);
190
+ }
191
+ const scope = children.length > 0 && hasNonMetaAttr(attributes) && hasElementChild(children) ? {
62
192
  ...data,
63
193
  props
64
194
  } : data;
65
- const childInPre = inPre || tag === "pre";
66
- const renderChildren = (nodes) => nodes.map((child, i) => renderNode(child, options, scope, i, childInPre)).filter((child) => child !== null);
67
- const image = children[0];
68
- if (tag === "p" && !component && children.length === 1 && typeof image !== "string" && image?.[0] === "img" && typeof image[1].title === "string" && !!image[1].src && !isUploadPlaceholder(image[1].src)) {
69
- const { title, ...rest } = image[1];
70
- return h("figure", { key }, [renderNode(["img", rest], options, scope, 0, childInPre), h("figcaption", null, title)]);
195
+ if (tag === "p" && !component && children.length === 1) {
196
+ const image = children[0];
197
+ if (typeof image !== "string" && image[0] === "img" && typeof image[1].title === "string" && !!image[1].src && !isUploadPlaceholder(image[1].src)) {
198
+ const { title, ...rest } = image[1];
199
+ return h("figure", { key }, [renderNode(["img", rest], options, scope, 0, depth + 1), h("figcaption", null, title)]);
200
+ }
71
201
  }
72
- if (!component) return h(tag, props, children.length ? renderChildren(children) : void 0);
202
+ if (!component) {
203
+ if (children.length === 0) return h(tag, props);
204
+ if (children.length === 1 && typeof children[0] === "string") return h(tag, props, children[0]);
205
+ const checkBoxes = tag === "li" || tag === "p";
206
+ const rendered = [];
207
+ for (let i = 0; i < children.length; i++) {
208
+ const raw = children[i];
209
+ const child = renderNode(checkBoxes && isCheckbox(raw) ? labelled(raw, children, i + 1) : raw, options, scope, i, depth + 1);
210
+ if (child !== null) rendered.push(child);
211
+ }
212
+ return h(tag, props, rendered);
213
+ }
214
+ const renderList = (nodes) => {
215
+ const rendered = [];
216
+ for (let i = 0; i < nodes.length; i++) {
217
+ const child = renderNode(nodes[i], options, scope, i, depth + 1);
218
+ if (child !== null) rendered.push(child);
219
+ }
220
+ return rendered;
221
+ };
73
222
  const slots = {};
74
223
  const rest = [];
75
- for (const child of children) {
224
+ for (let i = 0; i < children.length; i++) {
225
+ const child = children[i];
76
226
  const slot = slotOf(child);
77
- if (slot) slots[slot.name] = () => renderChildren(slot.children);
227
+ if (slot) slots[slot.name] = () => renderList(slot.children);
78
228
  else rest.push(child);
79
229
  }
80
- if (rest.length) slots.default ??= () => renderChildren(rest);
230
+ if (rest.length) slots.default ??= () => renderList(rest);
81
231
  return h(component, props, slots);
82
232
  }
83
233
  /** Renders a parsed document as Vue nodes. Only native Markdown elements and `blocks` render. */
84
234
  function renderDocument(document, options) {
85
- const isAllowed = (tag) => NATIVE_TAGS.has(tag) || Object.hasOwn(options.blocks, tag);
86
- const nodes = sanitize(document.nodes ?? [], isAllowed);
87
- const frontmatter = structuredClone(document.frontmatter ?? {});
88
- sanitizeData(frontmatter);
235
+ const { nodes, frontmatter, meta } = prepareDocument(document, options.blocks, options.security);
89
236
  const data = {
90
237
  frontmatter,
91
- meta: document.meta ?? {},
92
- data: {},
238
+ meta,
239
+ data: options.data ? sanitizeRecord(options.data) : {},
93
240
  props: {}
94
241
  };
95
- return nodes.map((node, i) => renderNode(node, options, data, i, false)).filter((node) => node !== null);
242
+ const result = [];
243
+ for (let i = 0; i < nodes.length; i++) {
244
+ const rendered = renderNode(nodes[i], options, data, i, 0);
245
+ if (rendered !== null) result.push(rendered);
246
+ }
247
+ return result;
96
248
  }
97
249
  export { renderDocument };
@@ -1,3 +1,4 @@
1
+ import { SecurityOptions } from "./parser-options.js";
1
2
  import { Node } from "comark";
2
3
  /** Elements the default Markdown syntax produces. Anything else must be a registered block. */
3
4
  export declare const NATIVE_TAGS: ReadonlySet<string>;
@@ -8,4 +9,5 @@ export declare function isSafeUrl(value: string): boolean;
8
9
  * With `isAllowed`, any other tag it rejects is replaced by its children, so unknown
9
10
  * components never render but their text stays.
10
11
  */
11
- export declare function sanitize(nodes: readonly Node[], isAllowed?: (tag: string) => boolean): Node[];
12
+ export declare function sanitize(nodes: readonly Node[], isAllowed?: (tag: string) => boolean, options?: SecurityOptions): Node[];
13
+ export type { SecurityOptions };
package/dist/sanitize.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { TREE_WALK_MAX_DEPTH } from "comark/utils";
1
2
  // src/sanitize.ts
2
3
  /** Elements the default Markdown syntax produces. Anything else must be a registered block. */
3
4
  const NATIVE_TAGS = /* @__PURE__ */ new Set([
@@ -54,6 +55,7 @@ const DROPPED_TAGS = /* @__PURE__ */ new Set([
54
55
  "textarea",
55
56
  "title"
56
57
  ]);
58
+ /** Attributes whose values are always URLs (must be a non-bound string passing URL validation). */
57
59
  const URL_ATTRIBUTES = /* @__PURE__ */ new Set([
58
60
  "href",
59
61
  "src",
@@ -61,16 +63,59 @@ const URL_ATTRIBUTES = /* @__PURE__ */ new Set([
61
63
  "cite",
62
64
  "action",
63
65
  "background",
64
- "srcset"
66
+ "srcset",
67
+ "to",
68
+ "ping",
69
+ "longdesc",
70
+ "xlinkhref"
65
71
  ]);
72
+ /** Image-bearing URL attributes (checked against `allowedImagePrefixes` and `allowDataImages`). */
73
+ const IMAGE_URL_ATTRIBUTES = /* @__PURE__ */ new Set([
74
+ "src",
75
+ "srcset",
76
+ "poster"
77
+ ]);
78
+ /** Heuristic for custom block props carrying URLs (e.g. `ctaUrl`, `imageSrc`, `externalLink`). */
79
+ const URL_PROP_SUFFIX = /(?:href|src|url|uri|link)s?$/;
66
80
  const BLOCKED_ATTRIBUTES = /* @__PURE__ */ new Set([
67
81
  "srcdoc",
68
82
  "formaction",
69
83
  "is",
70
84
  "innerhtml",
71
85
  "outerhtml",
86
+ "dangerouslysetinnerhtml",
87
+ "textcontent",
88
+ "__v_isvnode",
89
+ "vhtml",
90
+ "vtext"
91
+ ]);
92
+ /** Keys that turn a plain object prop into a Vue component definition or HTML sink. */
93
+ const UNSAFE_OBJECT_KEYS = /* @__PURE__ */ new Set([
94
+ "template",
95
+ "render",
96
+ "ssrrender",
97
+ "setup",
98
+ "extends",
99
+ "mixins",
100
+ "__v_isvnode",
101
+ "__isteleport",
102
+ "__issuspense",
103
+ "__iskeepalive",
104
+ "innerhtml",
105
+ "outerhtml",
106
+ "dangerouslysetinnerhtml",
72
107
  "textcontent"
73
108
  ]);
109
+ /** Task list checkboxes only need these attributes (blocks `form`, `name`, `value`, `autofocus`, …). */
110
+ const CHECKBOX_ATTRIBUTES = /* @__PURE__ */ new Set([
111
+ "type",
112
+ "checked",
113
+ "disabled",
114
+ "aria-label",
115
+ "class"
116
+ ]);
117
+ /** Raw attribute key prefixes used by Vue modifiers/directives that Markdown must never emit. */
118
+ const UNSAFE_KEY_PREFIX = /^[.^@]|^v-(?:bind|on):/i;
74
119
  const SCHEME = /^([a-z][a-z\d+.-]*):/i;
75
120
  const SAFE_SCHEMES = /* @__PURE__ */ new Set([
76
121
  "http",
@@ -79,28 +124,166 @@ const SAFE_SCHEMES = /* @__PURE__ */ new Set([
79
124
  "tel"
80
125
  ]);
81
126
  const DATA_IMAGE = /^data:image\/(?:png|jpe?g|gif|webp|avif|svg\+xml);base64,/i;
82
- const CODE_STYLE = /^(?:\s*(?:color|background-color|font-style|font-weight|text-decoration|--[\w-]+)\s*:\s*[^;:()]*;?)*\s*$/i;
127
+ const CODE_STYLE = /^(?:\s*(?:(?:color|background-color|font-style|font-weight|text-decoration|--[\w-]+)\s*:\s*[^;:()]*|display\s*:\s*inline(?:-block)?)\s*;?)*\s*$/i;
128
+ const HIGHLIGHTER_CLASS = /\b(?:shj|shiki)\b/;
129
+ const NAMED_ENTITIES = {
130
+ amp: "&",
131
+ lt: "<",
132
+ gt: ">",
133
+ quot: "\"",
134
+ apos: "'",
135
+ colon: ":",
136
+ sol: "/",
137
+ bsol: "\\",
138
+ tab: " ",
139
+ newline: "\n"
140
+ };
141
+ function decodeHtmlEntities(value) {
142
+ if (!value.includes("&")) return value;
143
+ let result = value;
144
+ for (let pass = 0; pass < 5; pass++) {
145
+ const decoded = result.replace(/&#x([0-9a-f]+);?/gi, (match, hex) => {
146
+ const code = Number.parseInt(hex, 16);
147
+ return code <= 1114111 ? String.fromCodePoint(code) : match;
148
+ }).replace(/&#(\d+);?/g, (match, dec) => {
149
+ const code = Number.parseInt(dec, 10);
150
+ return code <= 1114111 ? String.fromCodePoint(code) : match;
151
+ }).replace(/&([a-z]+);?/gi, (match, name) => NAMED_ENTITIES[name.toLowerCase()] ?? match);
152
+ if (decoded === result) break;
153
+ result = decoded;
154
+ }
155
+ return result;
156
+ }
157
+ /** Strips ASCII control characters (0x00–0x20, 0x7F) that browsers ignore inside URL schemes. */
158
+ function stripControlAndSpace(value) {
159
+ let out = "";
160
+ let start = 0;
161
+ for (let i = 0; i < value.length; i++) {
162
+ const code = value.charCodeAt(i);
163
+ if (code <= 32 || code === 127) {
164
+ if (i > start) out += value.slice(start, i);
165
+ start = i + 1;
166
+ }
167
+ }
168
+ return start === 0 ? value : out + value.slice(start);
169
+ }
83
170
  /** A relative URL, a fragment, or an http(s)/mailto/tel URL. */
84
171
  function isSafeUrl(value) {
85
- const scheme = SCHEME.exec(value.replace(/[\u0000- \u007F]/g, ""))?.[1];
172
+ const normalized = stripControlAndSpace(decodeHtmlEntities(value));
173
+ const scheme = SCHEME.exec(normalized)?.[1];
86
174
  return !scheme || SAFE_SCHEMES.has(scheme.toLowerCase());
87
175
  }
88
- function cleanAttributes(node, attributes, inCode) {
176
+ /** Whether `value` is a base64 `data:image/…` URL allowed on `<img>`. */
177
+ function isSafeDataImage(value) {
178
+ return DATA_IMAGE.test(value);
179
+ }
180
+ function matchesPrefix(url, prefix) {
181
+ const normalized = prefix.toLowerCase();
182
+ if (!normalized.includes("://")) return url.href.toLowerCase().startsWith(normalized);
183
+ try {
184
+ const allowed = new URL(normalized);
185
+ if (url.origin.toLowerCase() !== allowed.origin.toLowerCase()) return false;
186
+ if (allowed.pathname === "/") return true;
187
+ const path = url.pathname.toLowerCase();
188
+ const base = allowed.pathname.endsWith("/") ? allowed.pathname : `${allowed.pathname}/`;
189
+ return path === allowed.pathname || path.startsWith(base);
190
+ } catch {
191
+ return url.href.toLowerCase().startsWith(normalized);
192
+ }
193
+ }
194
+ function isAllowedUrl(value, isImage, isImgSrc, options) {
195
+ const allowDataImages = options?.allowDataImages ?? true;
196
+ if (isImgSrc && allowDataImages && DATA_IMAGE.test(value)) return true;
197
+ if (!isSafeUrl(value)) return false;
198
+ const prefixes = isImage ? options?.allowedImagePrefixes : options?.allowedLinkPrefixes;
199
+ if (!prefixes || prefixes.includes("*")) return true;
200
+ const normalized = stripControlAndSpace(decodeHtmlEntities(value));
201
+ if (!SCHEME.test(normalized) && !normalized.startsWith("//")) return true;
202
+ try {
203
+ const url = new URL(normalized.startsWith("//") ? `https:${normalized}` : normalized);
204
+ return prefixes.some((prefix) => matchesPrefix(url, prefix));
205
+ } catch {
206
+ return false;
207
+ }
208
+ }
209
+ function hasUnsafeObjectValue(value, depth = 0) {
210
+ if (typeof value !== "object" || value === null) return false;
211
+ if (depth >= 10) return true;
212
+ if (Array.isArray(value)) return value.some((item) => hasUnsafeObjectValue(item, depth + 1));
213
+ for (const [key, item] of Object.entries(value)) {
214
+ const normalized = key.toLowerCase().replace(/^(?:v-bind:|[:.^])+/, "").replace(/^(?:@|v-on:)/, "on").replace(/[:_-]/g, "");
215
+ if (normalized.startsWith("on") || normalized.endsWith("html") || UNSAFE_OBJECT_KEYS.has(normalized)) return true;
216
+ if (hasUnsafeObjectValue(item, depth + 1)) return true;
217
+ }
218
+ return false;
219
+ }
220
+ function normalizeAttrName(key, bound) {
221
+ return (bound ? key.slice(1) : key).toLowerCase().replace(/[:_-]/g, "");
222
+ }
223
+ function isHighlightedElement(attributes) {
224
+ const cls = attributes?.class ?? attributes?.className;
225
+ return typeof cls === "string" && HIGHLIGHTER_CLASS.test(cls);
226
+ }
227
+ function cleanAttributes(node, attributes, inCode, options) {
89
228
  const result = {};
90
- for (const [key, value] of Object.entries(attributes)) {
229
+ const isCheckbox = node === "input";
230
+ const isTemplate = node === "template";
231
+ for (const key in attributes) {
232
+ if (!Object.hasOwn(attributes, key)) continue;
233
+ const value = attributes[key];
91
234
  if (key === "$") {
92
235
  result.$ = attributes.$;
93
236
  continue;
94
237
  }
238
+ if (UNSAFE_KEY_PREFIX.test(key)) continue;
239
+ if (isCheckbox) {
240
+ if (CHECKBOX_ATTRIBUTES.has(key.toLowerCase())) {
241
+ if (options?.stripClasses && key.toLowerCase() === "class") continue;
242
+ result[key] = value;
243
+ }
244
+ continue;
245
+ }
246
+ if (isTemplate) {
247
+ if (key === "name" || key.startsWith("v-slot:")) result[key] = value;
248
+ continue;
249
+ }
95
250
  const bound = key.startsWith(":");
96
- const name = (bound ? key.slice(1) : key).toLowerCase();
97
- if (name.startsWith("on") || BLOCKED_ATTRIBUTES.has(name)) continue;
98
- if (name === "style" && !(inCode && typeof value === "string" && CODE_STYLE.test(value))) continue;
251
+ const name = normalizeAttrName(key, bound);
252
+ if (name.startsWith("on") || name.endsWith("html") || BLOCKED_ATTRIBUTES.has(name)) continue;
253
+ if (options?.stripClasses && (name === "class" || name === "classname")) continue;
254
+ if (options?.stripIds && name === "id") continue;
255
+ if (name === "style") {
256
+ if (bound || !(inCode && typeof value === "string" && CODE_STYLE.test(value))) continue;
257
+ result[key] = value;
258
+ continue;
259
+ }
99
260
  if (URL_ATTRIBUTES.has(name)) {
100
261
  if (bound || typeof value !== "string") continue;
101
- const urls = name === "srcset" ? value.split(",").map((part) => part.trim().split(/\s+/)[0] ?? "") : [value];
102
- if (!(node === "img" && name === "src" && DATA_IMAGE.test(value)) && !urls.every(isSafeUrl)) continue;
262
+ const isImage = IMAGE_URL_ATTRIBUTES.has(name);
263
+ const isImgSrc = node === "img" && name === "src";
264
+ if (!(name === "srcset" ? value.split(",").map((part) => part.trim().split(/\s+/)[0] ?? "") : [value]).every((url) => isAllowedUrl(url, isImage, isImgSrc, options))) continue;
265
+ } else if (URL_PROP_SUFFIX.test(name)) {
266
+ const isImage = name.endsWith("src") || name.endsWith("srcs");
267
+ if (bound) {
268
+ if (typeof value !== "string") {
269
+ if (typeof value !== "boolean" && typeof value !== "number") continue;
270
+ } else {
271
+ let parsed;
272
+ try {
273
+ parsed = JSON.parse(value);
274
+ } catch {
275
+ continue;
276
+ }
277
+ if (typeof parsed === "string") {
278
+ if (!isAllowedUrl(parsed, isImage, false, options)) continue;
279
+ } else if (typeof parsed !== "boolean" && typeof parsed !== "number") continue;
280
+ }
281
+ } else if (typeof value === "string" && !isAllowedUrl(value, isImage, false, options)) continue;
103
282
  }
283
+ if (typeof value === "object" && value !== null && hasUnsafeObjectValue(value)) continue;
284
+ if (bound && typeof value === "string" && (value.startsWith("{") || value.startsWith("["))) try {
285
+ if (hasUnsafeObjectValue(JSON.parse(value))) continue;
286
+ } catch {}
104
287
  result[key] = value;
105
288
  }
106
289
  return result;
@@ -110,30 +293,38 @@ function cleanAttributes(node, attributes, inCode) {
110
293
  * With `isAllowed`, any other tag it rejects is replaced by its children, so unknown
111
294
  * components never render but their text stays.
112
295
  */
113
- function sanitize(nodes, isAllowed) {
114
- return clean(nodes, isAllowed, false);
296
+ function sanitize(nodes, isAllowed, options) {
297
+ return clean(nodes, isAllowed, options, false, false, 0);
115
298
  }
116
- function clean(nodes, isAllowed, inCode) {
299
+ function clean(nodes, isAllowed, options, inCode, parentIsBlock, depth) {
300
+ if (depth >= TREE_WALK_MAX_DEPTH) return [];
117
301
  const result = [];
118
- for (const node of nodes) {
302
+ for (let i = 0; i < nodes.length; i++) {
303
+ const node = nodes[i];
119
304
  if (typeof node === "string" || node[0] === null) {
120
305
  result.push(node);
121
306
  continue;
122
307
  }
123
- const tag = node[0].toLowerCase();
308
+ const [rawTag, rawAttrs, ...rawChildren] = node;
309
+ const tag = rawTag.toLowerCase();
124
310
  if (DROPPED_TAGS.has(tag)) continue;
125
- if (tag === "input" && node[1]?.type !== "checkbox") continue;
126
- const children = clean(node.slice(2), isAllowed, inCode || tag === "pre");
311
+ if (tag === "input" && rawAttrs?.type !== "checkbox") continue;
312
+ const highlighted = (tag === "pre" || tag === "code") && isHighlightedElement(rawAttrs);
313
+ const childInCode = inCode || tag === "pre" || highlighted;
314
+ const isBlock = !NATIVE_TAGS.has(tag);
315
+ const children = rawChildren.length ? clean(rawChildren, isAllowed, options, childInCode, isBlock, depth + 1) : [];
316
+ if (tag === "template" && !parentIsBlock) {
317
+ result.push(...children);
318
+ continue;
319
+ }
127
320
  if (isAllowed && !isAllowed(tag)) {
128
321
  result.push(...children);
129
322
  continue;
130
323
  }
131
- result.push([
132
- tag,
133
- cleanAttributes(tag, node[1] ?? {}, inCode),
134
- ...children
135
- ]);
324
+ const out = [tag, rawAttrs ? cleanAttributes(tag, rawAttrs, inCode || highlighted, options) : {}];
325
+ for (let j = 0; j < children.length; j++) out.push(children[j]);
326
+ result.push(out);
136
327
  }
137
328
  return result;
138
329
  }
139
- export { NATIVE_TAGS, isSafeUrl, sanitize };
330
+ export { NATIVE_TAGS, isSafeDataImage, isSafeUrl, sanitize };
package/dist/stats.js CHANGED
@@ -1,8 +1,21 @@
1
1
  // src/stats.ts
2
2
  const WORD = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]|[\p{L}\p{N}]+(?:['’][\p{L}\p{N}]+)*/gu;
3
+ const FRONTMATTER = /^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/;
4
+ const CODE_FENCE = /^ {0,3}(`{3,}|~{3,})[^\n]*\n[\s\S]*?(?:^ {0,3}\1[ \t]*$|(?![\s\S]))/gm;
5
+ const INLINE_ATTRS = /(?<=[)\]*_~`])\{[^}\n]*\}/g;
6
+ const HEADING_ATTRS = /[ \t]\{[#.][^}\n]*\}[ \t]*$/gm;
7
+ const INLINE_CODE = /`[^`\n]*`/g;
8
+ const IMAGE = /!\[[^\]\n]*\]\([^)\n]*\)/g;
9
+ const LINK = /\[([^\]\n]*)\]\([^)\n]*\)/g;
10
+ const FOOTNOTE = /\[\^[^\]\s]+\]:?/g;
11
+ const BLOCK_FENCE = /^\s*:{2,}.*$/gm;
12
+ const URL_PATTERN = /<https?:[^>\s]+>|https?:\/\/\S+/g;
3
13
  /** Words in plain text. */
4
14
  function countTextWords(text) {
5
- return text.match(WORD)?.length ?? 0;
15
+ let count = 0;
16
+ WORD.lastIndex = 0;
17
+ while (WORD.exec(text) !== null) count++;
18
+ return count;
6
19
  }
7
20
  /**
8
21
  * Words a reader sees in Markdown: link text but not URLs, no image syntax, code,
@@ -10,7 +23,20 @@ function countTextWords(text) {
10
23
  * enough to run on every keystroke.
11
24
  */
12
25
  function countWords(markdown) {
13
- return countTextWords(markdown.replace(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/, " ").replace(/^ {0,3}(`{3,}|~{3,})[^\n]*\n[\s\S]*?(?:^ {0,3}\1[ \t]*$|(?![\s\S]))/gm, " ").replace(/(?<=[)\]*_~`])\{[^}\n]*\}/g, "").replace(/[ \t]\{[#.][^}\n]*\}[ \t]*$/gm, " ").replace(/`[^`\n]*`/g, " ").replace(/!\[[^\]\n]*\]\([^)\n]*\)/g, " ").replace(/\[([^\]\n]*)\]\([^)\n]*\)/g, "$1").replace(/\[\^[^\]\s]+\]:?/g, " ").replace(/^\s*:{2,}.*$/gm, " ").replace(/<https?:[^>\s]+>|https?:\/\/\S+/g, " "));
26
+ if (!markdown) return 0;
27
+ let prose = markdown;
28
+ if (prose.startsWith("---")) prose = prose.replace(FRONTMATTER, " ");
29
+ if (prose.includes("```") || prose.includes("~~~")) prose = prose.replace(CODE_FENCE, " ");
30
+ if (prose.includes("{")) prose = prose.replace(INLINE_ATTRS, "").replace(HEADING_ATTRS, " ");
31
+ if (prose.includes("`")) prose = prose.replace(INLINE_CODE, " ");
32
+ if (prose.includes("[")) {
33
+ if (prose.includes("![")) prose = prose.replace(IMAGE, " ");
34
+ prose = prose.replace(LINK, "$1");
35
+ if (prose.includes("[^")) prose = prose.replace(FOOTNOTE, " ");
36
+ }
37
+ if (prose.includes("::")) prose = prose.replace(BLOCK_FENCE, " ");
38
+ if (prose.includes("http")) prose = prose.replace(URL_PATTERN, " ");
39
+ return countTextWords(prose);
14
40
  }
15
41
  /** Minutes to read `words`, at least one. */
16
42
  const readingMinutes = (words, wordsPerMinute = 230) => Math.max(1, Math.round(words / wordsPerMinute));