ceulen 0.5.0 → 0.7.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 (358) hide show
  1. package/CHANGELOG.md +317 -12
  2. package/README.md +87 -91
  3. package/extensions/lib/advisor-marker.ts +33 -0
  4. package/extensions/lib/panel.ts +25 -2
  5. package/extensions/lib/rate.ts +24 -0
  6. package/extensions/lib/registry.ts +93 -7
  7. package/extensions/lib/tools.ts +47 -0
  8. package/extensions/lib/usage-store.ts +33 -0
  9. package/extensions/modules/advisor/commands/advisor.ts +244 -0
  10. package/extensions/modules/advisor/configPanel.ts +194 -0
  11. package/extensions/modules/advisor/index.ts +217 -0
  12. package/extensions/modules/advisor/lib/config.ts +248 -0
  13. package/extensions/modules/advisor/lib/emission-guard.ts +153 -0
  14. package/extensions/modules/advisor/lib/isolated-model.ts +160 -0
  15. package/extensions/modules/advisor/lib/model-picker.ts +47 -0
  16. package/extensions/modules/advisor/lib/watcher.ts +286 -0
  17. package/extensions/modules/advisor/test/compliance.test.ts +125 -0
  18. package/extensions/modules/advisor/test/config.test.ts +202 -0
  19. package/extensions/modules/advisor/test/configPanel.test.ts +223 -0
  20. package/extensions/modules/advisor/test/emission-guard.test.ts +201 -0
  21. package/extensions/modules/advisor/test/isolated-model.test.ts +311 -0
  22. package/extensions/modules/advisor/test/model-picker.test.ts +32 -0
  23. package/extensions/modules/advisor/test/module.test.ts +586 -0
  24. package/extensions/modules/advisor/test/watcher.test.ts +478 -0
  25. package/extensions/modules/classifier/configPanel.ts +104 -0
  26. package/extensions/modules/classifier/index.ts +297 -0
  27. package/extensions/modules/classifier/lib/settings.ts +95 -0
  28. package/extensions/modules/classifier/test/classifier.test.ts +475 -0
  29. package/extensions/modules/composer/index.ts +152 -3
  30. package/extensions/modules/composer/lib/footer.ts +119 -0
  31. package/extensions/modules/composer/lib/shapes.ts +265 -26
  32. package/extensions/modules/composer/test/editor.test.ts +1 -1
  33. package/extensions/modules/composer/test/footer.test.ts +96 -0
  34. package/extensions/modules/composer/test/module.test.ts +113 -11
  35. package/extensions/modules/composer/test/screen.test.ts +29 -1
  36. package/extensions/modules/composer/test/shapes.test.ts +224 -8
  37. package/extensions/modules/config/defaultTools.ts +96 -0
  38. package/extensions/modules/config/index.ts +147 -7
  39. package/extensions/modules/config/piSettings.ts +254 -69
  40. package/extensions/modules/config/test/defaultTools.test.ts +122 -0
  41. package/extensions/modules/config/test/menu.test.ts +64 -0
  42. package/extensions/modules/config/test/panel.test.ts +38 -23
  43. package/extensions/modules/config/test/piSettings.test.ts +130 -3
  44. package/extensions/modules/config/test/renderTools.test.ts +71 -0
  45. package/extensions/modules/config/test/tools.test.ts +146 -0
  46. package/extensions/modules/fff/index.ts +2094 -0
  47. package/extensions/modules/fff/lib/query.ts +129 -0
  48. package/extensions/modules/fff/test/index.test.ts +607 -0
  49. package/extensions/modules/fff/test/query.test.ts +71 -0
  50. package/extensions/modules/munin/configPanel.ts +105 -0
  51. package/extensions/modules/munin/index.ts +641 -0
  52. package/extensions/modules/munin/lib/helpers.ts +471 -0
  53. package/extensions/modules/munin/lib/retry.ts +20 -0
  54. package/extensions/modules/munin/lib/sdk.ts +218 -0
  55. package/extensions/modules/munin/test/config.test.ts +168 -0
  56. package/extensions/modules/munin/test/configPanel.test.ts +161 -0
  57. package/extensions/modules/munin/test/extension.test.ts +224 -0
  58. package/extensions/modules/munin/test/helpers.test.ts +523 -0
  59. package/extensions/modules/munin/test/retry.test.ts +145 -0
  60. package/extensions/modules/munin/test/stale-protocol.test.ts +554 -0
  61. package/extensions/modules/plan/configPanel.ts +152 -0
  62. package/extensions/modules/plan/index.ts +917 -0
  63. package/extensions/modules/plan/lib/plan-tools.ts +72 -0
  64. package/extensions/modules/plan/lib/prompt.ts +65 -0
  65. package/extensions/modules/plan/lib/settings.ts +166 -0
  66. package/extensions/modules/plan/lib/shell-gate.ts +200 -0
  67. package/extensions/modules/plan/test/configPanel.test.ts +96 -0
  68. package/extensions/modules/plan/test/harness.ts +133 -0
  69. package/extensions/modules/plan/test/module.test.ts +305 -0
  70. package/extensions/modules/plan/test/settings.test.ts +114 -0
  71. package/extensions/modules/plan/test/shell-gate.test.ts +103 -0
  72. package/extensions/modules/ponytail/index.ts +23 -73
  73. package/extensions/modules/ponytail/lib/config.ts +1 -6
  74. package/extensions/modules/ponytail/test/extension.test.ts +1 -85
  75. package/extensions/modules/repair/configPanel.ts +96 -0
  76. package/extensions/modules/repair/index.ts +414 -0
  77. package/extensions/modules/repair/lib/auto-bg.ts +333 -0
  78. package/extensions/modules/repair/lib/edit-repair.ts +155 -0
  79. package/extensions/modules/repair/lib/editor.ts +251 -0
  80. package/extensions/modules/repair/lib/guards.ts +34 -0
  81. package/extensions/modules/repair/lib/input-repair.ts +324 -0
  82. package/extensions/modules/repair/lib/patch.ts +481 -0
  83. package/extensions/modules/repair/lib/settings.ts +114 -0
  84. package/extensions/modules/repair/test/auto-bg.test.ts +405 -0
  85. package/extensions/modules/repair/test/edit-repair.test.ts +224 -0
  86. package/extensions/modules/repair/test/editor.test.ts +141 -0
  87. package/extensions/modules/repair/test/guards.test.ts +64 -0
  88. package/extensions/modules/repair/test/input-repair.test.ts +231 -0
  89. package/extensions/modules/repair/test/patch.test.ts +563 -0
  90. package/extensions/modules/repair/test/settings.test.ts +167 -0
  91. package/extensions/modules/repair/test/wrapper.test.ts +210 -0
  92. package/extensions/modules/router/commands/commands.ts +4 -0
  93. package/extensions/modules/router/lib/client.ts +61 -0
  94. package/extensions/modules/router/lib/provider.ts +34 -13
  95. package/extensions/modules/router/lib/systemone.ts +152 -0
  96. package/extensions/modules/router/test/unit.test.ts +179 -0
  97. package/extensions/modules/rtk/findFallback.js +68 -0
  98. package/extensions/modules/rtk/index.ts +248 -0
  99. package/extensions/modules/rtk/safe-rewrite.js +74 -0
  100. package/extensions/modules/rtk/test/findFallback.test.js +66 -0
  101. package/extensions/modules/rtk/test/index.test.js +131 -0
  102. package/extensions/modules/rtk/test/safe-rewrite.test.js +96 -0
  103. package/extensions/modules/rtk/version-gate.js +34 -0
  104. package/extensions/modules/serena/index.ts +629 -0
  105. package/extensions/modules/serena/lib/detect.ts +73 -0
  106. package/extensions/modules/serena/lib/env.ts +76 -0
  107. package/extensions/modules/serena/lib/guidance.ts +26 -0
  108. package/extensions/modules/serena/lib/normalize.ts +27 -0
  109. package/extensions/modules/serena/lib/symbol-key.ts +20 -0
  110. package/extensions/modules/serena/lib/truncate.ts +20 -0
  111. package/extensions/modules/serena/test/env.test.ts +122 -0
  112. package/extensions/modules/serena/test/index.test.ts +347 -0
  113. package/extensions/modules/serena/test/worker.test.ts +562 -0
  114. package/extensions/modules/serena/worker.ts +858 -0
  115. package/extensions/modules/steering/configPanel.ts +122 -0
  116. package/extensions/modules/steering/index.ts +616 -0
  117. package/extensions/modules/steering/lib/anchor.ts +175 -0
  118. package/extensions/modules/steering/lib/errors.ts +253 -0
  119. package/extensions/modules/steering/lib/family.ts +33 -0
  120. package/extensions/modules/steering/lib/guidance.ts +172 -0
  121. package/extensions/modules/steering/lib/history.ts +170 -0
  122. package/extensions/modules/steering/lib/settings.ts +127 -0
  123. package/extensions/modules/steering/test/anchor-regressions.test.ts +93 -0
  124. package/extensions/modules/steering/test/anchor-wiring.test.ts +99 -0
  125. package/extensions/modules/steering/test/anchor.test.ts +160 -0
  126. package/extensions/modules/steering/test/cache-stats.test.ts +43 -0
  127. package/extensions/modules/steering/test/errors.test.ts +309 -0
  128. package/extensions/modules/steering/test/family.test.ts +43 -0
  129. package/extensions/modules/steering/test/guidance.test.ts +357 -0
  130. package/extensions/modules/steering/test/harness.ts +93 -0
  131. package/extensions/modules/steering/test/history.test.ts +118 -0
  132. package/extensions/modules/steering/test/settings.test.ts +182 -0
  133. package/extensions/modules/steering/test/status.test.ts +71 -0
  134. package/extensions/modules/steering/test/toolCall.test.ts +99 -0
  135. package/extensions/modules/subagent/agents/planner.md +14 -0
  136. package/extensions/modules/subagent/agents/reviewer.md +42 -0
  137. package/extensions/modules/subagent/agents/scout.md +47 -0
  138. package/extensions/modules/subagent/agents/tester.md +12 -0
  139. package/extensions/modules/subagent/agents/worker.md +18 -0
  140. package/extensions/modules/subagent/configPanel.ts +219 -0
  141. package/extensions/modules/subagent/index.ts +2451 -0
  142. package/extensions/modules/subagent/lib/agents.ts +408 -0
  143. package/extensions/modules/subagent/lib/background.ts +383 -0
  144. package/extensions/modules/subagent/lib/herdr.ts +1019 -0
  145. package/extensions/modules/subagent/lib/history.ts +126 -0
  146. package/extensions/modules/subagent/lib/model.ts +156 -0
  147. package/extensions/modules/subagent/lib/render.ts +335 -0
  148. package/extensions/modules/subagent/lib/result.ts +110 -0
  149. package/extensions/modules/subagent/lib/roles.ts +296 -0
  150. package/extensions/modules/subagent/lib/routing.ts +223 -0
  151. package/extensions/modules/subagent/lib/runner.ts +559 -0
  152. package/extensions/modules/subagent/lib/schema.ts +21 -0
  153. package/extensions/modules/subagent/lib/security.ts +752 -0
  154. package/extensions/modules/subagent/lib/settings.ts +159 -0
  155. package/extensions/modules/subagent/lib/thread-viewer.ts +319 -0
  156. package/extensions/modules/subagent/lib/threads.ts +135 -0
  157. package/extensions/modules/subagent/lib/types.ts +18 -0
  158. package/extensions/modules/subagent/lib/widget.ts +475 -0
  159. package/extensions/modules/subagent/test/configPanel.test.ts +132 -0
  160. package/extensions/modules/subagent/test/herdr-advisor.test.ts +40 -0
  161. package/extensions/modules/subagent/test/routing.test.ts +350 -0
  162. package/extensions/modules/subagent/test/widget.test.ts +208 -0
  163. package/extensions/modules/usage/index.ts +59 -16
  164. package/extensions/modules/usage/test/genrate.test.ts +70 -0
  165. package/extensions/modules/usage/test/parsers.test.ts +13 -0
  166. package/extensions/modules/ux/UPSTREAM +24 -0
  167. package/extensions/modules/ux/index.ts +393 -0
  168. package/extensions/modules/ux/lib/audit.ts +562 -0
  169. package/extensions/modules/ux/lib/config.ts +136 -0
  170. package/extensions/modules/ux/lib/instructions.ts +77 -0
  171. package/extensions/modules/ux/test/audit.test.ts +756 -0
  172. package/extensions/modules/ux/test/extension.test.ts +394 -0
  173. package/extensions/modules/ux/test/instructions.test.ts +19 -0
  174. package/extensions/modules/web/configPanel.ts +193 -0
  175. package/extensions/modules/web/index.ts +978 -0
  176. package/extensions/modules/web/lib/agy.ts +209 -0
  177. package/extensions/modules/web/lib/brave.ts +42 -0
  178. package/extensions/modules/web/lib/cdp.ts +686 -0
  179. package/extensions/modules/web/lib/chatapi.ts +101 -0
  180. package/extensions/modules/web/lib/chatgpt.ts +796 -0
  181. package/extensions/modules/web/lib/chrome.ts +328 -0
  182. package/extensions/modules/web/lib/config.ts +136 -0
  183. package/extensions/modules/web/lib/content.ts +99 -0
  184. package/extensions/modules/web/lib/crawl4ai.ts +172 -0
  185. package/extensions/modules/web/lib/extract.ts +235 -0
  186. package/extensions/modules/web/lib/firecrawl.ts +56 -0
  187. package/extensions/modules/web/lib/format.ts +197 -0
  188. package/extensions/modules/web/lib/gemini-auth.ts +286 -0
  189. package/extensions/modules/web/lib/gemini-dr.ts +338 -0
  190. package/extensions/modules/web/lib/gemini.ts +551 -0
  191. package/extensions/modules/web/lib/imageapi.ts +559 -0
  192. package/extensions/modules/web/lib/retry.ts +71 -0
  193. package/extensions/modules/web/lib/search.ts +237 -0
  194. package/extensions/modules/web/lib/searxng.ts +69 -0
  195. package/extensions/modules/web/lib/settings.ts +148 -0
  196. package/extensions/modules/web/scripts/cdp-smoke.ts +77 -0
  197. package/extensions/modules/web/scripts/gemini-smoke.ts +107 -0
  198. package/extensions/modules/web/test/agy.test.ts +383 -0
  199. package/extensions/modules/web/test/cdp.test.ts +717 -0
  200. package/extensions/modules/web/test/chat.test.ts +171 -0
  201. package/extensions/modules/web/test/chatgpt.test.ts +633 -0
  202. package/extensions/modules/web/test/chrome.test.ts +282 -0
  203. package/extensions/modules/web/test/config.test.ts +218 -0
  204. package/extensions/modules/web/test/configPanel.test.ts +132 -0
  205. package/extensions/modules/web/test/crawl.test.ts +134 -0
  206. package/extensions/modules/web/test/crawl4ai.test.ts +105 -0
  207. package/extensions/modules/web/test/extension.test.ts +118 -0
  208. package/extensions/modules/web/test/extract.test.ts +436 -0
  209. package/extensions/modules/web/test/fixtures/dr-confirm.bin +12 -0
  210. package/extensions/modules/web/test/fixtures/dr-plan.bin +20 -0
  211. package/extensions/modules/web/test/fixtures/interaction.html +31 -0
  212. package/extensions/modules/web/test/format.test.ts +230 -0
  213. package/extensions/modules/web/test/gemini-auth.test.ts +465 -0
  214. package/extensions/modules/web/test/gemini-dr.test.ts +249 -0
  215. package/extensions/modules/web/test/gemini.test.ts +472 -0
  216. package/extensions/modules/web/test/hook.test.ts +101 -0
  217. package/extensions/modules/web/test/image.test.ts +1089 -0
  218. package/extensions/modules/web/test/retry.test.ts +119 -0
  219. package/extensions/modules/web/test/screenshot.test.ts +109 -0
  220. package/extensions/modules/web/test/search.test.ts +210 -0
  221. package/extensions/modules/web/test/settings.test.ts +165 -0
  222. package/extensions/modules/web/test/skill.test.ts +72 -0
  223. package/extensions/modules/web/types.d.ts +3 -0
  224. package/extensions/modules/web/vendor/package.json +1 -0
  225. package/extensions/modules/web/vendor/readability/LICENSE.md +13 -0
  226. package/extensions/modules/web/vendor/readability/Readability-readerable.js +123 -0
  227. package/extensions/modules/web/vendor/readability/Readability.js +2787 -0
  228. package/extensions/modules/web/vendor/readability/index.d.ts +64 -0
  229. package/extensions/modules/web/vendor/readability/index.js +9 -0
  230. package/extensions/modules/web/vendor/turndown/LICENSE +21 -0
  231. package/extensions/modules/web/vendor/turndown/turndown.cjs.js +784 -0
  232. package/extensions/modules/web/vendor/turndown-plugin-gfm/LICENSE +21 -0
  233. package/extensions/modules/web/vendor/turndown-plugin-gfm/turndown-plugin-gfm.cjs.js +163 -0
  234. package/extensions/modules/zai/configPanel.ts +151 -0
  235. package/extensions/modules/zai/index.ts +186 -0
  236. package/extensions/modules/zai/lib/anthropic.ts +159 -0
  237. package/extensions/modules/zai/lib/settings.ts +198 -0
  238. package/extensions/modules/zai/lib/signing.ts +718 -0
  239. package/extensions/modules/zai/lib/throttle.ts +198 -0
  240. package/extensions/modules/zai/test/anthropic.test.ts +132 -0
  241. package/extensions/modules/zai/test/configPanel.test.ts +207 -0
  242. package/extensions/modules/zai/test/extension.test.ts +249 -0
  243. package/extensions/modules/zai/test/settings.test.ts +183 -0
  244. package/extensions/modules/zai/test/signing-wiring.test.ts +108 -0
  245. package/extensions/modules/zai/test/signing.test.ts +345 -0
  246. package/extensions/modules/zai/test/throttle.test.ts +329 -0
  247. package/package.json +19 -4
  248. package/scripts/validate-themes.mjs +75 -0
  249. package/skills/munin/SKILL.md +117 -0
  250. package/skills/ux-capture/SKILL.md +202 -0
  251. package/skills/ux-design/SKILL.md +279 -0
  252. package/skills/ux-presets/SKILL.md +484 -0
  253. package/skills/ux-routing/SKILL.md +46 -0
  254. package/skills/web/SKILL.md +153 -0
  255. package/themes/alabaster.json +93 -0
  256. package/themes/amethyst.json +96 -0
  257. package/themes/anthracite.json +93 -0
  258. package/themes/basalt.json +91 -0
  259. package/themes/birch.json +95 -0
  260. package/themes/catppuccin-mocha.json +91 -0
  261. package/themes/dark-abyss.json +91 -0
  262. package/themes/dark-arctic.json +104 -0
  263. package/themes/dark-aurora.json +95 -0
  264. package/themes/dark-catppuccin.json +107 -0
  265. package/themes/dark-cavern.json +91 -0
  266. package/themes/dark-celestial.json +106 -0
  267. package/themes/dark-copper.json +95 -0
  268. package/themes/dark-cosmos.json +90 -0
  269. package/themes/dark-cyberpunk.json +102 -0
  270. package/themes/dark-dracula.json +98 -0
  271. package/themes/dark-eclipse.json +91 -0
  272. package/themes/dark-ember.json +95 -0
  273. package/themes/dark-equinox.json +90 -0
  274. package/themes/dark-forest.json +96 -0
  275. package/themes/dark-github.json +105 -0
  276. package/themes/dark-gruvbox.json +112 -0
  277. package/themes/dark-lavender.json +95 -0
  278. package/themes/dark-lunar.json +89 -0
  279. package/themes/dark-midnight.json +95 -0
  280. package/themes/dark-monochrome.json +94 -0
  281. package/themes/dark-monokai.json +98 -0
  282. package/themes/dark-nebula.json +90 -0
  283. package/themes/dark-neon-noir.json +100 -0
  284. package/themes/dark-nord.json +98 -0
  285. package/themes/dark-ocean.json +101 -0
  286. package/themes/dark-one.json +100 -0
  287. package/themes/dark-poimandres.json +115 -0
  288. package/themes/dark-rainforest.json +91 -0
  289. package/themes/dark-reef.json +91 -0
  290. package/themes/dark-retro.json +92 -0
  291. package/themes/dark-rose-pine.json +96 -0
  292. package/themes/dark-sakura.json +95 -0
  293. package/themes/dark-slate.json +95 -0
  294. package/themes/dark-solarized.json +97 -0
  295. package/themes/dark-solstice.json +90 -0
  296. package/themes/dark-starfall.json +91 -0
  297. package/themes/dark-sunset.json +99 -0
  298. package/themes/dark-swamp.json +90 -0
  299. package/themes/dark-synthwave.json +103 -0
  300. package/themes/dark-taiga.json +91 -0
  301. package/themes/dark-terminal.json +95 -0
  302. package/themes/dark-tokyo-night.json +101 -0
  303. package/themes/dark-tundra.json +91 -0
  304. package/themes/dark-twilight.json +91 -0
  305. package/themes/dark-volcanic.json +91 -0
  306. package/themes/dark.json +80 -0
  307. package/themes/graphite.json +92 -0
  308. package/themes/light-arctic.json +107 -0
  309. package/themes/light-aurora-day.json +91 -0
  310. package/themes/light-canyon.json +91 -0
  311. package/themes/light-catppuccin.json +106 -0
  312. package/themes/light-cirrus.json +90 -0
  313. package/themes/light-coral.json +95 -0
  314. package/themes/light-cyberpunk.json +96 -0
  315. package/themes/light-dawn.json +90 -0
  316. package/themes/light-dunes.json +91 -0
  317. package/themes/light-eucalyptus.json +95 -0
  318. package/themes/light-forest.json +100 -0
  319. package/themes/light-frost.json +95 -0
  320. package/themes/light-github.json +115 -0
  321. package/themes/light-glacier.json +91 -0
  322. package/themes/light-gruvbox.json +108 -0
  323. package/themes/light-haze.json +90 -0
  324. package/themes/light-honeycomb.json +95 -0
  325. package/themes/light-lagoon.json +91 -0
  326. package/themes/light-lavender.json +95 -0
  327. package/themes/light-meadow.json +91 -0
  328. package/themes/light-mint.json +95 -0
  329. package/themes/light-monochrome.json +101 -0
  330. package/themes/light-ocean.json +99 -0
  331. package/themes/light-one.json +99 -0
  332. package/themes/light-opal.json +91 -0
  333. package/themes/light-orchard.json +91 -0
  334. package/themes/light-paper.json +95 -0
  335. package/themes/light-poimandres.json +115 -0
  336. package/themes/light-prism.json +90 -0
  337. package/themes/light-retro.json +98 -0
  338. package/themes/light-sand.json +95 -0
  339. package/themes/light-savanna.json +91 -0
  340. package/themes/light-solarized.json +102 -0
  341. package/themes/light-soleil.json +90 -0
  342. package/themes/light-sunset.json +99 -0
  343. package/themes/light-synthwave.json +98 -0
  344. package/themes/light-tokyo-night.json +111 -0
  345. package/themes/light-wetland.json +91 -0
  346. package/themes/light-zenith.json +89 -0
  347. package/themes/light.json +80 -0
  348. package/themes/limestone.json +94 -0
  349. package/themes/mahogany.json +97 -0
  350. package/themes/marble.json +93 -0
  351. package/themes/mirage.json +79 -0
  352. package/themes/obsidian.json +91 -0
  353. package/themes/onyx.json +91 -0
  354. package/themes/pearl.json +93 -0
  355. package/themes/porcelain.json +91 -0
  356. package/themes/quartz.json +96 -0
  357. package/themes/sandstone.json +95 -0
  358. package/themes/titanium.json +90 -0
