llm-large-files 0.5.0 → 0.8.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.
Files changed (285) hide show
  1. package/CHANGELOG.md +1719 -466
  2. package/README.md +190 -60
  3. package/dist/analyze.d.ts +8 -1
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +198 -54
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts +14 -3
  8. package/dist/anthropic/adapter.d.ts.map +1 -1
  9. package/dist/anthropic/adapter.js +194 -40
  10. package/dist/anthropic/adapter.js.map +1 -1
  11. package/dist/ask.d.ts +63 -7
  12. package/dist/ask.d.ts.map +1 -1
  13. package/dist/ask.js +1131 -214
  14. package/dist/ask.js.map +1 -1
  15. package/dist/decode.d.ts +19 -0
  16. package/dist/decode.d.ts.map +1 -0
  17. package/dist/decode.js +97 -0
  18. package/dist/decode.js.map +1 -0
  19. package/dist/encoding.d.ts +17 -0
  20. package/dist/encoding.d.ts.map +1 -0
  21. package/dist/encoding.js +852 -0
  22. package/dist/encoding.js.map +1 -0
  23. package/dist/errors.d.ts +59 -0
  24. package/dist/errors.d.ts.map +1 -1
  25. package/dist/errors.js +80 -0
  26. package/dist/errors.js.map +1 -1
  27. package/dist/events.d.ts +339 -0
  28. package/dist/events.d.ts.map +1 -0
  29. package/dist/events.js +163 -0
  30. package/dist/events.js.map +1 -0
  31. package/dist/evidence.d.ts +2 -0
  32. package/dist/evidence.d.ts.map +1 -1
  33. package/dist/evidence.js +9 -2
  34. package/dist/evidence.js.map +1 -1
  35. package/dist/extract.d.ts +26 -7
  36. package/dist/extract.d.ts.map +1 -1
  37. package/dist/extract.js +180 -314
  38. package/dist/extract.js.map +1 -1
  39. package/dist/gemini/adapter.d.ts +17 -8
  40. package/dist/gemini/adapter.d.ts.map +1 -1
  41. package/dist/gemini/adapter.js +117 -66
  42. package/dist/gemini/adapter.js.map +1 -1
  43. package/dist/gemini/chat.d.ts +23 -3
  44. package/dist/gemini/chat.d.ts.map +1 -1
  45. package/dist/gemini/chat.js +6 -2
  46. package/dist/gemini/chat.js.map +1 -1
  47. package/dist/gemini/endpoints.d.ts +5 -1
  48. package/dist/gemini/endpoints.d.ts.map +1 -1
  49. package/dist/gemini/endpoints.js +11 -2
  50. package/dist/gemini/endpoints.js.map +1 -1
  51. package/dist/gemini/errors.d.ts +9 -4
  52. package/dist/gemini/errors.d.ts.map +1 -1
  53. package/dist/gemini/errors.js +32 -0
  54. package/dist/gemini/errors.js.map +1 -1
  55. package/dist/gemini/generate.d.ts +10 -2
  56. package/dist/gemini/generate.d.ts.map +1 -1
  57. package/dist/gemini/generate.js +33 -10
  58. package/dist/gemini/generate.js.map +1 -1
  59. package/dist/gemini/index.d.ts +3 -3
  60. package/dist/gemini/index.d.ts.map +1 -1
  61. package/dist/gemini/index.js +2 -2
  62. package/dist/gemini/index.js.map +1 -1
  63. package/dist/gemini/sse.d.ts +1 -1
  64. package/dist/gemini/sse.d.ts.map +1 -1
  65. package/dist/gemini/sse.js +1 -1
  66. package/dist/gemini/sse.js.map +1 -1
  67. package/dist/groups.d.ts +54 -0
  68. package/dist/groups.d.ts.map +1 -0
  69. package/dist/groups.js +136 -0
  70. package/dist/groups.js.map +1 -0
  71. package/dist/html.d.ts +11 -0
  72. package/dist/html.d.ts.map +1 -0
  73. package/dist/html.js +1112 -0
  74. package/dist/html.js.map +1 -0
  75. package/dist/http.d.ts +116 -0
  76. package/dist/http.d.ts.map +1 -1
  77. package/dist/http.js +347 -1
  78. package/dist/http.js.map +1 -1
  79. package/dist/index.d.ts +13 -7
  80. package/dist/index.d.ts.map +1 -1
  81. package/dist/index.js +7 -5
  82. package/dist/index.js.map +1 -1
  83. package/dist/library.d.ts +67 -5
  84. package/dist/library.d.ts.map +1 -1
  85. package/dist/library.js +449 -93
  86. package/dist/library.js.map +1 -1
  87. package/dist/limiter.d.ts +2 -1
  88. package/dist/limiter.d.ts.map +1 -1
  89. package/dist/limiter.js +3 -2
  90. package/dist/limiter.js.map +1 -1
  91. package/dist/map-reduce.d.ts +28 -1
  92. package/dist/map-reduce.d.ts.map +1 -1
  93. package/dist/map-reduce.js +240 -52
  94. package/dist/map-reduce.js.map +1 -1
  95. package/dist/model.d.ts +84 -2
  96. package/dist/model.d.ts.map +1 -1
  97. package/dist/model.js +190 -2
  98. package/dist/model.js.map +1 -1
  99. package/dist/node/handlers.d.ts +20 -4
  100. package/dist/node/handlers.d.ts.map +1 -1
  101. package/dist/node/handlers.js +184 -28
  102. package/dist/node/handlers.js.map +1 -1
  103. package/dist/node/index.d.ts +4 -0
  104. package/dist/node/index.d.ts.map +1 -1
  105. package/dist/node/index.js +2 -0
  106. package/dist/node/index.js.map +1 -1
  107. package/dist/node/ingest-child.d.ts +38 -0
  108. package/dist/node/ingest-child.d.ts.map +1 -0
  109. package/dist/node/ingest-child.js +42 -0
  110. package/dist/node/ingest-child.js.map +1 -0
  111. package/dist/node/isolated.d.ts +88 -0
  112. package/dist/node/isolated.d.ts.map +1 -0
  113. package/dist/node/isolated.js +381 -0
  114. package/dist/node/isolated.js.map +1 -0
  115. package/dist/node/sse.d.ts +59 -0
  116. package/dist/node/sse.d.ts.map +1 -0
  117. package/dist/node/sse.js +174 -0
  118. package/dist/node/sse.js.map +1 -0
  119. package/dist/office.d.ts +105 -0
  120. package/dist/office.d.ts.map +1 -0
  121. package/dist/office.js +1092 -0
  122. package/dist/office.js.map +1 -0
  123. package/dist/openai/adapter.d.ts +29 -5
  124. package/dist/openai/adapter.d.ts.map +1 -1
  125. package/dist/openai/adapter.js +325 -37
  126. package/dist/openai/adapter.js.map +1 -1
  127. package/dist/output-limit.d.ts +14 -2
  128. package/dist/output-limit.d.ts.map +1 -1
  129. package/dist/output-limit.js +39 -10
  130. package/dist/output-limit.js.map +1 -1
  131. package/dist/pause.d.ts +24 -0
  132. package/dist/pause.d.ts.map +1 -0
  133. package/dist/pause.js +38 -0
  134. package/dist/pause.js.map +1 -0
  135. package/dist/pdf-pages.d.ts +32 -2
  136. package/dist/pdf-pages.d.ts.map +1 -1
  137. package/dist/pdf-pages.js +277 -20
  138. package/dist/pdf-pages.js.map +1 -1
  139. package/dist/pdf-pictures.d.ts +30 -3
  140. package/dist/pdf-pictures.d.ts.map +1 -1
  141. package/dist/pdf-pictures.js +50 -8
  142. package/dist/pdf-pictures.js.map +1 -1
  143. package/dist/pdf-work.d.ts +40 -0
  144. package/dist/pdf-work.d.ts.map +1 -0
  145. package/dist/pdf-work.js +734 -0
  146. package/dist/pdf-work.js.map +1 -0
  147. package/dist/peers.d.ts +8 -0
  148. package/dist/peers.d.ts.map +1 -0
  149. package/dist/peers.js +32 -0
  150. package/dist/peers.js.map +1 -0
  151. package/dist/plan.d.ts +22 -4
  152. package/dist/plan.d.ts.map +1 -1
  153. package/dist/plan.js +61 -12
  154. package/dist/plan.js.map +1 -1
  155. package/dist/ranged.d.ts.map +1 -1
  156. package/dist/ranged.js +4 -2
  157. package/dist/ranged.js.map +1 -1
  158. package/dist/retry.d.ts +23 -1
  159. package/dist/retry.d.ts.map +1 -1
  160. package/dist/retry.js +33 -3
  161. package/dist/retry.js.map +1 -1
  162. package/dist/search.d.ts +107 -24
  163. package/dist/search.d.ts.map +1 -1
  164. package/dist/search.js +803 -149
  165. package/dist/search.js.map +1 -1
  166. package/dist/sse.d.ts +35 -2
  167. package/dist/sse.d.ts.map +1 -1
  168. package/dist/sse.js +145 -31
  169. package/dist/sse.js.map +1 -1
  170. package/dist/stores.d.ts.map +1 -1
  171. package/dist/stores.js +5 -2
  172. package/dist/stores.js.map +1 -1
  173. package/dist/text-index.d.ts +9 -1
  174. package/dist/text-index.d.ts.map +1 -1
  175. package/dist/text-index.js +28 -9
  176. package/dist/text-index.js.map +1 -1
  177. package/dist/text.d.ts +87 -3
  178. package/dist/text.d.ts.map +1 -1
  179. package/dist/text.js +526 -24
  180. package/dist/text.js.map +1 -1
  181. package/dist/tools.d.ts +61 -1
  182. package/dist/tools.d.ts.map +1 -1
  183. package/dist/tools.js +461 -46
  184. package/dist/tools.js.map +1 -1
  185. package/dist/types.d.ts +103 -4
  186. package/dist/types.d.ts.map +1 -1
  187. package/dist/word-styles.d.ts +102 -0
  188. package/dist/word-styles.d.ts.map +1 -0
  189. package/dist/word-styles.js +419 -0
  190. package/dist/word-styles.js.map +1 -0
  191. package/dist/xlsx.d.ts +23 -0
  192. package/dist/xlsx.d.ts.map +1 -0
  193. package/dist/xlsx.js +511 -0
  194. package/dist/xlsx.js.map +1 -0
  195. package/dist/xml-stream.d.ts +55 -0
  196. package/dist/xml-stream.d.ts.map +1 -0
  197. package/dist/xml-stream.js +235 -0
  198. package/dist/xml-stream.js.map +1 -0
  199. package/dist/zip-directory.d.ts +43 -0
  200. package/dist/zip-directory.d.ts.map +1 -0
  201. package/dist/zip-directory.js +130 -0
  202. package/dist/zip-directory.js.map +1 -0
  203. package/docs/README.md +288 -0
  204. package/docs/api.md +37 -381
  205. package/docs/configuration.md +28 -558
  206. package/docs/getting-started.md +407 -223
  207. package/docs/guides/anthropic.md +590 -0
  208. package/docs/guides/conversations.md +629 -0
  209. package/docs/guides/costs-and-limits.md +728 -0
  210. package/docs/guides/deployment.md +720 -0
  211. package/docs/guides/errors-and-reliability.md +748 -0
  212. package/docs/guides/explorer-model.md +399 -0
  213. package/docs/guides/openai-compatible.md +602 -0
  214. package/docs/guides/own-adapter-and-loop.md +1169 -0
  215. package/docs/guides/pdfs.md +1024 -0
  216. package/docs/guides/storage.md +731 -0
  217. package/docs/guides/testing.md +1203 -0
  218. package/docs/guides/vertex-and-gemini.md +717 -0
  219. package/docs/guides/web-app.md +1590 -0
  220. package/docs/how-it-works.md +1035 -164
  221. package/docs/measurements.md +881 -0
  222. package/docs/publishing.md +274 -46
  223. package/docs/reference/anthropic.md +427 -0
  224. package/docs/reference/ask.md +910 -0
  225. package/docs/reference/errors-and-retries.md +760 -0
  226. package/docs/reference/events.md +1001 -0
  227. package/docs/reference/gemini.md +827 -0
  228. package/docs/reference/library.md +1598 -0
  229. package/docs/reference/node.md +706 -0
  230. package/docs/reference/openai.md +385 -0
  231. package/docs/reference/tools.md +1031 -0
  232. package/docs/security.md +940 -101
  233. package/docs/troubleshooting.md +1410 -0
  234. package/package.json +7 -3
  235. package/src/analyze.ts +204 -49
  236. package/src/anthropic/adapter.ts +200 -40
  237. package/src/ask.ts +1151 -210
  238. package/src/decode.ts +89 -0
  239. package/src/encoding.ts +850 -0
  240. package/src/errors.ts +125 -0
  241. package/src/events.ts +451 -0
  242. package/src/evidence.ts +11 -2
  243. package/src/extract.ts +191 -308
  244. package/src/gemini/adapter.ts +127 -70
  245. package/src/gemini/chat.ts +28 -4
  246. package/src/gemini/endpoints.ts +12 -2
  247. package/src/gemini/errors.ts +34 -1
  248. package/src/gemini/generate.ts +42 -13
  249. package/src/gemini/index.ts +3 -3
  250. package/src/gemini/sse.ts +1 -1
  251. package/src/groups.ts +162 -0
  252. package/src/html.ts +1071 -0
  253. package/src/http.ts +376 -1
  254. package/src/index.ts +29 -6
  255. package/src/library.ts +498 -93
  256. package/src/limiter.ts +6 -1
  257. package/src/map-reduce.ts +252 -51
  258. package/src/model.ts +244 -4
  259. package/src/node/handlers.ts +196 -31
  260. package/src/node/index.ts +4 -0
  261. package/src/node/ingest-child.ts +61 -0
  262. package/src/node/isolated.ts +464 -0
  263. package/src/node/sse.ts +198 -0
  264. package/src/office.ts +1047 -0
  265. package/src/openai/adapter.ts +319 -38
  266. package/src/output-limit.ts +44 -8
  267. package/src/pause.ts +41 -0
  268. package/src/pdf-pages.ts +270 -20
  269. package/src/pdf-pictures.ts +56 -9
  270. package/src/pdf-work.ts +722 -0
  271. package/src/peers.ts +29 -0
  272. package/src/plan.ts +70 -12
  273. package/src/ranged.ts +4 -2
  274. package/src/retry.ts +49 -5
  275. package/src/search.ts +800 -155
  276. package/src/sse.ts +153 -28
  277. package/src/stores.ts +5 -2
  278. package/src/text-index.ts +30 -9
  279. package/src/text.ts +524 -23
  280. package/src/tools.ts +445 -46
  281. package/src/types.ts +108 -5
  282. package/src/word-styles.ts +420 -0
  283. package/src/xlsx.ts +478 -0
  284. package/src/xml-stream.ts +224 -0
  285. package/src/zip-directory.ts +136 -0
