@3kles/richtext-formats 0.0.0-stage → 1.0.0
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/README.md +138 -2
- package/lib/context.d.ts +19 -0
- package/lib/context.js +85 -0
- package/lib/context.js.map +1 -0
- package/lib/html-export.d.ts +8 -0
- package/lib/html-export.js +128 -0
- package/lib/html-export.js.map +1 -0
- package/lib/html-import.d.ts +4 -0
- package/lib/html-import.js +316 -0
- package/lib/html-import.js.map +1 -0
- package/lib/html-parser.d.ts +7 -0
- package/lib/html-parser.js +128 -0
- package/lib/html-parser.js.map +1 -0
- package/lib/plain-text.d.ts +6 -0
- package/lib/plain-text.js +81 -0
- package/lib/plain-text.js.map +1 -0
- package/lib/selection.d.ts +4 -0
- package/lib/selection.js +177 -0
- package/lib/selection.js.map +1 -0
- package/lib/tiptap-import.d.ts +5 -0
- package/lib/tiptap-import.js +470 -0
- package/lib/tiptap-import.js.map +1 -0
- package/lib/tiptap-types.d.ts +22 -0
- package/lib/tiptap-types.js +9 -0
- package/lib/tiptap-types.js.map +1 -0
- package/lib/types.d.ts +39 -0
- package/lib/types.js +11 -0
- package/lib/types.js.map +1 -0
- package/package.json +22 -4
- package/public-api.d.ts +8 -0
- package/public-api.js +8 -0
- package/public-api.js.map +1 -0
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
import { safeLinkPolicy } from '@3kles/richtext-core';
|
|
2
|
+
import { formatOperation } from './context.js';
|
|
3
|
+
import { isElement, parseBoundedHtml } from './html-parser.js';
|
|
4
|
+
const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
|
|
5
|
+
const REMOVED = new Set([
|
|
6
|
+
'script',
|
|
7
|
+
'style',
|
|
8
|
+
'iframe',
|
|
9
|
+
'frame',
|
|
10
|
+
'frameset',
|
|
11
|
+
'object',
|
|
12
|
+
'embed',
|
|
13
|
+
'applet',
|
|
14
|
+
'template',
|
|
15
|
+
'noscript',
|
|
16
|
+
'form',
|
|
17
|
+
'input',
|
|
18
|
+
'button',
|
|
19
|
+
'select',
|
|
20
|
+
'option',
|
|
21
|
+
'optgroup',
|
|
22
|
+
'textarea',
|
|
23
|
+
'fieldset',
|
|
24
|
+
'legend',
|
|
25
|
+
'datalist',
|
|
26
|
+
'img',
|
|
27
|
+
'picture',
|
|
28
|
+
'source',
|
|
29
|
+
'video',
|
|
30
|
+
'audio',
|
|
31
|
+
'track',
|
|
32
|
+
'canvas',
|
|
33
|
+
'map',
|
|
34
|
+
'area',
|
|
35
|
+
'link',
|
|
36
|
+
'meta',
|
|
37
|
+
'base',
|
|
38
|
+
'head',
|
|
39
|
+
'title',
|
|
40
|
+
'table',
|
|
41
|
+
'svg',
|
|
42
|
+
'math',
|
|
43
|
+
'xmp',
|
|
44
|
+
'plaintext',
|
|
45
|
+
'noembed',
|
|
46
|
+
'noframes',
|
|
47
|
+
]);
|
|
48
|
+
const BLOCKS = new Set(['p', 'div', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'li', 'blockquote', 'pre']);
|
|
49
|
+
const INLINE = new Set(['span', 'strong', 'b', 'em', 'i', 'u', 's', 'strike', 'del', 'code', 'a', 'br']);
|
|
50
|
+
const SIMPLE_MARKS = Object.freeze({
|
|
51
|
+
strong: 'bold',
|
|
52
|
+
b: 'bold',
|
|
53
|
+
em: 'italic',
|
|
54
|
+
i: 'italic',
|
|
55
|
+
u: 'underline',
|
|
56
|
+
s: 'strike',
|
|
57
|
+
strike: 'strike',
|
|
58
|
+
del: 'strike',
|
|
59
|
+
code: 'code',
|
|
60
|
+
});
|
|
61
|
+
const HEADING_LEVELS = Object.freeze({
|
|
62
|
+
h1: 1,
|
|
63
|
+
h2: 2,
|
|
64
|
+
h3: 3,
|
|
65
|
+
h4: 4,
|
|
66
|
+
h5: 5,
|
|
67
|
+
h6: 6,
|
|
68
|
+
});
|
|
69
|
+
function attribute(element, name) {
|
|
70
|
+
return element.attrs.find((item) => item.name === name && !item.namespace && !item.prefix)?.value;
|
|
71
|
+
}
|
|
72
|
+
function withMark(marks, mark) {
|
|
73
|
+
return [...marks.filter((existing) => existing.type !== mark.type), mark];
|
|
74
|
+
}
|
|
75
|
+
class InlineBuffer {
|
|
76
|
+
entries = [];
|
|
77
|
+
text(value, marks, preserve) {
|
|
78
|
+
let normalized = value.replace(/\r\n?|\n/gu, ' ');
|
|
79
|
+
if (!preserve) {
|
|
80
|
+
normalized = normalized.replace(/[\t\f ]+/gu, ' ');
|
|
81
|
+
const last = this.entries.at(-1)?.node;
|
|
82
|
+
if (!last || last.type === 'hardBreak' || (last.type === 'text' && last.text.endsWith(' '))) {
|
|
83
|
+
normalized = normalized.replace(/^ /u, '');
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
if (!normalized)
|
|
87
|
+
return;
|
|
88
|
+
const node = marks.length
|
|
89
|
+
? { type: 'text', text: normalized, marks }
|
|
90
|
+
: { type: 'text', text: normalized };
|
|
91
|
+
this.entries.push({ node, preserve });
|
|
92
|
+
}
|
|
93
|
+
break() {
|
|
94
|
+
this.trimEnd();
|
|
95
|
+
this.entries.push({ node: { type: 'hardBreak' }, preserve: false });
|
|
96
|
+
}
|
|
97
|
+
trimEnd() {
|
|
98
|
+
const last = this.entries.at(-1);
|
|
99
|
+
if (!last || last.preserve || last.node.type !== 'text' || !last.node.text.endsWith(' '))
|
|
100
|
+
return;
|
|
101
|
+
const text = last.node.text.slice(0, -1);
|
|
102
|
+
this.entries.pop();
|
|
103
|
+
if (text)
|
|
104
|
+
this.entries.push({ node: { ...last.node, text }, preserve: false });
|
|
105
|
+
}
|
|
106
|
+
take() {
|
|
107
|
+
this.trimEnd();
|
|
108
|
+
const result = this.entries.map((entry) => entry.node);
|
|
109
|
+
this.entries.length = 0;
|
|
110
|
+
return result;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
class HtmlReader {
|
|
114
|
+
context;
|
|
115
|
+
inline = true;
|
|
116
|
+
inspected = new WeakSet();
|
|
117
|
+
constructor(context) {
|
|
118
|
+
this.context = context;
|
|
119
|
+
}
|
|
120
|
+
inspect(element, path) {
|
|
121
|
+
if (element.namespaceURI !== HTML_NAMESPACE || REMOVED.has(element.tagName)) {
|
|
122
|
+
this.context.add('removedElement', 'warning', path, 'An unsupported or active element and its contents were removed.');
|
|
123
|
+
return false;
|
|
124
|
+
}
|
|
125
|
+
if (this.inspected.has(element))
|
|
126
|
+
return true;
|
|
127
|
+
this.inspected.add(element);
|
|
128
|
+
for (const item of element.attrs) {
|
|
129
|
+
const allowed = !item.namespace &&
|
|
130
|
+
!item.prefix &&
|
|
131
|
+
((element.tagName === 'a' && (item.name === 'href' || item.name === 'title')) ||
|
|
132
|
+
(element.tagName === 'ol' && item.name === 'start') ||
|
|
133
|
+
(element.tagName === 'code' && (item.name === 'class' || item.name === 'data-language')) ||
|
|
134
|
+
(element.tagName === 'span' && item.name === 'data-rt-whitespace' && item.value === 'preserve'));
|
|
135
|
+
if (!allowed)
|
|
136
|
+
this.context.add('removedAttribute', 'warning', [...path, 'attributes'], 'An attribute outside the format allowlist was removed.');
|
|
137
|
+
}
|
|
138
|
+
if (!BLOCKS.has(element.tagName) && !INLINE.has(element.tagName)) {
|
|
139
|
+
this.context.add('unsupportedElement', 'warning', path, 'An unsupported wrapper was removed while retaining its safe contents.');
|
|
140
|
+
}
|
|
141
|
+
return true;
|
|
142
|
+
}
|
|
143
|
+
flow(nodes, path = [], inherited = [], preserve = false) {
|
|
144
|
+
const blocks = [];
|
|
145
|
+
const buffer = new InlineBuffer();
|
|
146
|
+
const flush = () => {
|
|
147
|
+
const children = buffer.take();
|
|
148
|
+
if (children.length)
|
|
149
|
+
blocks.push({ type: 'paragraph', children });
|
|
150
|
+
};
|
|
151
|
+
const visit = (node, currentPath, marks, keepWhitespace) => {
|
|
152
|
+
if ('value' in node) {
|
|
153
|
+
buffer.text(node.value, marks, keepWhitespace);
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
if (!isElement(node)) {
|
|
157
|
+
this.context.add('removedElement', 'info', currentPath, 'Non-content HTML metadata was omitted.');
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
if (!this.inspect(node, currentPath))
|
|
161
|
+
return;
|
|
162
|
+
const tag = node.tagName;
|
|
163
|
+
if (BLOCKS.has(tag)) {
|
|
164
|
+
this.inline = false;
|
|
165
|
+
flush();
|
|
166
|
+
if (tag === 'ul' || tag === 'ol')
|
|
167
|
+
blocks.push(this.list(node, currentPath, marks, keepWhitespace));
|
|
168
|
+
else if (tag === 'blockquote') {
|
|
169
|
+
const children = this.flow(node.childNodes, currentPath, marks, keepWhitespace);
|
|
170
|
+
blocks.push({
|
|
171
|
+
type: 'blockquote',
|
|
172
|
+
children: children.length ? children : [{ type: 'paragraph', children: [] }],
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
else if (tag === 'pre')
|
|
176
|
+
blocks.push(this.pre(node, currentPath, marks));
|
|
177
|
+
else {
|
|
178
|
+
const children = this.flow(node.childNodes, currentPath, marks, keepWhitespace);
|
|
179
|
+
if (!children.length)
|
|
180
|
+
children.push({ type: 'paragraph', children: [] });
|
|
181
|
+
const level = HEADING_LEVELS[tag];
|
|
182
|
+
if (level) {
|
|
183
|
+
const first = children[0];
|
|
184
|
+
if (first?.type === 'paragraph')
|
|
185
|
+
children[0] = { type: 'heading', level, children: first.children };
|
|
186
|
+
else {
|
|
187
|
+
this.context.add('structuralRewrite', 'warning', currentPath, 'A heading containing block content required an empty heading boundary.');
|
|
188
|
+
children.unshift({ type: 'heading', level, children: [] });
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
if (tag === 'li')
|
|
192
|
+
this.context.add('structuralRewrite', 'warning', currentPath, 'A list item outside a list was unwrapped.');
|
|
193
|
+
blocks.push(...children);
|
|
194
|
+
}
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
if (tag === 'br') {
|
|
198
|
+
buffer.break();
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
let nextMarks = marks;
|
|
202
|
+
const markType = SIMPLE_MARKS[tag];
|
|
203
|
+
if (markType && markType !== 'link')
|
|
204
|
+
nextMarks = withMark(marks, { type: markType });
|
|
205
|
+
if (tag === 'a') {
|
|
206
|
+
const href = attribute(node, 'href');
|
|
207
|
+
if (href !== undefined) {
|
|
208
|
+
if (safeLinkPolicy(href) &&
|
|
209
|
+
(!this.context.options.linkPolicy || this.context.options.linkPolicy(href))) {
|
|
210
|
+
const title = attribute(node, 'title');
|
|
211
|
+
nextMarks = withMark(marks, title === undefined ? { type: 'link', href } : { type: 'link', href, title });
|
|
212
|
+
}
|
|
213
|
+
else
|
|
214
|
+
this.context.add('unsafeUrl', 'warning', currentPath, 'A link outside the safe URL policy was removed.');
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
const nextWhitespace = keepWhitespace || (tag === 'span' && attribute(node, 'data-rt-whitespace') === 'preserve');
|
|
218
|
+
node.childNodes.forEach((child, index) => visit(child, [...currentPath, index], nextMarks, nextWhitespace));
|
|
219
|
+
};
|
|
220
|
+
nodes.forEach((node, index) => visit(node, [...path, index], inherited, preserve));
|
|
221
|
+
flush();
|
|
222
|
+
return blocks;
|
|
223
|
+
}
|
|
224
|
+
list(element, path, inherited, preserve) {
|
|
225
|
+
const children = [];
|
|
226
|
+
element.childNodes.forEach((node, index) => {
|
|
227
|
+
const childPath = [...path, index];
|
|
228
|
+
if ('value' in node && /^[\t\n\f\r ]*$/u.test(node.value))
|
|
229
|
+
return;
|
|
230
|
+
if (isElement(node) && node.tagName === 'li' && this.inspect(node, childPath)) {
|
|
231
|
+
const blocks = this.flow(node.childNodes, childPath, inherited, preserve);
|
|
232
|
+
if (blocks[0]?.type !== 'paragraph')
|
|
233
|
+
blocks.unshift({ type: 'paragraph', children: [] });
|
|
234
|
+
children.push({ type: 'listItem', children: blocks });
|
|
235
|
+
}
|
|
236
|
+
else {
|
|
237
|
+
const blocks = this.flow([node], childPath, inherited, preserve);
|
|
238
|
+
if (blocks.length) {
|
|
239
|
+
if (blocks[0]?.type !== 'paragraph')
|
|
240
|
+
blocks.unshift({ type: 'paragraph', children: [] });
|
|
241
|
+
children.push({ type: 'listItem', children: blocks });
|
|
242
|
+
this.context.add('structuralRewrite', 'warning', childPath, 'Content outside a list item was wrapped in a list item.');
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
});
|
|
246
|
+
if (!children.length) {
|
|
247
|
+
children.push({ type: 'listItem', children: [{ type: 'paragraph', children: [] }] });
|
|
248
|
+
this.context.add('normalized', 'info', path, 'An empty list received an empty list item.');
|
|
249
|
+
}
|
|
250
|
+
if (element.tagName === 'ul')
|
|
251
|
+
return { type: 'bulletList', children };
|
|
252
|
+
let start = 1;
|
|
253
|
+
const raw = attribute(element, 'start');
|
|
254
|
+
if (raw !== undefined) {
|
|
255
|
+
if (/^[+-]?\d+$/u.test(raw.trim()) && Number.isSafeInteger(Number(raw)))
|
|
256
|
+
start = Number(raw);
|
|
257
|
+
else
|
|
258
|
+
this.context.add('removedAttribute', 'warning', [...path, 'start'], 'An invalid ordered list start was replaced by one.');
|
|
259
|
+
}
|
|
260
|
+
return { type: 'orderedList', start, children };
|
|
261
|
+
}
|
|
262
|
+
pre(element, path, inherited) {
|
|
263
|
+
if (inherited.length)
|
|
264
|
+
this.context.add('unsupportedElement', 'warning', path, 'Inherited text formatting cannot be represented inside a code block.');
|
|
265
|
+
let text = '';
|
|
266
|
+
let language;
|
|
267
|
+
const visit = (node, currentPath) => {
|
|
268
|
+
if ('value' in node)
|
|
269
|
+
text += node.value;
|
|
270
|
+
else if (isElement(node) && this.inspect(node, currentPath)) {
|
|
271
|
+
if (node.tagName === 'br')
|
|
272
|
+
text += '\n';
|
|
273
|
+
else {
|
|
274
|
+
if (node.tagName === 'code') {
|
|
275
|
+
const explicit = attribute(node, 'data-language');
|
|
276
|
+
const className = attribute(node, 'class');
|
|
277
|
+
const token = className
|
|
278
|
+
?.split(/[\t\n\f\r ]+/u)
|
|
279
|
+
.find((item) => /^language-[A-Za-z0-9_+.-]+$/u.test(item));
|
|
280
|
+
if (explicit !== undefined)
|
|
281
|
+
language = explicit;
|
|
282
|
+
else if (token)
|
|
283
|
+
language = token.slice('language-'.length);
|
|
284
|
+
if (className !== undefined && className !== token)
|
|
285
|
+
this.context.add('removedAttribute', 'warning', currentPath, 'Unsupported code classes were omitted.');
|
|
286
|
+
}
|
|
287
|
+
else
|
|
288
|
+
this.context.add('unsupportedElement', 'warning', currentPath, 'Formatting inside a code block was omitted.');
|
|
289
|
+
node.childNodes.forEach((child, index) => visit(child, [...currentPath, index]));
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
};
|
|
293
|
+
element.childNodes.forEach((node, index) => visit(node, [...path, index]));
|
|
294
|
+
const children = text ? [{ type: 'text', text }] : [];
|
|
295
|
+
return language === undefined ? { type: 'codeBlock', children } : { type: 'codeBlock', language, children };
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
export function importHtmlFragment(input, options = {}) {
|
|
299
|
+
return formatOperation(options, (context) => {
|
|
300
|
+
const parsed = parseBoundedHtml(input, context);
|
|
301
|
+
if (!parsed)
|
|
302
|
+
return context.failure();
|
|
303
|
+
const reader = new HtmlReader(context);
|
|
304
|
+
const children = reader.flow(parsed.childNodes);
|
|
305
|
+
const document = context.validate({
|
|
306
|
+
type: 'document',
|
|
307
|
+
children: children.length ? children : [{ type: 'paragraph', children: [] }],
|
|
308
|
+
});
|
|
309
|
+
return document ? context.finish(Object.freeze({ document, inline: reader.inline })) : context.failure();
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
export function importHtml(input, options = {}) {
|
|
313
|
+
const result = importHtmlFragment(input, options);
|
|
314
|
+
return result.ok ? Object.freeze({ ...result, value: result.value.document }) : result;
|
|
315
|
+
}
|
|
316
|
+
//# sourceMappingURL=html-import.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"html-import.js","sourceRoot":"","sources":["../../src/lib/html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Node,\n HeadingNode,\n InlineNode,\n ListItemNode,\n Mark,\n TextNode,\n} from '@3kles/richtext-core';\nimport { safeLinkPolicy } from '@3kles/richtext-core';\nimport type { FormatContext } from './context.js';\nimport { formatOperation } from './context.js';\nimport { isElement, parseBoundedHtml } from './html-parser.js';\nimport type { HtmlElement, HtmlNode } from './html-parser.js';\nimport type { FormatOptions, FormatResult, HtmlFragment } from './types.js';\n\nconst HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';\nconst REMOVED = new Set([\n 'script',\n 'style',\n 'iframe',\n 'frame',\n 'frameset',\n 'object',\n 'embed',\n 'applet',\n 'template',\n 'noscript',\n 'form',\n 'input',\n 'button',\n 'select',\n 'option',\n 'optgroup',\n 'textarea',\n 'fieldset',\n 'legend',\n 'datalist',\n 'img',\n 'picture',\n 'source',\n 'video',\n 'audio',\n 'track',\n 'canvas',\n 'map',\n 'area',\n 'link',\n 'meta',\n 'base',\n 'head',\n 'title',\n 'table',\n 'svg',\n 'math',\n 'xmp',\n 'plaintext',\n 'noembed',\n 'noframes',\n]);\nconst BLOCKS = new Set(['p', 'div', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'li', 'blockquote', 'pre']);\nconst INLINE = new Set(['span', 'strong', 'b', 'em', 'i', 'u', 's', 'strike', 'del', 'code', 'a', 'br']);\nconst SIMPLE_MARKS: Readonly<Record<string, Mark['type'] | undefined>> = Object.freeze({\n strong: 'bold',\n b: 'bold',\n em: 'italic',\n i: 'italic',\n u: 'underline',\n s: 'strike',\n strike: 'strike',\n del: 'strike',\n code: 'code',\n});\nconst HEADING_LEVELS: Readonly<Record<string, HeadingNode['level'] | undefined>> = Object.freeze({\n h1: 1,\n h2: 2,\n h3: 3,\n h4: 4,\n h5: 5,\n h6: 6,\n});\n\nfunction attribute(element: HtmlElement, name: string): string | undefined {\n return element.attrs.find((item) => item.name === name && !item.namespace && !item.prefix)?.value;\n}\n\nfunction withMark(marks: readonly Mark[], mark: Mark): readonly Mark[] {\n return [...marks.filter((existing) => existing.type !== mark.type), mark];\n}\n\ninterface BufferedInline {\n readonly node: InlineNode;\n readonly preserve: boolean;\n}\n\nclass InlineBuffer {\n private readonly entries: BufferedInline[] = [];\n\n text(value: string, marks: readonly Mark[], preserve: boolean): void {\n let normalized = value.replace(/\\r\\n?|\\n/gu, ' ');\n if (!preserve) {\n normalized = normalized.replace(/[\\t\\f ]+/gu, ' ');\n const last = this.entries.at(-1)?.node;\n if (!last || last.type === 'hardBreak' || (last.type === 'text' && last.text.endsWith(' '))) {\n normalized = normalized.replace(/^ /u, '');\n }\n }\n if (!normalized) return;\n const node: TextNode = marks.length\n ? { type: 'text', text: normalized, marks }\n : { type: 'text', text: normalized };\n this.entries.push({ node, preserve });\n }\n\n break(): void {\n this.trimEnd();\n this.entries.push({ node: { type: 'hardBreak' }, preserve: false });\n }\n\n private trimEnd(): void {\n const last = this.entries.at(-1);\n if (!last || last.preserve || last.node.type !== 'text' || !last.node.text.endsWith(' ')) return;\n const text = last.node.text.slice(0, -1);\n this.entries.pop();\n if (text) this.entries.push({ node: { ...last.node, text }, preserve: false });\n }\n\n take(): InlineNode[] {\n this.trimEnd();\n const result = this.entries.map((entry) => entry.node);\n this.entries.length = 0;\n return result;\n }\n}\n\nclass HtmlReader {\n inline = true;\n private readonly inspected = new WeakSet<HtmlElement>();\n\n constructor(private readonly context: FormatContext) {}\n\n private inspect(element: HtmlElement, path: readonly number[]): boolean {\n if (element.namespaceURI !== HTML_NAMESPACE || REMOVED.has(element.tagName)) {\n this.context.add(\n 'removedElement',\n 'warning',\n path,\n 'An unsupported or active element and its contents were removed.',\n );\n return false;\n }\n if (this.inspected.has(element)) return true;\n this.inspected.add(element);\n for (const item of element.attrs) {\n const allowed =\n !item.namespace &&\n !item.prefix &&\n ((element.tagName === 'a' && (item.name === 'href' || item.name === 'title')) ||\n (element.tagName === 'ol' && item.name === 'start') ||\n (element.tagName === 'code' && (item.name === 'class' || item.name === 'data-language')) ||\n (element.tagName === 'span' && item.name === 'data-rt-whitespace' && item.value === 'preserve'));\n if (!allowed)\n this.context.add(\n 'removedAttribute',\n 'warning',\n [...path, 'attributes'],\n 'An attribute outside the format allowlist was removed.',\n );\n }\n if (!BLOCKS.has(element.tagName) && !INLINE.has(element.tagName)) {\n this.context.add(\n 'unsupportedElement',\n 'warning',\n path,\n 'An unsupported wrapper was removed while retaining its safe contents.',\n );\n }\n return true;\n }\n\n flow(\n nodes: readonly HtmlNode[],\n path: readonly number[] = [],\n inherited: readonly Mark[] = [],\n preserve = false,\n ): BlockNode[] {\n const blocks: BlockNode[] = [];\n const buffer = new InlineBuffer();\n const flush = (): void => {\n const children = buffer.take();\n if (children.length) blocks.push({ type: 'paragraph', children });\n };\n const visit = (\n node: HtmlNode,\n currentPath: readonly number[],\n marks: readonly Mark[],\n keepWhitespace: boolean,\n ): void => {\n if ('value' in node) {\n buffer.text(node.value, marks, keepWhitespace);\n return;\n }\n if (!isElement(node)) {\n this.context.add('removedElement', 'info', currentPath, 'Non-content HTML metadata was omitted.');\n return;\n }\n if (!this.inspect(node, currentPath)) return;\n const tag = node.tagName;\n if (BLOCKS.has(tag)) {\n this.inline = false;\n flush();\n if (tag === 'ul' || tag === 'ol') blocks.push(this.list(node, currentPath, marks, keepWhitespace));\n else if (tag === 'blockquote') {\n const children = this.flow(node.childNodes, currentPath, marks, keepWhitespace);\n blocks.push({\n type: 'blockquote',\n children: children.length ? children : [{ type: 'paragraph', children: [] }],\n });\n } else if (tag === 'pre') blocks.push(this.pre(node, currentPath, marks));\n else {\n const children = this.flow(node.childNodes, currentPath, marks, keepWhitespace);\n if (!children.length) children.push({ type: 'paragraph', children: [] });\n const level = HEADING_LEVELS[tag];\n if (level) {\n const first = children[0];\n if (first?.type === 'paragraph')\n children[0] = { type: 'heading', level, children: first.children };\n else {\n this.context.add(\n 'structuralRewrite',\n 'warning',\n currentPath,\n 'A heading containing block content required an empty heading boundary.',\n );\n children.unshift({ type: 'heading', level, children: [] });\n }\n }\n if (tag === 'li')\n this.context.add(\n 'structuralRewrite',\n 'warning',\n currentPath,\n 'A list item outside a list was unwrapped.',\n );\n blocks.push(...children);\n }\n return;\n }\n if (tag === 'br') {\n buffer.break();\n return;\n }\n let nextMarks = marks;\n const markType = SIMPLE_MARKS[tag];\n if (markType && markType !== 'link') nextMarks = withMark(marks, { type: markType });\n if (tag === 'a') {\n const href = attribute(node, 'href');\n if (href !== undefined) {\n if (\n safeLinkPolicy(href) &&\n (!this.context.options.linkPolicy || this.context.options.linkPolicy(href))\n ) {\n const title = attribute(node, 'title');\n nextMarks = withMark(\n marks,\n title === undefined ? { type: 'link', href } : { type: 'link', href, title },\n );\n } else\n this.context.add(\n 'unsafeUrl',\n 'warning',\n currentPath,\n 'A link outside the safe URL policy was removed.',\n );\n }\n }\n const nextWhitespace =\n keepWhitespace || (tag === 'span' && attribute(node, 'data-rt-whitespace') === 'preserve');\n node.childNodes.forEach((child, index) => visit(child, [...currentPath, index], nextMarks, nextWhitespace));\n };\n nodes.forEach((node, index) => visit(node, [...path, index], inherited, preserve));\n flush();\n return blocks;\n }\n\n private list(\n element: HtmlElement,\n path: readonly number[],\n inherited: readonly Mark[],\n preserve: boolean,\n ): BlockNode {\n const children: ListItemNode[] = [];\n element.childNodes.forEach((node, index) => {\n const childPath = [...path, index];\n if ('value' in node && /^[\\t\\n\\f\\r ]*$/u.test(node.value)) return;\n if (isElement(node) && node.tagName === 'li' && this.inspect(node, childPath)) {\n const blocks = this.flow(node.childNodes, childPath, inherited, preserve);\n if (blocks[0]?.type !== 'paragraph') blocks.unshift({ type: 'paragraph', children: [] });\n children.push({ type: 'listItem', children: blocks });\n } else {\n const blocks = this.flow([node], childPath, inherited, preserve);\n if (blocks.length) {\n if (blocks[0]?.type !== 'paragraph') blocks.unshift({ type: 'paragraph', children: [] });\n children.push({ type: 'listItem', children: blocks });\n this.context.add(\n 'structuralRewrite',\n 'warning',\n childPath,\n 'Content outside a list item was wrapped in a list item.',\n );\n }\n }\n });\n if (!children.length) {\n children.push({ type: 'listItem', children: [{ type: 'paragraph', children: [] }] });\n this.context.add('normalized', 'info', path, 'An empty list received an empty list item.');\n }\n if (element.tagName === 'ul') return { type: 'bulletList', children };\n let start = 1;\n const raw = attribute(element, 'start');\n if (raw !== undefined) {\n if (/^[+-]?\\d+$/u.test(raw.trim()) && Number.isSafeInteger(Number(raw))) start = Number(raw);\n else\n this.context.add(\n 'removedAttribute',\n 'warning',\n [...path, 'start'],\n 'An invalid ordered list start was replaced by one.',\n );\n }\n return { type: 'orderedList', start, children };\n }\n\n private pre(element: HtmlElement, path: readonly number[], inherited: readonly Mark[]): BlockNode {\n if (inherited.length)\n this.context.add(\n 'unsupportedElement',\n 'warning',\n path,\n 'Inherited text formatting cannot be represented inside a code block.',\n );\n let text = '';\n let language: string | undefined;\n const visit = (node: HtmlNode, currentPath: readonly number[]): void => {\n if ('value' in node) text += node.value;\n else if (isElement(node) && this.inspect(node, currentPath)) {\n if (node.tagName === 'br') text += '\\n';\n else {\n if (node.tagName === 'code') {\n const explicit = attribute(node, 'data-language');\n const className = attribute(node, 'class');\n const token = className\n ?.split(/[\\t\\n\\f\\r ]+/u)\n .find((item) => /^language-[A-Za-z0-9_+.-]+$/u.test(item));\n if (explicit !== undefined) language = explicit;\n else if (token) language = token.slice('language-'.length);\n if (className !== undefined && className !== token)\n this.context.add(\n 'removedAttribute',\n 'warning',\n currentPath,\n 'Unsupported code classes were omitted.',\n );\n } else\n this.context.add(\n 'unsupportedElement',\n 'warning',\n currentPath,\n 'Formatting inside a code block was omitted.',\n );\n node.childNodes.forEach((child, index) => visit(child, [...currentPath, index]));\n }\n }\n };\n element.childNodes.forEach((node, index) => visit(node, [...path, index]));\n const children: TextNode[] = text ? [{ type: 'text', text }] : [];\n return language === undefined ? { type: 'codeBlock', children } : { type: 'codeBlock', language, children };\n }\n}\n\nexport function importHtmlFragment(input: unknown, options: FormatOptions = {}): FormatResult<HtmlFragment> {\n return formatOperation(options, (context) => {\n const parsed = parseBoundedHtml(input, context);\n if (!parsed) return context.failure();\n const reader = new HtmlReader(context);\n const children = reader.flow(parsed.childNodes);\n const document = context.validate({\n type: 'document',\n children: children.length ? children : [{ type: 'paragraph', children: [] }],\n });\n return document ? context.finish(Object.freeze({ document, inline: reader.inline })) : context.failure();\n });\n}\n\nexport function importHtml(input: unknown, options: FormatOptions = {}): FormatResult<DocumentNode> {\n const result = importHtmlFragment(input, options);\n return result.ok ? Object.freeze({ ...result, value: result.value.document }) : result;\n}\n"]}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { DefaultTreeAdapterTypes } from 'parse5';
|
|
2
|
+
import type { FormatContext } from './context.js';
|
|
3
|
+
export type HtmlNode = DefaultTreeAdapterTypes.ChildNode;
|
|
4
|
+
export type HtmlElement = DefaultTreeAdapterTypes.Element;
|
|
5
|
+
export declare function isElement(node: HtmlNode): node is HtmlElement;
|
|
6
|
+
/** The parser is a pure tree builder. It never creates browser nodes or loads resources. */
|
|
7
|
+
export declare function parseBoundedHtml(input: unknown, context: FormatContext): DefaultTreeAdapterTypes.DocumentFragment | undefined;
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { defaultTreeAdapter, parseFragment } from 'parse5';
|
|
2
|
+
import { isWellFormedText } from '@3kles/richtext-core';
|
|
3
|
+
import { FormatLimitError } from './context.js';
|
|
4
|
+
export function isElement(node) {
|
|
5
|
+
return 'tagName' in node;
|
|
6
|
+
}
|
|
7
|
+
/** The parser is a pure tree builder. It never creates browser nodes or loads resources. */
|
|
8
|
+
export function parseBoundedHtml(input, context) {
|
|
9
|
+
if (typeof input !== 'string') {
|
|
10
|
+
context.add('invalidInput', 'error', [], 'HTML input must be a string.');
|
|
11
|
+
return undefined;
|
|
12
|
+
}
|
|
13
|
+
if (input.length > context.limits.maxHtmlLength)
|
|
14
|
+
throw new FormatLimitError('HTML source length exceeds its limit.');
|
|
15
|
+
if (!isWellFormedText(input) || input.includes('\0')) {
|
|
16
|
+
context.add('invalidUnicode', 'error', [], 'HTML input must contain valid Unicode without NUL.');
|
|
17
|
+
return undefined;
|
|
18
|
+
}
|
|
19
|
+
let allocations = 0;
|
|
20
|
+
let textLength = 0;
|
|
21
|
+
const allocate = () => {
|
|
22
|
+
// parseFragment creates a small synthetic context in addition to source nodes.
|
|
23
|
+
if (++allocations > context.limits.maxNodes + 8)
|
|
24
|
+
throw new FormatLimitError('HTML node allocation exceeds its limit.');
|
|
25
|
+
};
|
|
26
|
+
const text = (value) => {
|
|
27
|
+
textLength += value.length;
|
|
28
|
+
if (textLength > context.limits.maxTextLength)
|
|
29
|
+
throw new FormatLimitError('HTML text length exceeds its limit.');
|
|
30
|
+
};
|
|
31
|
+
const attributes = (attrs) => {
|
|
32
|
+
if (attrs.length > context.limits.maxAttributesPerElement)
|
|
33
|
+
throw new FormatLimitError('HTML attribute count exceeds its limit.');
|
|
34
|
+
for (const attribute of attrs) {
|
|
35
|
+
if (attribute.name.length + attribute.value.length > context.limits.maxAttributeLength) {
|
|
36
|
+
throw new FormatLimitError('An HTML attribute exceeds its length limit.');
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
const parentDepth = (parent) => {
|
|
41
|
+
let current = parent;
|
|
42
|
+
let depth = 0;
|
|
43
|
+
while (current) {
|
|
44
|
+
if (++depth > context.limits.maxDepth + 4)
|
|
45
|
+
throw new FormatLimitError('HTML nesting exceeds its depth limit.');
|
|
46
|
+
current = 'parentNode' in current ? current.parentNode : null;
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
const adapter = {
|
|
50
|
+
...defaultTreeAdapter,
|
|
51
|
+
createElement(tagName, namespace, attrs) {
|
|
52
|
+
allocate();
|
|
53
|
+
attributes(attrs);
|
|
54
|
+
return defaultTreeAdapter.createElement(tagName, namespace, attrs);
|
|
55
|
+
},
|
|
56
|
+
createCommentNode(value) {
|
|
57
|
+
allocate();
|
|
58
|
+
text(value);
|
|
59
|
+
return defaultTreeAdapter.createCommentNode(value);
|
|
60
|
+
},
|
|
61
|
+
createTextNode(value) {
|
|
62
|
+
allocate();
|
|
63
|
+
text(value);
|
|
64
|
+
return defaultTreeAdapter.createTextNode(value);
|
|
65
|
+
},
|
|
66
|
+
insertText(parent, value) {
|
|
67
|
+
text(value);
|
|
68
|
+
const previous = parent.childNodes.at(-1);
|
|
69
|
+
if (!previous || !defaultTreeAdapter.isTextNode(previous))
|
|
70
|
+
allocate();
|
|
71
|
+
defaultTreeAdapter.insertText(parent, value);
|
|
72
|
+
},
|
|
73
|
+
insertTextBefore(parent, value, reference) {
|
|
74
|
+
text(value);
|
|
75
|
+
const previous = parent.childNodes[parent.childNodes.indexOf(reference) - 1];
|
|
76
|
+
if (!previous || !defaultTreeAdapter.isTextNode(previous))
|
|
77
|
+
allocate();
|
|
78
|
+
defaultTreeAdapter.insertTextBefore(parent, value, reference);
|
|
79
|
+
},
|
|
80
|
+
appendChild(parent, child) {
|
|
81
|
+
parentDepth(parent);
|
|
82
|
+
defaultTreeAdapter.appendChild(parent, child);
|
|
83
|
+
},
|
|
84
|
+
insertBefore(parent, child, reference) {
|
|
85
|
+
parentDepth(parent);
|
|
86
|
+
defaultTreeAdapter.insertBefore(parent, child, reference);
|
|
87
|
+
},
|
|
88
|
+
adoptAttributes(recipient, attrs) {
|
|
89
|
+
attributes(attrs);
|
|
90
|
+
defaultTreeAdapter.adoptAttributes(recipient, attrs);
|
|
91
|
+
attributes(recipient.attrs);
|
|
92
|
+
},
|
|
93
|
+
};
|
|
94
|
+
const fragment = parseFragment(input, {
|
|
95
|
+
treeAdapter: adapter,
|
|
96
|
+
scriptingEnabled: true,
|
|
97
|
+
onParseError(error) {
|
|
98
|
+
const characterNotice = error.code === 'control-character-reference' ||
|
|
99
|
+
error.code === 'noncharacter-character-reference' ||
|
|
100
|
+
error.code === 'control-character-in-input-stream' ||
|
|
101
|
+
error.code === 'noncharacter-in-input-stream';
|
|
102
|
+
context.add('malformedHtml', characterNotice ? 'info' : 'warning', [], characterNotice
|
|
103
|
+
? 'The HTML parser reported a non-canonical character encoding.'
|
|
104
|
+
: 'The HTML parser repaired malformed input.');
|
|
105
|
+
},
|
|
106
|
+
});
|
|
107
|
+
const pending = fragment.childNodes.map((node) => ({
|
|
108
|
+
node,
|
|
109
|
+
depth: 1,
|
|
110
|
+
}));
|
|
111
|
+
let count = 0;
|
|
112
|
+
while (pending.length) {
|
|
113
|
+
const entry = pending.pop();
|
|
114
|
+
if (!entry)
|
|
115
|
+
break;
|
|
116
|
+
if (++count > context.limits.maxNodes)
|
|
117
|
+
throw new FormatLimitError('HTML node count exceeds its limit.');
|
|
118
|
+
if (entry.depth > context.limits.maxDepth)
|
|
119
|
+
throw new FormatLimitError('HTML nesting exceeds its depth limit.');
|
|
120
|
+
if (isElement(entry.node)) {
|
|
121
|
+
const children = 'content' in entry.node ? entry.node.content.childNodes : entry.node.childNodes;
|
|
122
|
+
for (const node of children)
|
|
123
|
+
pending.push({ node, depth: entry.depth + 1 });
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return fragment;
|
|
127
|
+
}
|
|
128
|
+
//# sourceMappingURL=html-parser.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"html-parser.js","sourceRoot":"","sources":["../../src/lib/html-parser.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AAE3D,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAExD,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAKhD,MAAM,UAAU,SAAS,CAAC,IAAc;IACpC,OAAO,SAAS,IAAI,IAAI,CAAC;AAC7B,CAAC;AAED,4FAA4F;AAC5F,MAAM,UAAU,gBAAgB,CAC5B,KAAc,EACd,OAAsB;IAEtB,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC5B,OAAO,CAAC,GAAG,CAAC,cAAc,EAAE,OAAO,EAAE,EAAE,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AI,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,CAAC,KAAK,GAAG,CAAC,EAAE,CAAC,CAAC;QAChF,CAAC;IACL,CAAC;IACD,OAAO,QAAQ,CAAC;AACpB,CAAC","sourcesContent":["import { defaultTreeAdapter, parseFragment } from 'parse5';\nimport type { DefaultTreeAdapterMap, DefaultTreeAdapterTypes, TreeAdapter } from 'parse5';\nimport { isWellFormedText } from '@3kles/richtext-core';\nimport type { FormatContext } from './context.js';\nimport { FormatLimitError } from './context.js';\n\nexport type HtmlNode = DefaultTreeAdapterTypes.ChildNode;\nexport type HtmlElement = DefaultTreeAdapterTypes.Element;\n\nexport function isElement(node: HtmlNode): node is HtmlElement {\n return 'tagName' in node;\n}\n\n/** The parser is a pure tree builder. It never creates browser nodes or loads resources. */\nexport function parseBoundedHtml(\n input: unknown,\n context: FormatContext,\n): DefaultTreeAdapterTypes.DocumentFragment | undefined {\n if (typeof input !== 'string') {\n context.add('invalidInput', 'error', [], 'HTML input must be a string.');\n return undefined;\n }\n if (input.length > context.limits.maxHtmlLength)\n throw new FormatLimitError('HTML source length exceeds its limit.');\n if (!isWellFormedText(input) || input.includes('\\0')) {\n context.add('invalidUnicode', 'error', [], 'HTML input must contain valid Unicode without NUL.');\n return undefined;\n }\n let allocations = 0;\n let textLength = 0;\n const allocate = (): void => {\n // parseFragment creates a small synthetic context in addition to source nodes.\n if (++allocations > context.limits.maxNodes + 8)\n throw new FormatLimitError('HTML node allocation exceeds its limit.');\n };\n const text = (value: string): void => {\n textLength += value.length;\n if (textLength > context.limits.maxTextLength)\n throw new FormatLimitError('HTML text length exceeds its limit.');\n };\n const attributes = (attrs: HtmlElement['attrs']): void => {\n if (attrs.length > context.limits.maxAttributesPerElement)\n throw new FormatLimitError('HTML attribute count exceeds its limit.');\n for (const attribute of attrs) {\n if (attribute.name.length + attribute.value.length > context.limits.maxAttributeLength) {\n throw new FormatLimitError('An HTML attribute exceeds its length limit.');\n }\n }\n };\n const parentDepth = (parent: DefaultTreeAdapterTypes.ParentNode): void => {\n let current: DefaultTreeAdapterTypes.ParentNode | null = parent;\n let depth = 0;\n while (current) {\n if (++depth > context.limits.maxDepth + 4)\n throw new FormatLimitError('HTML nesting exceeds its depth limit.');\n current = 'parentNode' in current ? current.parentNode : null;\n }\n };\n const adapter: TreeAdapter<DefaultTreeAdapterMap> = {\n ...defaultTreeAdapter,\n createElement(tagName, namespace, attrs) {\n allocate();\n attributes(attrs);\n return defaultTreeAdapter.createElement(tagName, namespace, attrs);\n },\n createCommentNode(value) {\n allocate();\n text(value);\n return defaultTreeAdapter.createCommentNode(value);\n },\n createTextNode(value) {\n allocate();\n text(value);\n return defaultTreeAdapter.createTextNode(value);\n },\n insertText(parent, value) {\n text(value);\n const previous = parent.childNodes.at(-1);\n if (!previous || !defaultTreeAdapter.isTextNode(previous)) allocate();\n defaultTreeAdapter.insertText(parent, value);\n },\n insertTextBefore(parent, value, reference) {\n text(value);\n const previous = parent.childNodes[parent.childNodes.indexOf(reference) - 1];\n if (!previous || !defaultTreeAdapter.isTextNode(previous)) allocate();\n defaultTreeAdapter.insertTextBefore(parent, value, reference);\n },\n appendChild(parent, child) {\n parentDepth(parent);\n defaultTreeAdapter.appendChild(parent, child);\n },\n insertBefore(parent, child, reference) {\n parentDepth(parent);\n defaultTreeAdapter.insertBefore(parent, child, reference);\n },\n adoptAttributes(recipient, attrs) {\n attributes(attrs);\n defaultTreeAdapter.adoptAttributes(recipient, attrs);\n attributes(recipient.attrs);\n },\n };\n const fragment = parseFragment(input, {\n treeAdapter: adapter,\n scriptingEnabled: true,\n onParseError(error) {\n const characterNotice =\n error.code === 'control-character-reference' ||\n error.code === 'noncharacter-character-reference' ||\n error.code === 'control-character-in-input-stream' ||\n error.code === 'noncharacter-in-input-stream';\n context.add(\n 'malformedHtml',\n characterNotice ? 'info' : 'warning',\n [],\n characterNotice\n ? 'The HTML parser reported a non-canonical character encoding.'\n : 'The HTML parser repaired malformed input.',\n );\n },\n });\n const pending: { readonly node: HtmlNode; readonly depth: number }[] = fragment.childNodes.map((node) => ({\n node,\n depth: 1,\n }));\n let count = 0;\n while (pending.length) {\n const entry = pending.pop();\n if (!entry) break;\n if (++count > context.limits.maxNodes) throw new FormatLimitError('HTML node count exceeds its limit.');\n if (entry.depth > context.limits.maxDepth) throw new FormatLimitError('HTML nesting exceeds its depth limit.');\n if (isElement(entry.node)) {\n const children = 'content' in entry.node ? entry.node.content.childNodes : entry.node.childNodes;\n for (const node of children) pending.push({ node, depth: entry.depth + 1 });\n }\n }\n return fragment;\n}\n"]}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { DocumentNode } from '@3kles/richtext-core';
|
|
2
|
+
import type { FormatContext } from './context.js';
|
|
3
|
+
import type { FormatOptions, FormatResult } from './types.js';
|
|
4
|
+
export declare function importPlainText(input: unknown, options?: FormatOptions): FormatResult<DocumentNode>;
|
|
5
|
+
export declare function writePlainText(document: DocumentNode, context: FormatContext): string;
|
|
6
|
+
export declare function exportPlainText(document: unknown, options?: FormatOptions): FormatResult<string>;
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { getTextBlockText, isWellFormedText } from '@3kles/richtext-core';
|
|
2
|
+
import { FormatLimitError, formatOperation } from './context.js';
|
|
3
|
+
export function importPlainText(input, options = {}) {
|
|
4
|
+
return formatOperation(options, (context) => {
|
|
5
|
+
if (typeof input !== 'string') {
|
|
6
|
+
context.add('invalidInput', 'error', [], 'Plain text input must be a string.');
|
|
7
|
+
return context.failure();
|
|
8
|
+
}
|
|
9
|
+
if (input.length > context.limits.maxTextLength)
|
|
10
|
+
throw new FormatLimitError('Plain text length exceeds its limit.');
|
|
11
|
+
if (!isWellFormedText(input) || input.includes('\0')) {
|
|
12
|
+
context.add('invalidUnicode', 'error', [], 'Plain text must contain valid Unicode without NUL.');
|
|
13
|
+
return context.failure();
|
|
14
|
+
}
|
|
15
|
+
const normalized = input.replace(/\r\n?/gu, '\n');
|
|
16
|
+
if (normalized !== input)
|
|
17
|
+
context.add('normalized', 'info', [], 'Line endings were normalized to LF.');
|
|
18
|
+
let paragraphs = 1;
|
|
19
|
+
let textNodes = 0;
|
|
20
|
+
let hasText = false;
|
|
21
|
+
for (const character of normalized) {
|
|
22
|
+
if (character === '\n') {
|
|
23
|
+
paragraphs++;
|
|
24
|
+
if (hasText)
|
|
25
|
+
textNodes++;
|
|
26
|
+
hasText = false;
|
|
27
|
+
}
|
|
28
|
+
else
|
|
29
|
+
hasText = true;
|
|
30
|
+
if (1 + paragraphs + textNodes > context.limits.maxNodes)
|
|
31
|
+
throw new FormatLimitError('Plain text paragraph count exceeds its limit.');
|
|
32
|
+
}
|
|
33
|
+
if (hasText)
|
|
34
|
+
textNodes++;
|
|
35
|
+
if (1 + paragraphs + textNodes > context.limits.maxNodes)
|
|
36
|
+
throw new FormatLimitError('Plain text paragraph count exceeds its limit.');
|
|
37
|
+
const lines = normalized.split('\n');
|
|
38
|
+
const document = context.validate({
|
|
39
|
+
type: 'document',
|
|
40
|
+
children: lines.map((line) => ({
|
|
41
|
+
type: 'paragraph',
|
|
42
|
+
children: line ? [{ type: 'text', text: line }] : [],
|
|
43
|
+
})),
|
|
44
|
+
});
|
|
45
|
+
return document ? context.finish(document) : context.failure();
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
export function writePlainText(document, context) {
|
|
49
|
+
let structuralLoss = false;
|
|
50
|
+
let marksLoss = false;
|
|
51
|
+
const blockText = (node) => {
|
|
52
|
+
if (node.type === 'paragraph' || node.type === 'heading' || node.type === 'codeBlock') {
|
|
53
|
+
if (node.type !== 'paragraph')
|
|
54
|
+
structuralLoss = true;
|
|
55
|
+
if (node.children.some((child) => child.type === 'hardBreak'))
|
|
56
|
+
structuralLoss = true;
|
|
57
|
+
if (node.children.some((child) => child.type === 'text' && child.marks?.length))
|
|
58
|
+
marksLoss = true;
|
|
59
|
+
return getTextBlockText(node);
|
|
60
|
+
}
|
|
61
|
+
structuralLoss = true;
|
|
62
|
+
if (node.type === 'blockquote')
|
|
63
|
+
return node.children.map(blockText).join('\n');
|
|
64
|
+
return node.children.map((item) => item.children.map(blockText).join('\n')).join('\n');
|
|
65
|
+
};
|
|
66
|
+
const result = document.children.map(blockText).join('\n');
|
|
67
|
+
if (result.includes('\0'))
|
|
68
|
+
context.add('invalidUnicode', 'error', [], 'Plain text output cannot contain NUL.');
|
|
69
|
+
if (result.length > context.limits.maxOutputLength)
|
|
70
|
+
throw new FormatLimitError('Plain text output length exceeds its limit.');
|
|
71
|
+
if (structuralLoss || marksLoss)
|
|
72
|
+
context.add('plainTextLoss', 'warning', [], 'Plain text omits rich structure, marks and link metadata.');
|
|
73
|
+
return result;
|
|
74
|
+
}
|
|
75
|
+
export function exportPlainText(document, options = {}) {
|
|
76
|
+
return formatOperation(options, (context) => {
|
|
77
|
+
const validated = context.validate(document);
|
|
78
|
+
return validated ? context.finish(writePlainText(validated, context)) : context.failure();
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
//# sourceMappingURL=plain-text.js.map
|