@@ -0,0 +1,2787 @@
1
+ // ponytail: vendored from node_modules (see ceulen AGENTS.md web module section)
2
+ /*
3
+ * Copyright (c) 2010 Arc90 Inc
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ /*
19
+ * This code is heavily based on Arc90's readability.js (1.7.1) script
20
+ * available at: http://code.google.com/p/arc90labs-readability
21
+ */
22
+
23
+ /**
24
+ * Public constructor.
25
+ * @param {HTMLDocument} doc The document to parse.
26
+ * @param {Object} options The options object.
27
+ */
28
+ function Readability(doc, options) {
29
+ // In some older versions, people passed a URI as the first argument. Cope:
30
+ if (options && options.documentElement) {
31
+ doc = options;
32
+ options = arguments[2];
33
+ } else if (!doc || !doc.documentElement) {
34
+ throw new Error(
35
+ "First argument to Readability constructor should be a document object."
36
+ );
37
+ }
38
+ options = options || {};
39
+
40
+ this._doc = doc;
41
+ this._docJSDOMParser = this._doc.firstChild.__JSDOMParser__;
42
+ this._articleTitle = null;
43
+ this._articleByline = null;
44
+ this._articleDir = null;
45
+ this._articleSiteName = null;
46
+ this._attempts = [];
47
+ this._metadata = {};
48
+
49
+ // Configurable options
50
+ this._debug = !!options.debug;
51
+ this._maxElemsToParse =
52
+ options.maxElemsToParse || this.DEFAULT_MAX_ELEMS_TO_PARSE;
53
+ this._nbTopCandidates =
54
+ options.nbTopCandidates || this.DEFAULT_N_TOP_CANDIDATES;
55
+ this._charThreshold = options.charThreshold || this.DEFAULT_CHAR_THRESHOLD;
56
+ this._classesToPreserve = this.CLASSES_TO_PRESERVE.concat(
57
+ options.classesToPreserve || []
58
+ );
59
+ this._keepClasses = !!options.keepClasses;
60
+ this._serializer =
61
+ options.serializer ||
62
+ function (el) {
63
+ return el.innerHTML;
64
+ };
65
+ this._disableJSONLD = !!options.disableJSONLD;
66
+ this._allowedVideoRegex = options.allowedVideoRegex || this.REGEXPS.videos;
67
+ this._linkDensityModifier = options.linkDensityModifier || 0;
68
+
69
+ // Start with all flags set
70
+ this._flags =
71
+ this.FLAG_STRIP_UNLIKELYS |
72
+ this.FLAG_WEIGHT_CLASSES |
73
+ this.FLAG_CLEAN_CONDITIONALLY;
74
+
75
+ // Control whether log messages are sent to the console
76
+ if (this._debug) {
77
+ let logNode = function (node) {
78
+ if (node.nodeType == node.TEXT_NODE) {
79
+ return `${node.nodeName} ("${node.textContent}")`;
80
+ }
81
+ let attrPairs = Array.from(node.attributes || [], function (attr) {
82
+ return `${attr.name}="${attr.value}"`;
83
+ }).join(" ");
84
+ return `<${node.localName} ${attrPairs}>`;
85
+ };
86
+ this.log = function () {
87
+ if (typeof console !== "undefined") {
88
+ let args = Array.from(arguments, arg => {
89
+ if (arg && arg.nodeType == this.ELEMENT_NODE) {
90
+ return logNode(arg);
91
+ }
92
+ return arg;
93
+ });
94
+ args.unshift("Reader: (Readability)");
95
+ // eslint-disable-next-line no-console
96
+ console.log(...args);
97
+ } else if (typeof dump !== "undefined") {
98
+ /* global dump */
99
+ var msg = Array.prototype.map
100
+ .call(arguments, function (x) {
101
+ return x && x.nodeName ? logNode(x) : x;
102
+ })
103
+ .join(" ");
104
+ dump("Reader: (Readability) " + msg + "\n");
105
+ }
106
+ };
107
+ } else {
108
+ this.log = function () {};
109
+ }
110
+ }
111
+
112
+ Readability.prototype = {
113
+ FLAG_STRIP_UNLIKELYS: 0x1,
114
+ FLAG_WEIGHT_CLASSES: 0x2,
115
+ FLAG_CLEAN_CONDITIONALLY: 0x4,
116
+
117
+ // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
118
+ ELEMENT_NODE: 1,
119
+ TEXT_NODE: 3,
120
+
121
+ // Max number of nodes supported by this parser. Default: 0 (no limit)
122
+ DEFAULT_MAX_ELEMS_TO_PARSE: 0,
123
+
124
+ // The number of top candidates to consider when analysing how
125
+ // tight the competition is among candidates.
126
+ DEFAULT_N_TOP_CANDIDATES: 5,
127
+
128
+ // Element tags to score by default.
129
+ DEFAULT_TAGS_TO_SCORE: "section,h2,h3,h4,h5,h6,p,td,pre"
130
+ .toUpperCase()
131
+ .split(","),
132
+
133
+ // The default number of chars an article must have in order to return a result
134
+ DEFAULT_CHAR_THRESHOLD: 500,
135
+
136
+ // All of the regular expressions in use within readability.
137
+ // Defined up here so we don't instantiate them repeatedly in loops.
138
+ REGEXPS: {
139
+ // NOTE: These two regular expressions are duplicated in
140
+ // Readability-readerable.js. Please keep both copies in sync.
141
+ unlikelyCandidates:
142
+ /-ad-|ai2html|banner|breadcrumbs|combx|comment|community|cover-wrap|disqus|extra|footer|gdpr|header|legends|menu|related|remark|replies|rss|shoutbox|sidebar|skyscraper|social|sponsor|supplemental|ad-break|agegate|pagination|pager|popup|yom-remote/i,
143
+ okMaybeItsACandidate: /and|article|body|column|content|main|shadow/i,
144
+
145
+ positive:
146
+ /article|body|content|entry|hentry|h-entry|main|page|pagination|post|text|blog|story/i,
147
+ negative:
148
+ /-ad-|hidden|^hid$| hid$| hid |^hid |banner|combx|comment|com-|contact|footer|gdpr|masthead|media|meta|outbrain|promo|related|scroll|share|shoutbox|sidebar|skyscraper|sponsor|shopping|tags|widget/i,
149
+ extraneous:
150
+ /print|archive|comment|discuss|e[\-]?mail|share|reply|all|login|sign|single|utility/i,
151
+ byline: /byline|author|dateline|writtenby|p-author/i,
152
+ replaceFonts: /<(\/?)font[^>]*>/gi,
153
+ normalize: /\s{2,}/g,
154
+ videos:
155
+ /\/\/(www\.)?((dailymotion|youtube|youtube-nocookie|player\.vimeo|v\.qq)\.com|(archive|upload\.wikimedia)\.org|player\.twitch\.tv)/i,
156
+ shareElements: /(\b|_)(share|sharedaddy)(\b|_)/i,
157
+ nextLink: /(next|weiter|continue|>([^\|]|$)|»([^\|]|$))/i,
158
+ prevLink: /(prev|earl|old|new|<|«)/i,
159
+ tokenize: /\W+/g,
160
+ whitespace: /^\s*$/,
161
+ hasContent: /\S$/,
162
+ hashUrl: /^#.+/,
163
+ srcsetUrl: /(\S+)(\s+[\d.]+[xw])?(\s*(?:,|$))/g,
164
+ b64DataUrl: /^data:\s*([^\s;,]+)\s*;\s*base64\s*,/i,
165
+ // Commas as used in Latin, Sindhi, Chinese and various other scripts.
166
+ // see: https://en.wikipedia.org/wiki/Comma#Comma_variants
167
+ commas: /\u002C|\u060C|\uFE50|\uFE10|\uFE11|\u2E41|\u2E34|\u2E32|\uFF0C/g,
168
+ // See: https://schema.org/Article
169
+ jsonLdArticleTypes:
170
+ /^Article|AdvertiserContentArticle|NewsArticle|AnalysisNewsArticle|AskPublicNewsArticle|BackgroundNewsArticle|OpinionNewsArticle|ReportageNewsArticle|ReviewNewsArticle|Report|SatiricalArticle|ScholarlyArticle|MedicalScholarlyArticle|SocialMediaPosting|BlogPosting|LiveBlogPosting|DiscussionForumPosting|TechArticle|APIReference$/,
171
+ // used to see if a node's content matches words commonly used for ad blocks or loading indicators
172
+ adWords:
173
+ /^(ad(vertising|vertisement)?|pub(licité)?|werb(ung)?|广告|Реклама|Anuncio)$/iu,
174
+ loadingWords:
175
+ /^((loading|正在加载|Загрузка|chargement|cargando)(…|\.\.\.)?)$/iu,
176
+ },
177
+
178
+ UNLIKELY_ROLES: [
179
+ "menu",
180
+ "menubar",
181
+ "complementary",
182
+ "navigation",
183
+ "alert",
184
+ "alertdialog",
185
+ "dialog",
186
+ ],
187
+
188
+ DIV_TO_P_ELEMS: new Set([
189
+ "BLOCKQUOTE",
190
+ "DL",
191
+ "DIV",
192
+ "IMG",
193
+ "OL",
194
+ "P",
195
+ "PRE",
196
+ "TABLE",
197
+ "UL",
198
+ ]),
199
+
200
+ ALTER_TO_DIV_EXCEPTIONS: ["DIV", "ARTICLE", "SECTION", "P", "OL", "UL"],
201
+
202
+ PRESENTATIONAL_ATTRIBUTES: [
203
+ "align",
204
+ "background",
205
+ "bgcolor",
206
+ "border",
207
+ "cellpadding",
208
+ "cellspacing",
209
+ "frame",
210
+ "hspace",
211
+ "rules",
212
+ "style",
213
+ "valign",
214
+ "vspace",
215
+ ],
216
+
217
+ DEPRECATED_SIZE_ATTRIBUTE_ELEMS: ["TABLE", "TH", "TD", "HR", "PRE"],
218
+
219
+ // The commented out elements qualify as phrasing content but tend to be
220
+ // removed by readability when put into paragraphs, so we ignore them here.
221
+ PHRASING_ELEMS: [
222
+ // "CANVAS", "IFRAME", "SVG", "VIDEO",
223
+ "ABBR",
224
+ "AUDIO",
225
+ "B",
226
+ "BDO",
227
+ "BR",
228
+ "BUTTON",
229
+ "CITE",
230
+ "CODE",
231
+ "DATA",
232
+ "DATALIST",
233
+ "DFN",
234
+ "EM",
235
+ "EMBED",
236
+ "I",
237
+ "IMG",
238
+ "INPUT",
239
+ "KBD",
240
+ "LABEL",
241
+ "MARK",
242
+ "MATH",
243
+ "METER",
244
+ "NOSCRIPT",
245
+ "OBJECT",
246
+ "OUTPUT",
247
+ "PROGRESS",
248
+ "Q",
249
+ "RUBY",
250
+ "SAMP",
251
+ "SCRIPT",
252
+ "SELECT",
253
+ "SMALL",
254
+ "SPAN",
255
+ "STRONG",
256
+ "SUB",
257
+ "SUP",
258
+ "TEXTAREA",
259
+ "TIME",
260
+ "VAR",
261
+ "WBR",
262
+ ],
263
+
264
+ // These are the classes that readability sets itself.
265
+ CLASSES_TO_PRESERVE: ["page"],
266
+
267
+ // These are the list of HTML entities that need to be escaped.
268
+ HTML_ESCAPE_MAP: {
269
+ lt: "<",
270
+ gt: ">",
271
+ amp: "&",
272
+ quot: '"',
273
+ apos: "'",
274
+ },
275
+
276
+ /**
277
+ * Run any post-process modifications to article content as necessary.
278
+ *
279
+ * @param Element
280
+ * @return void
281
+ **/
282
+ _postProcessContent(articleContent) {
283
+ // Readability cannot open relative uris so we convert them to absolute uris.
284
+ this._fixRelativeUris(articleContent);
285
+
286
+ this._simplifyNestedElements(articleContent);
287
+
288
+ if (!this._keepClasses) {
289
+ // Remove classes.
290
+ this._cleanClasses(articleContent);
291
+ }
292
+ },
293
+
294
+ /**
295
+ * Iterates over a NodeList, calls `filterFn` for each node and removes node
296
+ * if function returned `true`.
297
+ *
298
+ * If function is not passed, removes all the nodes in node list.
299
+ *
300
+ * @param NodeList nodeList The nodes to operate on
301
+ * @param Function filterFn the function to use as a filter
302
+ * @return void
303
+ */
304
+ _removeNodes(nodeList, filterFn) {
305
+ // Avoid ever operating on live node lists.
306
+ if (this._docJSDOMParser && nodeList._isLiveNodeList) {
307
+ throw new Error("Do not pass live node lists to _removeNodes");
308
+ }
309
+ for (var i = nodeList.length - 1; i >= 0; i--) {
310
+ var node = nodeList[i];
311
+ var parentNode = node.parentNode;
312
+ if (parentNode) {
313
+ if (!filterFn || filterFn.call(this, node, i, nodeList)) {
314
+ parentNode.removeChild(node);
315
+ }
316
+ }
317
+ }
318
+ },
319
+
320
+ /**
321
+ * Iterates over a NodeList, and calls _setNodeTag for each node.
322
+ *
323
+ * @param NodeList nodeList The nodes to operate on
324
+ * @param String newTagName the new tag name to use
325
+ * @return void
326
+ */
327
+ _replaceNodeTags(nodeList, newTagName) {
328
+ // Avoid ever operating on live node lists.
329
+ if (this._docJSDOMParser && nodeList._isLiveNodeList) {
330
+ throw new Error("Do not pass live node lists to _replaceNodeTags");
331
+ }
332
+ for (const node of nodeList) {
333
+ this._setNodeTag(node, newTagName);
334
+ }
335
+ },
336
+
337
+ /**
338
+ * Iterate over a NodeList, which doesn't natively fully implement the Array
339
+ * interface.
340
+ *
341
+ * For convenience, the current object context is applied to the provided
342
+ * iterate function.
343
+ *
344
+ * @param NodeList nodeList The NodeList.
345
+ * @param Function fn The iterate function.
346
+ * @return void
347
+ */
348
+ _forEachNode(nodeList, fn) {
349
+ Array.prototype.forEach.call(nodeList, fn, this);
350
+ },
351
+
352
+ /**
353
+ * Iterate over a NodeList, and return the first node that passes
354
+ * the supplied test function
355
+ *
356
+ * For convenience, the current object context is applied to the provided
357
+ * test function.
358
+ *
359
+ * @param NodeList nodeList The NodeList.
360
+ * @param Function fn The test function.
361
+ * @return void
362
+ */
363
+ _findNode(nodeList, fn) {
364
+ return Array.prototype.find.call(nodeList, fn, this);
365
+ },
366
+
367
+ /**
368
+ * Iterate over a NodeList, return true if any of the provided iterate
369
+ * function calls returns true, false otherwise.
370
+ *
371
+ * For convenience, the current object context is applied to the
372
+ * provided iterate function.
373
+ *
374
+ * @param NodeList nodeList The NodeList.
375
+ * @param Function fn The iterate function.
376
+ * @return Boolean
377
+ */
378
+ _someNode(nodeList, fn) {
379
+ return Array.prototype.some.call(nodeList, fn, this);
380
+ },
381
+
382
+ /**
383
+ * Iterate over a NodeList, return true if all of the provided iterate
384
+ * function calls return true, false otherwise.
385
+ *
386
+ * For convenience, the current object context is applied to the
387
+ * provided iterate function.
388
+ *
389
+ * @param NodeList nodeList The NodeList.
390
+ * @param Function fn The iterate function.
391
+ * @return Boolean
392
+ */
393
+ _everyNode(nodeList, fn) {
394
+ return Array.prototype.every.call(nodeList, fn, this);
395
+ },
396
+
397
+ _getAllNodesWithTag(node, tagNames) {
398
+ if (node.querySelectorAll) {
399
+ return node.querySelectorAll(tagNames.join(","));
400
+ }
401
+ return [].concat.apply(
402
+ [],
403
+ tagNames.map(function (tag) {
404
+ var collection = node.getElementsByTagName(tag);
405
+ return Array.isArray(collection) ? collection : Array.from(collection);
406
+ })
407
+ );
408
+ },
409
+
410
+ /**
411
+ * Removes the class="" attribute from every element in the given
412
+ * subtree, except those that match CLASSES_TO_PRESERVE and
413
+ * the classesToPreserve array from the options object.
414
+ *
415
+ * @param Element
416
+ * @return void
417
+ */
418
+ _cleanClasses(node) {
419
+ var classesToPreserve = this._classesToPreserve;
420
+ var className = (node.getAttribute("class") || "")
421
+ .split(/\s+/)
422
+ .filter(cls => classesToPreserve.includes(cls))
423
+ .join(" ");
424
+
425
+ if (className) {
426
+ node.setAttribute("class", className);
427
+ } else {
428
+ node.removeAttribute("class");
429
+ }
430
+
431
+ for (node = node.firstElementChild; node; node = node.nextElementSibling) {
432
+ this._cleanClasses(node);
433
+ }
434
+ },
435
+
436
+ /**
437
+ * Tests whether a string is a URL or not.
438
+ *
439
+ * @param {string} str The string to test
440
+ * @return {boolean} true if str is a URL, false if not
441
+ */
442
+ _isUrl(str) {
443
+ try {
444
+ new URL(str);
445
+ return true;
446
+ } catch {
447
+ return false;
448
+ }
449
+ },
450
+ /**
451
+ * Converts each <a> and <img> uri in the given element to an absolute URI,
452
+ * ignoring #ref URIs.
453
+ *
454
+ * @param Element
455
+ * @return void
456
+ */
457
+ _fixRelativeUris(articleContent) {
458
+ var baseURI = this._doc.baseURI;
459
+ var documentURI = this._doc.documentURI;
460
+ function toAbsoluteURI(uri) {
461
+ // Leave hash links alone if the base URI matches the document URI:
462
+ if (baseURI == documentURI && uri.charAt(0) == "#") {
463
+ return uri;
464
+ }
465
+
466
+ // Otherwise, resolve against base URI:
467
+ try {
468
+ return new URL(uri, baseURI).href;
469
+ } catch (ex) {
470
+ // Something went wrong, just return the original:
471
+ }
472
+ return uri;
473
+ }
474
+
475
+ var links = this._getAllNodesWithTag(articleContent, ["a"]);
476
+ this._forEachNode(links, function (link) {
477
+ var href = link.getAttribute("href");
478
+ if (href) {
479
+ // Remove links with javascript: URIs, since
480
+ // they won't work after scripts have been removed from the page.
481
+ if (href.indexOf("javascript:") === 0) {
482
+ // if the link only contains simple text content, it can be converted to a text node
483
+ if (
484
+ link.childNodes.length === 1 &&
485
+ link.childNodes[0].nodeType === this.TEXT_NODE
486
+ ) {
487
+ var text = this._doc.createTextNode(link.textContent);
488
+ link.parentNode.replaceChild(text, link);
489
+ } else {
490
+ // if the link has multiple children, they should all be preserved
491
+ var container = this._doc.createElement("span");
492
+ while (link.firstChild) {
493
+ container.appendChild(link.firstChild);
494
+ }
495
+ link.parentNode.replaceChild(container, link);
496
+ }
497
+ } else {
498
+ link.setAttribute("href", toAbsoluteURI(href));
499
+ }
500
+ }
501
+ });
502
+
503
+ var medias = this._getAllNodesWithTag(articleContent, [
504
+ "img",
505
+ "picture",
506
+ "figure",
507
+ "video",
508
+ "audio",
509
+ "source",
510
+ ]);
511
+
512
+ this._forEachNode(medias, function (media) {
513
+ var src = media.getAttribute("src");
514
+ var poster = media.getAttribute("poster");
515
+ var srcset = media.getAttribute("srcset");
516
+
517
+ if (src) {
518
+ media.setAttribute("src", toAbsoluteURI(src));
519
+ }
520
+
521
+ if (poster) {
522
+ media.setAttribute("poster", toAbsoluteURI(poster));
523
+ }
524
+
525
+ if (srcset) {
526
+ var newSrcset = srcset.replace(
527
+ this.REGEXPS.srcsetUrl,
528
+ function (_, p1, p2, p3) {
529
+ return toAbsoluteURI(p1) + (p2 || "") + p3;
530
+ }
531
+ );
532
+
533
+ media.setAttribute("srcset", newSrcset);
534
+ }
535
+ });
536
+ },
537
+
538
+ _simplifyNestedElements(articleContent) {
539
+ var node = articleContent;
540
+
541
+ while (node) {
542
+ if (
543
+ node.parentNode &&
544
+ ["DIV", "SECTION"].includes(node.tagName) &&
545
+ !(node.id && node.id.startsWith("readability"))
546
+ ) {
547
+ if (this._isElementWithoutContent(node)) {
548
+ node = this._removeAndGetNext(node);
549
+ continue;
550
+ } else if (
551
+ this._hasSingleTagInsideElement(node, "DIV") ||
552
+ this._hasSingleTagInsideElement(node, "SECTION")
553
+ ) {
554
+ var child = node.children[0];
555
+ for (var i = 0; i < node.attributes.length; i++) {
556
+ child.setAttributeNode(node.attributes[i].cloneNode());
557
+ }
558
+ node.parentNode.replaceChild(child, node);
559
+ node = child;
560
+ continue;
561
+ }
562
+ }
563
+
564
+ node = this._getNextNode(node);
565
+ }
566
+ },
567
+
568
+ /**
569
+ * Get the article title as an H1.
570
+ *
571
+ * @return string
572
+ **/
573
+ _getArticleTitle() {
574
+ var doc = this._doc;
575
+ var curTitle = "";
576
+ var origTitle = "";
577
+
578
+ try {
579
+ curTitle = origTitle = doc.title.trim();
580
+
581
+ // If they had an element with id "title" in their HTML
582
+ if (typeof curTitle !== "string") {
583
+ curTitle = origTitle = this._getInnerText(
584
+ doc.getElementsByTagName("title")[0]
585
+ );
586
+ }
587
+ } catch (e) {
588
+ /* ignore exceptions setting the title. */
589
+ }
590
+
591
+ var titleHadHierarchicalSeparators = false;
592
+ function wordCount(str) {
593
+ return str.split(/\s+/).length;
594
+ }
595
+
596
+ // If there's a separator in the title, first remove the final part
597
+ if (/ [\|\-\\\/>»] /.test(curTitle)) {
598
+ titleHadHierarchicalSeparators = / [\\\/>»] /.test(curTitle);
599
+ let allSeparators = Array.from(origTitle.matchAll(/ [\|\-\\\/>»] /gi));
600
+ curTitle = origTitle.substring(0, allSeparators.pop().index);
601
+
602
+ // If the resulting title is too short, remove the first part instead:
603
+ if (wordCount(curTitle) < 3) {
604
+ curTitle = origTitle.replace(/^[^\|\-\\\/>»]*[\|\-\\\/>»]/gi, "");
605
+ }
606
+ } else if (curTitle.includes(": ")) {
607
+ // Check if we have an heading containing this exact string, so we
608
+ // could assume it's the full title.
609
+ var headings = this._getAllNodesWithTag(doc, ["h1", "h2"]);
610
+ var trimmedTitle = curTitle.trim();
611
+ var match = this._someNode(headings, function (heading) {
612
+ return heading.textContent.trim() === trimmedTitle;
613
+ });
614
+
615
+ // If we don't, let's extract the title out of the original title string.
616
+ if (!match) {
617
+ curTitle = origTitle.substring(origTitle.lastIndexOf(":") + 1);
618
+
619
+ // If the title is now too short, try the first colon instead:
620
+ if (wordCount(curTitle) < 3) {
621
+ curTitle = origTitle.substring(origTitle.indexOf(":") + 1);
622
+ // But if we have too many words before the colon there's something weird
623
+ // with the titles and the H tags so let's just use the original title instead
624
+ } else if (wordCount(origTitle.substr(0, origTitle.indexOf(":"))) > 5) {
625
+ curTitle = origTitle;
626
+ }
627
+ }
628
+ } else if (curTitle.length > 150 || curTitle.length < 15) {
629
+ var hOnes = doc.getElementsByTagName("h1");
630
+
631
+ if (hOnes.length === 1) {
632
+ curTitle = this._getInnerText(hOnes[0]);
633
+ }
634
+ }
635
+
636
+ curTitle = curTitle.trim().replace(this.REGEXPS.normalize, " ");
637
+ // If we now have 4 words or fewer as our title, and either no
638
+ // 'hierarchical' separators (\, /, > or ») were found in the original
639
+ // title or we decreased the number of words by more than 1 word, use
640
+ // the original title.
641
+ var curTitleWordCount = wordCount(curTitle);
642
+ if (
643
+ curTitleWordCount <= 4 &&
644
+ (!titleHadHierarchicalSeparators ||
645
+ curTitleWordCount !=
646
+ wordCount(origTitle.replace(/[\|\-\\\/>»]+/g, "")) - 1)
647
+ ) {
648
+ curTitle = origTitle;
649
+ }
650
+
651
+ return curTitle;
652
+ },
653
+
654
+ /**
655
+ * Prepare the HTML document for readability to scrape it.
656
+ * This includes things like stripping javascript, CSS, and handling terrible markup.
657
+ *
658
+ * @return void
659
+ **/
660
+ _prepDocument() {
661
+ var doc = this._doc;
662
+
663
+ // Remove all style tags in head
664
+ this._removeNodes(this._getAllNodesWithTag(doc, ["style"]));
665
+
666
+ if (doc.body) {
667
+ this._replaceBrs(doc.body);
668
+ }
669
+
670
+ this._replaceNodeTags(this._getAllNodesWithTag(doc, ["font"]), "SPAN");
671
+ },
672
+
673
+ /**
674
+ * Finds the next node, starting from the given node, and ignoring
675
+ * whitespace in between. If the given node is an element, the same node is
676
+ * returned.
677
+ */
678
+ _nextNode(node) {
679
+ var next = node;
680
+ while (
681
+ next &&
682
+ next.nodeType != this.ELEMENT_NODE &&
683
+ this.REGEXPS.whitespace.test(next.textContent)
684
+ ) {
685
+ next = next.nextSibling;
686
+ }
687
+ return next;
688
+ },
689
+
690
+ /**
691
+ * Replaces 2 or more successive <br> elements with a single <p>.
692
+ * Whitespace between <br> elements are ignored. For example:
693
+ * <div>foo<br>bar<br> <br><br>abc</div>
694
+ * will become:
695
+ * <div>foo<br>bar<p>abc</p></div>
696
+ */
697
+ _replaceBrs(elem) {
698
+ this._forEachNode(this._getAllNodesWithTag(elem, ["br"]), function (br) {
699
+ var next = br.nextSibling;
700
+
701
+ // Whether 2 or more <br> elements have been found and replaced with a
702
+ // <p> block.
703
+ var replaced = false;
704
+
705
+ // If we find a <br> chain, remove the <br>s until we hit another node
706
+ // or non-whitespace. This leaves behind the first <br> in the chain
707
+ // (which will be replaced with a <p> later).
708
+ while ((next = this._nextNode(next)) && next.tagName == "BR") {
709
+ replaced = true;
710
+ var brSibling = next.nextSibling;
711
+ next.remove();
712
+ next = brSibling;
713
+ }
714
+
715
+ // If we removed a <br> chain, replace the remaining <br> with a <p>. Add
716
+ // all sibling nodes as children of the <p> until we hit another <br>
717
+ // chain.
718
+ if (replaced) {
719
+ var p = this._doc.createElement("p");
720
+ br.parentNode.replaceChild(p, br);
721
+
722
+ next = p.nextSibling;
723
+ while (next) {
724
+ // If we've hit another <br><br>, we're done adding children to this <p>.
725
+ if (next.tagName == "BR") {
726
+ var nextElem = this._nextNode(next.nextSibling);
727
+ if (nextElem && nextElem.tagName == "BR") {
728
+ break;
729
+ }
730
+ }
731
+
732
+ if (!this._isPhrasingContent(next)) {
733
+ break;
734
+ }
735
+
736
+ // Otherwise, make this node a child of the new <p>.
737
+ var sibling = next.nextSibling;
738
+ p.appendChild(next);
739
+ next = sibling;
740
+ }
741
+
742
+ while (p.lastChild && this._isWhitespace(p.lastChild)) {
743
+ p.lastChild.remove();
744
+ }
745
+
746
+ if (p.parentNode.tagName === "P") {
747
+ this._setNodeTag(p.parentNode, "DIV");
748
+ }
749
+ }
750
+ });
751
+ },
752
+
753
+ _setNodeTag(node, tag) {
754
+ this.log("_setNodeTag", node, tag);
755
+ if (this._docJSDOMParser) {
756
+ node.localName = tag.toLowerCase();
757
+ node.tagName = tag.toUpperCase();
758
+ return node;
759
+ }
760
+
761
+ var replacement = node.ownerDocument.createElement(tag);
762
+ while (node.firstChild) {
763
+ replacement.appendChild(node.firstChild);
764
+ }
765
+ node.parentNode.replaceChild(replacement, node);
766
+ if (node.readability) {
767
+ replacement.readability = node.readability;
768
+ }
769
+
770
+ for (var i = 0; i < node.attributes.length; i++) {
771
+ replacement.setAttributeNode(node.attributes[i].cloneNode());
772
+ }
773
+ return replacement;
774
+ },
775
+
776
+ /**
777
+ * Prepare the article node for display. Clean out any inline styles,
778
+ * iframes, forms, strip extraneous <p> tags, etc.
779
+ *
780
+ * @param Element
781
+ * @return void
782
+ **/
783
+ _prepArticle(articleContent) {
784
+ this._cleanStyles(articleContent);
785
+
786
+ // Check for data tables before we continue, to avoid removing items in
787
+ // those tables, which will often be isolated even though they're
788
+ // visually linked to other content-ful elements (text, images, etc.).
789
+ this._markDataTables(articleContent);
790
+
791
+ this._fixLazyImages(articleContent);
792
+
793
+ // Clean out junk from the article content
794
+ this._cleanConditionally(articleContent, "form");
795
+ this._cleanConditionally(articleContent, "fieldset");
796
+ this._clean(articleContent, "object");
797
+ this._clean(articleContent, "embed");
798
+ this._clean(articleContent, "footer");
799
+ this._clean(articleContent, "link");
800
+ this._clean(articleContent, "aside");
801
+
802
+ // Clean out elements with little content that have "share" in their id/class combinations from final top candidates,
803
+ // which means we don't remove the top candidates even they have "share".
804
+
805
+ var shareElementThreshold = this.DEFAULT_CHAR_THRESHOLD;
806
+
807
+ this._forEachNode(articleContent.children, function (topCandidate) {
808
+ this._cleanMatchedNodes(topCandidate, function (node, matchString) {
809
+ return (
810
+ this.REGEXPS.shareElements.test(matchString) &&
811
+ node.textContent.length < shareElementThreshold
812
+ );
813
+ });
814
+ });
815
+
816
+ this._clean(articleContent, "iframe");
817
+ this._clean(articleContent, "input");
818
+ this._clean(articleContent, "textarea");
819
+ this._clean(articleContent, "select");
820
+ this._clean(articleContent, "button");
821
+ this._cleanHeaders(articleContent);
822
+
823
+ // Do these last as the previous stuff may have removed junk
824
+ // that will affect these
825
+ this._cleanConditionally(articleContent, "table");
826
+ this._cleanConditionally(articleContent, "ul");
827
+ this._cleanConditionally(articleContent, "div");
828
+
829
+ // replace H1 with H2 as H1 should be only title that is displayed separately
830
+ this._replaceNodeTags(
831
+ this._getAllNodesWithTag(articleContent, ["h1"]),
832
+ "h2"
833
+ );
834
+
835
+ // Remove extra paragraphs
836
+ this._removeNodes(
837
+ this._getAllNodesWithTag(articleContent, ["p"]),
838
+ function (paragraph) {
839
+ // At this point, nasty iframes have been removed; only embedded video
840
+ // ones remain.
841
+ var contentElementCount = this._getAllNodesWithTag(paragraph, [
842
+ "img",
843
+ "embed",
844
+ "object",
845
+ "iframe",
846
+ ]).length;
847
+ return (
848
+ contentElementCount === 0 && !this._getInnerText(paragraph, false)
849
+ );
850
+ }
851
+ );
852
+
853
+ this._forEachNode(
854
+ this._getAllNodesWithTag(articleContent, ["br"]),
855
+ function (br) {
856
+ var next = this._nextNode(br.nextSibling);
857
+ if (next && next.tagName == "P") {
858
+ br.remove();
859
+ }
860
+ }
861
+ );
862
+
863
+ // Remove single-cell tables
864
+ this._forEachNode(
865
+ this._getAllNodesWithTag(articleContent, ["table"]),
866
+ function (table) {
867
+ var tbody = this._hasSingleTagInsideElement(table, "TBODY")
868
+ ? table.firstElementChild
869
+ : table;
870
+ if (this._hasSingleTagInsideElement(tbody, "TR")) {
871
+ var row = tbody.firstElementChild;
872
+ if (this._hasSingleTagInsideElement(row, "TD")) {
873
+ var cell = row.firstElementChild;
874
+ cell = this._setNodeTag(
875
+ cell,
876
+ this._everyNode(cell.childNodes, this._isPhrasingContent)
877
+ ? "P"
878
+ : "DIV"
879
+ );
880
+ table.parentNode.replaceChild(cell, table);
881
+ }
882
+ }
883
+ }
884
+ );
885
+ },
886
+
887
+ /**
888
+ * Initialize a node with the readability object. Also checks the
889
+ * className/id for special names to add to its score.
890
+ *
891
+ * @param Element
892
+ * @return void
893
+ **/
894
+ _initializeNode(node) {
895
+ node.readability = { contentScore: 0 };
896
+
897
+ switch (node.tagName) {
898
+ case "DIV":
899
+ node.readability.contentScore += 5;
900
+ break;
901
+
902
+ case "PRE":
903
+ case "TD":
904
+ case "BLOCKQUOTE":
905
+ node.readability.contentScore += 3;
906
+ break;
907
+
908
+ case "ADDRESS":
909
+ case "OL":
910
+ case "UL":
911
+ case "DL":
912
+ case "DD":
913
+ case "DT":
914
+ case "LI":
915
+ case "FORM":
916
+ node.readability.contentScore -= 3;
917
+ break;
918
+
919
+ case "H1":
920
+ case "H2":
921
+ case "H3":
922
+ case "H4":
923
+ case "H5":
924
+ case "H6":
925
+ case "TH":
926
+ node.readability.contentScore -= 5;
927
+ break;
928
+ }
929
+
930
+ node.readability.contentScore += this._getClassWeight(node);
931
+ },
932
+
933
+ _removeAndGetNext(node) {
934
+ var nextNode = this._getNextNode(node, true);
935
+ node.remove();
936
+ return nextNode;
937
+ },
938
+
939
+ /**
940
+ * Traverse the DOM from node to node, starting at the node passed in.
941
+ * Pass true for the second parameter to indicate this node itself
942
+ * (and its kids) are going away, and we want the next node over.
943
+ *
944
+ * Calling this in a loop will traverse the DOM depth-first.
945
+ *
946
+ * @param {Element} node
947
+ * @param {boolean} ignoreSelfAndKids
948
+ * @return {Element}
949
+ */
950
+ _getNextNode(node, ignoreSelfAndKids) {
951
+ // First check for kids if those aren't being ignored
952
+ if (!ignoreSelfAndKids && node.firstElementChild) {
953
+ return node.firstElementChild;
954
+ }
955
+ // Then for siblings...
956
+ if (node.nextElementSibling) {
957
+ return node.nextElementSibling;
958
+ }
959
+ // And finally, move up the parent chain *and* find a sibling
960
+ // (because this is depth-first traversal, we will have already
961
+ // seen the parent nodes themselves).
962
+ do {
963
+ node = node.parentNode;
964
+ } while (node && !node.nextElementSibling);
965
+ return node && node.nextElementSibling;
966
+ },
967
+
968
+ // compares second text to first one
969
+ // 1 = same text, 0 = completely different text
970
+ // works the way that it splits both texts into words and then finds words that are unique in second text
971
+ // the result is given by the lower length of unique parts
972
+ _textSimilarity(textA, textB) {
973
+ var tokensA = textA
974
+ .toLowerCase()
975
+ .split(this.REGEXPS.tokenize)
976
+ .filter(Boolean);
977
+ var tokensB = textB
978
+ .toLowerCase()
979
+ .split(this.REGEXPS.tokenize)
980
+ .filter(Boolean);
981
+ if (!tokensA.length || !tokensB.length) {
982
+ return 0;
983
+ }
984
+ var uniqTokensB = tokensB.filter(token => !tokensA.includes(token));
985
+ var distanceB = uniqTokensB.join(" ").length / tokensB.join(" ").length;
986
+ return 1 - distanceB;
987
+ },
988
+
989
+ /**
990
+ * Checks whether an element node contains a valid byline
991
+ *
992
+ * @param node {Element}
993
+ * @param matchString {string}
994
+ * @return boolean
995
+ */
996
+ _isValidByline(node, matchString) {
997
+ var rel = node.getAttribute("rel");
998
+ var itemprop = node.getAttribute("itemprop");
999
+ var bylineLength = node.textContent.trim().length;
1000
+
1001
+ return (
1002
+ (rel === "author" ||
1003
+ (itemprop && itemprop.includes("author")) ||
1004
+ this.REGEXPS.byline.test(matchString)) &&
1005
+ !!bylineLength &&
1006
+ bylineLength < 100
1007
+ );
1008
+ },
1009
+
1010
+ _getNodeAncestors(node, maxDepth) {
1011
+ maxDepth = maxDepth || 0;
1012
+ var i = 0,
1013
+ ancestors = [];
1014
+ while (node.parentNode) {
1015
+ ancestors.push(node.parentNode);
1016
+ if (maxDepth && ++i === maxDepth) {
1017
+ break;
1018
+ }
1019
+ node = node.parentNode;
1020
+ }
1021
+ return ancestors;
1022
+ },
1023
+
1024
+ /***
1025
+ * grabArticle - Using a variety of metrics (content score, classname, element types), find the content that is
1026
+ * most likely to be the stuff a user wants to read. Then return it wrapped up in a div.
1027
+ *
1028
+ * @param page a document to run upon. Needs to be a full document, complete with body.
1029
+ * @return Element
1030
+ **/
1031
+ /* eslint-disable-next-line complexity */
1032
+ _grabArticle(page) {
1033
+ this.log("**** grabArticle ****");
1034
+ var doc = this._doc;
1035
+ var isPaging = page !== null;
1036
+ page = page ? page : this._doc.body;
1037
+
1038
+ // We can't grab an article if we don't have a page!
1039
+ if (!page) {
1040
+ this.log("No body found in document. Abort.");
1041
+ return null;
1042
+ }
1043
+
1044
+ var pageCacheHtml = page.innerHTML;
1045
+
1046
+ while (true) {
1047
+ this.log("Starting grabArticle loop");
1048
+ var stripUnlikelyCandidates = this._flagIsActive(
1049
+ this.FLAG_STRIP_UNLIKELYS
1050
+ );
1051
+
1052
+ // First, node prepping. Trash nodes that look cruddy (like ones with the
1053
+ // class name "comment", etc), and turn divs into P tags where they have been
1054
+ // used inappropriately (as in, where they contain no other block level elements.)
1055
+ var elementsToScore = [];
1056
+ var node = this._doc.documentElement;
1057
+
1058
+ let shouldRemoveTitleHeader = true;
1059
+
1060
+ while (node) {
1061
+ if (node.tagName === "HTML") {
1062
+ this._articleLang = node.getAttribute("lang");
1063
+ }
1064
+
1065
+ var matchString = node.className + " " + node.id;
1066
+
1067
+ if (!this._isProbablyVisible(node)) {
1068
+ this.log("Removing hidden node - " + matchString);
1069
+ node = this._removeAndGetNext(node);
1070
+ continue;
1071
+ }
1072
+
1073
+ // User is not able to see elements applied with both "aria-modal = true" and "role = dialog"
1074
+ if (
1075
+ node.getAttribute("aria-modal") == "true" &&
1076
+ node.getAttribute("role") == "dialog"
1077
+ ) {
1078
+ node = this._removeAndGetNext(node);
1079
+ continue;
1080
+ }
1081
+
1082
+ // If we don't have a byline yet check to see if this node is a byline; if it is store the byline and remove the node.
1083
+ if (
1084
+ !this._articleByline &&
1085
+ !this._metadata.byline &&
1086
+ this._isValidByline(node, matchString)
1087
+ ) {
1088
+ // Find child node matching [itemprop="name"] and use that if it exists for a more accurate author name byline
1089
+ var endOfSearchMarkerNode = this._getNextNode(node, true);
1090
+ var next = this._getNextNode(node);
1091
+ var itemPropNameNode = null;
1092
+ while (next && next != endOfSearchMarkerNode) {
1093
+ var itemprop = next.getAttribute("itemprop");
1094
+ if (itemprop && itemprop.includes("name")) {
1095
+ itemPropNameNode = next;
1096
+ break;
1097
+ } else {
1098
+ next = this._getNextNode(next);
1099
+ }
1100
+ }
1101
+ this._articleByline = (itemPropNameNode ?? node).textContent.trim();
1102
+ node = this._removeAndGetNext(node);
1103
+ continue;
1104
+ }
1105
+
1106
+ if (shouldRemoveTitleHeader && this._headerDuplicatesTitle(node)) {
1107
+ this.log(
1108
+ "Removing header: ",
1109
+ node.textContent.trim(),
1110
+ this._articleTitle.trim()
1111
+ );
1112
+ shouldRemoveTitleHeader = false;
1113
+ node = this._removeAndGetNext(node);
1114
+ continue;
1115
+ }
1116
+
1117
+ // Remove unlikely candidates
1118
+ if (stripUnlikelyCandidates) {
1119
+ if (
1120
+ this.REGEXPS.unlikelyCandidates.test(matchString) &&
1121
+ !this.REGEXPS.okMaybeItsACandidate.test(matchString) &&
1122
+ !this._hasAncestorTag(node, "table") &&
1123
+ !this._hasAncestorTag(node, "code") &&
1124
+ node.tagName !== "BODY" &&
1125
+ node.tagName !== "A"
1126
+ ) {
1127
+ this.log("Removing unlikely candidate - " + matchString);
1128
+ node = this._removeAndGetNext(node);
1129
+ continue;
1130
+ }
1131
+
1132
+ if (this.UNLIKELY_ROLES.includes(node.getAttribute("role"))) {
1133
+ this.log(
1134
+ "Removing content with role " +
1135
+ node.getAttribute("role") +
1136
+ " - " +
1137
+ matchString
1138
+ );
1139
+ node = this._removeAndGetNext(node);
1140
+ continue;
1141
+ }
1142
+ }
1143
+
1144
+ // Remove DIV, SECTION, and HEADER nodes without any content(e.g. text, image, video, or iframe).
1145
+ if (
1146
+ (node.tagName === "DIV" ||
1147
+ node.tagName === "SECTION" ||
1148
+ node.tagName === "HEADER" ||
1149
+ node.tagName === "H1" ||
1150
+ node.tagName === "H2" ||
1151
+ node.tagName === "H3" ||
1152
+ node.tagName === "H4" ||
1153
+ node.tagName === "H5" ||
1154
+ node.tagName === "H6") &&
1155
+ this._isElementWithoutContent(node)
1156
+ ) {
1157
+ node = this._removeAndGetNext(node);
1158
+ continue;
1159
+ }
1160
+
1161
+ if (this.DEFAULT_TAGS_TO_SCORE.includes(node.tagName)) {
1162
+ elementsToScore.push(node);
1163
+ }
1164
+
1165
+ // Turn all divs that don't have children block level elements into p's
1166
+ if (node.tagName === "DIV") {
1167
+ // Put phrasing content into paragraphs.
1168
+ var p = null;
1169
+ var childNode = node.firstChild;
1170
+ while (childNode) {
1171
+ var nextSibling = childNode.nextSibling;
1172
+ if (this._isPhrasingContent(childNode)) {
1173
+ if (p !== null) {
1174
+ p.appendChild(childNode);
1175
+ } else if (!this._isWhitespace(childNode)) {
1176
+ p = doc.createElement("p");
1177
+ node.replaceChild(p, childNode);
1178
+ p.appendChild(childNode);
1179
+ }
1180
+ } else if (p !== null) {
1181
+ while (p.lastChild && this._isWhitespace(p.lastChild)) {
1182
+ p.lastChild.remove();
1183
+ }
1184
+ p = null;
1185
+ }
1186
+ childNode = nextSibling;
1187
+ }
1188
+
1189
+ // Sites like http://mobile.slate.com encloses each paragraph with a DIV
1190
+ // element. DIVs with only a P element inside and no text content can be
1191
+ // safely converted into plain P elements to avoid confusing the scoring
1192
+ // algorithm with DIVs with are, in practice, paragraphs.
1193
+ if (
1194
+ this._hasSingleTagInsideElement(node, "P") &&
1195
+ this._getLinkDensity(node) < 0.25
1196
+ ) {
1197
+ var newNode = node.children[0];
1198
+ node.parentNode.replaceChild(newNode, node);
1199
+ node = newNode;
1200
+ elementsToScore.push(node);
1201
+ } else if (!this._hasChildBlockElement(node)) {
1202
+ node = this._setNodeTag(node, "P");
1203
+ elementsToScore.push(node);
1204
+ }
1205
+ }
1206
+ node = this._getNextNode(node);
1207
+ }
1208
+
1209
+ /**
1210
+ * Loop through all paragraphs, and assign a score to them based on how content-y they look.
1211
+ * Then add their score to their parent node.
1212
+ *
1213
+ * A score is determined by things like number of commas, class names, etc. Maybe eventually link density.
1214
+ **/
1215
+ var candidates = [];
1216
+ this._forEachNode(elementsToScore, function (elementToScore) {
1217
+ if (
1218
+ !elementToScore.parentNode ||
1219
+ typeof elementToScore.parentNode.tagName === "undefined"
1220
+ ) {
1221
+ return;
1222
+ }
1223
+
1224
+ // If this paragraph is less than 25 characters, don't even count it.
1225
+ var innerText = this._getInnerText(elementToScore);
1226
+ if (innerText.length < 25) {
1227
+ return;
1228
+ }
1229
+
1230
+ // Exclude nodes with no ancestor.
1231
+ var ancestors = this._getNodeAncestors(elementToScore, 5);
1232
+ if (ancestors.length === 0) {
1233
+ return;
1234
+ }
1235
+
1236
+ var contentScore = 0;
1237
+
1238
+ // Add a point for the paragraph itself as a base.
1239
+ contentScore += 1;
1240
+
1241
+ // Add points for any commas within this paragraph.
1242
+ contentScore += innerText.split(this.REGEXPS.commas).length;
1243
+
1244
+ // For every 100 characters in this paragraph, add another point. Up to 3 points.
1245
+ contentScore += Math.min(Math.floor(innerText.length / 100), 3);
1246
+
1247
+ // Initialize and score ancestors.
1248
+ this._forEachNode(ancestors, function (ancestor, level) {
1249
+ if (
1250
+ !ancestor.tagName ||
1251
+ !ancestor.parentNode ||
1252
+ typeof ancestor.parentNode.tagName === "undefined"
1253
+ ) {
1254
+ return;
1255
+ }
1256
+
1257
+ if (typeof ancestor.readability === "undefined") {
1258
+ this._initializeNode(ancestor);
1259
+ candidates.push(ancestor);
1260
+ }
1261
+
1262
+ // Node score divider:
1263
+ // - parent: 1 (no division)
1264
+ // - grandparent: 2
1265
+ // - great grandparent+: ancestor level * 3
1266
+ if (level === 0) {
1267
+ var scoreDivider = 1;
1268
+ } else if (level === 1) {
1269
+ scoreDivider = 2;
1270
+ } else {
1271
+ scoreDivider = level * 3;
1272
+ }
1273
+ ancestor.readability.contentScore += contentScore / scoreDivider;
1274
+ });
1275
+ });
1276
+
1277
+ // After we've calculated scores, loop through all of the possible
1278
+ // candidate nodes we found and find the one with the highest score.
1279
+ var topCandidates = [];
1280
+ for (var c = 0, cl = candidates.length; c < cl; c += 1) {
1281
+ var candidate = candidates[c];
1282
+
1283
+ // Scale the final candidates score based on link density. Good content
1284
+ // should have a relatively small link density (5% or less) and be mostly
1285
+ // unaffected by this operation.
1286
+ var candidateScore =
1287
+ candidate.readability.contentScore *
1288
+ (1 - this._getLinkDensity(candidate));
1289
+ candidate.readability.contentScore = candidateScore;
1290
+
1291
+ this.log("Candidate:", candidate, "with score " + candidateScore);
1292
+
1293
+ for (var t = 0; t < this._nbTopCandidates; t++) {
1294
+ var aTopCandidate = topCandidates[t];
1295
+
1296
+ if (
1297
+ !aTopCandidate ||
1298
+ candidateScore > aTopCandidate.readability.contentScore
1299
+ ) {
1300
+ topCandidates.splice(t, 0, candidate);
1301
+ if (topCandidates.length > this._nbTopCandidates) {
1302
+ topCandidates.pop();
1303
+ }
1304
+ break;
1305
+ }
1306
+ }
1307
+ }
1308
+
1309
+ var topCandidate = topCandidates[0] || null;
1310
+ var neededToCreateTopCandidate = false;
1311
+ var parentOfTopCandidate;
1312
+
1313
+ // If we still have no top candidate, just use the body as a last resort.
1314
+ // We also have to copy the body node so it is something we can modify.
1315
+ if (topCandidate === null || topCandidate.tagName === "BODY") {
1316
+ // Move all of the page's children into topCandidate
1317
+ topCandidate = doc.createElement("DIV");
1318
+ neededToCreateTopCandidate = true;
1319
+ // Move everything (not just elements, also text nodes etc.) into the container
1320
+ // so we even include text directly in the body:
1321
+ while (page.firstChild) {
1322
+ this.log("Moving child out:", page.firstChild);
1323
+ topCandidate.appendChild(page.firstChild);
1324
+ }
1325
+
1326
+ page.appendChild(topCandidate);
1327
+
1328
+ this._initializeNode(topCandidate);
1329
+ } else if (topCandidate) {
1330
+ // Find a better top candidate node if it contains (at least three) nodes which belong to `topCandidates` array
1331
+ // and whose scores are quite closed with current `topCandidate` node.
1332
+ var alternativeCandidateAncestors = [];
1333
+ for (var i = 1; i < topCandidates.length; i++) {
1334
+ if (
1335
+ topCandidates[i].readability.contentScore /
1336
+ topCandidate.readability.contentScore >=
1337
+ 0.75
1338
+ ) {
1339
+ alternativeCandidateAncestors.push(
1340
+ this._getNodeAncestors(topCandidates[i])
1341
+ );
1342
+ }
1343
+ }
1344
+ var MINIMUM_TOPCANDIDATES = 3;
1345
+ if (alternativeCandidateAncestors.length >= MINIMUM_TOPCANDIDATES) {
1346
+ parentOfTopCandidate = topCandidate.parentNode;
1347
+ while (parentOfTopCandidate.tagName !== "BODY") {
1348
+ var listsContainingThisAncestor = 0;
1349
+ for (
1350
+ var ancestorIndex = 0;
1351
+ ancestorIndex < alternativeCandidateAncestors.length &&
1352
+ listsContainingThisAncestor < MINIMUM_TOPCANDIDATES;
1353
+ ancestorIndex++
1354
+ ) {
1355
+ listsContainingThisAncestor += Number(
1356
+ alternativeCandidateAncestors[ancestorIndex].includes(
1357
+ parentOfTopCandidate
1358
+ )
1359
+ );
1360
+ }
1361
+ if (listsContainingThisAncestor >= MINIMUM_TOPCANDIDATES) {
1362
+ topCandidate = parentOfTopCandidate;
1363
+ break;
1364
+ }
1365
+ parentOfTopCandidate = parentOfTopCandidate.parentNode;
1366
+ }
1367
+ }
1368
+ if (!topCandidate.readability) {
1369
+ this._initializeNode(topCandidate);
1370
+ }
1371
+
1372
+ // Because of our bonus system, parents of candidates might have scores
1373
+ // themselves. They get half of the node. There won't be nodes with higher
1374
+ // scores than our topCandidate, but if we see the score going *up* in the first
1375
+ // few steps up the tree, that's a decent sign that there might be more content
1376
+ // lurking in other places that we want to unify in. The sibling stuff
1377
+ // below does some of that - but only if we've looked high enough up the DOM
1378
+ // tree.
1379
+ parentOfTopCandidate = topCandidate.parentNode;
1380
+ var lastScore = topCandidate.readability.contentScore;
1381
+ // The scores shouldn't get too low.
1382
+ var scoreThreshold = lastScore / 3;
1383
+ while (parentOfTopCandidate.tagName !== "BODY") {
1384
+ if (!parentOfTopCandidate.readability) {
1385
+ parentOfTopCandidate = parentOfTopCandidate.parentNode;
1386
+ continue;
1387
+ }
1388
+ var parentScore = parentOfTopCandidate.readability.contentScore;
1389
+ if (parentScore < scoreThreshold) {
1390
+ break;
1391
+ }
1392
+ if (parentScore > lastScore) {
1393
+ // Alright! We found a better parent to use.
1394
+ topCandidate = parentOfTopCandidate;
1395
+ break;
1396
+ }
1397
+ lastScore = parentOfTopCandidate.readability.contentScore;
1398
+ parentOfTopCandidate = parentOfTopCandidate.parentNode;
1399
+ }
1400
+
1401
+ // If the top candidate is the only child, use parent instead. This will help sibling
1402
+ // joining logic when adjacent content is actually located in parent's sibling node.
1403
+ parentOfTopCandidate = topCandidate.parentNode;
1404
+ while (
1405
+ parentOfTopCandidate.tagName != "BODY" &&
1406
+ parentOfTopCandidate.children.length == 1
1407
+ ) {
1408
+ topCandidate = parentOfTopCandidate;
1409
+ parentOfTopCandidate = topCandidate.parentNode;
1410
+ }
1411
+ if (!topCandidate.readability) {
1412
+ this._initializeNode(topCandidate);
1413
+ }
1414
+ }
1415
+
1416
+ // Now that we have the top candidate, look through its siblings for content
1417
+ // that might also be related. Things like preambles, content split by ads
1418
+ // that we removed, etc.
1419
+ var articleContent = doc.createElement("DIV");
1420
+ if (isPaging) {
1421
+ articleContent.id = "readability-content";
1422
+ }
1423
+
1424
+ var siblingScoreThreshold = Math.max(
1425
+ 10,
1426
+ topCandidate.readability.contentScore * 0.2
1427
+ );
1428
+ // Keep potential top candidate's parent node to try to get text direction of it later.
1429
+ parentOfTopCandidate = topCandidate.parentNode;
1430
+ var siblings = parentOfTopCandidate.children;
1431
+
1432
+ for (var s = 0, sl = siblings.length; s < sl; s++) {
1433
+ var sibling = siblings[s];
1434
+ var append = false;
1435
+
1436
+ this.log(
1437
+ "Looking at sibling node:",
1438
+ sibling,
1439
+ sibling.readability
1440
+ ? "with score " + sibling.readability.contentScore
1441
+ : ""
1442
+ );
1443
+ this.log(
1444
+ "Sibling has score",
1445
+ sibling.readability ? sibling.readability.contentScore : "Unknown"
1446
+ );
1447
+
1448
+ if (sibling === topCandidate) {
1449
+ append = true;
1450
+ } else {
1451
+ var contentBonus = 0;
1452
+
1453
+ // Give a bonus if sibling nodes and top candidates have the example same classname
1454
+ if (
1455
+ sibling.className === topCandidate.className &&
1456
+ topCandidate.className !== ""
1457
+ ) {
1458
+ contentBonus += topCandidate.readability.contentScore * 0.2;
1459
+ }
1460
+
1461
+ if (
1462
+ sibling.readability &&
1463
+ sibling.readability.contentScore + contentBonus >=
1464
+ siblingScoreThreshold
1465
+ ) {
1466
+ append = true;
1467
+ } else if (sibling.nodeName === "P") {
1468
+ var linkDensity = this._getLinkDensity(sibling);
1469
+ var nodeContent = this._getInnerText(sibling);
1470
+ var nodeLength = nodeContent.length;
1471
+
1472
+ if (nodeLength > 80 && linkDensity < 0.25) {
1473
+ append = true;
1474
+ } else if (
1475
+ nodeLength < 80 &&
1476
+ nodeLength > 0 &&
1477
+ linkDensity === 0 &&
1478
+ nodeContent.search(/\.( |$)/) !== -1
1479
+ ) {
1480
+ append = true;
1481
+ }
1482
+ }
1483
+ }
1484
+
1485
+ if (append) {
1486
+ this.log("Appending node:", sibling);
1487
+
1488
+ if (!this.ALTER_TO_DIV_EXCEPTIONS.includes(sibling.nodeName)) {
1489
+ // We have a node that isn't a common block level element, like a form or td tag.
1490
+ // Turn it into a div so it doesn't get filtered out later by accident.
1491
+ this.log("Altering sibling:", sibling, "to div.");
1492
+
1493
+ sibling = this._setNodeTag(sibling, "DIV");
1494
+ }
1495
+
1496
+ articleContent.appendChild(sibling);
1497
+ // Fetch children again to make it compatible
1498
+ // with DOM parsers without live collection support.
1499
+ siblings = parentOfTopCandidate.children;
1500
+ // siblings is a reference to the children array, and
1501
+ // sibling is removed from the array when we call appendChild().
1502
+ // As a result, we must revisit this index since the nodes
1503
+ // have been shifted.
1504
+ s -= 1;
1505
+ sl -= 1;
1506
+ }
1507
+ }
1508
+
1509
+ if (this._debug) {
1510
+ this.log("Article content pre-prep: " + articleContent.innerHTML);
1511
+ }
1512
+ // So we have all of the content that we need. Now we clean it up for presentation.
1513
+ this._prepArticle(articleContent);
1514
+ if (this._debug) {
1515
+ this.log("Article content post-prep: " + articleContent.innerHTML);
1516
+ }
1517
+
1518
+ if (neededToCreateTopCandidate) {
1519
+ // We already created a fake div thing, and there wouldn't have been any siblings left
1520
+ // for the previous loop, so there's no point trying to create a new div, and then
1521
+ // move all the children over. Just assign IDs and class names here. No need to append
1522
+ // because that already happened anyway.
1523
+ topCandidate.id = "readability-page-1";
1524
+ topCandidate.className = "page";
1525
+ } else {
1526
+ var div = doc.createElement("DIV");
1527
+ div.id = "readability-page-1";
1528
+ div.className = "page";
1529
+ while (articleContent.firstChild) {
1530
+ div.appendChild(articleContent.firstChild);
1531
+ }
1532
+ articleContent.appendChild(div);
1533
+ }
1534
+
1535
+ if (this._debug) {
1536
+ this.log("Article content after paging: " + articleContent.innerHTML);
1537
+ }
1538
+
1539
+ var parseSuccessful = true;
1540
+
1541
+ // Now that we've gone through the full algorithm, check to see if
1542
+ // we got any meaningful content. If we didn't, we may need to re-run
1543
+ // grabArticle with different flags set. This gives us a higher likelihood of
1544
+ // finding the content, and the sieve approach gives us a higher likelihood of
1545
+ // finding the -right- content.
1546
+ var textLength = this._getInnerText(articleContent, true).length;
1547
+ if (textLength < this._charThreshold) {
1548
+ parseSuccessful = false;
1549
+ // eslint-disable-next-line no-unsanitized/property
1550
+ page.innerHTML = pageCacheHtml;
1551
+
1552
+ this._attempts.push({
1553
+ articleContent,
1554
+ textLength,
1555
+ });
1556
+
1557
+ if (this._flagIsActive(this.FLAG_STRIP_UNLIKELYS)) {
1558
+ this._removeFlag(this.FLAG_STRIP_UNLIKELYS);
1559
+ } else if (this._flagIsActive(this.FLAG_WEIGHT_CLASSES)) {
1560
+ this._removeFlag(this.FLAG_WEIGHT_CLASSES);
1561
+ } else if (this._flagIsActive(this.FLAG_CLEAN_CONDITIONALLY)) {
1562
+ this._removeFlag(this.FLAG_CLEAN_CONDITIONALLY);
1563
+ } else {
1564
+ // No luck after removing flags, just return the longest text we found during the different loops
1565
+ this._attempts.sort(function (a, b) {
1566
+ return b.textLength - a.textLength;
1567
+ });
1568
+
1569
+ // But first check if we actually have something
1570
+ if (!this._attempts[0].textLength) {
1571
+ return null;
1572
+ }
1573
+
1574
+ articleContent = this._attempts[0].articleContent;
1575
+ parseSuccessful = true;
1576
+ }
1577
+ }
1578
+
1579
+ if (parseSuccessful) {
1580
+ // Find out text direction from ancestors of final top candidate.
1581
+ var ancestors = [parentOfTopCandidate, topCandidate].concat(
1582
+ this._getNodeAncestors(parentOfTopCandidate)
1583
+ );
1584
+ this._someNode(ancestors, function (ancestor) {
1585
+ if (!ancestor.tagName) {
1586
+ return false;
1587
+ }
1588
+ var articleDir = ancestor.getAttribute("dir");
1589
+ if (articleDir) {
1590
+ this._articleDir = articleDir;
1591
+ return true;
1592
+ }
1593
+ return false;
1594
+ });
1595
+ return articleContent;
1596
+ }
1597
+ }
1598
+ },
1599
+
1600
+ /**
1601
+ * Converts some of the common HTML entities in string to their corresponding characters.
1602
+ *
1603
+ * @param str {string} - a string to unescape.
1604
+ * @return string without HTML entity.
1605
+ */
1606
+ _unescapeHtmlEntities(str) {
1607
+ if (!str) {
1608
+ return str;
1609
+ }
1610
+
1611
+ var htmlEscapeMap = this.HTML_ESCAPE_MAP;
1612
+ return str
1613
+ .replace(/&(quot|amp|apos|lt|gt);/g, function (_, tag) {
1614
+ return htmlEscapeMap[tag];
1615
+ })
1616
+ .replace(/&#(?:x([0-9a-f]+)|([0-9]+));/gi, function (_, hex, numStr) {
1617
+ var num = parseInt(hex || numStr, hex ? 16 : 10);
1618
+
1619
+ // these character references are replaced by a conforming HTML parser
1620
+ if (num == 0 || num > 0x10ffff || (num >= 0xd800 && num <= 0xdfff)) {
1621
+ num = 0xfffd;
1622
+ }
1623
+
1624
+ return String.fromCodePoint(num);
1625
+ });
1626
+ },
1627
+
1628
+ /**
1629
+ * Try to extract metadata from JSON-LD object.
1630
+ * For now, only Schema.org objects of type Article or its subtypes are supported.
1631
+ * @return Object with any metadata that could be extracted (possibly none)
1632
+ */
1633
+ _getJSONLD(doc) {
1634
+ var scripts = this._getAllNodesWithTag(doc, ["script"]);
1635
+
1636
+ var metadata;
1637
+
1638
+ this._forEachNode(scripts, function (jsonLdElement) {
1639
+ if (
1640
+ !metadata &&
1641
+ jsonLdElement.getAttribute("type") === "application/ld+json"
1642
+ ) {
1643
+ try {
1644
+ // Strip CDATA markers if present
1645
+ var content = jsonLdElement.textContent.replace(
1646
+ /^\s*<!\[CDATA\[|\]\]>\s*$/g,
1647
+ ""
1648
+ );
1649
+ var parsed = JSON.parse(content);
1650
+
1651
+ if (Array.isArray(parsed)) {
1652
+ parsed = parsed.find(it => {
1653
+ return (
1654
+ it["@type"] &&
1655
+ it["@type"].match(this.REGEXPS.jsonLdArticleTypes)
1656
+ );
1657
+ });
1658
+ if (!parsed) {
1659
+ return;
1660
+ }
1661
+ }
1662
+
1663
+ var schemaDotOrgRegex = /^https?\:\/\/schema\.org\/?$/;
1664
+ var matches =
1665
+ (typeof parsed["@context"] === "string" &&
1666
+ parsed["@context"].match(schemaDotOrgRegex)) ||
1667
+ (typeof parsed["@context"] === "object" &&
1668
+ typeof parsed["@context"]["@vocab"] == "string" &&
1669
+ parsed["@context"]["@vocab"].match(schemaDotOrgRegex));
1670
+
1671
+ if (!matches) {
1672
+ return;
1673
+ }
1674
+
1675
+ if (!parsed["@type"] && Array.isArray(parsed["@graph"])) {
1676
+ parsed = parsed["@graph"].find(it => {
1677
+ return (it["@type"] || "").match(this.REGEXPS.jsonLdArticleTypes);
1678
+ });
1679
+ }
1680
+
1681
+ if (
1682
+ !parsed ||
1683
+ !parsed["@type"] ||
1684
+ !parsed["@type"].match(this.REGEXPS.jsonLdArticleTypes)
1685
+ ) {
1686
+ return;
1687
+ }
1688
+
1689
+ metadata = {};
1690
+
1691
+ if (
1692
+ typeof parsed.name === "string" &&
1693
+ typeof parsed.headline === "string" &&
1694
+ parsed.name !== parsed.headline
1695
+ ) {
1696
+ // we have both name and headline element in the JSON-LD. They should both be the same but some websites like aktualne.cz
1697
+ // put their own name into "name" and the article title to "headline" which confuses Readability. So we try to check if either
1698
+ // "name" or "headline" closely matches the html title, and if so, use that one. If not, then we use "name" by default.
1699
+
1700
+ var title = this._getArticleTitle();
1701
+ var nameMatches = this._textSimilarity(parsed.name, title) > 0.75;
1702
+ var headlineMatches =
1703
+ this._textSimilarity(parsed.headline, title) > 0.75;
1704
+
1705
+ if (headlineMatches && !nameMatches) {
1706
+ metadata.title = parsed.headline;
1707
+ } else {
1708
+ metadata.title = parsed.name;
1709
+ }
1710
+ } else if (typeof parsed.name === "string") {
1711
+ metadata.title = parsed.name.trim();
1712
+ } else if (typeof parsed.headline === "string") {
1713
+ metadata.title = parsed.headline.trim();
1714
+ }
1715
+ if (parsed.author) {
1716
+ if (typeof parsed.author.name === "string") {
1717
+ metadata.byline = parsed.author.name.trim();
1718
+ } else if (
1719
+ Array.isArray(parsed.author) &&
1720
+ parsed.author[0] &&
1721
+ typeof parsed.author[0].name === "string"
1722
+ ) {
1723
+ metadata.byline = parsed.author
1724
+ .filter(function (author) {
1725
+ return author && typeof author.name === "string";
1726
+ })
1727
+ .map(function (author) {
1728
+ return author.name.trim();
1729
+ })
1730
+ .join(", ");
1731
+ }
1732
+ }
1733
+ if (typeof parsed.description === "string") {
1734
+ metadata.excerpt = parsed.description.trim();
1735
+ }
1736
+ if (parsed.publisher && typeof parsed.publisher.name === "string") {
1737
+ metadata.siteName = parsed.publisher.name.trim();
1738
+ }
1739
+ if (typeof parsed.datePublished === "string") {
1740
+ metadata.datePublished = parsed.datePublished.trim();
1741
+ }
1742
+ } catch (err) {
1743
+ this.log(err.message);
1744
+ }
1745
+ }
1746
+ });
1747
+ return metadata ? metadata : {};
1748
+ },
1749
+
1750
+ /**
1751
+ * Attempts to get excerpt and byline metadata for the article.
1752
+ *
1753
+ * @param {Object} jsonld — object containing any metadata that
1754
+ * could be extracted from JSON-LD object.
1755
+ *
1756
+ * @return Object with optional "excerpt" and "byline" properties
1757
+ */
1758
+ _getArticleMetadata(jsonld) {
1759
+ var metadata = {};
1760
+ var values = {};
1761
+ var metaElements = this._doc.getElementsByTagName("meta");
1762
+
1763
+ // property is a space-separated list of values
1764
+ var propertyPattern =
1765
+ /\s*(article|dc|dcterm|og|twitter)\s*:\s*(author|creator|description|published_time|title|site_name)\s*/gi;
1766
+
1767
+ // name is a single value
1768
+ var namePattern =
1769
+ /^\s*(?:(dc|dcterm|og|twitter|parsely|weibo:(article|webpage))\s*[-\.:]\s*)?(author|creator|pub-date|description|title|site_name)\s*$/i;
1770
+
1771
+ // Find description tags.
1772
+ this._forEachNode(metaElements, function (element) {
1773
+ var elementName = element.getAttribute("name");
1774
+ var elementProperty = element.getAttribute("property");
1775
+ var content = element.getAttribute("content");
1776
+ if (!content) {
1777
+ return;
1778
+ }
1779
+ var matches = null;
1780
+ var name = null;
1781
+
1782
+ if (elementProperty) {
1783
+ matches = elementProperty.match(propertyPattern);
1784
+ if (matches) {
1785
+ // Convert to lowercase, and remove any whitespace
1786
+ // so we can match below.
1787
+ name = matches[0].toLowerCase().replace(/\s/g, "");
1788
+ // multiple authors
1789
+ values[name] = content.trim();
1790
+ }
1791
+ }
1792
+ if (!matches && elementName && namePattern.test(elementName)) {
1793
+ name = elementName;
1794
+ if (content) {
1795
+ // Convert to lowercase, remove any whitespace, and convert dots
1796
+ // to colons so we can match below.
1797
+ name = name.toLowerCase().replace(/\s/g, "").replace(/\./g, ":");
1798
+ values[name] = content.trim();
1799
+ }
1800
+ }
1801
+ });
1802
+
1803
+ // get title
1804
+ metadata.title =
1805
+ jsonld.title ||
1806
+ values["dc:title"] ||
1807
+ values["dcterm:title"] ||
1808
+ values["og:title"] ||
1809
+ values["weibo:article:title"] ||
1810
+ values["weibo:webpage:title"] ||
1811
+ values.title ||
1812
+ values["twitter:title"] ||
1813
+ values["parsely-title"];
1814
+
1815
+ if (!metadata.title) {
1816
+ metadata.title = this._getArticleTitle();
1817
+ }
1818
+
1819
+ const articleAuthor =
1820
+ typeof values["article:author"] === "string" &&
1821
+ !this._isUrl(values["article:author"])
1822
+ ? values["article:author"]
1823
+ : undefined;
1824
+
1825
+ // get author
1826
+ metadata.byline =
1827
+ jsonld.byline ||
1828
+ values["dc:creator"] ||
1829
+ values["dcterm:creator"] ||
1830
+ values.author ||
1831
+ values["parsely-author"] ||
1832
+ articleAuthor;
1833
+
1834
+ // get description
1835
+ metadata.excerpt =
1836
+ jsonld.excerpt ||
1837
+ values["dc:description"] ||
1838
+ values["dcterm:description"] ||
1839
+ values["og:description"] ||
1840
+ values["weibo:article:description"] ||
1841
+ values["weibo:webpage:description"] ||
1842
+ values.description ||
1843
+ values["twitter:description"];
1844
+
1845
+ // get site name
1846
+ metadata.siteName = jsonld.siteName || values["og:site_name"];
1847
+
1848
+ // get article published time
1849
+ metadata.publishedTime =
1850
+ jsonld.datePublished ||
1851
+ values["article:published_time"] ||
1852
+ values["parsely-pub-date"] ||
1853
+ null;
1854
+
1855
+ // in many sites the meta value is escaped with HTML entities,
1856
+ // so here we need to unescape it
1857
+ metadata.title = this._unescapeHtmlEntities(metadata.title);
1858
+ metadata.byline = this._unescapeHtmlEntities(metadata.byline);
1859
+ metadata.excerpt = this._unescapeHtmlEntities(metadata.excerpt);
1860
+ metadata.siteName = this._unescapeHtmlEntities(metadata.siteName);
1861
+ metadata.publishedTime = this._unescapeHtmlEntities(metadata.publishedTime);
1862
+
1863
+ return metadata;
1864
+ },
1865
+
1866
+ /**
1867
+ * Check if node is image, or if node contains exactly only one image
1868
+ * whether as a direct child or as its descendants.
1869
+ *
1870
+ * @param Element
1871
+ **/
1872
+ _isSingleImage(node) {
1873
+ while (node) {
1874
+ if (node.tagName === "IMG") {
1875
+ return true;
1876
+ }
1877
+ if (node.children.length !== 1 || node.textContent.trim() !== "") {
1878
+ return false;
1879
+ }
1880
+ node = node.children[0];
1881
+ }
1882
+ return false;
1883
+ },
1884
+
1885
+ /**
1886
+ * Find all <noscript> that are located after <img> nodes, and which contain only one
1887
+ * <img> element. Replace the first image with the image from inside the <noscript> tag,
1888
+ * and remove the <noscript> tag. This improves the quality of the images we use on
1889
+ * some sites (e.g. Medium).
1890
+ *
1891
+ * @param Element
1892
+ **/
1893
+ _unwrapNoscriptImages(doc) {
1894
+ // Find img without source or attributes that might contains image, and remove it.
1895
+ // This is done to prevent a placeholder img is replaced by img from noscript in next step.
1896
+ var imgs = Array.from(doc.getElementsByTagName("img"));
1897
+ this._forEachNode(imgs, function (img) {
1898
+ for (var i = 0; i < img.attributes.length; i++) {
1899
+ var attr = img.attributes[i];
1900
+ switch (attr.name) {
1901
+ case "src":
1902
+ case "srcset":
1903
+ case "data-src":
1904
+ case "data-srcset":
1905
+ return;
1906
+ }
1907
+
1908
+ if (/\.(jpg|jpeg|png|webp)/i.test(attr.value)) {
1909
+ return;
1910
+ }
1911
+ }
1912
+
1913
+ img.remove();
1914
+ });
1915
+
1916
+ // Next find noscript and try to extract its image
1917
+ var noscripts = Array.from(doc.getElementsByTagName("noscript"));
1918
+ this._forEachNode(noscripts, function (noscript) {
1919
+ // Parse content of noscript and make sure it only contains image
1920
+ if (!this._isSingleImage(noscript)) {
1921
+ return;
1922
+ }
1923
+ var tmp = doc.createElement("div");
1924
+ // We're running in the document context, and using unmodified
1925
+ // document contents, so doing this should be safe.
1926
+ // (Also we heavily discourage people from allowing script to
1927
+ // run at all in this document...)
1928
+ // eslint-disable-next-line no-unsanitized/property
1929
+ tmp.innerHTML = noscript.innerHTML;
1930
+
1931
+ // If noscript has previous sibling and it only contains image,
1932
+ // replace it with noscript content. However we also keep old
1933
+ // attributes that might contains image.
1934
+ var prevElement = noscript.previousElementSibling;
1935
+ if (prevElement && this._isSingleImage(prevElement)) {
1936
+ var prevImg = prevElement;
1937
+ if (prevImg.tagName !== "IMG") {
1938
+ prevImg = prevElement.getElementsByTagName("img")[0];
1939
+ }
1940
+
1941
+ var newImg = tmp.getElementsByTagName("img")[0];
1942
+ for (var i = 0; i < prevImg.attributes.length; i++) {
1943
+ var attr = prevImg.attributes[i];
1944
+ if (attr.value === "") {
1945
+ continue;
1946
+ }
1947
+
1948
+ if (
1949
+ attr.name === "src" ||
1950
+ attr.name === "srcset" ||
1951
+ /\.(jpg|jpeg|png|webp)/i.test(attr.value)
1952
+ ) {
1953
+ if (newImg.getAttribute(attr.name) === attr.value) {
1954
+ continue;
1955
+ }
1956
+
1957
+ var attrName = attr.name;
1958
+ if (newImg.hasAttribute(attrName)) {
1959
+ attrName = "data-old-" + attrName;
1960
+ }
1961
+
1962
+ newImg.setAttribute(attrName, attr.value);
1963
+ }
1964
+ }
1965
+
1966
+ noscript.parentNode.replaceChild(tmp.firstElementChild, prevElement);
1967
+ }
1968
+ });
1969
+ },
1970
+
1971
+ /**
1972
+ * Removes script tags from the document.
1973
+ *
1974
+ * @param Element
1975
+ **/
1976
+ _removeScripts(doc) {
1977
+ this._removeNodes(this._getAllNodesWithTag(doc, ["script", "noscript"]));
1978
+ },
1979
+
1980
+ /**
1981
+ * Check if this node has only whitespace and a single element with given tag
1982
+ * Returns false if the DIV node contains non-empty text nodes
1983
+ * or if it contains no element with given tag or more than 1 element.
1984
+ *
1985
+ * @param Element
1986
+ * @param string tag of child element
1987
+ **/
1988
+ _hasSingleTagInsideElement(element, tag) {
1989
+ // There should be exactly 1 element child with given tag
1990
+ if (element.children.length != 1 || element.children[0].tagName !== tag) {
1991
+ return false;
1992
+ }
1993
+
1994
+ // And there should be no text nodes with real content
1995
+ return !this._someNode(element.childNodes, function (node) {
1996
+ return (
1997
+ node.nodeType === this.TEXT_NODE &&
1998
+ this.REGEXPS.hasContent.test(node.textContent)
1999
+ );
2000
+ });
2001
+ },
2002
+
2003
+ _isElementWithoutContent(node) {
2004
+ return (
2005
+ node.nodeType === this.ELEMENT_NODE &&
2006
+ !node.textContent.trim().length &&
2007
+ (!node.children.length ||
2008
+ node.children.length ==
2009
+ node.getElementsByTagName("br").length +
2010
+ node.getElementsByTagName("hr").length)
2011
+ );
2012
+ },
2013
+
2014
+ /**
2015
+ * Determine whether element has any children block level elements.
2016
+ *
2017
+ * @param Element
2018
+ */
2019
+ _hasChildBlockElement(element) {
2020
+ return this._someNode(element.childNodes, function (node) {
2021
+ return (
2022
+ this.DIV_TO_P_ELEMS.has(node.tagName) ||
2023
+ this._hasChildBlockElement(node)
2024
+ );
2025
+ });
2026
+ },
2027
+
2028
+ /***
2029
+ * Determine if a node qualifies as phrasing content.
2030
+ * https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Content_categories#Phrasing_content
2031
+ **/
2032
+ _isPhrasingContent(node) {
2033
+ return (
2034
+ node.nodeType === this.TEXT_NODE ||
2035
+ this.PHRASING_ELEMS.includes(node.tagName) ||
2036
+ ((node.tagName === "A" ||
2037
+ node.tagName === "DEL" ||
2038
+ node.tagName === "INS") &&
2039
+ this._everyNode(node.childNodes, this._isPhrasingContent))
2040
+ );
2041
+ },
2042
+
2043
+ _isWhitespace(node) {
2044
+ return (
2045
+ (node.nodeType === this.TEXT_NODE &&
2046
+ node.textContent.trim().length === 0) ||
2047
+ (node.nodeType === this.ELEMENT_NODE && node.tagName === "BR")
2048
+ );
2049
+ },
2050
+
2051
+ /**
2052
+ * Get the inner text of a node - cross browser compatibly.
2053
+ * This also strips out any excess whitespace to be found.
2054
+ *
2055
+ * @param Element
2056
+ * @param Boolean normalizeSpaces (default: true)
2057
+ * @return string
2058
+ **/
2059
+ _getInnerText(e, normalizeSpaces) {
2060
+ normalizeSpaces =
2061
+ typeof normalizeSpaces === "undefined" ? true : normalizeSpaces;
2062
+ var textContent = e.textContent.trim();
2063
+
2064
+ if (normalizeSpaces) {
2065
+ return textContent.replace(this.REGEXPS.normalize, " ");
2066
+ }
2067
+ return textContent;
2068
+ },
2069
+
2070
+ /**
2071
+ * Get the number of times a string s appears in the node e.
2072
+ *
2073
+ * @param Element
2074
+ * @param string - what to split on. Default is ","
2075
+ * @return number (integer)
2076
+ **/
2077
+ _getCharCount(e, s) {
2078
+ s = s || ",";
2079
+ return this._getInnerText(e).split(s).length - 1;
2080
+ },
2081
+
2082
+ /**
2083
+ * Remove the style attribute on every e and under.
2084
+ * TODO: Test if getElementsByTagName(*) is faster.
2085
+ *
2086
+ * @param Element
2087
+ * @return void
2088
+ **/
2089
+ _cleanStyles(e) {
2090
+ if (!e || e.tagName.toLowerCase() === "svg") {
2091
+ return;
2092
+ }
2093
+
2094
+ // Remove `style` and deprecated presentational attributes
2095
+ for (var i = 0; i < this.PRESENTATIONAL_ATTRIBUTES.length; i++) {
2096
+ e.removeAttribute(this.PRESENTATIONAL_ATTRIBUTES[i]);
2097
+ }
2098
+
2099
+ if (this.DEPRECATED_SIZE_ATTRIBUTE_ELEMS.includes(e.tagName)) {
2100
+ e.removeAttribute("width");
2101
+ e.removeAttribute("height");
2102
+ }
2103
+
2104
+ var cur = e.firstElementChild;
2105
+ while (cur !== null) {
2106
+ this._cleanStyles(cur);
2107
+ cur = cur.nextElementSibling;
2108
+ }
2109
+ },
2110
+
2111
+ /**
2112
+ * Get the density of links as a percentage of the content
2113
+ * This is the amount of text that is inside a link divided by the total text in the node.
2114
+ *
2115
+ * @param Element
2116
+ * @return number (float)
2117
+ **/
2118
+ _getLinkDensity(element) {
2119
+ var textLength = this._getInnerText(element).length;
2120
+ if (textLength === 0) {
2121
+ return 0;
2122
+ }
2123
+
2124
+ var linkLength = 0;
2125
+
2126
+ // XXX implement _reduceNodeList?
2127
+ this._forEachNode(element.getElementsByTagName("a"), function (linkNode) {
2128
+ var href = linkNode.getAttribute("href");
2129
+ var coefficient = href && this.REGEXPS.hashUrl.test(href) ? 0.3 : 1;
2130
+ linkLength += this._getInnerText(linkNode).length * coefficient;
2131
+ });
2132
+
2133
+ return linkLength / textLength;
2134
+ },
2135
+
2136
+ /**
2137
+ * Get an elements class/id weight. Uses regular expressions to tell if this
2138
+ * element looks good or bad.
2139
+ *
2140
+ * @param Element
2141
+ * @return number (Integer)
2142
+ **/
2143
+ _getClassWeight(e) {
2144
+ if (!this._flagIsActive(this.FLAG_WEIGHT_CLASSES)) {
2145
+ return 0;
2146
+ }
2147
+
2148
+ var weight = 0;
2149
+
2150
+ // Look for a special classname
2151
+ if (typeof e.className === "string" && e.className !== "") {
2152
+ if (this.REGEXPS.negative.test(e.className)) {
2153
+ weight -= 25;
2154
+ }
2155
+
2156
+ if (this.REGEXPS.positive.test(e.className)) {
2157
+ weight += 25;
2158
+ }
2159
+ }
2160
+
2161
+ // Look for a special ID
2162
+ if (typeof e.id === "string" && e.id !== "") {
2163
+ if (this.REGEXPS.negative.test(e.id)) {
2164
+ weight -= 25;
2165
+ }
2166
+
2167
+ if (this.REGEXPS.positive.test(e.id)) {
2168
+ weight += 25;
2169
+ }
2170
+ }
2171
+
2172
+ return weight;
2173
+ },
2174
+
2175
+ /**
2176
+ * Clean a node of all elements of type "tag".
2177
+ * (Unless it's a youtube/vimeo video. People love movies.)
2178
+ *
2179
+ * @param Element
2180
+ * @param string tag to clean
2181
+ * @return void
2182
+ **/
2183
+ _clean(e, tag) {
2184
+ var isEmbed = ["object", "embed", "iframe"].includes(tag);
2185
+
2186
+ this._removeNodes(this._getAllNodesWithTag(e, [tag]), function (element) {
2187
+ // Allow youtube and vimeo videos through as people usually want to see those.
2188
+ if (isEmbed) {
2189
+ // First, check the elements attributes to see if any of them contain youtube or vimeo
2190
+ for (var i = 0; i < element.attributes.length; i++) {
2191
+ if (this._allowedVideoRegex.test(element.attributes[i].value)) {
2192
+ return false;
2193
+ }
2194
+ }
2195
+
2196
+ // For embed with <object> tag, check inner HTML as well.
2197
+ if (
2198
+ element.tagName === "object" &&
2199
+ this._allowedVideoRegex.test(element.innerHTML)
2200
+ ) {
2201
+ return false;
2202
+ }
2203
+ }
2204
+
2205
+ return true;
2206
+ });
2207
+ },
2208
+
2209
+ /**
2210
+ * Check if a given node has one of its ancestor tag name matching the
2211
+ * provided one.
2212
+ * @param HTMLElement node
2213
+ * @param String tagName
2214
+ * @param Number maxDepth
2215
+ * @param Function filterFn a filter to invoke to determine whether this node 'counts'
2216
+ * @return Boolean
2217
+ */
2218
+ _hasAncestorTag(node, tagName, maxDepth, filterFn) {
2219
+ maxDepth = maxDepth || 3;
2220
+ tagName = tagName.toUpperCase();
2221
+ var depth = 0;
2222
+ while (node.parentNode) {
2223
+ if (maxDepth > 0 && depth > maxDepth) {
2224
+ return false;
2225
+ }
2226
+ if (
2227
+ node.parentNode.tagName === tagName &&
2228
+ (!filterFn || filterFn(node.parentNode))
2229
+ ) {
2230
+ return true;
2231
+ }
2232
+ node = node.parentNode;
2233
+ depth++;
2234
+ }
2235
+ return false;
2236
+ },
2237
+
2238
+ /**
2239
+ * Return an object indicating how many rows and columns this table has.
2240
+ */
2241
+ _getRowAndColumnCount(table) {
2242
+ var rows = 0;
2243
+ var columns = 0;
2244
+ var trs = table.getElementsByTagName("tr");
2245
+ for (var i = 0; i < trs.length; i++) {
2246
+ var rowspan = trs[i].getAttribute("rowspan") || 0;
2247
+ if (rowspan) {
2248
+ rowspan = parseInt(rowspan, 10);
2249
+ }
2250
+ rows += rowspan || 1;
2251
+
2252
+ // Now look for column-related info
2253
+ var columnsInThisRow = 0;
2254
+ var cells = trs[i].getElementsByTagName("td");
2255
+ for (var j = 0; j < cells.length; j++) {
2256
+ var colspan = cells[j].getAttribute("colspan") || 0;
2257
+ if (colspan) {
2258
+ colspan = parseInt(colspan, 10);
2259
+ }
2260
+ columnsInThisRow += colspan || 1;
2261
+ }
2262
+ columns = Math.max(columns, columnsInThisRow);
2263
+ }
2264
+ return { rows, columns };
2265
+ },
2266
+
2267
+ /**
2268
+ * Look for 'data' (as opposed to 'layout') tables, for which we use
2269
+ * similar checks as
2270
+ * https://searchfox.org/mozilla-central/rev/f82d5c549f046cb64ce5602bfd894b7ae807c8f8/accessible/generic/TableAccessible.cpp#19
2271
+ */
2272
+ _markDataTables(root) {
2273
+ var tables = root.getElementsByTagName("table");
2274
+ for (var i = 0; i < tables.length; i++) {
2275
+ var table = tables[i];
2276
+ var role = table.getAttribute("role");
2277
+ if (role == "presentation") {
2278
+ table._readabilityDataTable = false;
2279
+ continue;
2280
+ }
2281
+ var datatable = table.getAttribute("datatable");
2282
+ if (datatable == "0") {
2283
+ table._readabilityDataTable = false;
2284
+ continue;
2285
+ }
2286
+ var summary = table.getAttribute("summary");
2287
+ if (summary) {
2288
+ table._readabilityDataTable = true;
2289
+ continue;
2290
+ }
2291
+
2292
+ var caption = table.getElementsByTagName("caption")[0];
2293
+ if (caption && caption.childNodes.length) {
2294
+ table._readabilityDataTable = true;
2295
+ continue;
2296
+ }
2297
+
2298
+ // If the table has a descendant with any of these tags, consider a data table:
2299
+ var dataTableDescendants = ["col", "colgroup", "tfoot", "thead", "th"];
2300
+ var descendantExists = function (tag) {
2301
+ return !!table.getElementsByTagName(tag)[0];
2302
+ };
2303
+ if (dataTableDescendants.some(descendantExists)) {
2304
+ this.log("Data table because found data-y descendant");
2305
+ table._readabilityDataTable = true;
2306
+ continue;
2307
+ }
2308
+
2309
+ // Nested tables indicate a layout table:
2310
+ if (table.getElementsByTagName("table")[0]) {
2311
+ table._readabilityDataTable = false;
2312
+ continue;
2313
+ }
2314
+
2315
+ var sizeInfo = this._getRowAndColumnCount(table);
2316
+
2317
+ if (sizeInfo.columns == 1 || sizeInfo.rows == 1) {
2318
+ // single colum/row tables are commonly used for page layout purposes.
2319
+ table._readabilityDataTable = false;
2320
+ continue;
2321
+ }
2322
+
2323
+ if (sizeInfo.rows >= 10 || sizeInfo.columns > 4) {
2324
+ table._readabilityDataTable = true;
2325
+ continue;
2326
+ }
2327
+ // Now just go by size entirely:
2328
+ table._readabilityDataTable = sizeInfo.rows * sizeInfo.columns > 10;
2329
+ }
2330
+ },
2331
+
2332
+ /* convert images and figures that have properties like data-src into images that can be loaded without JS */
2333
+ _fixLazyImages(root) {
2334
+ this._forEachNode(
2335
+ this._getAllNodesWithTag(root, ["img", "picture", "figure"]),
2336
+ function (elem) {
2337
+ // In some sites (e.g. Kotaku), they put 1px square image as base64 data uri in the src attribute.
2338
+ // So, here we check if the data uri is too short, just might as well remove it.
2339
+ if (elem.src && this.REGEXPS.b64DataUrl.test(elem.src)) {
2340
+ // Make sure it's not SVG, because SVG can have a meaningful image in under 133 bytes.
2341
+ var parts = this.REGEXPS.b64DataUrl.exec(elem.src);
2342
+ if (parts[1] === "image/svg+xml") {
2343
+ return;
2344
+ }
2345
+
2346
+ // Make sure this element has other attributes which contains image.
2347
+ // If it doesn't, then this src is important and shouldn't be removed.
2348
+ var srcCouldBeRemoved = false;
2349
+ for (var i = 0; i < elem.attributes.length; i++) {
2350
+ var attr = elem.attributes[i];
2351
+ if (attr.name === "src") {
2352
+ continue;
2353
+ }
2354
+
2355
+ if (/\.(jpg|jpeg|png|webp)/i.test(attr.value)) {
2356
+ srcCouldBeRemoved = true;
2357
+ break;
2358
+ }
2359
+ }
2360
+
2361
+ // Here we assume if image is less than 100 bytes (or 133 after encoded to base64)
2362
+ // it will be too small, therefore it might be placeholder image.
2363
+ if (srcCouldBeRemoved) {
2364
+ var b64starts = parts[0].length;
2365
+ var b64length = elem.src.length - b64starts;
2366
+ if (b64length < 133) {
2367
+ elem.removeAttribute("src");
2368
+ }
2369
+ }
2370
+ }
2371
+
2372
+ // also check for "null" to work around https://github.com/jsdom/jsdom/issues/2580
2373
+ if (
2374
+ (elem.src || (elem.srcset && elem.srcset != "null")) &&
2375
+ !elem.className.toLowerCase().includes("lazy")
2376
+ ) {
2377
+ return;
2378
+ }
2379
+
2380
+ for (var j = 0; j < elem.attributes.length; j++) {
2381
+ attr = elem.attributes[j];
2382
+ if (
2383
+ attr.name === "src" ||
2384
+ attr.name === "srcset" ||
2385
+ attr.name === "alt"
2386
+ ) {
2387
+ continue;
2388
+ }
2389
+ var copyTo = null;
2390
+ if (/\.(jpg|jpeg|png|webp)\s+\d/.test(attr.value)) {
2391
+ copyTo = "srcset";
2392
+ } else if (/^\s*\S+\.(jpg|jpeg|png|webp)\S*\s*$/.test(attr.value)) {
2393
+ copyTo = "src";
2394
+ }
2395
+ if (copyTo) {
2396
+ //if this is an img or picture, set the attribute directly
2397
+ if (elem.tagName === "IMG" || elem.tagName === "PICTURE") {
2398
+ elem.setAttribute(copyTo, attr.value);
2399
+ } else if (
2400
+ elem.tagName === "FIGURE" &&
2401
+ !this._getAllNodesWithTag(elem, ["img", "picture"]).length
2402
+ ) {
2403
+ //if the item is a <figure> that does not contain an image or picture, create one and place it inside the figure
2404
+ //see the nytimes-3 testcase for an example
2405
+ var img = this._doc.createElement("img");
2406
+ img.setAttribute(copyTo, attr.value);
2407
+ elem.appendChild(img);
2408
+ }
2409
+ }
2410
+ }
2411
+ }
2412
+ );
2413
+ },
2414
+
2415
+ _getTextDensity(e, tags) {
2416
+ var textLength = this._getInnerText(e, true).length;
2417
+ if (textLength === 0) {
2418
+ return 0;
2419
+ }
2420
+ var childrenLength = 0;
2421
+ var children = this._getAllNodesWithTag(e, tags);
2422
+ this._forEachNode(
2423
+ children,
2424
+ child => (childrenLength += this._getInnerText(child, true).length)
2425
+ );
2426
+ return childrenLength / textLength;
2427
+ },
2428
+
2429
+ /**
2430
+ * Clean an element of all tags of type "tag" if they look fishy.
2431
+ * "Fishy" is an algorithm based on content length, classnames, link density, number of images & embeds, etc.
2432
+ *
2433
+ * @return void
2434
+ **/
2435
+ _cleanConditionally(e, tag) {
2436
+ if (!this._flagIsActive(this.FLAG_CLEAN_CONDITIONALLY)) {
2437
+ return;
2438
+ }
2439
+
2440
+ // Gather counts for other typical elements embedded within.
2441
+ // Traverse backwards so we can remove nodes at the same time
2442
+ // without effecting the traversal.
2443
+ //
2444
+ // TODO: Consider taking into account original contentScore here.
2445
+ this._removeNodes(this._getAllNodesWithTag(e, [tag]), function (node) {
2446
+ // First check if this node IS data table, in which case don't remove it.
2447
+ var isDataTable = function (t) {
2448
+ return t._readabilityDataTable;
2449
+ };
2450
+
2451
+ var isList = tag === "ul" || tag === "ol";
2452
+ if (!isList) {
2453
+ var listLength = 0;
2454
+ var listNodes = this._getAllNodesWithTag(node, ["ul", "ol"]);
2455
+ this._forEachNode(
2456
+ listNodes,
2457
+ list => (listLength += this._getInnerText(list).length)
2458
+ );
2459
+ isList = listLength / this._getInnerText(node).length > 0.9;
2460
+ }
2461
+
2462
+ if (tag === "table" && isDataTable(node)) {
2463
+ return false;
2464
+ }
2465
+
2466
+ // Next check if we're inside a data table, in which case don't remove it as well.
2467
+ if (this._hasAncestorTag(node, "table", -1, isDataTable)) {
2468
+ return false;
2469
+ }
2470
+
2471
+ if (this._hasAncestorTag(node, "code")) {
2472
+ return false;
2473
+ }
2474
+
2475
+ // keep element if it has a data tables
2476
+ if (
2477
+ [...node.getElementsByTagName("table")].some(
2478
+ tbl => tbl._readabilityDataTable
2479
+ )
2480
+ ) {
2481
+ return false;
2482
+ }
2483
+
2484
+ var weight = this._getClassWeight(node);
2485
+
2486
+ this.log("Cleaning Conditionally", node);
2487
+
2488
+ var contentScore = 0;
2489
+
2490
+ if (weight + contentScore < 0) {
2491
+ return true;
2492
+ }
2493
+
2494
+ if (this._getCharCount(node, ",") < 10) {
2495
+ // If there are not very many commas, and the number of
2496
+ // non-paragraph elements is more than paragraphs or other
2497
+ // ominous signs, remove the element.
2498
+ var p = node.getElementsByTagName("p").length;
2499
+ var img = node.getElementsByTagName("img").length;
2500
+ var li = node.getElementsByTagName("li").length - 100;
2501
+ var input = node.getElementsByTagName("input").length;
2502
+ var headingDensity = this._getTextDensity(node, [
2503
+ "h1",
2504
+ "h2",
2505
+ "h3",
2506
+ "h4",
2507
+ "h5",
2508
+ "h6",
2509
+ ]);
2510
+
2511
+ var embedCount = 0;
2512
+ var embeds = this._getAllNodesWithTag(node, [
2513
+ "object",
2514
+ "embed",
2515
+ "iframe",
2516
+ ]);
2517
+
2518
+ for (var i = 0; i < embeds.length; i++) {
2519
+ // If this embed has attribute that matches video regex, don't delete it.
2520
+ for (var j = 0; j < embeds[i].attributes.length; j++) {
2521
+ if (this._allowedVideoRegex.test(embeds[i].attributes[j].value)) {
2522
+ return false;
2523
+ }
2524
+ }
2525
+
2526
+ // For embed with <object> tag, check inner HTML as well.
2527
+ if (
2528
+ embeds[i].tagName === "object" &&
2529
+ this._allowedVideoRegex.test(embeds[i].innerHTML)
2530
+ ) {
2531
+ return false;
2532
+ }
2533
+
2534
+ embedCount++;
2535
+ }
2536
+
2537
+ var innerText = this._getInnerText(node);
2538
+
2539
+ // toss any node whose inner text contains nothing but suspicious words
2540
+ if (
2541
+ this.REGEXPS.adWords.test(innerText) ||
2542
+ this.REGEXPS.loadingWords.test(innerText)
2543
+ ) {
2544
+ return true;
2545
+ }
2546
+
2547
+ var contentLength = innerText.length;
2548
+ var linkDensity = this._getLinkDensity(node);
2549
+ var textishTags = ["SPAN", "LI", "TD"].concat(
2550
+ Array.from(this.DIV_TO_P_ELEMS)
2551
+ );
2552
+ var textDensity = this._getTextDensity(node, textishTags);
2553
+ var isFigureChild = this._hasAncestorTag(node, "figure");
2554
+
2555
+ // apply shadiness checks, then check for exceptions
2556
+ const shouldRemoveNode = () => {
2557
+ const errs = [];
2558
+ if (!isFigureChild && img > 1 && p / img < 0.5) {
2559
+ errs.push(`Bad p to img ratio (img=${img}, p=${p})`);
2560
+ }
2561
+ if (!isList && li > p) {
2562
+ errs.push(`Too many li's outside of a list. (li=${li} > p=${p})`);
2563
+ }
2564
+ if (input > Math.floor(p / 3)) {
2565
+ errs.push(`Too many inputs per p. (input=${input}, p=${p})`);
2566
+ }
2567
+ if (
2568
+ !isList &&
2569
+ !isFigureChild &&
2570
+ headingDensity < 0.9 &&
2571
+ contentLength < 25 &&
2572
+ (img === 0 || img > 2) &&
2573
+ linkDensity > 0
2574
+ ) {
2575
+ errs.push(
2576
+ `Suspiciously short. (headingDensity=${headingDensity}, img=${img}, linkDensity=${linkDensity})`
2577
+ );
2578
+ }
2579
+ if (
2580
+ !isList &&
2581
+ weight < 25 &&
2582
+ linkDensity > 0.2 + this._linkDensityModifier
2583
+ ) {
2584
+ errs.push(
2585
+ `Low weight and a little linky. (linkDensity=${linkDensity})`
2586
+ );
2587
+ }
2588
+ if (weight >= 25 && linkDensity > 0.5 + this._linkDensityModifier) {
2589
+ errs.push(
2590
+ `High weight and mostly links. (linkDensity=${linkDensity})`
2591
+ );
2592
+ }
2593
+ if ((embedCount === 1 && contentLength < 75) || embedCount > 1) {
2594
+ errs.push(
2595
+ `Suspicious embed. (embedCount=${embedCount}, contentLength=${contentLength})`
2596
+ );
2597
+ }
2598
+ if (img === 0 && textDensity === 0) {
2599
+ errs.push(
2600
+ `No useful content. (img=${img}, textDensity=${textDensity})`
2601
+ );
2602
+ }
2603
+
2604
+ if (errs.length) {
2605
+ this.log("Checks failed", errs);
2606
+ return true;
2607
+ }
2608
+
2609
+ return false;
2610
+ };
2611
+
2612
+ var haveToRemove = shouldRemoveNode();
2613
+
2614
+ // Allow simple lists of images to remain in pages
2615
+ if (isList && haveToRemove) {
2616
+ for (var x = 0; x < node.children.length; x++) {
2617
+ let child = node.children[x];
2618
+ // Don't filter in lists with li's that contain more than one child
2619
+ if (child.children.length > 1) {
2620
+ return haveToRemove;
2621
+ }
2622
+ }
2623
+ let li_count = node.getElementsByTagName("li").length;
2624
+ // Only allow the list to remain if every li contains an image
2625
+ if (img == li_count) {
2626
+ return false;
2627
+ }
2628
+ }
2629
+ return haveToRemove;
2630
+ }
2631
+ return false;
2632
+ });
2633
+ },
2634
+
2635
+ /**
2636
+ * Clean out elements that match the specified conditions
2637
+ *
2638
+ * @param Element
2639
+ * @param Function determines whether a node should be removed
2640
+ * @return void
2641
+ **/
2642
+ _cleanMatchedNodes(e, filter) {
2643
+ var endOfSearchMarkerNode = this._getNextNode(e, true);
2644
+ var next = this._getNextNode(e);
2645
+ while (next && next != endOfSearchMarkerNode) {
2646
+ if (filter.call(this, next, next.className + " " + next.id)) {
2647
+ next = this._removeAndGetNext(next);
2648
+ } else {
2649
+ next = this._getNextNode(next);
2650
+ }
2651
+ }
2652
+ },
2653
+
2654
+ /**
2655
+ * Clean out spurious headers from an Element.
2656
+ *
2657
+ * @param Element
2658
+ * @return void
2659
+ **/
2660
+ _cleanHeaders(e) {
2661
+ let headingNodes = this._getAllNodesWithTag(e, ["h1", "h2"]);
2662
+ this._removeNodes(headingNodes, function (node) {
2663
+ let shouldRemove = this._getClassWeight(node) < 0;
2664
+ if (shouldRemove) {
2665
+ this.log("Removing header with low class weight:", node);
2666
+ }
2667
+ return shouldRemove;
2668
+ });
2669
+ },
2670
+
2671
+ /**
2672
+ * Check if this node is an H1 or H2 element whose content is mostly
2673
+ * the same as the article title.
2674
+ *
2675
+ * @param Element the node to check.
2676
+ * @return boolean indicating whether this is a title-like header.
2677
+ */
2678
+ _headerDuplicatesTitle(node) {
2679
+ if (node.tagName != "H1" && node.tagName != "H2") {
2680
+ return false;
2681
+ }
2682
+ var heading = this._getInnerText(node, false);
2683
+ this.log("Evaluating similarity of header:", heading, this._articleTitle);
2684
+ return this._textSimilarity(this._articleTitle, heading) > 0.75;
2685
+ },
2686
+
2687
+ _flagIsActive(flag) {
2688
+ return (this._flags & flag) > 0;
2689
+ },
2690
+
2691
+ _removeFlag(flag) {
2692
+ this._flags = this._flags & ~flag;
2693
+ },
2694
+
2695
+ _isProbablyVisible(node) {
2696
+ // Have to null-check node.style and node.className.includes to deal with SVG and MathML nodes.
2697
+ return (
2698
+ (!node.style || node.style.display != "none") &&
2699
+ (!node.style || node.style.visibility != "hidden") &&
2700
+ !node.hasAttribute("hidden") &&
2701
+ //check for "fallback-image" so that wikimedia math images are displayed
2702
+ (!node.hasAttribute("aria-hidden") ||
2703
+ node.getAttribute("aria-hidden") != "true" ||
2704
+ (node.className &&
2705
+ node.className.includes &&
2706
+ node.className.includes("fallback-image")))
2707
+ );
2708
+ },
2709
+
2710
+ /**
2711
+ * Runs readability.
2712
+ *
2713
+ * Workflow:
2714
+ * 1. Prep the document by removing script tags, css, etc.
2715
+ * 2. Build readability's DOM tree.
2716
+ * 3. Grab the article content from the current dom tree.
2717
+ * 4. Replace the current DOM tree with the new one.
2718
+ * 5. Read peacefully.
2719
+ *
2720
+ * @return void
2721
+ **/
2722
+ parse() {
2723
+ // Avoid parsing too large documents, as per configuration option
2724
+ if (this._maxElemsToParse > 0) {
2725
+ var numTags = this._doc.getElementsByTagName("*").length;
2726
+ if (numTags > this._maxElemsToParse) {
2727
+ throw new Error(
2728
+ "Aborting parsing document; " + numTags + " elements found"
2729
+ );
2730
+ }
2731
+ }
2732
+
2733
+ // Unwrap image from noscript
2734
+ this._unwrapNoscriptImages(this._doc);
2735
+
2736
+ // Extract JSON-LD metadata before removing scripts
2737
+ var jsonLd = this._disableJSONLD ? {} : this._getJSONLD(this._doc);
2738
+
2739
+ // Remove script tags from the document.
2740
+ this._removeScripts(this._doc);
2741
+
2742
+ this._prepDocument();
2743
+
2744
+ var metadata = this._getArticleMetadata(jsonLd);
2745
+ this._metadata = metadata;
2746
+ this._articleTitle = metadata.title;
2747
+
2748
+ var articleContent = this._grabArticle();
2749
+ if (!articleContent) {
2750
+ return null;
2751
+ }
2752
+
2753
+ this.log("Grabbed: " + articleContent.innerHTML);
2754
+
2755
+ this._postProcessContent(articleContent);
2756
+
2757
+ // If we haven't found an excerpt in the article's metadata, use the article's
2758
+ // first paragraph as the excerpt. This is used for displaying a preview of
2759
+ // the article's content.
2760
+ if (!metadata.excerpt) {
2761
+ var paragraphs = articleContent.getElementsByTagName("p");
2762
+ if (paragraphs.length) {
2763
+ metadata.excerpt = paragraphs[0].textContent.trim();
2764
+ }
2765
+ }
2766
+
2767
+ var textContent = articleContent.textContent;
2768
+ return {
2769
+ title: this._articleTitle,
2770
+ byline: metadata.byline || this._articleByline,
2771
+ dir: this._articleDir,
2772
+ lang: this._articleLang,
2773
+ content: this._serializer(articleContent),
2774
+ textContent,
2775
+ length: textContent.length,
2776
+ excerpt: metadata.excerpt,
2777
+ siteName: metadata.siteName || this._articleSiteName,
2778
+ publishedTime: metadata.publishedTime,
2779
+ };
2780
+ },
2781
+ };
2782
+
2783
+ if (typeof module === "object") {
2784
+ /* eslint-disable-next-line no-redeclare */
2785
+ /* global module */
2786
+ module.exports = Readability;
2787
+ }