package/dist/html.js ADDED
@@ -0,0 +1,1112 @@
1
+ import { decodeSteps } from "./decode.js";
2
+ import { HIDDEN_TEXT } from "./office.js";
3
+ import { TimeSlicer } from "./pause.js";
4
+ import { formatBytes } from "./plan.js";
5
+ import { MAX_LINE_CHARACTERS, sliceWhole } from "./text.js";
6
+ /**
7
+ * HTML pages, as text a model can search and cite: the text a browser shows, without scripts,
8
+ * styles and markup. Headings become Markdown headings, list items "- item" (or "1. item"), each
9
+ * table row `| cell | cell |` with its empty cells (a merged cell is followed by an empty cell for
10
+ * each other column it covers), a link "text (https://…)", and a picture its alt text. Entities are
11
+ * decoded: "AT&T" is found as "AT&T". Saved pages in an older encoding are read as text files
12
+ * are.
13
+ *
14
+ * Text that the page hides (an element with the `hidden` attribute, or an inline style of
15
+ * `display: none` or `visibility: hidden`) is kept, as Word's hidden text is: it comes after the
16
+ * text of its line that shows, and each of its lines starts with `HIDDEN_TEXT`. A style sheet, or a
17
+ * class it names, is not read: text it hides is read as text that shows.
18
+ *
19
+ * The page is read a piece of text at a time, with pauses for other requests. White space is made
20
+ * one space in each piece as it comes, and the lines are written into blocks as they end, so that
21
+ * no step works on a whole line or the whole text in one call; and a page whose text grows past
22
+ * `maxTextBytes` is refused as soon as it does.
23
+ */
24
+ /** Elements whose content is not text a person reads: left out with all they hold. */
25
+ const SKIPPED = new Set(["script", "style", "noscript", "template", "svg", "math", "iframe", "object", "canvas", "select"]);
26
+ /** Elements read as raw text up to their end tag, whatever "<" they hold. */
27
+ const RAW_TEXT = new Set(["script", "style", "textarea", "title", "xmp", "plaintext"]);
28
+ /** Elements that start and end a line of their own. */
29
+ const BLOCKS = new Set([
30
+ "address", "article", "aside", "blockquote", "body", "caption", "center", "dd", "details", "dialog", "dir", "div", "dl", "dt",
31
+ "fieldset", "figcaption", "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hgroup", "hr", "html",
32
+ "legend", "li", "main", "menu", "nav", "ol", "p", "pre", "section", "summary", "table", "tbody", "td", "tfoot", "th", "thead", "tr", "ul",
33
+ ]);
34
+ /** Elements without content or end tag: a hidden one hides only itself. */
35
+ const VOID = new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr"]);
36
+ /** Elements that hold list items. */
37
+ const LISTS = new Set(["ul", "ol", "menu", "dir"]);
38
+ const HEADING = /^h[1-6]$/;
39
+ /** The parts of a table by how deep in it they are: a row group, a row, a cell. */
40
+ const TABLE_PARTS = new Map([["caption", 1], ["colgroup", 1], ["thead", 1], ["tbody", 1], ["tfoot", 1], ["tr", 2], ["td", 3], ["th", 3]]);
41
+ /** List items are indented by their depth, up to this many levels. */
42
+ const MAX_INDENT = 6;
43
+ /** Ordered lists nested deeper than this count their items with the list this deep. */
44
+ const MAX_LISTS = 64;
45
+ /** A tag is read up to this many characters; past it, it ends at its first ">". */
46
+ const MAX_TAG = 64 * 1024;
47
+ /** Text is read in pieces of this many characters at most, with a look at the clock between them. */
48
+ const TEXT_PIECE = 64 * 1024;
49
+ /** A character reference is at most 34 characters long (`&` and a name of 32, and `;`): a piece of text never ends this close after an `&`. */
50
+ const MAX_REFERENCE = 40;
51
+ /** The lines written are joined into blocks of about this many characters, or of this many pieces. */
52
+ const BLOCK = 64 * 1024;
53
+ const BLOCK_PARTS = 1024;
54
+ /** A page's title is kept up to this many characters. */
55
+ const MAX_TITLE = 1_000;
56
+ /** The title is looked for in this many characters at the start of the page's text. */
57
+ const TITLE_SEARCH = 64 * 1024;
58
+ /** A link's address is written after its text up to this length; a longer one is left out. */
59
+ const MAX_ADDRESS = 2_048;
60
+ /** A link's text is compared with its address up to this many characters: a longer text is not its address. */
61
+ const MAX_LINK_TEXT = 8 * 1024;
62
+ /** A picture's alt text is kept up to this many characters. */
63
+ const MAX_ALT = 1_000;
64
+ /** Rows one table cell may span, as browsers read `rowspan`. */
65
+ const MAX_ROWSPAN = 65_534;
66
+ /**
67
+ * The columns covered by merged cells are written as empty cells in the first 64 columns of a table
68
+ * only: a page of short cells that each span thousands of columns, or rows below thousands of cells
69
+ * that each span all of them, must not grow its text a thousand times.
70
+ */
71
+ const MAX_SPANNED_COLUMNS = 64;
72
+ /**
73
+ * A line of hidden text longer than this is cut into pieces, each marked. A mark and its piece then
74
+ * fit on one line, which ingest does not cut: past `MAX_LINE_CHARACTERS` it would put the rest of
75
+ * the hidden line on a line of its own, without the mark.
76
+ */
77
+ // A tenth is kept free: ingest composes the text (NFC) and bounds runs of marks after it is cut,
78
+ // which can lengthen a line, and a line past the wrap limit would leave its rest without a mark.
79
+ const HIDDEN_PIECE = Math.floor((MAX_LINE_CHARACTERS - HIDDEN_TEXT.length - 1) * 0.9);
80
+ const HIDDEN_MARK = `${HIDDEN_TEXT} `;
81
+ /**
82
+ * Runs of white space, made one space as a browser shows them (a no-break space is one too). A
83
+ * single space is not matched: prose is then left as it is, five times faster than with `/\s+/g`.
84
+ */
85
+ const SPACES = /\s{2,}|[^\S ]/g;
86
+ /** The same in hidden text, and U+0085 too: ingest may read it as a line break, and the text after it would lose its mark. */
87
+ const HIDDEN_SPACES = /[\s\x85]{2,}|[^\S ]|\x85/g;
88
+ /** A line break in preformatted text: a browser reads a carriage return as one too. */
89
+ const LINE_BREAK = /\r\n?|\n/;
90
+ /** The named entities pages use most; any other is left as it is written. Numeric ones are all decoded. */
91
+ const ENTITIES = {
92
+ amp: "&", lt: "<", gt: ">", quot: "\"", apos: "'", nbsp: " ", ensp: " ", emsp: " ", thinsp: " ",
93
+ shy: "­", zwnj: "‌", zwj: "‍", lrm: "‎", rlm: "‏",
94
+ ndash: "–", mdash: "—", minus: "−", hellip: "…", bull: "•", middot: "·", prime: "′", Prime: "″",
95
+ lsquo: "‘", rsquo: "’", sbquo: "‚", ldquo: "“", rdquo: "”", bdquo: "„", laquo: "«", raquo: "»", lsaquo: "‹", rsaquo: "›",
96
+ copy: "©", reg: "®", trade: "™", deg: "°", plusmn: "±", times: "×", divide: "÷", frac12: "½", frac14: "¼", frac34: "¾",
97
+ sup1: "¹", sup2: "²", sup3: "³", micro: "µ", para: "¶", sect: "§", dagger: "†", Dagger: "‡", permil: "‰",
98
+ euro: "€", pound: "£", yen: "¥", cent: "¢", curren: "¤", shekel: "₪",
99
+ larr: "←", rarr: "→", uarr: "↑", darr: "↓", harr: "↔", rArr: "⇒", lArr: "⇐", hArr: "⇔",
100
+ le: "≤", ge: "≥", ne: "≠", asymp: "≈", infin: "∞", sum: "∑", radic: "√", check: "✓",
101
+ iexcl: "¡", iquest: "¿", ordf: "ª", ordm: "º", not: "¬", macr: "¯", acute: "´", cedil: "¸", uml: "¨",
102
+ agrave: "à", aacute: "á", acirc: "â", atilde: "ã", auml: "ä", aring: "å", aelig: "æ", ccedil: "ç",
103
+ egrave: "è", eacute: "é", ecirc: "ê", euml: "ë", igrave: "ì", iacute: "í", icirc: "î", iuml: "ï",
104
+ ntilde: "ñ", ograve: "ò", oacute: "ó", ocirc: "ô", otilde: "õ", ouml: "ö", oslash: "ø", ugrave: "ù",
105
+ uacute: "ú", ucirc: "û", uuml: "ü", yacute: "ý", yuml: "ÿ", szlig: "ß", eth: "ð", thorn: "þ",
106
+ Agrave: "À", Aacute: "Á", Acirc: "Â", Atilde: "Ã", Auml: "Ä", Aring: "Å", AElig: "Æ", Ccedil: "Ç",
107
+ Egrave: "È", Eacute: "É", Ecirc: "Ê", Euml: "Ë", Igrave: "Ì", Iacute: "Í", Icirc: "Î", Iuml: "Ï",
108
+ Ntilde: "Ñ", Ograve: "Ò", Oacute: "Ó", Ocirc: "Ô", Otilde: "Õ", Ouml: "Ö", Oslash: "Ø", Ugrave: "Ù",
109
+ Uacute: "Ú", Ucirc: "Û", Uuml: "Ü", Yacute: "Ý", ETH: "Ð", THORN: "Þ", oelig: "œ", OElig: "Œ", scaron: "š", Scaron: "Š",
110
+ alpha: "α", beta: "β", gamma: "γ", delta: "δ", pi: "π", sigma: "σ", omega: "ω", mu: "μ", lambda: "λ", Delta: "Δ", Omega: "Ω",
111
+ };
112
+ /** Decodes the character references of HTML text: numeric ones, and the named ones of `ENTITIES`. */
113
+ export function decodeHtmlEntities(text) {
114
+ if (!text.includes("&"))
115
+ return text;
116
+ return text.replace(/&(#[xX][0-9a-fA-F]{1,6}|#\d{1,7}|[A-Za-z][A-Za-z0-9]{1,31});?/g, (match, entity) => {
117
+ if (entity.startsWith("#")) {
118
+ const code = entity[1] === "x" || entity[1] === "X" ? Number.parseInt(entity.slice(2), 16) : Number.parseInt(entity.slice(1), 10);
119
+ // HTML reads 0x80-0x9F as windows-1252 by mistake; and a surrogate or 0 is a replacement character.
120
+ if (code === 0 || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff))
121
+ return "�";
122
+ return String.fromCodePoint(code);
123
+ }
124
+ // Only a name of the table, not one an object has from its prototype ("&constructor;").
125
+ // "AT&T" and "?a=1&b=2" stay as they are.
126
+ return Object.hasOwn(ENTITIES, entity) ? ENTITIES[entity] : match;
127
+ });
128
+ }
129
+ /**
130
+ * The text of a line, or of a table cell, as it is read: in pieces, each with its runs of white
131
+ * space made one space as it comes, and none at the start. A line of megabytes is never searched or
132
+ * copied whole. Its pieces are joined into blocks as they come, as the lines of `Output` are, so
133
+ * that a line of millions of short pieces (a word between each two tags) is written in a few steps.
134
+ */
135
+ class Run {
136
+ cell;
137
+ hidden;
138
+ /** The blocks the pieces were joined into, the pieces since, and their length. */
139
+ blocks = [];
140
+ parts = [];
141
+ size = 0;
142
+ length = 0;
143
+ /** Whether the text so far is empty or ends with a space: a space after it is left out. */
144
+ spaced = true;
145
+ /** `cell`: its pipes are escaped, as the PDF extractor writes cells. `hidden`: text the page hides. */
146
+ constructor(cell = false, hidden = false) {
147
+ this.cell = cell;
148
+ this.hidden = hidden;
149
+ }
150
+ /** The text, in pieces. */
151
+ get pieces() {
152
+ return this.blocks.length === 0 ? this.parts : [...this.blocks, ...this.parts];
153
+ }
154
+ /**
155
+ * Adds text, and returns how many characters it added. `preformatted`: its white space is kept,
156
+ * except in hidden text, which is marked line by line.
157
+ */
158
+ add(text, preformatted = false) {
159
+ let piece = text;
160
+ if (!preformatted || this.hidden) {
161
+ piece = piece.replace(this.hidden ? HIDDEN_SPACES : SPACES, " ");
162
+ if (this.spaced && piece.charCodeAt(0) === 32)
163
+ piece = piece.slice(1);
164
+ }
165
+ if (piece === "")
166
+ return 0;
167
+ if (this.cell && piece.includes("|"))
168
+ piece = piece.replace(/\|/g, "\\|");
169
+ this.spaced = piece.charCodeAt(piece.length - 1) === 32;
170
+ this.parts.push(piece);
171
+ this.size += piece.length;
172
+ this.length += piece.length;
173
+ if (this.size >= BLOCK || this.parts.length >= BLOCK_PARTS) {
174
+ this.blocks.push(this.parts.join(""));
175
+ this.parts = [];
176
+ this.size = 0;
177
+ }
178
+ return piece.length;
179
+ }
180
+ /** The last `length` characters of the text (a link's, to compare with its address). */
181
+ tail(length) {
182
+ const taken = [];
183
+ let size = 0;
184
+ for (const list of [this.parts, this.blocks]) {
185
+ for (let index = list.length - 1; index >= 0 && size < length; index--) {
186
+ taken.push(list[index]);
187
+ size += list[index].length;
188
+ }
189
+ }
190
+ const text = taken.reverse().join("");
191
+ return text.slice(text.length - Math.min(length, text.length));
192
+ }
193
+ /**
194
+ * Drops the white space at its end, and returns how many characters it dropped. Only the last
195
+ * pieces are looked at: `/\s+$/` on a line was tried at each space of a run, and took the square
196
+ * of its length (28 seconds for a run of 120,000 spaces in a `<pre>`).
197
+ */
198
+ trimEnd() {
199
+ const before = this.length;
200
+ for (;;) {
201
+ const list = this.parts.length > 0 ? this.parts : this.blocks;
202
+ const last = list.at(-1);
203
+ if (last === undefined)
204
+ break;
205
+ const trimmed = last.trimEnd();
206
+ this.length -= last.length - trimmed.length;
207
+ if (trimmed !== "") {
208
+ list[list.length - 1] = trimmed;
209
+ break;
210
+ }
211
+ list.pop();
212
+ }
213
+ return before - this.length;
214
+ }
215
+ }
216
+ /**
217
+ * The text written so far. The lines are joined into blocks of about `BLOCK` characters as they
218
+ * come, so that a page of millions of short lines is held in a few long strings, and the text is
219
+ * joined once, at the end. It starts at its first character that is not white space, and a blank
220
+ * line is written only before another line.
221
+ */
222
+ class Output {
223
+ blocks = [];
224
+ parts = [];
225
+ size = 0;
226
+ /** Characters written, with the line breaks between the lines. */
227
+ characters = 0;
228
+ lines = 0;
229
+ /** A blank line is due before the next line (two `<br>` in a row). */
230
+ blank = false;
231
+ /** Writes a line: `prefix`, then `parts`, `length` characters in all. */
232
+ line(prefix, parts, length) {
233
+ let size = length;
234
+ // The first line (a list nested in nothing, or a block of code) starts at its first character.
235
+ let starting = this.lines === 0;
236
+ if (!starting) {
237
+ const breaks = this.blank ? "\n\n" : "\n";
238
+ this.blank = false;
239
+ this.push(breaks);
240
+ size += breaks.length;
241
+ }
242
+ const put = (part) => {
243
+ if (!starting) {
244
+ this.push(part);
245
+ return;
246
+ }
247
+ const trimmed = part.trimStart();
248
+ size -= part.length - trimmed.length;
249
+ if (trimmed === "")
250
+ return;
251
+ starting = false;
252
+ this.push(trimmed);
253
+ };
254
+ put(prefix);
255
+ for (const part of parts)
256
+ put(part);
257
+ // A first line of nothing but white space is not written.
258
+ if (starting)
259
+ return;
260
+ this.characters += size;
261
+ this.lines++;
262
+ }
263
+ /** A blank line before the next line, unless no line was written yet. */
264
+ blankLine() {
265
+ if (this.lines > 0)
266
+ this.blank = true;
267
+ }
268
+ /** The text written, joined. */
269
+ text() {
270
+ if (this.parts.length > 0)
271
+ this.blocks.push(this.parts.join(""));
272
+ this.parts = [];
273
+ this.size = 0;
274
+ return this.blocks.length === 1 ? this.blocks[0] : this.blocks.join("");
275
+ }
276
+ push(part) {
277
+ if (part === "")
278
+ return;
279
+ this.parts.push(part);
280
+ this.size += part.length;
281
+ if (this.size >= BLOCK || this.parts.length >= BLOCK_PARTS) {
282
+ this.blocks.push(this.parts.join(""));
283
+ this.parts = [];
284
+ this.size = 0;
285
+ }
286
+ }
287
+ }
288
+ const newLine = (prefix = "") => ({ prefix, shown: new Run(), hidden: undefined });
289
+ /** Elements open around the one being read, at most: past it, end tags are matched no further. */
290
+ const MAX_OPEN = 512;
291
+ /** Elements a browser closes and opens again around what follows them, not ends at an end tag around them. */
292
+ const FORMATTING = new Set(["a", "b", "big", "code", "em", "font", "i", "nobr", "s", "small", "strike", "strong", "tt", "u"]);
293
+ /**
294
+ * Builds the text of a page as its tags and text go past. A table row is collected cell by cell
295
+ * and written as one line when it ends; a table inside a cell is read as text of that cell.
296
+ */
297
+ class HtmlText {
298
+ maxCharacters;
299
+ out = new Output();
300
+ line = newLine();
301
+ /**
302
+ * How deep inside skipped elements, `pre` elements, and lists, with the count of each ordered
303
+ * list of the first `MAX_LISTS`: a page of lists nested millions deep must not hold one each.
304
+ */
305
+ skipping = 0;
306
+ preformatted = 0;
307
+ listDepth = 0;
308
+ lists = [];
309
+ heading = 0;
310
+ /** The table row being read, and how deep in tables (a table inside a cell is text of that cell). */
311
+ row;
312
+ tableDepth = 0;
313
+ /** For each of the first `MAX_SPANNED_COLUMNS` columns of the table: how many rows after this one a cell above still covers. */
314
+ spans = [];
315
+ /** The link open, to write its address after its text: the text its text went to, and that text's length before it. */
316
+ link;
317
+ hidden;
318
+ /**
319
+ * The names of the elements open, outermost first, up to `MAX_OPEN`: a hidden element ends at the
320
+ * end tag of an element that was open around it (`<p>a <span hidden>b</p>`), as a browser ends it.
321
+ * Elements a page leaves open (a `<p>` with no end tag) stay in it; they only make such an end
322
+ * less likely to be seen, never wrongly seen.
323
+ */
324
+ opened = [];
325
+ /** `maxCharacters`: the page is refused as soon as its text grows past it. */
326
+ constructor(maxCharacters = Number.POSITIVE_INFINITY) {
327
+ this.maxCharacters = maxCharacters;
328
+ }
329
+ /** Whether the reading is inside an element whose content is left out. */
330
+ get skipped() {
331
+ return this.skipping > 0;
332
+ }
333
+ open(name, attributes) {
334
+ if (SKIPPED.has(name)) {
335
+ this.skipping++;
336
+ return;
337
+ }
338
+ if (this.skipping > 0)
339
+ return;
340
+ if (this.hidden && this.endedByStart(this.hidden, name))
341
+ this.hidden = undefined;
342
+ const hiddenBefore = this.hidden !== undefined;
343
+ // Not inside a hidden element, which hides it already; not `<html>` or `<body>`: a page hidden
344
+ // whole until a script shows it is meant to be read.
345
+ const hides = this.hidden || name === "html" || name === "body" ? undefined : hiding(attributes);
346
+ if (hides && VOID.has(name))
347
+ return;
348
+ if (this.hidden) {
349
+ this.hiddenOpens(this.hidden, name);
350
+ }
351
+ else if (hides) {
352
+ const listed = this.listDepth > 0 && !LISTS.has(name) && name !== "li" && name !== "dl" && name !== "dt" && name !== "dd";
353
+ const celled = this.row?.cell !== undefined && !TABLE_PARTS.has(name) && name !== "table";
354
+ this.hidden = { name, depth: 1, lists: 0, tables: 0, keepsPlace: hides === "invisible", listed, celled, outer: this.opened.length };
355
+ }
356
+ if (!VOID.has(name) && this.opened.length < MAX_OPEN)
357
+ this.opened.push(name);
358
+ if (name === "table") {
359
+ this.tableDepth++;
360
+ if (this.tableDepth === 1) {
361
+ this.flush();
362
+ // The rows are lines of their own: a list item's mark is not written before them.
363
+ if (this.heading === 0)
364
+ this.line.prefix = "";
365
+ this.spans = [];
366
+ }
367
+ else if (this.row?.cell) {
368
+ this.space();
369
+ }
370
+ return;
371
+ }
372
+ if (this.tableDepth === 1 && (name === "thead" || name === "tbody" || name === "tfoot")) {
373
+ // A row group ends the row before it, and the rows that cells above span: they span their group only.
374
+ this.endRow();
375
+ this.spans = [];
376
+ return;
377
+ }
378
+ if (this.tableDepth === 1 && (name === "tr" || name === "td" || name === "th")) {
379
+ if (name === "tr") {
380
+ this.endRow();
381
+ this.row = this.startRow(this.hidden !== undefined);
382
+ }
383
+ else {
384
+ this.row ??= this.startRow(hiddenBefore);
385
+ this.startCell(attributes);
386
+ }
387
+ return;
388
+ }
389
+ if (this.row?.cell) {
390
+ // Inside a cell: line breaks and blocks (paragraphs, list items, the cells of a table inside
391
+ // it) become spaces, as the cell is one cell of one row.
392
+ if (name === "br" || BLOCKS.has(name))
393
+ this.space();
394
+ else if (name === "img")
395
+ this.image(attributes);
396
+ else if (name === "a")
397
+ this.startLink(attributes);
398
+ return;
399
+ }
400
+ if (name === "br") {
401
+ // In hidden text a line break is a space: the hidden text is written after its line, which it does not end.
402
+ if (this.hidden)
403
+ this.space();
404
+ else
405
+ this.flush(true);
406
+ return;
407
+ }
408
+ if (name === "img") {
409
+ this.image(attributes);
410
+ return;
411
+ }
412
+ if (name === "a") {
413
+ this.startLink(attributes);
414
+ return;
415
+ }
416
+ if (name === "pre")
417
+ this.preformatted++;
418
+ if (LISTS.has(name)) {
419
+ this.flush();
420
+ if (++this.listDepth <= MAX_LISTS) {
421
+ this.lists.push({ ordered: name === "ol", count: Number.parseInt(attributeOf(attributes, "start", 16) ?? "1", 10) - 1 || 0 });
422
+ }
423
+ return;
424
+ }
425
+ if (BLOCKS.has(name))
426
+ this.flush();
427
+ // Hidden text is written after its own mark: it gets no heading's or list item's.
428
+ if (this.hidden)
429
+ return;
430
+ const level = /^h([1-6])$/.exec(name);
431
+ if (level) {
432
+ this.heading = Number(level[1]);
433
+ this.line.prefix = `${"#".repeat(this.heading)} `;
434
+ }
435
+ else if (name === "li") {
436
+ const list = this.lists.at(-1);
437
+ // Indented up to a few levels: a page of lists nested thousands deep must not grow its text by the square.
438
+ const indent = " ".repeat(Math.min(MAX_INDENT, Math.max(0, this.listDepth - 1)));
439
+ if (list?.ordered)
440
+ this.line.prefix = `${indent}${++list.count}. `;
441
+ else
442
+ this.line.prefix = `${indent}- `;
443
+ }
444
+ else if (name === "hr") {
445
+ this.write("---", [], 3);
446
+ this.line.prefix = "";
447
+ }
448
+ else if (name === "blockquote") {
449
+ this.line.prefix = "> ";
450
+ }
451
+ }
452
+ close(name) {
453
+ if (SKIPPED.has(name)) {
454
+ if (this.skipping > 0)
455
+ this.skipping--;
456
+ return;
457
+ }
458
+ if (this.skipping > 0)
459
+ return;
460
+ // The innermost open element of this name is closed, and those inside it.
461
+ const index = this.opened.lastIndexOf(name);
462
+ this.end(name);
463
+ if (this.hidden && (this.endedByEnd(this.hidden, name) || (index !== -1 && index < this.hidden.outer && !FORMATTING.has(name))))
464
+ this.hidden = undefined;
465
+ if (index !== -1)
466
+ this.opened.length = index;
467
+ }
468
+ text(raw) {
469
+ if (this.skipping > 0 || raw === "")
470
+ return;
471
+ const text = decodeHtmlEntities(raw);
472
+ if (!this.row?.cell) {
473
+ // Text between the cells of a table (white space, or a caption's text outside a cell).
474
+ if (this.tableDepth > 0 && !text.trim())
475
+ return;
476
+ if (this.preformatted > 0) {
477
+ const lines = text.split(LINE_BREAK);
478
+ for (let index = 0; index < lines.length; index++) {
479
+ if (index > 0)
480
+ this.flush(true);
481
+ this.add(lines[index], true);
482
+ }
483
+ return;
484
+ }
485
+ }
486
+ this.add(text);
487
+ }
488
+ result() {
489
+ this.endRow();
490
+ this.flush();
491
+ return this.out.text();
492
+ }
493
+ end(name) {
494
+ if (name === "table") {
495
+ if (this.tableDepth === 1) {
496
+ this.endRow();
497
+ this.spans = [];
498
+ }
499
+ else if (this.row?.cell) {
500
+ this.space();
501
+ }
502
+ if (this.tableDepth > 0)
503
+ this.tableDepth--;
504
+ return;
505
+ }
506
+ if (this.tableDepth === 1 && (name === "thead" || name === "tbody" || name === "tfoot")) {
507
+ this.endRow();
508
+ this.spans = [];
509
+ return;
510
+ }
511
+ if (name === "a") {
512
+ this.endLink();
513
+ return;
514
+ }
515
+ if (this.tableDepth === 1 && this.row) {
516
+ if (name === "tr")
517
+ this.endRow();
518
+ else if (name === "td" || name === "th")
519
+ this.endCell();
520
+ else if (this.row.cell && BLOCKS.has(name))
521
+ this.space();
522
+ return;
523
+ }
524
+ if (this.row?.cell) {
525
+ // The end of a block inside a cell, or of a row or cell of a table inside it.
526
+ if (BLOCKS.has(name))
527
+ this.space();
528
+ return;
529
+ }
530
+ if (name === "pre" && this.preformatted > 0) {
531
+ // The last line of the block keeps its spaces: it ends while the block is still open.
532
+ this.flush();
533
+ this.preformatted--;
534
+ return;
535
+ }
536
+ if (LISTS.has(name)) {
537
+ this.flush();
538
+ if (this.listDepth > 0 && this.listDepth-- <= MAX_LISTS)
539
+ this.lists.pop();
540
+ // The mark of a last item left with no text (an icon, a picture without words) is not given to what follows the list.
541
+ if (this.heading === 0)
542
+ this.line.prefix = "";
543
+ return;
544
+ }
545
+ if (HEADING.test(name))
546
+ this.heading = 0;
547
+ if (BLOCKS.has(name))
548
+ this.flush();
549
+ // A list item, quote or heading that ends before any text of its own: its mark is not given to the text after it.
550
+ if (name === "li" || name === "blockquote" || HEADING.test(name))
551
+ this.line.prefix = "";
552
+ }
553
+ /** Adds text where it goes now (see `target`). */
554
+ add(text, preformatted = false) {
555
+ const row = this.row;
556
+ if (row?.cell)
557
+ row.held += this.target().add(text);
558
+ else
559
+ this.target().add(text, preformatted);
560
+ this.check();
561
+ }
562
+ /**
563
+ * Where text goes now: to the cell open or to the line, with the text that shows or with the text
564
+ * that the page hides. In a row that the page hides whole, the row is marked: its cells are read
565
+ * as cells. The text a cell hides is the row's, written after it.
566
+ */
567
+ target() {
568
+ const row = this.row;
569
+ if (row?.cell)
570
+ return this.hidden && !row.hidden ? (row.hiddenText ??= new Run(false, true)) : row.cell.shown;
571
+ return this.hidden ? (this.line.hidden ??= new Run(false, true)) : this.line.shown;
572
+ }
573
+ space() {
574
+ this.add(" ");
575
+ }
576
+ /** Refuses the page as soon as the text written, with what the line and the row not yet written hold, passes the limit. */
577
+ check() {
578
+ const held = this.line.shown.length + (this.line.hidden?.length ?? 0) + (this.row?.held ?? 0);
579
+ if (this.out.characters + held > this.maxCharacters)
580
+ throw tooMuchText(this.maxCharacters);
581
+ }
582
+ write(prefix, parts, length) {
583
+ this.out.line(prefix, parts, length);
584
+ this.check();
585
+ }
586
+ /**
587
+ * Writes text the page hides, after the text that shows: each of its lines starts with
588
+ * `HIDDEN_TEXT`, as the hidden text of a Word document does. A line longer than `HIDDEN_PIECE` is
589
+ * cut into pieces, after a space near the end of each where there is one and never between the
590
+ * two halves of an emoji, and each piece is marked.
591
+ */
592
+ writeHidden(pieces) {
593
+ let rest = "";
594
+ for (const written of pieces) {
595
+ // A U+0085 ends a line in a text with no other line break: ingest would split the text from its mark there.
596
+ const piece = written.includes("\x85") ? written.replace(/\x85/g, " ") : written;
597
+ rest = rest === "" ? piece.trimStart() : rest + piece;
598
+ while (rest.length > HIDDEN_PIECE) {
599
+ const window = sliceWhole(rest, HIDDEN_PIECE);
600
+ const space = window.lastIndexOf(" ");
601
+ const end = space > HIDDEN_PIECE * 0.8 ? space + 1 : window.length;
602
+ this.write(HIDDEN_MARK, [rest.slice(0, end)], HIDDEN_MARK.length + end);
603
+ rest = rest.slice(end).trimStart();
604
+ }
605
+ }
606
+ rest = rest.trimEnd();
607
+ if (rest !== "")
608
+ this.write(HIDDEN_MARK, [rest], HIDDEN_MARK.length + rest.length);
609
+ }
610
+ image(attributes) {
611
+ // Up to `MAX_ALT` characters, read from the start of the text only: an attribute can be megabytes long.
612
+ const alt = sliceWhole(decodeSpaces(attributeOf(attributes, "alt", MAX_ALT * 4) ?? "").trim(), MAX_ALT).trim();
613
+ if (alt)
614
+ this.text(` [Image: ${alt}] `);
615
+ }
616
+ startLink(attributes) {
617
+ // An address too long to follow is not decoded at all.
618
+ const written = attributeOf(attributes, "href", MAX_ADDRESS * 2 + 1) ?? "";
619
+ if (written.length > MAX_ADDRESS * 2)
620
+ return;
621
+ // A browser leaves out the tabs and line breaks of an address.
622
+ const href = written.replace(/[\t\n\r]/g, "").trim();
623
+ // Only addresses a person can follow outside the page: not "#top", not "javascript:".
624
+ if (/^(https?:|mailto:)/i.test(href) && href.length <= MAX_ADDRESS) {
625
+ const run = this.target();
626
+ this.link = { href, run, length: run.length };
627
+ }
628
+ }
629
+ endLink() {
630
+ const link = this.link;
631
+ this.link = undefined;
632
+ if (!link)
633
+ return;
634
+ const run = this.target();
635
+ // The link's text; or, when its line or cell ended inside it, the text since.
636
+ const length = run.length - (run === link.run ? link.length : 0);
637
+ if (length === 0)
638
+ return;
639
+ const address = link.href.replace(/^mailto:/i, "");
640
+ if (length <= MAX_LINK_TEXT) {
641
+ const shown = run.tail(length);
642
+ // A link whose text is its address says it once.
643
+ if (!shown.trim() || shown.includes(address))
644
+ return;
645
+ }
646
+ this.add(` (${link.href.startsWith("mailto:") ? address : link.href})`);
647
+ }
648
+ /** Starts a row of the table. `hidden`: the page hides the whole row, which is written marked. */
649
+ startRow(hidden) {
650
+ // The columns that cells above cover in this row; after it, each covers one row fewer.
651
+ // Most tables span no rows: then nothing is worked out for each row.
652
+ const spanning = this.spans.some((rows) => rows > 0);
653
+ const covered = spanning ? this.spans.map((rows) => rows > 0) : [];
654
+ if (spanning)
655
+ this.spans = this.spans.map((rows) => Math.max(0, rows - 1));
656
+ return { parts: [], size: 0, blocks: [], columns: 0, text: false, cell: undefined, hidden, hiddenText: undefined, held: 0, covered };
657
+ }
658
+ startCell(attributes) {
659
+ const row = this.row;
660
+ this.endCell();
661
+ // A cell hidden by `visibility` keeps its column, empty; one hidden otherwise takes none.
662
+ const dropped = this.hidden !== undefined && !row.hidden && !this.hidden.keepsPlace;
663
+ let colspan = 1;
664
+ let rowspan = 1;
665
+ if (!dropped) {
666
+ // The columns that cells above cover come first, empty, so that this cell is under its heading.
667
+ while (row.columns < row.covered.length && row.covered[row.columns])
668
+ this.addCell(row, undefined);
669
+ if (/span/i.test(attributes)) {
670
+ colspan = Math.min(MAX_SPANNED_COLUMNS, Math.max(1, Number.parseInt(attributeOf(attributes, "colspan", 16) ?? "1", 10) || 1));
671
+ const rows = Number.parseInt(attributeOf(attributes, "rowspan", 16) ?? "1", 10);
672
+ // `rowspan="0"` spans the rest of the rows of its group.
673
+ rowspan = rows === 0 ? MAX_ROWSPAN : Math.min(MAX_ROWSPAN, Math.max(1, rows || 1));
674
+ }
675
+ }
676
+ row.cell = { shown: new Run(true), dropped, colspan, rowspan };
677
+ }
678
+ endCell() {
679
+ const row = this.row;
680
+ const cell = row?.cell;
681
+ if (!row || !cell)
682
+ return;
683
+ row.cell = undefined;
684
+ // The hidden text of one cell is a word apart from that of the next.
685
+ row.held += row.hiddenText?.add(" ") ?? 0;
686
+ if (cell.dropped) {
687
+ // Text after the end of what hid the cell, in the cell: hidden with it.
688
+ if (cell.shown.length > 0)
689
+ for (const piece of cell.shown.pieces)
690
+ (row.hiddenText ??= new Run(false, true)).add(piece);
691
+ return;
692
+ }
693
+ row.held -= cell.shown.trimEnd();
694
+ const column = row.columns;
695
+ this.addCell(row, cell.shown.length > 0 ? cell.shown : undefined);
696
+ if (cell.rowspan > 1) {
697
+ for (let index = column; index < column + cell.colspan && index < MAX_SPANNED_COLUMNS; index++) {
698
+ this.spans[index] = Math.max(this.spans[index] ?? 0, cell.rowspan - 1);
699
+ }
700
+ }
701
+ // Each column it spans past the first is an empty cell, so that the cells after it stay under their headings.
702
+ for (let extra = 1; extra < cell.colspan && row.columns < MAX_SPANNED_COLUMNS; extra++)
703
+ this.addCell(row, undefined);
704
+ }
705
+ /**
706
+ * Adds a cell to the row's line: ` text |`, or ` |` for an empty one (also for a column that a
707
+ * merged cell covers). Each cell is counted with its separator, empty or not: a row of millions of
708
+ * empty cells is bounded too.
709
+ */
710
+ addCell(row, cell) {
711
+ if (!cell) {
712
+ this.rowPart(row, " |");
713
+ }
714
+ else if (cell.pieces.length === 1) {
715
+ this.rowPart(row, ` ${cell.pieces[0]} |`);
716
+ }
717
+ else {
718
+ this.rowPart(row, " ");
719
+ for (const piece of cell.pieces)
720
+ this.rowPart(row, piece);
721
+ this.rowPart(row, " |");
722
+ }
723
+ if (cell)
724
+ row.text = true;
725
+ row.columns++;
726
+ row.held += 3;
727
+ this.check();
728
+ }
729
+ rowPart(row, part) {
730
+ row.parts.push(part);
731
+ row.size += part.length;
732
+ if (row.size >= BLOCK) {
733
+ row.blocks.push(row.parts.join(""));
734
+ row.parts = [];
735
+ row.size = 0;
736
+ }
737
+ }
738
+ endRow() {
739
+ this.endCell();
740
+ const row = this.row;
741
+ if (!row)
742
+ return;
743
+ if (row.text) {
744
+ // The columns that cells above cover after its last cell are empty cells too: the row has all its columns.
745
+ const last = row.covered.lastIndexOf(true);
746
+ while (row.columns <= last)
747
+ this.addCell(row, undefined);
748
+ if (row.parts.length > 0)
749
+ row.blocks.push(row.parts.join(""));
750
+ }
751
+ // The row is let go before it is written: what it held is not counted twice.
752
+ this.row = undefined;
753
+ if (row.text) {
754
+ if (row.hidden)
755
+ this.writeHidden(["|", ...row.blocks]);
756
+ else
757
+ this.write("|", row.blocks, row.blocks.reduce((sum, block) => sum + block.length, 1));
758
+ }
759
+ if (row.hiddenText)
760
+ this.writeHidden(row.hiddenText.pieces);
761
+ }
762
+ /** Ends the line being built. `always`: also an empty one (a `<br>` in a row of them). */
763
+ flush(always = false) {
764
+ const { prefix, shown, hidden } = this.line;
765
+ if (shown.length === 0 && !hidden?.length) {
766
+ // A list item or quote whose text starts in a paragraph inside it keeps its mark for that text.
767
+ if (always && !this.hidden)
768
+ this.out.blankLine();
769
+ return;
770
+ }
771
+ shown.trimEnd();
772
+ // A heading keeps its mark on each of its lines, a list item and a quote on their first line of
773
+ // text. The line is let go before it is written: what it held is not counted twice.
774
+ this.line = newLine(this.heading > 0 || shown.length === 0 ? prefix : "");
775
+ if (shown.length > 0)
776
+ this.write(prefix, shown.pieces, prefix.length + shown.length);
777
+ else if (always && !this.hidden)
778
+ this.out.blankLine();
779
+ if (hidden?.length)
780
+ this.writeHidden(hidden.pieces);
781
+ }
782
+ /** Whether `name` starting ends the hidden element, which cannot hold it. */
783
+ endedByStart(hidden, name) {
784
+ const kind = hidden.name;
785
+ // A paragraph holds no block, and a heading no heading.
786
+ if (kind === "p")
787
+ return BLOCKS.has(name);
788
+ if (HEADING.test(kind))
789
+ return HEADING.test(name);
790
+ // The next item of its list, or the next term or definition of its list.
791
+ if (hidden.lists === 0 && name === "li" && (kind === "li" || hidden.listed))
792
+ return true;
793
+ if (hidden.lists === 0 && (name === "dt" || name === "dd") && (kind === "dt" || kind === "dd"))
794
+ return true;
795
+ // The next part of its table at its level or above: the next cell, row or row group.
796
+ const level = this.tableLevel(hidden);
797
+ const other = TABLE_PARTS.get(name);
798
+ if (level === undefined || other === undefined || hidden.tables > 0)
799
+ return false;
800
+ return kind === "caption" || kind === "colgroup" || other <= level;
801
+ }
802
+ /** How deep in its table the hidden element is (see `TABLE_PARTS`): inside a cell, below a cell. */
803
+ tableLevel(hidden) {
804
+ return TABLE_PARTS.get(hidden.name) ?? (hidden.celled ? 4 : undefined);
805
+ }
806
+ /** Counts what opens inside the hidden element, to tell its end from the end of an element inside it. */
807
+ hiddenOpens(hidden, name) {
808
+ if (name === hidden.name)
809
+ hidden.depth++;
810
+ if (LISTS.has(name) || name === "dl")
811
+ hidden.lists++;
812
+ if (name === "table")
813
+ hidden.tables++;
814
+ }
815
+ /** Whether `name` ending ends the hidden element: its own end tag, or that of an element around it. */
816
+ endedByEnd(hidden, name) {
817
+ const kind = hidden.name;
818
+ if (LISTS.has(name) || name === "dl") {
819
+ if (hidden.lists > 0)
820
+ hidden.lists--;
821
+ else if (kind === "li" || kind === "dt" || kind === "dd" || hidden.listed)
822
+ return true;
823
+ }
824
+ if (name === "table") {
825
+ if (hidden.tables > 0)
826
+ hidden.tables--;
827
+ else if (TABLE_PARTS.has(kind) || hidden.celled)
828
+ return true;
829
+ }
830
+ if (kind === "p")
831
+ return BLOCKS.has(name);
832
+ if (HEADING.test(kind))
833
+ return HEADING.test(name);
834
+ if (name === "li" && hidden.lists === 0 && hidden.listed)
835
+ return true;
836
+ const level = this.tableLevel(hidden);
837
+ const other = TABLE_PARTS.get(name);
838
+ if (level !== undefined && other !== undefined && hidden.tables === 0 && other < level)
839
+ return true;
840
+ return name === kind && --hidden.depth === 0;
841
+ }
842
+ }
843
+ /** Runs of white space as one space, as a browser shows them; a no-break space stays a space. */
844
+ const decodeSpaces = (text) => text.replace(/\s+/g, " ");
845
+ const isAttributeSpace = (code) => code === 32 || code === 9 || code === 10 || code === 13 || code === 12;
846
+ /**
847
+ * The value of one attribute of an HTML tag, by its name in lower case (HTML reads `HREF` as
848
+ * `href`, and keeps the first of two of a name), with its character references decoded, or
849
+ * undefined when the tag has none. Only the first `maxRaw` characters of the value are decoded:
850
+ * an attribute can be megabytes of references (`alt="&amp;&amp;…"`), and decoding all of them, or
851
+ * every attribute of the tag, held the server and, at 100 MB, ran it out of memory. One pass over
852
+ * the tag, with no regular expression.
853
+ */
854
+ function attributeOf(inside, wanted, maxRaw) {
855
+ const length = inside.length;
856
+ let at = 0;
857
+ while (at < length) {
858
+ while (at < length && (isAttributeSpace(inside.charCodeAt(at)) || inside[at] === "/"))
859
+ at++;
860
+ const start = at;
861
+ while (at < length && !isAttributeSpace(inside.charCodeAt(at)) && inside[at] !== "=" && inside[at] !== "/" && inside[at] !== ">")
862
+ at++;
863
+ const name = at - start === wanted.length ? inside.slice(start, at).toLowerCase() : undefined;
864
+ while (at < length && isAttributeSpace(inside.charCodeAt(at)))
865
+ at++;
866
+ if (inside[at] !== "=") {
867
+ if (name === wanted)
868
+ return "";
869
+ if (at === start)
870
+ at++;
871
+ continue;
872
+ }
873
+ at++;
874
+ while (at < length && isAttributeSpace(inside.charCodeAt(at)))
875
+ at++;
876
+ const quote = inside[at];
877
+ let valueStart;
878
+ let valueEnd;
879
+ if (quote === "\"" || quote === "'") {
880
+ valueStart = at + 1;
881
+ const end = inside.indexOf(quote, valueStart);
882
+ valueEnd = end === -1 ? length : end;
883
+ at = end === -1 ? length : end + 1;
884
+ }
885
+ else {
886
+ valueStart = at;
887
+ while (at < length && !isAttributeSpace(inside.charCodeAt(at)) && inside[at] !== ">")
888
+ at++;
889
+ valueEnd = at;
890
+ }
891
+ if (name === wanted)
892
+ return decodeHtmlEntities(inside.slice(valueStart, Math.min(valueEnd, valueStart + maxRaw)));
893
+ }
894
+ return undefined;
895
+ }
896
+ /**
897
+ * Whether a tag's attributes hide its element: "none" for the `hidden` attribute or an inline style
898
+ * of `display: none`, "invisible" for `visibility: hidden` or `collapse`, which keeps the element's
899
+ * place. Only the first `MAX_TAG` characters of the tag are read for it: a picture's address can be
900
+ * megabytes long.
901
+ */
902
+ function hiding(attributes) {
903
+ if (attributes.length < 5)
904
+ return undefined;
905
+ const inside = attributes.length > MAX_TAG ? attributes.slice(0, MAX_TAG) : attributes;
906
+ // Most tags have none of these words: their attributes are not read at all.
907
+ if (!/hidden|none|collapse/i.test(inside))
908
+ return undefined;
909
+ if (attributeOf(inside, "hidden", 0) !== undefined)
910
+ return "none";
911
+ const style = attributeOf(inside, "style", MAX_STYLE);
912
+ return style === undefined ? undefined : styleHiding(style);
913
+ }
914
+ /** An inline style is read up to this many characters for whether it hides its element. */
915
+ const MAX_STYLE = 4_096;
916
+ /** The values of `display` and `visibility` a browser takes: a declaration with another value is dropped, as CSS drops it. */
917
+ const DISPLAY_VALUES = /^(?:none|block|inline|inline-block|flex|inline-flex|grid|inline-grid|contents|flow|flow-root|list-item|table|inline-table|table-row|table-cell|table-row-group|table-header-group|table-footer-group|table-column|table-column-group|table-caption|ruby|ruby-base|ruby-text|run-in|math|inherit|initial|unset|revert|revert-layer)$/;
918
+ const VISIBILITY_VALUES = /^(?:visible|hidden|collapse|inherit|initial|unset|revert|revert-layer)$/;
919
+ /** `hiding` of an inline style: the last `display` and `visibility` of it count, an `!important` one first. */
920
+ function styleHiding(style) {
921
+ const values = new Map();
922
+ for (const declaration of style.split(";")) {
923
+ const colon = declaration.indexOf(":");
924
+ if (colon === -1)
925
+ continue;
926
+ const property = declaration.slice(0, colon).trim().toLowerCase();
927
+ if (property !== "display" && property !== "visibility")
928
+ continue;
929
+ let value = declaration.slice(colon + 1).trim().toLowerCase();
930
+ const important = /!\s*important$/.test(value);
931
+ if (important)
932
+ value = value.slice(0, value.lastIndexOf("!")).trim();
933
+ // "display: foo" is dropped by CSS, and the declaration before it stays.
934
+ if (!(property === "display" ? DISPLAY_VALUES : VISIBILITY_VALUES).test(value))
935
+ continue;
936
+ if (important || !values.get(property)?.important)
937
+ values.set(property, { value, important });
938
+ }
939
+ if (values.get("display")?.value === "none")
940
+ return "none";
941
+ const visibility = values.get("visibility")?.value;
942
+ return visibility === "hidden" || visibility === "collapse" ? "invisible" : undefined;
943
+ }
944
+ /** The refusal of a page with more text than `maxTextBytes`, in the words of the other extractors. */
945
+ const tooMuchText = (maxTextBytes) => new Error(`This HTML page holds more than ${formatBytes(maxTextBytes)} of text, more than is kept from one file. Split it, and attach the part you need.`);
946
+ /**
947
+ * Where a piece of the text from `from` to `to` ends: after `TEXT_PIECE` characters at most, and
948
+ * not inside a character reference, between the two characters of "\r\n", or between the two
949
+ * halves of a character outside the basic plane.
950
+ */
951
+ function pieceEnd(html, from, to) {
952
+ if (to - from <= TEXT_PIECE)
953
+ return to;
954
+ const end = from + TEXT_PIECE;
955
+ const reference = html.slice(end - MAX_REFERENCE, end).lastIndexOf("&");
956
+ if (reference !== -1)
957
+ return end - MAX_REFERENCE + reference;
958
+ const last = html.charCodeAt(end - 1);
959
+ return last === 13 || (last >= 0xd800 && last <= 0xdbff) ? end - 1 : end;
960
+ }
961
+ /** A page's title from the text of its `<title>`: its first `MAX_TITLE` characters, read from the start of that text only. */
962
+ function titleOf(content) {
963
+ return sliceWhole(decodeSpaces(decodeHtmlEntities(content.slice(0, MAX_TITLE * 8))).trim(), MAX_TITLE).trimEnd();
964
+ }
965
+ const TAG_NAME = /<(\/?)([A-Za-z][A-Za-z0-9:-]*)/y;
966
+ /**
967
+ * The text of an HTML page (see the comment at the top of this file), with pauses for other
968
+ * requests. `maxTextBytes`: it is refused as soon as its text grows past this many characters (a
969
+ * character is at least one byte).
970
+ */
971
+ export async function htmlToText(html, signal, maxTextBytes = Number.POSITIVE_INFINITY) {
972
+ const slicer = new TimeSlicer(signal);
973
+ const out = new HtmlText(maxTextBytes);
974
+ let title;
975
+ let hasHeading = false;
976
+ const length = html.length;
977
+ // Raw-text elements whose end tag was looked for and is not there: it is not looked for again.
978
+ const unclosed = new Set();
979
+ let steps = 0;
980
+ let looked = 0;
981
+ // Text longer than a piece is read a piece at a time, with a look at the clock after each.
982
+ const readText = async (from, to) => {
983
+ for (let at = from; at < to;) {
984
+ const end = pieceEnd(html, at, to);
985
+ out.text(html.slice(at, end));
986
+ at = end;
987
+ await slicer.maybePause();
988
+ }
989
+ };
990
+ for (let at = 0; at < length;) {
991
+ // A look at the clock every so many tags, and after each piece of text or tags of some length.
992
+ if ((++steps & 1023) === 0 || at - looked >= TEXT_PIECE) {
993
+ looked = at;
994
+ await slicer.maybePause();
995
+ }
996
+ const start = html.indexOf("<", at);
997
+ const textEnd = start === -1 ? length : start;
998
+ if (textEnd - at > TEXT_PIECE)
999
+ await readText(at, textEnd);
1000
+ else if (textEnd > at)
1001
+ out.text(html.slice(at, textEnd));
1002
+ if (start === -1)
1003
+ break;
1004
+ if (html.startsWith("<!--", start)) {
1005
+ const end = html.indexOf("-->", start + 4);
1006
+ at = end === -1 ? length : end + 3;
1007
+ continue;
1008
+ }
1009
+ if (html.startsWith("<!", start) || html.startsWith("<?", start)) {
1010
+ const end = html.indexOf(">", start);
1011
+ at = end === -1 ? length : end + 1;
1012
+ continue;
1013
+ }
1014
+ TAG_NAME.lastIndex = start;
1015
+ const named = TAG_NAME.exec(html);
1016
+ if (!named) {
1017
+ out.text("<");
1018
+ at = start + 1;
1019
+ continue;
1020
+ }
1021
+ const closing = named[1] === "/";
1022
+ const name = named[2].toLowerCase();
1023
+ // The tag's end: its first ">" outside quotes, unless the quotes run on too far.
1024
+ let end = -1;
1025
+ let quote = 0;
1026
+ const limit = Math.min(length, TAG_NAME.lastIndex + MAX_TAG);
1027
+ for (let index = TAG_NAME.lastIndex; index < limit; index++) {
1028
+ const code = html.charCodeAt(index);
1029
+ if (quote !== 0) {
1030
+ if (code === quote)
1031
+ quote = 0;
1032
+ }
1033
+ else if (code === 34 || code === 39) {
1034
+ quote = code;
1035
+ }
1036
+ else if (code === 62) {
1037
+ end = index;
1038
+ break;
1039
+ }
1040
+ }
1041
+ if (end === -1)
1042
+ end = html.indexOf(">", TAG_NAME.lastIndex);
1043
+ if (end === -1)
1044
+ end = length;
1045
+ const inside = html.slice(TAG_NAME.lastIndex, end);
1046
+ const selfClosing = inside.endsWith("/");
1047
+ const attributes = selfClosing ? inside.slice(0, -1) : inside;
1048
+ at = end + 1;
1049
+ if (closing) {
1050
+ out.close(name);
1051
+ continue;
1052
+ }
1053
+ if (HEADING.test(name))
1054
+ hasHeading = true;
1055
+ if (RAW_TEXT.has(name)) {
1056
+ let found = null;
1057
+ if (!unclosed.has(name)) {
1058
+ const closer = new RegExp(`</${name}\\s*>`, "gi");
1059
+ closer.lastIndex = at;
1060
+ found = closer.exec(html);
1061
+ if (!found)
1062
+ unclosed.add(name);
1063
+ }
1064
+ if (name === "title") {
1065
+ // A title never closed would take the rest of the page, which a browser then does not show:
1066
+ // the rest is read as the page instead. The title of an inline SVG (or of anything else left
1067
+ // out) does not name the page: it is left out with what holds it.
1068
+ if (!found)
1069
+ continue;
1070
+ if (title === undefined && !out.skipped)
1071
+ title = titleOf(html.slice(at, found.index));
1072
+ at = found.index + found[0].length;
1073
+ continue;
1074
+ }
1075
+ if (name === "textarea" || name === "xmp" || name === "plaintext") {
1076
+ out.open("pre", attributes);
1077
+ await readText(at, found ? found.index : length);
1078
+ out.close("pre");
1079
+ }
1080
+ at = found ? found.index + found[0].length : length;
1081
+ continue;
1082
+ }
1083
+ out.open(name, attributes);
1084
+ // `<svg/>` holds nothing: it ends where it starts.
1085
+ if (selfClosing && SKIPPED.has(name))
1086
+ out.close(name);
1087
+ }
1088
+ await slicer.maybePause();
1089
+ const body = out.result();
1090
+ // The title names the page, when no heading of it does. It is looked for at the start of the text
1091
+ // only: in a text of megabytes, a title written to be found nowhere took seconds to look for.
1092
+ if (!title || (hasHeading && body.slice(0, TITLE_SEARCH).includes(title)))
1093
+ return body;
1094
+ if (body.length + title.length + 4 > maxTextBytes)
1095
+ throw tooMuchText(maxTextBytes);
1096
+ return body ? `# ${title}\n\n${body}` : `# ${title}`;
1097
+ }
1098
+ export const html = async (bytes, input) => {
1099
+ input?.signal?.throwIfAborted();
1100
+ const slicer = new TimeSlicer(input?.signal);
1101
+ const steps = decodeSteps(bytes);
1102
+ let step = steps.next();
1103
+ while (!step.done) {
1104
+ await slicer.maybePause();
1105
+ step = steps.next();
1106
+ }
1107
+ const { text, encoding, replacedCharacters } = step.value;
1108
+ const converted = await htmlToText(text, input?.signal, input?.maxTextBytes);
1109
+ input?.onProgress?.({ stage: "decode", done: bytes.byteLength, total: bytes.byteLength, unit: "bytes" });
1110
+ return { text: converted, ...(encoding ? { encoding } : {}), ...(replacedCharacters ? { replacedCharacters } : {}) };
1111
+ };
1112
+ //# sourceMappingURL=html.js.map