-
-
Notifications
You must be signed in to change notification settings - Fork 224
/
index.js
188 lines (164 loc) · 5.65 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import { hp2Builder } from '@selderee/plugin-htmlparser2';
import { parseDocument } from 'htmlparser2';
import { DecisionTree } from 'selderee';
import { BlockTextBuilder } from './block-text-builder';
import { limitedDepthRecursive } from './util';
/**
* Compile selectors into a decision tree,
* return a function intended for batch processing.
*
* @param { Options } [options = {}] HtmlToText options (defaults, formatters, user options merged, deduplicated).
* @returns { (html: string, metadata?: any) => string } Pre-configured converter function.
* @static
*/
function compile (options = {}) {
const selectorsWithoutFormat = options.selectors.filter(s => !s.format);
if (selectorsWithoutFormat.length) {
throw new Error(
'Following selectors have no specified format: ' +
selectorsWithoutFormat.map(s => `\`${s.selector}\``).join(', ')
);
}
const picker = new DecisionTree(
options.selectors.map(s => [s.selector, s])
).build(hp2Builder);
if (typeof options.encodeCharacters !== 'function') {
options.encodeCharacters = makeReplacerFromDict(options.encodeCharacters);
}
const baseSelectorsPicker = new DecisionTree(
options.baseElements.selectors.map((s, i) => [s, i + 1])
).build(hp2Builder);
function findBaseElements (dom) {
return findBases(dom, options, baseSelectorsPicker);
}
const limitedWalk = limitedDepthRecursive(
options.limits.maxDepth,
recursiveWalk,
function (dom, builder) {
builder.addInline(options.limits.ellipsis || '');
}
);
return function (html, metadata = undefined) {
return process(html, metadata, options, picker, findBaseElements, limitedWalk);
};
}
/**
* Convert given HTML according to preprocessed options.
*
* @param { string } html HTML content to convert.
* @param { any } metadata Optional metadata for HTML document, for use in formatters.
* @param { Options } options HtmlToText options (preprocessed).
* @param { import('selderee').Picker<DomNode, TagDefinition> } picker
* Tag definition picker for DOM nodes processing.
* @param { (dom: DomNode[]) => DomNode[] } findBaseElements
* Function to extract elements from HTML DOM
* that will only be present in the output text.
* @param { RecursiveCallback } walk Recursive callback.
* @returns { string }
*/
function process (html, metadata, options, picker, findBaseElements, walk) {
const maxInputLength = options.limits.maxInputLength;
if (maxInputLength && html && html.length > maxInputLength) {
console.warn(
`Input length ${html.length} is above allowed limit of ${maxInputLength}. Truncating without ellipsis.`
);
html = html.substring(0, maxInputLength);
}
const document = parseDocument(html, { decodeEntities: options.decodeEntities });
const bases = findBaseElements(document.children);
const builder = new BlockTextBuilder(options, picker, metadata);
walk(bases, builder);
return builder.toString();
}
function findBases (dom, options, baseSelectorsPicker) {
const results = [];
function recursiveWalk (walk, /** @type { DomNode[] } */ dom) {
dom = dom.slice(0, options.limits.maxChildNodes);
for (const elem of dom) {
if (elem.type !== 'tag') {
continue;
}
const pickedSelectorIndex = baseSelectorsPicker.pick1(elem);
if (pickedSelectorIndex > 0) {
results.push({ selectorIndex: pickedSelectorIndex, element: elem });
} else if (elem.children) {
walk(elem.children);
}
if (results.length >= options.limits.maxBaseElements) {
return;
}
}
}
const limitedWalk = limitedDepthRecursive(
options.limits.maxDepth,
recursiveWalk
);
limitedWalk(dom);
if (options.baseElements.orderBy !== 'occurrence') { // 'selectors'
results.sort((a, b) => a.selectorIndex - b.selectorIndex);
}
return (options.baseElements.returnDomByDefault && results.length === 0)
? dom
: results.map(x => x.element);
}
/**
* Function to walk through DOM nodes and accumulate their string representations.
*
* @param { RecursiveCallback } walk Recursive callback.
* @param { DomNode[] } [dom] Nodes array to process.
* @param { BlockTextBuilder } builder Passed around to accumulate output text.
* @private
*/
function recursiveWalk (walk, dom, builder) {
if (!dom) { return; }
const options = builder.options;
const tooManyChildNodes = dom.length > options.limits.maxChildNodes;
if (tooManyChildNodes) {
dom = dom.slice(0, options.limits.maxChildNodes);
dom.push({
data: options.limits.ellipsis,
type: 'text'
});
}
for (const elem of dom) {
switch (elem.type) {
case 'text': {
builder.addInline(elem.data);
break;
}
case 'tag': {
const tagDefinition = builder.picker.pick1(elem);
const format = options.formatters[tagDefinition.format];
format(elem, walk, builder, tagDefinition.options || {});
break;
}
default:
/* do nothing */
break;
}
}
return;
}
/**
* @param { Object<string,string> } dict
* A dictionary where keys are characters to replace
* and values are replacement strings.
*
* @returns { ((str: string) => string) | undefined }
*/
function makeReplacerFromDict (dict) {
if (!dict || Object.keys(dict).length === 0) {
return undefined;
}
const entries = [...Object.entries(dict)];
const regex = new RegExp(
entries
.map(([c]) => `(\\u${(c.charCodeAt(0).toString(16).padStart(4, '0'))})`)
.join('|'),
'g'
);
const values = entries.map(([, v]) => v);
const replacer = (m, ...cgs) => values[cgs.findIndex(cg => cg)];
return (str) => str.replace(regex, replacer);
}
export { compile };