@dvaji/cheerox 0.0.0-stage → 0.1.1

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 (253) hide show
  1. package/CONTRIBUTING.md +74 -0
  2. package/Cargo.lock +1094 -0
  3. package/Cargo.toml +46 -0
  4. package/LICENSE +21 -0
  5. package/README.md +121 -2
  6. package/RELEASING.md +114 -0
  7. package/THIRD_PARTY_NOTICES.md +7579 -0
  8. package/build.rs +3 -0
  9. package/cheerox.darwin-arm64.node +0 -0
  10. package/cheerox.darwin-x64.node +0 -0
  11. package/cheerox.linux-arm64-gnu.node +0 -0
  12. package/cheerox.linux-arm64-musl.node +0 -0
  13. package/cheerox.linux-x64-gnu.node +0 -0
  14. package/cheerox.linux-x64-musl.node +0 -0
  15. package/cheerox.win32-arm64-msvc.node +0 -0
  16. package/cheerox.win32-x64-msvc.node +0 -0
  17. package/dist/cheerio-compat-BS--qPzw.mjs +1648 -0
  18. package/dist/cheerio-compat-BS--qPzw.mjs.map +1 -0
  19. package/dist/cheerio-compat-DRLPzBdX.d.mts +88 -0
  20. package/dist/cheerio-compat-DRsINTwV.d.cts +88 -0
  21. package/dist/cheerio-compat-DRsINTwV.d.ts +88 -0
  22. package/dist/cheerio-compat-DSwBAJ1s.cjs +1719 -0
  23. package/dist/cheerio-compat-DSwBAJ1s.cjs.map +1 -0
  24. package/dist/cheerio-compat.cjs +18 -0
  25. package/dist/cheerio-compat.d.cts +2 -0
  26. package/dist/cheerio-compat.d.mts +2 -0
  27. package/dist/cheerio-compat.d.ts +2 -0
  28. package/dist/cheerio-compat.mjs +1 -0
  29. package/dist/index.cjs +13 -0
  30. package/dist/index.cjs.map +1 -0
  31. package/dist/index.d.cts +28 -0
  32. package/dist/index.d.mts +6 -0
  33. package/dist/index.d.ts +28 -0
  34. package/dist/index.mjs +53 -0
  35. package/dist/index.mjs.map +1 -0
  36. package/dist/legacy-parse.cjs +5 -0
  37. package/dist/legacy-parse.d.mts +8 -0
  38. package/dist/legacy-parse.d.ts +7 -0
  39. package/dist/legacy-parse.mjs +1 -0
  40. package/dist/modern-B7hyW4cI.d.cts +102 -0
  41. package/dist/modern-B7hyW4cI.d.ts +102 -0
  42. package/dist/modern-CHQGP0Yt.cjs +2858 -0
  43. package/dist/modern-CHQGP0Yt.cjs.map +1 -0
  44. package/dist/modern-CJvSD_y5.d.mts +102 -0
  45. package/dist/modern-CvXcTn82.mjs +2769 -0
  46. package/dist/modern-CvXcTn82.mjs.map +1 -0
  47. package/dist/modern.cjs +19 -0
  48. package/dist/modern.d.cts +3 -0
  49. package/dist/modern.d.mts +3 -0
  50. package/dist/modern.d.ts +3 -0
  51. package/dist/modern.mjs +3 -0
  52. package/dist/nodes-jbWWhssj.cjs +4210 -0
  53. package/dist/nodes-jbWWhssj.cjs.map +1 -0
  54. package/dist/nodes-sYxb5qyZ.mjs +3803 -0
  55. package/dist/nodes-sYxb5qyZ.mjs.map +1 -0
  56. package/dist/slim.cjs +16 -0
  57. package/dist/slim.cjs.map +1 -0
  58. package/dist/slim.d.cts +6 -0
  59. package/dist/slim.d.mts +6 -0
  60. package/dist/slim.d.ts +6 -0
  61. package/dist/slim.mjs +12 -0
  62. package/dist/slim.mjs.map +1 -0
  63. package/dist/types-CA01Zg3r.d.cts +526 -0
  64. package/dist/types-CA01Zg3r.d.mts +526 -0
  65. package/dist/types-CA01Zg3r.d.ts +526 -0
  66. package/dist/utils.cjs +31 -0
  67. package/dist/utils.cjs.map +1 -0
  68. package/dist/utils.d.cts +8 -0
  69. package/dist/utils.d.mts +8 -0
  70. package/dist/utils.d.ts +8 -0
  71. package/dist/utils.mjs +25 -0
  72. package/dist/utils.mjs.map +1 -0
  73. package/native/src/arena.rs +2109 -0
  74. package/native/src/attributes.rs +946 -0
  75. package/native/src/codec.rs +298 -0
  76. package/native/src/diagnostics.rs +1249 -0
  77. package/native/src/document_order.rs +711 -0
  78. package/native/src/extraction.rs +321 -0
  79. package/native/src/gc.rs +175 -0
  80. package/native/src/hook_sink.rs +801 -0
  81. package/native/src/hook_stream.rs +513 -0
  82. package/native/src/id_hash.rs +42 -0
  83. package/native/src/immutable.rs +333 -0
  84. package/native/src/lib.rs +4119 -0
  85. package/native/src/location.rs +392 -0
  86. package/native/src/markup_tokenizer.rs +668 -0
  87. package/native/src/runtime.rs +368 -0
  88. package/native/src/selector.rs +1596 -0
  89. package/native/src/sink.rs +274 -0
  90. package/native/src/snapshot.rs +672 -0
  91. package/native/src/stream.rs +334 -0
  92. package/native/src/tokenizer.rs +581 -0
  93. package/native/src/tracker.rs +232 -0
  94. package/native/vendor/README.md +26 -0
  95. package/native/vendor/html5ever-0.35.0/.cargo_vcs_info.json +6 -0
  96. package/native/vendor/html5ever-0.35.0/Cargo.lock +828 -0
  97. package/native/vendor/html5ever-0.35.0/Cargo.toml +85 -0
  98. package/native/vendor/html5ever-0.35.0/LICENSE-APACHE +201 -0
  99. package/native/vendor/html5ever-0.35.0/LICENSE-MIT +25 -0
  100. package/native/vendor/html5ever-0.35.0/README.md +60 -0
  101. package/native/vendor/html5ever-0.35.0/benches/html5ever.rs +86 -0
  102. package/native/vendor/html5ever-0.35.0/data/bench/lipsum-zh.html +19 -0
  103. package/native/vendor/html5ever-0.35.0/data/bench/lipsum.html +40 -0
  104. package/native/vendor/html5ever-0.35.0/data/bench/medium-fragment.html +24 -0
  105. package/native/vendor/html5ever-0.35.0/data/bench/small-fragment.html +7 -0
  106. package/native/vendor/html5ever-0.35.0/data/bench/strong.html +1 -0
  107. package/native/vendor/html5ever-0.35.0/data/bench/tiny-fragment.html +1 -0
  108. package/native/vendor/html5ever-0.35.0/examples/arena.rs +356 -0
  109. package/native/vendor/html5ever-0.35.0/examples/capi/tokenize.c +74 -0
  110. package/native/vendor/html5ever-0.35.0/examples/noop-tokenize.rs +47 -0
  111. package/native/vendor/html5ever-0.35.0/examples/noop-tree-builder.rs +132 -0
  112. package/native/vendor/html5ever-0.35.0/examples/print-tree-actions.rs +185 -0
  113. package/native/vendor/html5ever-0.35.0/examples/tokenize.rs +111 -0
  114. package/native/vendor/html5ever-0.35.0/src/driver.rs +148 -0
  115. package/native/vendor/html5ever-0.35.0/src/lib.rs +30 -0
  116. package/native/vendor/html5ever-0.35.0/src/macros.rs +34 -0
  117. package/native/vendor/html5ever-0.35.0/src/serialize/mod.rs +255 -0
  118. package/native/vendor/html5ever-0.35.0/src/tokenizer/char_ref/mod.rs +530 -0
  119. package/native/vendor/html5ever-0.35.0/src/tokenizer/interface.rs +99 -0
  120. package/native/vendor/html5ever-0.35.0/src/tokenizer/mod.rs +2628 -0
  121. package/native/vendor/html5ever-0.35.0/src/tokenizer/states.rs +97 -0
  122. package/native/vendor/html5ever-0.35.0/src/tree_builder/data.rs +170 -0
  123. package/native/vendor/html5ever-0.35.0/src/tree_builder/mod.rs +1848 -0
  124. package/native/vendor/html5ever-0.35.0/src/tree_builder/rules.rs +1494 -0
  125. package/native/vendor/html5ever-0.35.0/src/tree_builder/tag_sets.rs +114 -0
  126. package/native/vendor/html5ever-0.35.0/src/tree_builder/types.rs +91 -0
  127. package/native/vendor/html5ever-0.35.0/src/util/str.rs +52 -0
  128. package/native/vendor/html5gum-0.8.4/Cargo.lock +1006 -0
  129. package/native/vendor/html5gum-0.8.4/Cargo.toml +109 -0
  130. package/native/vendor/html5gum-0.8.4/LICENSE +19 -0
  131. package/native/vendor/html5gum-0.8.4/README.md +110 -0
  132. package/native/vendor/html5gum-0.8.4/benches/files/0050.html +2131 -0
  133. package/native/vendor/html5gum-0.8.4/benches/files/6D30.html +1004 -0
  134. package/native/vendor/html5gum-0.8.4/benches/files.rs +32 -0
  135. package/native/vendor/html5gum-0.8.4/benches/patterns.rs +31 -0
  136. package/native/vendor/html5gum-0.8.4/src/arrayvec.rs +29 -0
  137. package/native/vendor/html5gum-0.8.4/src/char_validator.rs +134 -0
  138. package/native/vendor/html5gum-0.8.4/src/emitters/callback.rs +676 -0
  139. package/native/vendor/html5gum-0.8.4/src/emitters/default.rs +207 -0
  140. package/native/vendor/html5gum-0.8.4/src/emitters/emitter.rs +344 -0
  141. package/native/vendor/html5gum-0.8.4/src/emitters/html5ever.rs +306 -0
  142. package/native/vendor/html5gum-0.8.4/src/emitters/mod.rs +25 -0
  143. package/native/vendor/html5gum-0.8.4/src/entities.rs +3342 -0
  144. package/native/vendor/html5gum-0.8.4/src/error.rs +96 -0
  145. package/native/vendor/html5gum-0.8.4/src/htmlstring.rs +130 -0
  146. package/native/vendor/html5gum-0.8.4/src/lib.rs +66 -0
  147. package/native/vendor/html5gum-0.8.4/src/machine.rs +2136 -0
  148. package/native/vendor/html5gum-0.8.4/src/machine_helper.rs +277 -0
  149. package/native/vendor/html5gum-0.8.4/src/read_helper.rs +244 -0
  150. package/native/vendor/html5gum-0.8.4/src/reader.rs +440 -0
  151. package/native/vendor/html5gum-0.8.4/src/span.rs +98 -0
  152. package/native/vendor/html5gum-0.8.4/src/state.rs +16 -0
  153. package/native/vendor/html5gum-0.8.4/src/testutils.rs +71 -0
  154. package/native/vendor/html5gum-0.8.4/src/tokenizer.rs +189 -0
  155. package/native/vendor/html5gum-0.8.4/src/utils.rs +88 -0
  156. package/native/vendor/markup5ever-0.35.0/.cargo_vcs_info.json +6 -0
  157. package/native/vendor/markup5ever-0.35.0/Cargo.toml +45 -0
  158. package/native/vendor/markup5ever-0.35.0/LICENSE-APACHE +201 -0
  159. package/native/vendor/markup5ever-0.35.0/LICENSE-MIT +25 -0
  160. package/native/vendor/markup5ever-0.35.0/interface/mod.rs +422 -0
  161. package/native/vendor/markup5ever-0.35.0/interface/tree_builder.rs +280 -0
  162. package/native/vendor/markup5ever-0.35.0/lib.rs +59 -0
  163. package/native/vendor/markup5ever-0.35.0/serialize.rs +77 -0
  164. package/native/vendor/markup5ever-0.35.0/util/buffer_queue.rs +333 -0
  165. package/native/vendor/markup5ever-0.35.0/util/smallcharset.rs +88 -0
  166. package/package.json +167 -4
  167. package/scripts/check-native.mjs +15 -0
  168. package/scripts/check-release.mjs +234 -0
  169. package/scripts/fix-declarations.mjs +39 -0
  170. package/scripts/generate-notices.mjs +188 -0
  171. package/scripts/notices/README.md +13 -0
  172. package/scripts/notices/cheerio-MIT.txt +21 -0
  173. package/scripts/notices/html5ever-AUTHORS.txt +20 -0
  174. package/scripts/notices/html5ever-COPYRIGHT.txt +8 -0
  175. package/scripts/notices/html5ever-LICENSE-APACHE.txt +201 -0
  176. package/scripts/notices/html5ever-LICENSE-MIT.txt +25 -0
  177. package/scripts/notices/htmlparser2-MIT.txt +18 -0
  178. package/scripts/notices/napi-rs-MIT.txt +43 -0
  179. package/scripts/notices/neon-MIT.txt +19 -0
  180. package/scripts/notices/runtime-01c266bced4a434da005.txt +3 -0
  181. package/scripts/notices/runtime-0a54e647fe54104658b5.txt +14 -0
  182. package/scripts/notices/runtime-0b74dfa0bcee5c420c6b.txt +25 -0
  183. package/scripts/notices/runtime-0d542e0c8804e39aa7f3.txt +177 -0
  184. package/scripts/notices/runtime-0f96a83840e146e43c0e.txt +21 -0
  185. package/scripts/notices/runtime-123a331b5dbf04c30097.txt +25 -0
  186. package/scripts/notices/runtime-172020dbfd5b53a226df.txt +34 -0
  187. package/scripts/notices/runtime-209fbbe0ad52d9235e37.txt +26 -0
  188. package/scripts/notices/runtime-23f18e03dc49df91622f.txt +23 -0
  189. package/scripts/notices/runtime-268872b9816f90fd8e85.txt +220 -0
  190. package/scripts/notices/runtime-35242e7a83f69875e6ed.txt +176 -0
  191. package/scripts/notices/runtime-378f5840b258e2779c39.txt +25 -0
  192. package/scripts/notices/runtime-4108245a1f2df9d4e94d.txt +25 -0
  193. package/scripts/notices/runtime-4455bf75a91154108304.txt +21 -0
  194. package/scripts/notices/runtime-553fffcd9b1cb158bc3e.txt +13 -0
  195. package/scripts/notices/runtime-62c7a1e35f56406896d7.txt +176 -0
  196. package/scripts/notices/runtime-6485b8ed310d3f0340bf.txt +25 -0
  197. package/scripts/notices/runtime-69fef7b0f322a6555415.txt +201 -0
  198. package/scripts/notices/runtime-6df43f6f4b5d4587f3d8.txt +187 -0
  199. package/scripts/notices/runtime-799e9ca9d179295ef372.txt +24 -0
  200. package/scripts/notices/runtime-7b63ecd5f1902af1b637.txt +25 -0
  201. package/scripts/notices/runtime-7bc7d5de2a0b793d4e1a.txt +21 -0
  202. package/scripts/notices/runtime-7e12e5df4bae12cb2158.txt +24 -0
  203. package/scripts/notices/runtime-861399f8c21c042b1105.txt +12 -0
  204. package/scripts/notices/runtime-8ada45cd9f843acf64e4.txt +201 -0
  205. package/scripts/notices/runtime-90eb64f0279b0d9432ac.txt +12 -0
  206. package/scripts/notices/runtime-a60eea817514531668d7.txt +201 -0
  207. package/scripts/notices/runtime-a7c936ff1ed8fa340172.txt +25 -0
  208. package/scripts/notices/runtime-ab6eec6caf0fa5775e41.txt +275 -0
  209. package/scripts/notices/runtime-b1181a40b2a7b25cf66f.txt +19 -0
  210. package/scripts/notices/runtime-b71bd43a069ca0641a9e.txt +25 -0
  211. package/scripts/notices/runtime-c16f8dcf1a368b83be78.txt +201 -0
  212. package/scripts/notices/runtime-c2cfccb812fe482101a8.txt +21 -0
  213. package/scripts/notices/runtime-e99d88d232bf57d70f0f.txt +25 -0
  214. package/scripts/notices/runtime-f32fb3b417a194167cfa.txt +9 -0
  215. package/scripts/notices/runtime-f5062c9a188d81dfe66b.txt +39 -0
  216. package/scripts/notices/runtime-f9070a832833fa7488fd.txt +4 -0
  217. package/scripts/notices/runtime-fab3dd6bdab226f1c086.txt +373 -0
  218. package/scripts/notices/runtime-fba3318d0c600380177e.txt +62 -0
  219. package/scripts/notices/runtime-ff8f68cb076caf8cefe7.txt +25 -0
  220. package/scripts/notices/runtime-ff92bed461f50338dd70.txt +74 -0
  221. package/scripts/notices/runtime.json +1632 -0
  222. package/scripts/notices/sources.json +561 -0
  223. package/scripts/notices/xray-MIT.txt +21 -0
  224. package/src/attribute-object.ts +71 -0
  225. package/src/attributes.ts +308 -0
  226. package/src/cheerio-compat/css.ts +58 -0
  227. package/src/cheerio-compat/render.ts +106 -0
  228. package/src/cheerio-compat/selectors.ts +51 -0
  229. package/src/cheerio-compat/types.ts +52 -0
  230. package/src/cheerio-compat.ts +2055 -0
  231. package/src/codec.ts +96 -0
  232. package/src/dom.ts +87 -0
  233. package/src/extract-plan.ts +97 -0
  234. package/src/extract.ts +322 -0
  235. package/src/hooks.ts +369 -0
  236. package/src/index.ts +48 -0
  237. package/src/io.ts +491 -0
  238. package/src/match.ts +207 -0
  239. package/src/modern.ts +259 -0
  240. package/src/native.ts +149 -0
  241. package/src/nodes.ts +831 -0
  242. package/src/parse.ts +53 -0
  243. package/src/parser-types.ts +157 -0
  244. package/src/router.ts +1129 -0
  245. package/src/selection.ts +682 -0
  246. package/src/slim.ts +12 -0
  247. package/src/snapshot.ts +291 -0
  248. package/src/transport.ts +113 -0
  249. package/src/types.ts +186 -0
  250. package/src/utils.ts +29 -0
  251. package/src/workers.ts +21 -0
  252. package/tsconfig.json +15 -0
  253. package/tsdown.config.mjs +17 -0
@@ -0,0 +1,2055 @@
1
+ /**
2
+ * The Cheerio 0.22.0 facade, backed by the Rust engine.
3
+ *
4
+ * Every public behavior is ported from cheerio@0.22.0 (commit
5
+ * 49b477e7fe98b74f61f77acd06a0ef4edb5c333e): lib/cheerio.js, lib/static.js,
6
+ * lib/parse.js, lib/utils.js and lib/api/*.js. DOM storage, parsing and
7
+ * selection stay in the native arena; this file supplies the legacy object
8
+ * model (plain field semantics, `root` references, 0.22.0 serialization and
9
+ * css-select 1.2.0 selection semantics) on top of it.
10
+ *
11
+ * Structural rule: sibling and parent links are owned by the engine. All
12
+ * tree surgery installs whole child lists (see writeChildren), which rebuilds
13
+ * the links exactly as 0.22.0's raw `prev`/`next`/`parent` writes did
14
+ * observably; raw pointer writes on attached nodes would fight the engine's
15
+ * own invariants.
16
+ */
17
+ import { requireNative, type NativeDocument } from './native.js';
18
+ import { getCss, setCss } from './cheerio-compat/css.js';
19
+ import { validateLegacySelector } from './cheerio-compat/selectors.js';
20
+ import { renderWith } from './cheerio-compat/render.js';
21
+ import { getNode, getNodesOfType, hasMaterializedAttributes, hasMaterializedChildren, importNodes, nodeBinding, operation, rootNode, setRootIfCached, viewId, viewIdIn } from './nodes.js';
22
+ import { routeDocument } from './router.js';
23
+ import { cleanParserOptions, hasParserHooks } from './hooks.js';
24
+ import type { LegacyOptions, LegacyNode, CheerioInstance, CheerioConstructor, CheerioPrototype, CheerioStatic } from './cheerio-compat/types.js';
25
+ export type { CheerioStatic } from './cheerio-compat/types.js';
26
+ import { version as packageVersion } from '../package.json';
27
+
28
+ /** Cheerio.prototype.options — the exact 0.22.0 defaults. */
29
+ const defaultOpts: LegacyOptions = {
30
+ withDomLvl1: true,
31
+ normalizeWhitespace: false,
32
+ xmlMode: false,
33
+ decodeEntities: true,
34
+ };
35
+
36
+ /** lodash.defaults semantics: fill undefined keys from the sources. */
37
+ function defaults<T extends object>(target: T, ...sources: (object | undefined | null)[]): T {
38
+ for (const source of sources) {
39
+ if (!source) continue;
40
+ for (const key of Object.keys(source)) {
41
+ const value = (source as Record<string, unknown>)[key];
42
+ if ((target as Record<string, unknown>)[key] === undefined && value !== undefined) {
43
+ (target as Record<string, unknown>)[key] = value;
44
+ }
45
+ }
46
+ }
47
+ return target;
48
+ }
49
+
50
+ type AttributeDocument = NativeDocument & {
51
+ setAttribute?: (ids: number[], name: string, value: string | null) => void;
52
+ addClass?: (ids: number[], name: string) => void;
53
+ insertHtml?: (targetIds: number[], html: string, position: string) => number[] | undefined;
54
+ remove?: (ids: number[]) => void;
55
+ };
56
+
57
+ const isTag = (elem: unknown): boolean => {
58
+ const type = typeof elem === 'object' && elem !== null ? (elem as { type?: string }).type : elem;
59
+ return (type !== undefined && (tags as Record<string, boolean>)[type as string]) || false;
60
+ };
61
+ const tags: Record<string, boolean> = { tag: true, script: true, style: true };
62
+
63
+ const camelCase = (str: string): string => str.replace(/[_.-](\w|$)/g, (_, x: string) => x.toUpperCase());
64
+ const cssCase = (str: string): string => str.replace(/[A-Z]/g, '-$&').toLowerCase();
65
+
66
+ const domEach = <T, C = unknown>(cheerio: { length: number; [index: number]: T }, fn: (this: C, i: number, el: T) => unknown): typeof cheerio => {
67
+ let i = 0;
68
+ const len = cheerio.length;
69
+ while (i < len && fn.call(cheerio as unknown as C, i, cheerio[i]) !== false) ++i;
70
+ return cheerio;
71
+ };
72
+
73
+ /** Create a deep copy by rendering and re-parsing, as 0.22.0 does. */
74
+ function cloneDom(dom: LegacyNode[], options: LegacyOptions): LegacyNode[] {
75
+ return evaluate(renderWith(options, dom), options);
76
+ }
77
+
78
+ const quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/;
79
+ const simpleTagExpr = /^\s*([A-Za-z][\w-]*)\s*$/;
80
+ // These selectors can only return elements of their final explicit tag.
81
+ const finalTagExpr = /^\s*(?:[A-Za-z][\w-]*\s+)*([A-Za-z][\w-]*)(?:\[[\w-]+\])?\s*$/;
82
+ const specialTagExpr = /^(?:script|style)$/i;
83
+
84
+ const isHtml = (str: string): boolean => {
85
+ if (str.charAt(0) === '<' && str.charAt(str.length - 1) === '>' && str.length >= 3) return true;
86
+ const match = quickExpr.exec(str);
87
+ return !!(match && match[1]);
88
+ };
89
+
90
+ /*
91
+ * parse.js
92
+ */
93
+
94
+ /** Legacy options with the native parser mode folded in. */
95
+ function legacyOptions(options?: LegacyOptions | null): LegacyOptions {
96
+ return defaults({ ...(options ?? {}) } as LegacyOptions, defaultOpts, { _useHtmlParser2: true, _legacyDom: true });
97
+ }
98
+
99
+ function newDocument(options: LegacyOptions): NativeDocument {
100
+ return routeDocument(new (requireNative().NativeDocument)('', false, JSON.stringify(cleanParserOptions(options))), options);
101
+ }
102
+
103
+ /** As nodes under the legacy model: views that read like plain objects. */
104
+ function asNodes(document: NativeDocument, ids: number[], knownType?: string): LegacyNode[] {
105
+ if (knownType) return getNodesOfType(document, ids, knownType) as LegacyNode[];
106
+ return ids.map((id) => getNode(document, id) as LegacyNode);
107
+ }
108
+
109
+ /**
110
+ * htmlparser2 3.9.1's `normalizeWhitespace`: collapse whitespace runs in
111
+ * regular text nodes to single spaces (script/style contents stay raw).
112
+ */
113
+ function normalizeWhitespace(nodes: LegacyNode[]): void {
114
+ for (const node of nodes) {
115
+ if (node.type === 'text') {
116
+ if (/\s\s|\s$|^\s/.test(node.data ?? '')) node.data = (node.data ?? '').replace(/\s+/g, ' ');
117
+ } else if (node.type !== 'script' && node.type !== 'style' && node.children) {
118
+ normalizeWhitespace(node.children);
119
+ }
120
+ }
121
+ }
122
+
123
+ /** htmlparser.parseDOM(content, options): the parsed children, without a root wrapper. */
124
+ export function evaluate(content: string | Buffer | ArrayLike<LegacyNode> | LegacyNode, options?: LegacyOptions | null): LegacyNode[] {
125
+ const opts = legacyOptions(options);
126
+ if (typeof content !== 'string' && !Buffer.isBuffer(content)) {
127
+ // A pre-parsed DOM passes through, as in 0.22.0's parse.evaluate: the
128
+ // nodes are imported once and keep their object identities.
129
+ const document = newDocument(opts);
130
+ const nodes = Array.isArray(content) || (content && typeof content === 'object' && 'length' in (content as object))
131
+ ? Array.from(content as ArrayLike<LegacyNode>)
132
+ : [content as LegacyNode];
133
+ return asNodes(document, importNodes(document, nodes));
134
+ }
135
+ const document = routeDocument(
136
+ new (requireNative().NativeDocument)(Buffer.isBuffer(content) ? content.toString() : content, false, JSON.stringify(cleanParserOptions(opts))),
137
+ opts,
138
+ );
139
+ const root = rootNode(document, document.rootId());
140
+ const children = Array.from((root as LegacyNode).children ?? []) as LegacyNode[];
141
+ if (opts.normalizeWhitespace) normalizeWhitespace(children);
142
+ return children;
143
+ }
144
+
145
+ /** One native write that installs a parent's child list and sibling links. */
146
+ function writeChildren(parent: LegacyNode, list: LegacyNode[]): void {
147
+ const binding = bindingOf(parent);
148
+ if (!binding) return;
149
+ operation(binding.document, 'setNode', { id: binding.id, field: 'children', value: importNodes(binding.document, list) });
150
+ }
151
+
152
+ /**
153
+ * Update the dom structure for one changed layer — lib/parse.js `update`.
154
+ * The new level is installed with one children write per changed parent;
155
+ * the engine rebuilds the `prev`/`next`/`parent` links.
156
+ */
157
+ export function update(arrInput: unknown, parent: LegacyNode | null): LegacyNode | null {
158
+ const arr: LegacyNode[] = Array.isArray(arrInput) ? (arrInput as LegacyNode[]) : [arrInput as LegacyNode];
159
+ // Capture the previous parents before the install re-parents the nodes.
160
+ const oldParents = arr.map((node) => node.parent || node.root);
161
+ if (parent) {
162
+ writeChildren(parent, arr);
163
+ }
164
+ for (let i = 0; i < arr.length; i++) {
165
+ const node = arr[i];
166
+ const oldParent = oldParents[i];
167
+ // 0.22.0 installs `arr` on `parent` first, so members of the new list
168
+ // skip the removal pass by the `oldSiblings !== arr` identity check.
169
+ if (oldParent && oldParent !== parent) {
170
+ const list = Array.from(oldParent.children ?? []);
171
+ const index = list.indexOf(node);
172
+ if (index >= 0) writeChildren(oldParent, list.filter((item, at) => at !== index));
173
+ }
174
+ if (parent && parent.type === 'root') {
175
+ node.root = parent;
176
+ } else {
177
+ node.root = null;
178
+ }
179
+ }
180
+ return parent;
181
+ }
182
+
183
+ /** lib/parse.js: parse into a fresh document and return its `<root>` node. */
184
+ export function parse(content: string | Buffer | ArrayLike<LegacyNode> | LegacyNode, options?: LegacyOptions | null): LegacyNode {
185
+ const opts = legacyOptions(options);
186
+ let document: NativeDocument;
187
+ let root: LegacyNode;
188
+ if (typeof content === 'string' || Buffer.isBuffer(content)) {
189
+ document = routeDocument(
190
+ new (requireNative().NativeDocument)(Buffer.isBuffer(content) ? content.toString() : content, false, JSON.stringify(cleanParserOptions(opts))),
191
+ opts,
192
+ );
193
+ root = rootNode(document, document.rootId()) as LegacyNode;
194
+ } else {
195
+ // A pre-parsed DOM: 0.22.0 wraps it in the synthetic root via update().
196
+ document = newDocument(opts);
197
+ const nodes = Array.isArray(content) || (content && typeof content === 'object' && 'length' in (content as object))
198
+ ? Array.from(content as ArrayLike<LegacyNode>)
199
+ : [content as LegacyNode];
200
+ root = rootNode(document, document.rootId()) as LegacyNode;
201
+ writeChildren(root, nodes);
202
+ }
203
+ let children: LegacyNode[];
204
+ if (opts.normalizeWhitespace) {
205
+ children = Array.from(root.children ?? []) as LegacyNode[];
206
+ normalizeWhitespace(children);
207
+ } else {
208
+ const record = operation<{ children?: number[] }>(document, 'node', { id: viewId(root)! });
209
+ children = asNodes(document, record.children ?? []);
210
+ }
211
+ for (const child of children) child.root = root;
212
+ return root;
213
+ }
214
+
215
+ /*
216
+ * css-select 1.2.0 scoped selection, over native matching.
217
+ */
218
+
219
+ function bindingOf(node: unknown): { document: NativeDocument; id: number } | undefined {
220
+ return node && typeof node === 'object' ? nodeBinding(node) : undefined;
221
+ }
222
+
223
+ function idsOf(document: NativeDocument, nodes: ArrayLike<unknown>): number[] {
224
+ const len = (nodes as any).length;
225
+ if (typeof len !== 'number' || len < 0) return importNodes(document, nodes as unknown[]);
226
+ const out = new Array<number>(len);
227
+ for (let i = 0; i < len; i++) {
228
+ const id = viewIdIn(document, (nodes as any)[i]);
229
+ if (id === undefined) return importNodes(document, nodes as unknown[]);
230
+ out[i] = id;
231
+ }
232
+ return out;
233
+ }
234
+
235
+ /**
236
+ * css-select 1.2 `select(query, elems, options)`: candidates are the members
237
+ * of `elems` and their descendants, in list order (domutils.findAll, with
238
+ * removeSubsets applied). A candidate matches when it satisfies the selector
239
+ * and is a context node or a descendant of one — the absolutized `:scope`
240
+ * descendant rule, whose `acceptSelf` branch lets a context node match itself.
241
+ */
242
+ function scopedSelect(selector: string, elems: LegacyNode[], options: LegacyOptions): LegacyNode[] {
243
+ if (!selector || !elems.length) return [];
244
+ const document = bindingOf(elems[0])?.document;
245
+ if (!document) return [];
246
+ const context = (options.context as LegacyNode[] | undefined) ?? elems;
247
+ const contextIds = new Set(idsOf(document, context));
248
+ // domutils.removeSubsets: drop members that contain other members.
249
+ const roots = elems.filter((node, index) => !elems.some((other, otherIndex) => otherIndex !== index && isAncestorOf(other, node)));
250
+ const candidates: number[] = [];
251
+ const seen = new Set<number>();
252
+ for (const root of roots) {
253
+ const rootId = viewIdIn(document, root)!;
254
+ if (!seen.has(rootId)) { seen.add(rootId); candidates.push(rootId); }
255
+ for (const id of document.select('*', [rootId])) {
256
+ if (!seen.has(id)) { seen.add(id); candidates.push(id); }
257
+ }
258
+ }
259
+ // css-select 1.2 absolutizes a leading combinator to `:scope >|+|~ ...`:
260
+ // the anchor sits at the context, one relation away from the candidate.
261
+ const leading = /^\s*([>+~])\s*/.exec(selector);
262
+ let rest = selector;
263
+ let combinator: string | undefined;
264
+ if (leading) {
265
+ combinator = leading[1];
266
+ rest = selector.slice(leading[0].length);
267
+ }
268
+ const matched = new Set(matchesSelector(document, candidates, rest, options));
269
+ const result: LegacyNode[] = [];
270
+ for (const id of candidates) {
271
+ if (!matched.has(id)) continue;
272
+ const node = getNode(document, id) as LegacyNode;
273
+ if (combinator && !combinatorAnchored(node, combinator, contextIds)) continue;
274
+ if (!combinator && !withinContext(node, contextIds)) continue;
275
+ result.push(node);
276
+ }
277
+ return result;
278
+ }
279
+
280
+ /**
281
+ * The `:scope` anchor of a leading-combinator selector: the candidate's
282
+ * parent, previous element sibling, or any earlier element sibling must be a
283
+ * context node.
284
+ */
285
+ function combinatorAnchored(node: LegacyNode, combinator: string, contextIds: Set<number>): boolean {
286
+ if (combinator === '>') {
287
+ const parent = node.parent;
288
+ return parent !== null && parent !== undefined && contextIds.has(viewId(parent) ?? NaN);
289
+ }
290
+ if (combinator === '+') {
291
+ let sibling = node.prev as LegacyNode | null | undefined;
292
+ while (sibling && !isTag(sibling)) sibling = sibling.prev as LegacyNode | null | undefined;
293
+ return sibling !== null && sibling !== undefined && contextIds.has(viewId(sibling) ?? NaN);
294
+ }
295
+ // '~'
296
+ let sibling = node.prev as LegacyNode | null | undefined;
297
+ while (sibling) {
298
+ if (isTag(sibling) && contextIds.has(viewId(sibling) ?? NaN)) return true;
299
+ sibling = sibling.prev as LegacyNode | null | undefined;
300
+ }
301
+ return false;
302
+ }
303
+
304
+ /** Native matching for a batch of ids, with 0.22.0's SyntaxError behavior. */
305
+ function matchesSelector(document: NativeDocument, ids: number[], selector: string, options: LegacyOptions): number[] {
306
+ validateLegacySelector(selector);
307
+ try {
308
+ return operation<number[]>(document, 'matches', { ids, selector, options: { xmlMode: options.xmlMode } }) ?? [];
309
+ } catch (error) {
310
+ throw error instanceof SyntaxError ? error : new SyntaxError((error as Error)?.message ?? String(error));
311
+ }
312
+ }
313
+
314
+ /** Whether the node or one of its ancestors belongs to the context set. */
315
+ function withinContext(node: LegacyNode, contextIds: Set<number>): boolean {
316
+ for (let current: LegacyNode | null = node; current; ) {
317
+ const id = viewId(current);
318
+ if (id !== undefined && contextIds.has(id)) return true;
319
+ const parent: LegacyNode | null | undefined = current.parent;
320
+ if (parent === null || parent === current) {
321
+ // Top-level nodes carry their document root in `.root` (0.22.0 model).
322
+ const root = current.root as LegacyNode | null | undefined;
323
+ return root !== null && root !== undefined && contextIds.has(viewId(root) ?? NaN);
324
+ }
325
+ current = parent!;
326
+ }
327
+ return false;
328
+ }
329
+
330
+ function isAncestorOf(ancestor: LegacyNode, node: LegacyNode | null | undefined): boolean {
331
+ if (node === ancestor) return false;
332
+ for (let current = node?.parent; current; current = current.parent) {
333
+ if (current === ancestor) return true;
334
+ if (current.parent === current) break;
335
+ }
336
+ return false;
337
+ }
338
+
339
+ /** htmlparser2 DomUtils.uniqueSort over views: document order, deduplicated. */
340
+ function uniqueSort(nodes: LegacyNode[]): LegacyNode[] {
341
+ const grouped = new Map<NativeDocument, { id: number; node: LegacyNode }[]>();
342
+ for (const node of nodes) {
343
+ const binding = bindingOf(node);
344
+ if (!binding) continue;
345
+ let list = grouped.get(binding.document);
346
+ if (!list) grouped.set(binding.document, list = []);
347
+ list.push({ id: binding.id, node });
348
+ }
349
+ const sorted: LegacyNode[] = [];
350
+ for (const [document, list] of grouped) {
351
+ const order = operation<number[]>(document, 'uniqueSort', { ids: list.map((entry) => entry.id) });
352
+ for (const id of order ?? []) {
353
+ const entry = list.find((candidate) => candidate.id === id);
354
+ if (entry) sorted.push(entry.node);
355
+ }
356
+ }
357
+ return sorted;
358
+ }
359
+
360
+ /*
361
+ * lib/cheerio.js
362
+ */
363
+
364
+ const isNode = (obj: unknown): boolean => {
365
+ if (viewId(obj) !== undefined) return true;
366
+ const node = obj as LegacyNode;
367
+ return !!(obj && typeof obj === 'object' && (node.name || node.type === 'text' || node.type === 'comment'));
368
+ };
369
+
370
+ function makeCheerio(): CheerioConstructor {
371
+ const Cheerio = function (this: CheerioInstance, selector?: any, context?: any, root?: any, options?: LegacyOptions) {
372
+ if (!(this instanceof Cheerio)) {
373
+ return new Cheerio(selector, context, root, options);
374
+ }
375
+
376
+ this.options = defaults(options || {}, this.options);
377
+
378
+ // $(), $(null), $(undefined), $(false)
379
+ if (!selector) return this;
380
+
381
+ if (root) {
382
+ if (typeof root === 'string') root = parse(root, this.options);
383
+ this._root = Cheerio.call(this, root);
384
+ }
385
+
386
+ // $($)
387
+ if (selector.cheerio) return selector;
388
+
389
+ // $(dom)
390
+ if (isNode(selector)) selector = [selector];
391
+
392
+ // $([dom])
393
+ if (Array.isArray(selector)) {
394
+ selector.forEach((elem: LegacyNode, idx: number) => {
395
+ this[idx] = elem;
396
+ });
397
+ this.length = selector.length;
398
+ return this;
399
+ }
400
+
401
+ // $(<html>)
402
+ if (typeof selector === 'string' && isHtml(selector)) {
403
+ return Cheerio.call(this, (parse(selector, this.options) as LegacyNode).children ?? []);
404
+ }
405
+
406
+ // If we don't have a context, maybe we have a root, from loading
407
+ if (!context) {
408
+ context = this._root;
409
+ } else if (typeof context === 'string') {
410
+ if (isHtml(context)) {
411
+ // $('li', '<ul>...</ul>')
412
+ context = Cheerio.call(this, parse(context, this.options));
413
+ } else {
414
+ // $('li', 'ul')
415
+ selector = [context, selector].join(' ');
416
+ context = this._root;
417
+ }
418
+ // $('li', node), $('li', [nodes])
419
+ } else if (!context.cheerio) {
420
+ context = Cheerio.call(this, context);
421
+ }
422
+
423
+ // If we still don't have a context, return
424
+ if (!context) return this;
425
+
426
+ // #id, .class, tag
427
+ return context.find(selector);
428
+ } as unknown as CheerioStatic;
429
+
430
+ Cheerio.prototype.cheerio = '[cheerio object]';
431
+ Cheerio.prototype.options = defaultOpts;
432
+ Cheerio.prototype.length = 0;
433
+ Cheerio.prototype.splice = Array.prototype.splice;
434
+
435
+ Cheerio.prototype._make = function (this: CheerioInstance, dom: any, context?: any): CheerioInstance {
436
+ const cheerio = new (this.constructor as CheerioConstructor)(dom, context, this._root, this.options);
437
+ cheerio.prevObject = this;
438
+ return cheerio;
439
+ };
440
+
441
+ Cheerio.prototype.toArray = function (this: CheerioInstance): LegacyNode[] {
442
+ return this.get() as LegacyNode[];
443
+ };
444
+
445
+ return Cheerio;
446
+ }
447
+
448
+ /*
449
+ * api/attributes.js
450
+ */
451
+
452
+ const hasOwn = Object.prototype.hasOwnProperty;
453
+ const rspace = /\s+/;
454
+ const dataAttrPrefix = 'data-';
455
+ const primitives: Record<string, unknown> = { null: null, true: true, false: false };
456
+ const rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i;
457
+ const rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/;
458
+
459
+ function getAttr(elem: LegacyNode | undefined, name?: string): unknown {
460
+ if (!elem || !isTag(elem)) return;
461
+
462
+ if (!elem.attribs) {
463
+ elem.attribs = {};
464
+ }
465
+
466
+ // Return the entire attribs object if no attribute specified
467
+ if (!name) {
468
+ return elem.attribs;
469
+ }
470
+
471
+ if (hasOwn.call(elem.attribs, name)) {
472
+ // Get the (decoded) attribute
473
+ return rboolean.test(name) ? name : elem.attribs[name];
474
+ }
475
+
476
+ // Mimic the DOM and return text content as value for `option's`
477
+ if (elem.name === 'option' && name === 'value') {
478
+ return staticText((elem.children ?? []) as unknown as ArrayLike<LegacyNode>);
479
+ }
480
+
481
+ // Mimic DOM with default value for radios/checkboxes
482
+ if (elem.name === 'input' && (elem.attribs.type === 'radio' || elem.attribs.type === 'checkbox') && name === 'value') {
483
+ return 'on';
484
+ }
485
+ }
486
+
487
+ function setAttr(el: LegacyNode, name: string, value: unknown): void {
488
+ if (value === null) {
489
+ removeAttribute(el, name);
490
+ return;
491
+ }
492
+ const stringValue = value + '';
493
+ const binding = bindingOf(el);
494
+ const document = binding?.document as AttributeDocument | undefined;
495
+ if (binding && document?.setAttribute) {
496
+ document.setAttribute([binding.id], name, stringValue);
497
+ } else {
498
+ el.attribs![name] = stringValue;
499
+ }
500
+ }
501
+
502
+ function removeAttribute(elem: LegacyNode, name: string): void {
503
+ if (!elem.attribs || !hasOwn.call(elem.attribs, name)) return;
504
+ const binding = bindingOf(elem);
505
+ const document = binding?.document as AttributeDocument | undefined;
506
+ if (binding && document?.setAttribute) {
507
+ document.setAttribute([binding.id], name, null);
508
+ } else {
509
+ delete elem.attribs[name];
510
+ }
511
+ }
512
+
513
+ const splitClass = (className?: string): string[] => (className ? className.trim().split(rspace) : []);
514
+
515
+ function setDataStore(el: LegacyNode): Record<string, unknown> {
516
+ if (!el.data || typeof el.data !== 'object') (el as any).data = {};
517
+ return (el as any).data;
518
+ }
519
+
520
+ function readData(el: LegacyNode, name?: string): unknown {
521
+ const readAll = arguments.length < 2;
522
+ let domNames: string[], jsNames: string[];
523
+
524
+ if (readAll) {
525
+ domNames = Object.keys(el.attribs ?? {}).filter((attrName) => attrName.slice(0, dataAttrPrefix.length) === dataAttrPrefix);
526
+ jsNames = domNames.map((domName) => camelCase(domName.slice(dataAttrPrefix.length)));
527
+ } else {
528
+ domNames = [dataAttrPrefix + cssCase(name!)];
529
+ jsNames = [name!];
530
+ }
531
+
532
+ let value: unknown;
533
+ const store = setDataStore(el);
534
+ for (let idx = 0; idx < domNames.length; ++idx) {
535
+ const domName = domNames[idx];
536
+ const jsName = jsNames[idx];
537
+ if (hasOwn.call(el.attribs ?? {}, domName)) {
538
+ value = el.attribs![domName];
539
+
540
+ if (hasOwn.call(primitives, value as string)) {
541
+ value = primitives[value as string];
542
+ } else if (value === String(Number(value))) {
543
+ value = Number(value);
544
+ } else if (rbrace.test(value as string)) {
545
+ try {
546
+ value = JSON.parse(value as string);
547
+ } catch { /* keep the string */ }
548
+ }
549
+
550
+ store[jsName] = value;
551
+ }
552
+ }
553
+
554
+ return readAll ? store : value;
555
+ }
556
+
557
+ const getProp = (el: LegacyNode, name: string): unknown => {
558
+ if (!el || !isTag(el)) return;
559
+ return hasOwn.call(el, name)
560
+ ? (el as any)[name]
561
+ : rboolean.test(name)
562
+ ? getAttr(el, name) !== undefined
563
+ : getAttr(el, name);
564
+ };
565
+
566
+ const setProp = (el: LegacyNode, name: string, value: unknown): void => {
567
+ (el as any)[name] = rboolean.test(name) ? !!value : value;
568
+ };
569
+
570
+ const attributesApi: CheerioPrototype = {
571
+ attr(this: CheerioInstance, name?: any, value?: any) {
572
+ // Set the value (with attr map support)
573
+ if (typeof name === 'object' || value !== undefined) {
574
+ if (typeof value === 'function') {
575
+ return domEach(this, function (i, el) {
576
+ setAttr(el, name, value.call(el, i, el.attribs![name]));
577
+ });
578
+ }
579
+ if (typeof name === 'string') {
580
+ if (this.length === 1 && isTag(this[0])) {
581
+ setAttr(this[0], name, value);
582
+ return this;
583
+ }
584
+ // Batch the plain set across the selection: one native call instead
585
+ // of one per element. `null` removes, as in setAttr.
586
+ const groups = new Map<NativeDocument, Array<{ id: number; name: string; value: string | null }>>();
587
+ let usable = this.length > 0;
588
+ for (let i = 0; i < this.length; i++) {
589
+ const el = this[i];
590
+ if (!isTag(el)) continue;
591
+ if (!el.attribs) el.attribs = {};
592
+ const binding = bindingOf(el);
593
+ if (!binding) { usable = false; break; }
594
+ let group = groups.get(binding.document);
595
+ if (!group) groups.set(binding.document, group = []);
596
+ group.push({ id: binding.id, name, value: value === null ? null : value + '' });
597
+ }
598
+ if (usable) {
599
+ for (const [document, writes] of groups) {
600
+ const attributeDocument = document as AttributeDocument;
601
+ const firstValue = writes[0]?.value;
602
+ if (attributeDocument.setAttribute && writes.every((write) => write.value === firstValue)) {
603
+ attributeDocument.setAttribute(writes.map((write) => write.id), name, firstValue ?? null);
604
+ } else {
605
+ operation(document, 'setAttrs', { writes });
606
+ }
607
+ }
608
+ return this;
609
+ }
610
+ }
611
+ return domEach(this, function (_i, el) {
612
+ if (!isTag(el)) return;
613
+ if (typeof name === 'object') {
614
+ for (const key of Object.keys(name)) setAttr(el, key, name[key]);
615
+ } else {
616
+ setAttr(el, name, value);
617
+ }
618
+ });
619
+ }
620
+
621
+ return getAttr(this[0], name);
622
+ },
623
+
624
+ prop(this: CheerioInstance, name?: any, value?: any) {
625
+ if (typeof name === 'string' && value === undefined) {
626
+ switch (name) {
627
+ case 'style': {
628
+ const property = this.css() as Record<string, unknown>;
629
+ let i = 0;
630
+ for (const p of Object.keys(property)) {
631
+ property[i++] = p;
632
+ }
633
+ property.length = i;
634
+ return property;
635
+ }
636
+ case 'tagName':
637
+ case 'nodeName':
638
+ return this[0].name!.toUpperCase();
639
+ default:
640
+ return getProp(this[0], name);
641
+ }
642
+ }
643
+
644
+ if (typeof name === 'object' || value !== undefined) {
645
+ if (typeof value === 'function') {
646
+ return domEach(this, function (i, el) {
647
+ setProp(el, name, value.call(el, i, getProp(el, name)));
648
+ });
649
+ }
650
+ return domEach(this, function (_i, el) {
651
+ if (!isTag(el)) return;
652
+ if (typeof name === 'object') {
653
+ for (const key of Object.keys(name)) setProp(el, key, name[key]);
654
+ } else {
655
+ setProp(el, name, value);
656
+ }
657
+ });
658
+ }
659
+ },
660
+
661
+ data(this: CheerioInstance, name?: any, value?: any) {
662
+ const elem = this[0] as LegacyNode;
663
+
664
+ if (!elem || !isTag(elem)) return;
665
+
666
+ // Return the entire data object if no data specified
667
+ if (!name) {
668
+ return readData(elem);
669
+ }
670
+
671
+ // Set the value (with attr map support)
672
+ if (typeof name === 'object' || value !== undefined) {
673
+ domEach(this, function (_i, el) {
674
+ const store = setDataStore(el);
675
+ if (typeof name === 'object') Object.assign(store, name);
676
+ else store[name] = value;
677
+ });
678
+ return this;
679
+ } else if (hasOwn.call(setDataStore(elem), name)) {
680
+ return setDataStore(elem)[name];
681
+ }
682
+
683
+ return readData(elem, name);
684
+ },
685
+
686
+ val(this: CheerioInstance, value?: any) {
687
+ const querying = arguments.length === 0;
688
+ const element = this[0] as LegacyNode;
689
+
690
+ if (!element) return;
691
+
692
+ switch (element.name) {
693
+ case 'textarea':
694
+ return this.text(value);
695
+ case 'input':
696
+ switch (this.attr('type')) {
697
+ case 'radio':
698
+ if (querying) {
699
+ return this.attr('value');
700
+ } else {
701
+ this.attr('value', value);
702
+ return this;
703
+ }
704
+ default:
705
+ return this.attr('value', value);
706
+ }
707
+ case 'select': {
708
+ const option = this.find('option:selected') as CheerioInstance | undefined;
709
+ let returnValue: unknown;
710
+ if (option === undefined) return undefined;
711
+ if (!querying) {
712
+ if (!(this.attr() as any).hasOwnProperty('multiple') && typeof value === 'object') {
713
+ return this;
714
+ }
715
+ if (typeof value !== 'object') {
716
+ value = [value];
717
+ }
718
+ this.find('option').removeAttr('selected');
719
+ for (let i = 0; i < value.length; i++) {
720
+ this.find(`option[value="${value[i]}"]`).attr('selected', '');
721
+ }
722
+ return this;
723
+ }
724
+ returnValue = option.attr('value');
725
+ if ((this.attr() as any).hasOwnProperty('multiple')) {
726
+ returnValue = [];
727
+ domEach(option, function (_i, el) {
728
+ (returnValue as unknown[]).push(getAttr(el, 'value'));
729
+ });
730
+ }
731
+ return returnValue;
732
+ }
733
+ case 'option':
734
+ if (!querying) {
735
+ this.attr('value', value);
736
+ return this;
737
+ }
738
+ return this.attr('value');
739
+ }
740
+ },
741
+
742
+ removeAttr(this: CheerioInstance, name: string) {
743
+ domEach(this, function (_i, elem) {
744
+ removeAttribute(elem, name);
745
+ });
746
+ return this;
747
+ },
748
+
749
+ hasClass(this: CheerioInstance, className: string): boolean {
750
+ for (let i = 0; i < this.length; i++) {
751
+ const elem = this[i];
752
+ const attrs = elem.attribs;
753
+ const clazz = attrs && attrs['class'];
754
+ let idx = -1;
755
+ let end: number;
756
+
757
+ if (clazz) {
758
+ while ((idx = clazz.indexOf(className, idx + 1)) > -1) {
759
+ end = idx + className.length;
760
+ if ((idx === 0 || rspace.test(clazz[idx - 1])) && (end === clazz.length || rspace.test(clazz[end]))) {
761
+ return true;
762
+ }
763
+ }
764
+ }
765
+ }
766
+ return false;
767
+ },
768
+
769
+ addClass(this: CheerioInstance, value?: any) {
770
+ // Support functions
771
+ if (typeof value === 'function') {
772
+ return domEach(this, function (i, el) {
773
+ const className = el.attribs!['class'] || '';
774
+ attributesApi.addClass.call([el] as unknown as CheerioInstance, value.call(el, i, className));
775
+ });
776
+ }
777
+
778
+ // Return if no value or not a string or function
779
+ if (!value || typeof value !== 'string') return this;
780
+
781
+ const numElements = this.length;
782
+ if (numElements === 1 && isTag(this[0]) && !hasMaterializedAttributes(this[0])) {
783
+ const binding = bindingOf(this[0]);
784
+ const document = binding?.document as AttributeDocument | undefined;
785
+ if (binding && document?.addClass) {
786
+ document.addClass([binding.id], value);
787
+ return this;
788
+ }
789
+ }
790
+ const groups = new Map<AttributeDocument, number[]>();
791
+ let native = true;
792
+ for (let i = 0; i < numElements; i++) {
793
+ if (!isTag(this[i])) continue;
794
+ const binding = bindingOf(this[i]);
795
+ const document = binding?.document as AttributeDocument | undefined;
796
+ if (!binding || !document?.addClass || hasMaterializedAttributes(this[i])) { native = false; break; }
797
+ const ids = groups.get(document);
798
+ if (ids) ids.push(binding.id);
799
+ else groups.set(document, [binding.id]);
800
+ }
801
+ if (native) {
802
+ for (const [document, ids] of groups) document.addClass!(ids, value);
803
+ return this;
804
+ }
805
+
806
+ const classNames = value.split(rspace);
807
+ for (let i = 0; i < numElements; i++) {
808
+ // If selected element isn't a tag, move on
809
+ if (!isTag(this[i])) continue;
810
+
811
+ // If we don't already have classes
812
+ const className = getAttr(this[i], 'class') as string | undefined;
813
+
814
+ if (!className) {
815
+ setAttr(this[i], 'class', classNames.join(' ').trim());
816
+ } else {
817
+ let setClass = ` ${className} `;
818
+ const numClasses = classNames.length;
819
+
820
+ // Check if class already exists
821
+ for (let j = 0; j < numClasses; j++) {
822
+ const appendClass = `${classNames[j]} `;
823
+ if (setClass.indexOf(` ${appendClass}`) < 0) setClass += appendClass;
824
+ }
825
+
826
+ setAttr(this[i], 'class', setClass.trim());
827
+ }
828
+ }
829
+
830
+ return this;
831
+ },
832
+
833
+ removeClass(this: CheerioInstance, value?: any) {
834
+ // Handle if value is a function
835
+ if (typeof value === 'function') {
836
+ return domEach(this, function (i, el) {
837
+ attributesApi.removeClass.call([el] as unknown as CheerioInstance, value.call(el, i, el.attribs!['class'] || ''));
838
+ });
839
+ }
840
+
841
+ const classes = splitClass(value);
842
+ const numClasses = classes.length;
843
+ const removeAll = arguments.length === 0;
844
+
845
+ return domEach(this, function (_i, el) {
846
+ if (!isTag(el)) return;
847
+
848
+ if (removeAll) {
849
+ // Short circuit the remove all case as this is the nice one
850
+ el.attribs!.class = '';
851
+ } else {
852
+ const elClasses = splitClass(el.attribs!.class);
853
+ let changed: boolean | undefined;
854
+
855
+ for (let j = 0; j < numClasses; j++) {
856
+ const index = elClasses.indexOf(classes[j]);
857
+
858
+ if (index >= 0) {
859
+ elClasses.splice(index, 1);
860
+ changed = true;
861
+
862
+ // We have to do another pass to ensure that there are not duplicate
863
+ // classes listed
864
+ j--;
865
+ }
866
+ }
867
+ if (changed) {
868
+ el.attribs!.class = elClasses.join(' ');
869
+ }
870
+ }
871
+ });
872
+ },
873
+
874
+ toggleClass(this: CheerioInstance, value?: any, stateVal?: boolean) {
875
+ // Support functions
876
+ if (typeof value === 'function') {
877
+ return domEach(this, function (i, el) {
878
+ attributesApi.toggleClass.call([el] as unknown as CheerioInstance, value.call(el, i, el.attribs!['class'] || '', stateVal), stateVal);
879
+ });
880
+ }
881
+
882
+ // Return if no value or not a string or function
883
+ if (!value || typeof value !== 'string') return this;
884
+
885
+ const classNames = value.split(rspace);
886
+ const numClasses = classNames.length;
887
+ const state = typeof stateVal === 'boolean' ? (stateVal ? 1 : -1) : 0;
888
+ const numElements = this.length;
889
+
890
+ for (let i = 0; i < numElements; i++) {
891
+ // If selected element isn't a tag, move on
892
+ if (!isTag(this[i])) continue;
893
+
894
+ const elementClasses = splitClass(this[i].attribs!.class);
895
+
896
+ // Check if class already exists
897
+ for (let j = 0; j < numClasses; j++) {
898
+ // Check if the class name is currently defined
899
+ const index = elementClasses.indexOf(classNames[j]);
900
+
901
+ // Add if stateValue === true or we are toggling and there is no value
902
+ if (state >= 0 && index < 0) {
903
+ elementClasses.push(classNames[j]);
904
+ } else if (state <= 0 && index >= 0) {
905
+ // Otherwise remove but only if the item exists
906
+ elementClasses.splice(index, 1);
907
+ }
908
+ }
909
+
910
+ this[i].attribs!.class = elementClasses.join(' ');
911
+ }
912
+
913
+ return this;
914
+ },
915
+
916
+ is(this: CheerioInstance, selector?: any): boolean {
917
+ if (selector) {
918
+ return (traversingApi.filter as any).call(this, selector).length > 0;
919
+ }
920
+ return false;
921
+ },
922
+ };
923
+
924
+ /*
925
+ * api/traversing.js
926
+ */
927
+
928
+ const traversingApi: CheerioPrototype = {
929
+ find(this: CheerioInstance, selectorOrHaystack?: any) {
930
+ const self = this;
931
+ if (selectorOrHaystack && typeof selectorOrHaystack !== 'string') {
932
+ const haystack: LegacyNode[] = selectorOrHaystack.cheerio ? selectorOrHaystack.get() : [selectorOrHaystack];
933
+ const contains = (self.constructor as any).contains;
934
+ return this._make(haystack.filter(function (elem: LegacyNode) {
935
+ for (let idx = 0, len = self.length; idx < len; ++idx) {
936
+ if (contains(self[idx], elem)) return true;
937
+ }
938
+ return false;
939
+ }));
940
+ }
941
+
942
+ // The native within-select covers the 0.22.0 candidate set (every
943
+ // descendant of the matched elements) in one call, at any document size.
944
+ const binding = bindingOf(this[0]);
945
+ const document = binding?.document;
946
+ if (document && selectorOrHaystack) {
947
+ const contexts = this.length === 1 && binding ? [binding.id] : idsOf(document, this.toArray());
948
+ if (contexts.length) {
949
+ try {
950
+ const simpleTag = simpleTagExpr.exec(selectorOrHaystack);
951
+ if (!simpleTag) validateLegacySelector(selectorOrHaystack);
952
+ const finalTag = simpleTag ?? finalTagExpr.exec(selectorOrHaystack);
953
+ const knownType = finalTag && !specialTagExpr.test(finalTag[1]) ? 'tag' : undefined;
954
+ const found = document.select(selectorOrHaystack, contexts);
955
+ if (found) return this._make(asNodes(document, found, knownType) as LegacyNode[]);
956
+ } catch (error) {
957
+ throw error instanceof SyntaxError ? error : new SyntaxError((error as Error)?.message ?? String(error));
958
+ }
959
+ }
960
+ }
961
+
962
+ const elems: LegacyNode[] = [];
963
+ for (let i = 0; i < this.length; i++) {
964
+ for (const child of this[i].children ?? []) if (isTag(child)) elems.push(child);
965
+ }
966
+
967
+ const options = { ...this.options, context: this.toArray() } as LegacyOptions;
968
+ return this._make(scopedSelect(selectorOrHaystack, elems, options));
969
+ },
970
+
971
+ parent(this: CheerioInstance, selector?: any) {
972
+ const set: LegacyNode[] = [];
973
+
974
+ domEach(this, function (_idx, elem) {
975
+ const parentElem = elem.parent;
976
+ if (parentElem && set.indexOf(parentElem) < 0) {
977
+ set.push(parentElem);
978
+ }
979
+ });
980
+
981
+ const filtered = arguments.length ? (traversingApi.filter as any).call(set as unknown as CheerioInstance, selector, this) : set;
982
+ return this._make(filtered as LegacyNode[]);
983
+ },
984
+
985
+ parents(this: CheerioInstance, selector?: any) {
986
+ const parentNodes: LegacyNode[] = [];
987
+
988
+ // When multiple DOM elements are in the original set, the resulting set
989
+ // will be in *reverse* order of the original elements as well, with
990
+ // duplicates removed.
991
+ this.get().reverse().forEach(function (this: CheerioInstance, elem: LegacyNode) {
992
+ traverseParents(this, elem.parent, selector, Infinity).forEach((node) => {
993
+ if (parentNodes.indexOf(node) === -1) {
994
+ parentNodes.push(node);
995
+ }
996
+ });
997
+ }, this);
998
+
999
+ return this._make(parentNodes);
1000
+ },
1001
+
1002
+ parentsUntil(this: CheerioInstance, selector?: any, filter?: any) {
1003
+ const parentNodes: LegacyNode[] = [];
1004
+ let untilNode: LegacyNode | undefined;
1005
+ let untilNodes: LegacyNode[] | undefined;
1006
+
1007
+ if (typeof selector === 'string') {
1008
+ untilNode = scopedSelect(selector, this.parents().toArray() as LegacyNode[], this.options)[0];
1009
+ } else if (selector && selector.cheerio) {
1010
+ untilNodes = selector.toArray();
1011
+ } else if (selector) {
1012
+ untilNode = selector;
1013
+ }
1014
+
1015
+ this.toArray().reverse().forEach(function (elem: LegacyNode) {
1016
+ while ((elem = elem.parent as LegacyNode)) {
1017
+ if ((untilNode && elem !== untilNode) ||
1018
+ (untilNodes && untilNodes.indexOf(elem) === -1) ||
1019
+ (!untilNode && !untilNodes)) {
1020
+ if (isTag(elem) && parentNodes.indexOf(elem) === -1) parentNodes.push(elem);
1021
+ } else {
1022
+ break;
1023
+ }
1024
+ }
1025
+ });
1026
+
1027
+ return this._make((filter ? scopedSelect(filter, parentNodes, this.options) : parentNodes) as LegacyNode[]);
1028
+ },
1029
+
1030
+ closest(this: CheerioInstance, selector?: any) {
1031
+ const set: LegacyNode[] = [];
1032
+
1033
+ if (!selector) {
1034
+ return this._make(set);
1035
+ }
1036
+
1037
+ domEach(this, function (this: CheerioInstance, _idx, elem) {
1038
+ const closestElem = traverseParents(this, elem, selector, 1)[0];
1039
+
1040
+ // Do not add duplicate elements to the set
1041
+ if (closestElem && set.indexOf(closestElem) < 0) {
1042
+ set.push(closestElem);
1043
+ }
1044
+ });
1045
+
1046
+ return this._make(set);
1047
+ },
1048
+
1049
+ next(this: CheerioInstance, selector?: any) {
1050
+ if (!this[0]) return this;
1051
+ const elems: LegacyNode[] = [];
1052
+
1053
+ for (let i = 0; i < this.length; i++) {
1054
+ let elem: LegacyNode = this[i];
1055
+ while ((elem = elem.next as LegacyNode)) {
1056
+ if (isTag(elem)) {
1057
+ elems.push(elem);
1058
+ break;
1059
+ }
1060
+ }
1061
+ }
1062
+
1063
+ return selector ? (traversingApi.filter as any).call(elems as unknown as CheerioInstance, selector, this) : this._make(elems);
1064
+ },
1065
+
1066
+ nextAll(this: CheerioInstance, selector?: any) {
1067
+ if (!this[0]) return this;
1068
+ const elems: LegacyNode[] = [];
1069
+
1070
+ for (let i = 0; i < this.length; i++) {
1071
+ let elem: LegacyNode = this[i];
1072
+ while ((elem = elem.next as LegacyNode)) {
1073
+ if (isTag(elem) && elems.indexOf(elem) === -1) {
1074
+ elems.push(elem);
1075
+ }
1076
+ }
1077
+ }
1078
+
1079
+ return selector ? (traversingApi.filter as any).call(elems as unknown as CheerioInstance, selector, this) : this._make(elems);
1080
+ },
1081
+
1082
+ nextUntil(this: CheerioInstance, selector?: any, filterSelector?: any) {
1083
+ if (!this[0]) return this;
1084
+ const elems: LegacyNode[] = [];
1085
+ let untilNode: LegacyNode | undefined;
1086
+ let untilNodes: LegacyNode[] | undefined;
1087
+
1088
+ if (typeof selector === 'string') {
1089
+ untilNode = scopedSelect(selector, this.nextAll().get() as LegacyNode[], this.options)[0];
1090
+ } else if (selector && selector.cheerio) {
1091
+ untilNodes = selector.get();
1092
+ } else if (selector) {
1093
+ untilNode = selector;
1094
+ }
1095
+
1096
+ for (let i = 0; i < this.length; i++) {
1097
+ let elem: LegacyNode = this[i];
1098
+ while ((elem = elem.next as LegacyNode)) {
1099
+ if ((untilNode && elem !== untilNode) ||
1100
+ (untilNodes && untilNodes.indexOf(elem) === -1) ||
1101
+ (!untilNode && !untilNodes)) {
1102
+ if (isTag(elem) && elems.indexOf(elem) === -1) {
1103
+ elems.push(elem);
1104
+ }
1105
+ } else {
1106
+ break;
1107
+ }
1108
+ }
1109
+ }
1110
+
1111
+ return filterSelector ? (traversingApi.filter as any).call(elems as unknown as CheerioInstance, filterSelector, this) : this._make(elems);
1112
+ },
1113
+
1114
+ prev(this: CheerioInstance, selector?: any) {
1115
+ if (!this[0]) return this;
1116
+ const elems: LegacyNode[] = [];
1117
+
1118
+ for (let i = 0; i < this.length; i++) {
1119
+ let elem: LegacyNode = this[i];
1120
+ while ((elem = elem.prev as LegacyNode)) {
1121
+ if (isTag(elem)) {
1122
+ elems.push(elem);
1123
+ break;
1124
+ }
1125
+ }
1126
+ }
1127
+
1128
+ return selector ? (traversingApi.filter as any).call(elems as unknown as CheerioInstance, selector, this) : this._make(elems);
1129
+ },
1130
+
1131
+ prevAll(this: CheerioInstance, selector?: any) {
1132
+ if (!this[0]) return this;
1133
+ const elems: LegacyNode[] = [];
1134
+
1135
+ for (let i = 0; i < this.length; i++) {
1136
+ let elem: LegacyNode = this[i];
1137
+ while ((elem = elem.prev as LegacyNode)) {
1138
+ if (isTag(elem) && elems.indexOf(elem) === -1) {
1139
+ elems.push(elem);
1140
+ }
1141
+ }
1142
+ }
1143
+
1144
+ return selector ? (traversingApi.filter as any).call(elems as unknown as CheerioInstance, selector, this) : this._make(elems);
1145
+ },
1146
+
1147
+ prevUntil(this: CheerioInstance, selector?: any, filterSelector?: any) {
1148
+ if (!this[0]) return this;
1149
+ const elems: LegacyNode[] = [];
1150
+ let untilNode: LegacyNode | undefined;
1151
+ let untilNodes: LegacyNode[] | undefined;
1152
+
1153
+ if (typeof selector === 'string') {
1154
+ untilNode = scopedSelect(selector, this.prevAll().get() as LegacyNode[], this.options)[0];
1155
+ } else if (selector && selector.cheerio) {
1156
+ untilNodes = selector.get();
1157
+ } else if (selector) {
1158
+ untilNode = selector;
1159
+ }
1160
+
1161
+ for (let i = 0; i < this.length; i++) {
1162
+ let elem: LegacyNode = this[i];
1163
+ while ((elem = elem.prev as LegacyNode)) {
1164
+ if ((untilNode && elem !== untilNode) ||
1165
+ (untilNodes && untilNodes.indexOf(elem) === -1) ||
1166
+ (!untilNode && !untilNodes)) {
1167
+ if (isTag(elem) && elems.indexOf(elem) === -1) {
1168
+ elems.push(elem);
1169
+ }
1170
+ } else {
1171
+ break;
1172
+ }
1173
+ }
1174
+ }
1175
+
1176
+ return filterSelector ? (traversingApi.filter as any).call(elems as unknown as CheerioInstance, filterSelector, this) : this._make(elems);
1177
+ },
1178
+
1179
+ siblingsAndMe(this: CheerioInstance) {
1180
+ const elems: LegacyNode[] = [];
1181
+ const parent = this[0] ? this[0].parent || this[0].root : undefined;
1182
+ if (parent) for (const sibling of parent.children ?? []) elems.push(sibling);
1183
+ return this._make(elems);
1184
+ },
1185
+
1186
+ siblings(this: CheerioInstance, selector?: any) {
1187
+ const parent = this.parent() as CheerioInstance;
1188
+
1189
+ const source = parent.length ? parent.children() : this.siblingsAndMe();
1190
+ const elems: LegacyNode[] = (source as CheerioInstance).toArray().filter((elem: LegacyNode) => isTag(elem) && !this.is(elem));
1191
+
1192
+ if (selector !== undefined) {
1193
+ return (traversingApi.filter as any).call(elems as unknown as CheerioInstance, selector, this);
1194
+ } else {
1195
+ return this._make(elems);
1196
+ }
1197
+ },
1198
+
1199
+ children(this: CheerioInstance, selector?: any) {
1200
+ const elems: LegacyNode[] = [];
1201
+ for (let i = 0; i < this.length; i++) {
1202
+ for (const child of this[i].children ?? []) if (isTag(child)) elems.push(child);
1203
+ }
1204
+
1205
+ if (selector === undefined) return this._make(elems);
1206
+
1207
+ return (traversingApi.filter as any).call(elems as unknown as CheerioInstance, selector, this);
1208
+ },
1209
+
1210
+ contents(this: CheerioInstance) {
1211
+ const all: LegacyNode[] = [];
1212
+ for (let i = 0; i < this.length; i++) {
1213
+ all.push(...(this[i].children ?? []));
1214
+ }
1215
+ return this._make(all);
1216
+ },
1217
+
1218
+ each(this: CheerioInstance, fn: (this: LegacyNode, i: number, el: LegacyNode) => unknown) {
1219
+ let i = 0;
1220
+ const len = this.length;
1221
+ while (i < len && fn.call(this[i], i, this[i]) !== false) ++i;
1222
+ return this;
1223
+ },
1224
+
1225
+ map(this: CheerioInstance, fn: (this: LegacyNode, i: number, el: LegacyNode) => any) {
1226
+ const memo: unknown[] = [];
1227
+ for (let i = 0; i < this.length; i++) {
1228
+ const el = this[i];
1229
+ const val = fn.call(el, i, el);
1230
+ if (val != null) {
1231
+ if (Array.isArray(val)) memo.push(...val);
1232
+ else memo.push(val);
1233
+ }
1234
+ }
1235
+ return this._make(memo as LegacyNode[]);
1236
+ },
1237
+
1238
+ filter(this: CheerioInstance, match?: any, container?: CheerioInstance) {
1239
+ return makeFilterMethod((list, testFn) => list.filter((el, i) => testFn(el, i))).call(this, match, container);
1240
+ },
1241
+
1242
+ not(this: CheerioInstance, match?: any, container?: CheerioInstance) {
1243
+ return makeFilterMethod((list, testFn) => list.filter((el, i) => !testFn(el, i))).call(this, match, container);
1244
+ },
1245
+
1246
+ has(this: CheerioInstance, selectorOrHaystack?: any) {
1247
+ const that = this;
1248
+ return traversingApi.filter.call(this, function (this: LegacyNode) {
1249
+ return that._make(this).find(selectorOrHaystack).length > 0;
1250
+ }) as CheerioInstance;
1251
+ },
1252
+
1253
+ first(this: CheerioInstance) {
1254
+ return this.length > 1 ? this._make(this[0]) : this;
1255
+ },
1256
+
1257
+ last(this: CheerioInstance) {
1258
+ return this.length > 1 ? this._make(this[this.length - 1]) : this;
1259
+ },
1260
+
1261
+ eq(this: CheerioInstance, i: number) {
1262
+ i = +i;
1263
+
1264
+ // Use the first identity optimization if possible
1265
+ if (i === 0 && this.length <= 1) return this;
1266
+
1267
+ if (i < 0) i = this.length + i;
1268
+ return this[i] ? this._make(this[i]) : this._make([]);
1269
+ },
1270
+
1271
+ get(this: CheerioInstance, i?: number) {
1272
+ if (i == null) {
1273
+ return Array.prototype.slice.call(this);
1274
+ } else {
1275
+ return this[i < 0 ? this.length + i : i];
1276
+ }
1277
+ },
1278
+
1279
+ index(this: CheerioInstance, selectorOrNeedle?: any) {
1280
+ let $haystack: CheerioInstance, needle: unknown;
1281
+
1282
+ if (arguments.length === 0) {
1283
+ $haystack = this.parent().children() as CheerioInstance;
1284
+ needle = this[0];
1285
+ } else if (typeof selectorOrNeedle === 'string') {
1286
+ $haystack = this._make(selectorOrNeedle);
1287
+ needle = this[0];
1288
+ } else {
1289
+ $haystack = this;
1290
+ needle = selectorOrNeedle.cheerio ? selectorOrNeedle[0] : selectorOrNeedle;
1291
+ }
1292
+
1293
+ return ($haystack.get() as unknown[]).indexOf(needle);
1294
+ },
1295
+
1296
+ slice(this: CheerioInstance, ...args: any[]) {
1297
+ return this._make((Array.prototype.slice as any).apply(this, args));
1298
+ },
1299
+
1300
+ end(this: CheerioInstance) {
1301
+ return this.prevObject || this._make([]);
1302
+ },
1303
+
1304
+ add(this: CheerioInstance, other?: any, context?: any) {
1305
+ const selection = this._make(other, context);
1306
+ const merged = uniqueSort(selection.get().concat(this.get()));
1307
+ for (let i = 0; i < merged.length; ++i) {
1308
+ selection[i] = merged[i];
1309
+ }
1310
+ selection.length = merged.length;
1311
+ return selection;
1312
+ },
1313
+
1314
+ addBack(this: CheerioInstance, selector?: any) {
1315
+ return this.add(arguments.length ? this.prevObject!.filter(selector) : this.prevObject);
1316
+ },
1317
+ };
1318
+
1319
+ function makeFilterMethod(filterFn: (list: LegacyNode[], testFn: (el: LegacyNode, i: number) => boolean) => LegacyNode[]) {
1320
+ return function (this: CheerioInstance | ArrayLike<LegacyNode>, match: any, container?: CheerioInstance) {
1321
+ let testFn: (el: LegacyNode, i: number) => boolean;
1322
+ const self = this as CheerioInstance;
1323
+ const list: LegacyNode[] = typeof (this as CheerioInstance).toArray === 'function'
1324
+ ? (this as CheerioInstance).toArray()
1325
+ : Array.from(this as ArrayLike<LegacyNode>);
1326
+ container = container || (typeof (this as CheerioInstance)._make === 'function' ? self : undefined);
1327
+
1328
+ if (typeof match === 'string') {
1329
+ const binding = bindingOf(list[0] ?? (container as CheerioInstance | undefined)?.[0]);
1330
+ let compiled: Set<number> | undefined;
1331
+ testFn = (el: LegacyNode) => {
1332
+ if (!binding) return false;
1333
+ if (!compiled) {
1334
+ const ids = idsOf(binding.document, list);
1335
+ compiled = new Set(matchesSelector(binding.document, ids, match, { xmlMode: container?.options?.xmlMode } as LegacyOptions));
1336
+ }
1337
+ const id = viewId(el);
1338
+ return id !== undefined && compiled.has(id);
1339
+ };
1340
+ } else if (typeof match === 'function') {
1341
+ testFn = (el: LegacyNode, i: number) => !!match.call(el, i, el);
1342
+ } else if (match.cheerio) {
1343
+ testFn = (el: LegacyNode) => match.toArray().includes(el);
1344
+ } else {
1345
+ testFn = (el: LegacyNode) => match === el;
1346
+ }
1347
+
1348
+ if (!container) {
1349
+ // 0.22.0 would call `container._make` on the plain list and crash; be
1350
+ // more robust and wrap through the module constructor instead.
1351
+ const constructor = ((this as any).constructor && (this as any).constructor.prototype?._make ? (this as any).constructor : moduleCheerio) as CheerioConstructor;
1352
+ return new constructor(filterFn(list, testFn)) as CheerioInstance;
1353
+ }
1354
+
1355
+ return container._make(filterFn(list, testFn));
1356
+ };
1357
+ }
1358
+
1359
+ function traverseParents(self: CheerioInstance, elem: LegacyNode | null | undefined, selector: any, limit: number): LegacyNode[] {
1360
+ const elems: LegacyNode[] = [];
1361
+ while (elem && elems.length < limit) {
1362
+ if (!selector || (traversingApi.filter as any).call([elem] as unknown as CheerioInstance, selector, self).length) {
1363
+ elems.push(elem);
1364
+ }
1365
+ elem = elem.parent;
1366
+ }
1367
+ return elems;
1368
+ }
1369
+
1370
+ function insertAdjacentStatic(this: CheerioInstance, elems: any[], position: 'before' | 'after'): boolean {
1371
+ if (elems.length !== 1 || typeof elems[0] !== 'string') return false;
1372
+ const options = legacyOptions(this.options);
1373
+ if (options.normalizeWhitespace || hasParserHooks(options)) return false;
1374
+
1375
+ let document: NativeDocument | undefined;
1376
+ const targetIds: number[] = [];
1377
+ for (let i = 0; i < this.length; i++) {
1378
+ const el = this[i];
1379
+ if (!isTag(el)) return false;
1380
+ const binding = bindingOf(el);
1381
+ if (!binding || (document && binding.document !== document)) return false;
1382
+ document ??= binding.document;
1383
+ const parent = el.parent || el.root;
1384
+ if (!parent || bindingOf(parent)?.document !== document || hasMaterializedChildren(parent)) return false;
1385
+ targetIds.push(binding.id);
1386
+ }
1387
+ if (!document) return false;
1388
+
1389
+ const fused = (document as AttributeDocument).insertHtml?.(targetIds, elems[0], position);
1390
+ if (fused) {
1391
+ for (let i = 0; i < fused.length; i++) setRootIfCached(document, fused[i], null);
1392
+ return true;
1393
+ }
1394
+
1395
+ const nodeIds = operation<number[]>(document, 'create', { html: elems[0], options });
1396
+ if (!nodeIds.length) return true;
1397
+ const inserted = operation<number[]>(document, 'insert', { targetIds, nodeIds, position });
1398
+ for (let i = 0; i < inserted.length; i++) setRootIfCached(document, inserted[i], null);
1399
+ return true;
1400
+ }
1401
+
1402
+ function removeNative(elems: CheerioInstance): boolean {
1403
+ const groups = new Map<NativeDocument, { ids: number[]; nodes: LegacyNode[] }>();
1404
+ for (let i = 0; i < elems.length; i++) {
1405
+ const el = elems[i];
1406
+ const binding = bindingOf(el);
1407
+ if (!binding) return false;
1408
+ const parent = el.parent || el.root;
1409
+ if (!parent) continue;
1410
+ if (bindingOf(parent)?.document !== binding.document || hasMaterializedChildren(parent)) return false;
1411
+ let group = groups.get(binding.document);
1412
+ if (!group) groups.set(binding.document, group = { ids: [], nodes: [] });
1413
+ group.ids.push(binding.id);
1414
+ group.nodes.push(el);
1415
+ }
1416
+ for (const [document, group] of groups) {
1417
+ const nativeDocument = document as AttributeDocument;
1418
+ if (nativeDocument.remove) nativeDocument.remove(group.ids);
1419
+ else operation(document, 'remove', { ids: group.ids });
1420
+ for (const node of group.nodes) node.root = null;
1421
+ }
1422
+ return true;
1423
+ }
1424
+
1425
+ /*
1426
+ * api/manipulation.js
1427
+ */
1428
+
1429
+ const manipulationApi: CheerioPrototype = {
1430
+ _makeDomArray(this: CheerioInstance, elem: any, clone?: boolean): LegacyNode[] {
1431
+ if (elem == null) {
1432
+ return [];
1433
+ } else if (elem.cheerio) {
1434
+ return clone ? cloneDom(elem.get(), elem.options) : elem.get();
1435
+ } else if (Array.isArray(elem)) {
1436
+ return elem.reduce<LegacyNode[]>((memo, el) => memo.concat(this._makeDomArray(el, clone)), []);
1437
+ } else if (typeof elem === 'string') {
1438
+ return evaluate(elem, this.options);
1439
+ } else {
1440
+ return clone ? cloneDom([elem], this.options) : [elem];
1441
+ }
1442
+ },
1443
+
1444
+ appendTo(this: CheerioInstance, target: any) {
1445
+ if (!target.cheerio) {
1446
+ target = (this.constructor as CheerioConstructor).call(this.constructor, target, null, this._originalRoot);
1447
+ }
1448
+ target.append(this);
1449
+ return this;
1450
+ },
1451
+
1452
+ prependTo(this: CheerioInstance, target: any) {
1453
+ if (!target.cheerio) {
1454
+ target = (this.constructor as CheerioConstructor).call(this.constructor, target, null, this._originalRoot);
1455
+ }
1456
+ target.prepend(this);
1457
+ return this;
1458
+ },
1459
+
1460
+ append(this: CheerioInstance, ...elems: any[]) {
1461
+ return insert.call(this, (dom: LegacyNode[], children: LegacyNode[], parent: LegacyNode) => {
1462
+ uniqueSplice(children, children.length, 0, dom, parent);
1463
+ }, elems);
1464
+ },
1465
+
1466
+ prepend(this: CheerioInstance, ...elems: any[]) {
1467
+ return insert.call(this, (dom: LegacyNode[], children: LegacyNode[], parent: LegacyNode) => {
1468
+ uniqueSplice(children, 0, 0, dom, parent);
1469
+ }, elems);
1470
+ },
1471
+
1472
+ wrap(this: CheerioInstance, wrapper: any) {
1473
+ const wrapperFn = typeof wrapper === 'function' && wrapper;
1474
+ const lastIdx = this.length - 1;
1475
+
1476
+ for (let i = 0; i < this.length; i++) {
1477
+ const el = this[i];
1478
+ const parent = el.parent || el.root;
1479
+
1480
+ if (!parent) {
1481
+ continue;
1482
+ }
1483
+ const siblings = Array.from(parent.children ?? []);
1484
+
1485
+ let currentWrapper = wrapper;
1486
+ if (wrapperFn) {
1487
+ currentWrapper = wrapperFn.call(el, i);
1488
+ }
1489
+
1490
+ if (typeof currentWrapper === 'string' && !isHtml(currentWrapper)) {
1491
+ currentWrapper = this.parents().last().find(currentWrapper).clone();
1492
+ }
1493
+
1494
+ const dom = this._makeDomArray(currentWrapper, i < lastIdx).slice(0, 1);
1495
+ const index = siblings.indexOf(el);
1496
+
1497
+ update([el], dom[0]);
1498
+ // The previous operation removed the current element from the
1499
+ // `siblings` list, so the `dom` array can be inserted without
1500
+ // removing any additional elements.
1501
+ siblings.splice(siblings.indexOf(el), 1);
1502
+ uniqueSplice(siblings, index, 0, dom, parent);
1503
+ }
1504
+
1505
+ return this;
1506
+ },
1507
+
1508
+ after(this: CheerioInstance, ...elems: any[]) {
1509
+ if (insertAdjacentStatic.call(this, elems, 'after')) return this;
1510
+ const lastIdx = this.length - 1;
1511
+
1512
+ domEach(this, function (this: CheerioInstance, i, el) {
1513
+ const parent = el.parent || el.root;
1514
+ if (!parent) {
1515
+ return;
1516
+ }
1517
+
1518
+ const siblings = Array.from(parent.children ?? []);
1519
+ const index = siblings.indexOf(el);
1520
+ let domSrc: any;
1521
+ let dom: LegacyNode[];
1522
+
1523
+ // If not found, move on
1524
+ if (index < 0) return;
1525
+
1526
+ if (typeof elems[0] === 'function') {
1527
+ domSrc = elems[0].call(el, i, staticHtml.call(this, el.children));
1528
+ } else {
1529
+ domSrc = elems;
1530
+ }
1531
+ dom = this._makeDomArray(domSrc, i < lastIdx);
1532
+
1533
+ // Add element after `this` element
1534
+ uniqueSplice(siblings, index + 1, 0, dom, parent);
1535
+ });
1536
+
1537
+ return this;
1538
+ },
1539
+
1540
+ insertAfter(this: CheerioInstance, target: any) {
1541
+ const self = this;
1542
+ if (typeof target === 'string') {
1543
+ target = (this.constructor as CheerioConstructor).call(this.constructor, target, null, this._originalRoot);
1544
+ }
1545
+ const targetNodes = this._makeDomArray(target);
1546
+ self.remove();
1547
+ const clones: LegacyNode[][] = [];
1548
+ domEach(targetNodes as unknown as { length: number; [index: number]: LegacyNode }, function (this: CheerioInstance, _i, el) {
1549
+ const clonedSelf = self._makeDomArray(self.clone());
1550
+ const parent = el.parent || el.root;
1551
+ if (!parent) {
1552
+ return;
1553
+ }
1554
+
1555
+ const siblings = Array.from(parent.children ?? []);
1556
+ const index = siblings.indexOf(el);
1557
+
1558
+ // If not found, move on
1559
+ if (index < 0) return;
1560
+
1561
+ // Add cloned `this` element(s) after target element
1562
+ uniqueSplice(siblings, index + 1, 0, clonedSelf, parent);
1563
+ clones.push(clonedSelf);
1564
+ });
1565
+ return (this.constructor as CheerioConstructor).call(this.constructor, this._makeDomArray(clones as any)) as CheerioInstance;
1566
+ },
1567
+
1568
+ before(this: CheerioInstance, ...elems: any[]) {
1569
+ if (insertAdjacentStatic.call(this, elems, 'before')) return this;
1570
+ const lastIdx = this.length - 1;
1571
+
1572
+ domEach(this, function (this: CheerioInstance, i, el) {
1573
+ const parent = el.parent || el.root;
1574
+ if (!parent) {
1575
+ return;
1576
+ }
1577
+
1578
+ const siblings = Array.from(parent.children ?? []);
1579
+ const index = siblings.indexOf(el);
1580
+ let domSrc: any;
1581
+ let dom: LegacyNode[];
1582
+
1583
+ // If not found, move on
1584
+ if (index < 0) return;
1585
+
1586
+ if (typeof elems[0] === 'function') {
1587
+ domSrc = elems[0].call(el, i, staticHtml.call(this, el.children));
1588
+ } else {
1589
+ domSrc = elems;
1590
+ }
1591
+
1592
+ dom = this._makeDomArray(domSrc, i < lastIdx);
1593
+
1594
+ // Add element before `el` element
1595
+ uniqueSplice(siblings, index, 0, dom, parent);
1596
+ });
1597
+
1598
+ return this;
1599
+ },
1600
+
1601
+ insertBefore(this: CheerioInstance, target: any) {
1602
+ const self = this;
1603
+ if (typeof target === 'string') {
1604
+ target = (this.constructor as CheerioConstructor).call(this.constructor, target, null, this._originalRoot);
1605
+ }
1606
+ const targetNodes = this._makeDomArray(target);
1607
+ self.remove();
1608
+ const clones: LegacyNode[][] = [];
1609
+ domEach(targetNodes as unknown as { length: number; [index: number]: LegacyNode }, function (this: CheerioInstance, _i, el) {
1610
+ const clonedSelf = self._makeDomArray(self.clone());
1611
+ const parent = el.parent || el.root;
1612
+ if (!parent) {
1613
+ return;
1614
+ }
1615
+
1616
+ const siblings = Array.from(parent.children ?? []);
1617
+ const index = siblings.indexOf(el);
1618
+
1619
+ // If not found, move on
1620
+ if (index < 0) return;
1621
+
1622
+ // Add cloned `this` element(s) after target element
1623
+ uniqueSplice(siblings, index, 0, clonedSelf, parent);
1624
+ clones.push(clonedSelf);
1625
+ });
1626
+ return (this.constructor as CheerioConstructor).call(this.constructor, this._makeDomArray(clones as any)) as CheerioInstance;
1627
+ },
1628
+
1629
+ remove(this: CheerioInstance, selector?: any) {
1630
+ const elems: CheerioInstance = selector ? this.filter(selector) : this;
1631
+ if (removeNative(elems)) return this;
1632
+
1633
+ domEach(elems, function (_i, el) {
1634
+ const parent = el.parent || el.root;
1635
+ if (!parent) {
1636
+ return;
1637
+ }
1638
+
1639
+ const siblings = Array.from(parent.children ?? []);
1640
+ const index = siblings.indexOf(el);
1641
+
1642
+ if (index < 0) return;
1643
+
1644
+ writeChildren(parent, siblings.filter((item, at) => at !== index));
1645
+ // The rebuild above cleared the arena links; drop the legacy root ref.
1646
+ el.root = null;
1647
+ });
1648
+
1649
+ return this;
1650
+ },
1651
+
1652
+ replaceWith(this: CheerioInstance, content: any) {
1653
+ const self = this;
1654
+
1655
+ domEach(this, function (this: CheerioInstance, i, el) {
1656
+ const parent = el.parent || el.root;
1657
+ if (!parent) {
1658
+ return;
1659
+ }
1660
+
1661
+ const siblings = Array.from(parent.children ?? []);
1662
+ const dom = self._makeDomArray(typeof content === 'function' ? content.call(el, i, el) : content);
1663
+ const index = siblings.indexOf(el);
1664
+
1665
+ // In the case that `dom` contains nodes that already exist in other
1666
+ // structures, ensure those nodes are properly removed.
1667
+ for (const node of dom) update(node, null);
1668
+
1669
+ // Completely remove old element
1670
+ uniqueSplice(siblings, index, 1, dom, parent);
1671
+ el.root = null;
1672
+ });
1673
+
1674
+ return this;
1675
+ },
1676
+
1677
+ empty(this: CheerioInstance) {
1678
+ domEach(this, function (_i, el) {
1679
+ writeChildren(el, []);
1680
+ });
1681
+ return this;
1682
+ },
1683
+
1684
+ html(this: CheerioInstance, str?: any) {
1685
+ if (str === undefined) {
1686
+ if (!this[0] || !this[0].children) return null;
1687
+ return staticHtml.call(this, this[0].children, this.options);
1688
+ }
1689
+
1690
+ const opts = this.options;
1691
+
1692
+ domEach(this, function (this: CheerioInstance, _i, el) {
1693
+ const content = str.cheerio ? str.clone().get() : evaluate(`${str}`, opts);
1694
+ update(content, el);
1695
+ });
1696
+
1697
+ return this;
1698
+ },
1699
+
1700
+ toString(this: CheerioInstance): string {
1701
+ return staticHtml.call(this, this as unknown as LegacyNode[], this.options);
1702
+ },
1703
+
1704
+ text(this: CheerioInstance, str?: any) {
1705
+ // If `str` is undefined, act as a "getter"
1706
+ if (str === undefined) {
1707
+ return staticText.call(this, this as unknown as ArrayLike<LegacyNode>);
1708
+ } else if (typeof str === 'function') {
1709
+ // Function support
1710
+ return domEach(this, function (this: CheerioInstance, i, el) {
1711
+ const $el = [el] as unknown as CheerioInstance;
1712
+ return manipulationApi.text.call($el, str.call(el, i, staticText($el)));
1713
+ });
1714
+ }
1715
+
1716
+ // Append text node to each selected elements
1717
+ domEach(this, function (this: CheerioInstance, _i, el) {
1718
+ const document = bindingOf(el)!.document;
1719
+ const textId = operation<number>(document, 'createNode', { type: 'text', data: `${str}`, options: legacyOptions(this.options) });
1720
+ const elem = getNode(document, textId) as LegacyNode;
1721
+ update(elem, el);
1722
+ });
1723
+
1724
+ return this;
1725
+ },
1726
+
1727
+ clone(this: CheerioInstance) {
1728
+ return this._make(cloneDom(this.get(), this.options));
1729
+ },
1730
+ };
1731
+
1732
+ function insert(this: CheerioInstance, concatenator: (dom: LegacyNode[], children: LegacyNode[], parent: LegacyNode) => void, elems: any[]) {
1733
+ const lastIdx = this.length - 1;
1734
+
1735
+ return domEach(this, function (this: CheerioInstance, i, el) {
1736
+ let domSrc: any;
1737
+ let dom: LegacyNode[];
1738
+
1739
+ if (typeof elems[0] === 'function') {
1740
+ domSrc = elems[0].call(el, i, staticHtml.call(this, el.children));
1741
+ } else {
1742
+ domSrc = elems;
1743
+ }
1744
+
1745
+ dom = this._makeDomArray(domSrc, i < lastIdx);
1746
+ concatenator(dom, el.children!, el as LegacyNode);
1747
+ });
1748
+ }
1749
+
1750
+ /**
1751
+ * Modify an array in-place, removing some number of elements and adding new
1752
+ * elements directly following them — lib/api/manipulation.js `uniqueSplice`.
1753
+ * Structural changes install whole child lists (see writeChildren); the
1754
+ * engine rebuilds the sibling links.
1755
+ */
1756
+ function uniqueSplice(array: LegacyNode[], spliceIdx: number, spliceCount: number, newElems: LegacyNode[], parent: LegacyNode): void {
1757
+ const current = Array.from(array);
1758
+
1759
+ // Before splicing in new elements, ensure they do not already appear in the
1760
+ // current array.
1761
+ for (let idx = 0; idx < newElems.length; ++idx) {
1762
+ const node = newElems[idx];
1763
+ const oldParent = node.parent || node.root;
1764
+ const prevIdx = oldParent ? Array.from(oldParent.children ?? []).indexOf(node) : -1;
1765
+
1766
+ if (oldParent && prevIdx > -1) {
1767
+ if (oldParent === parent) {
1768
+ // 0.22.0 splices the node out of the same list and compensates the
1769
+ // splice index for the shift.
1770
+ current.splice(prevIdx, 1);
1771
+ if (spliceIdx > prevIdx) spliceIdx--;
1772
+ } else {
1773
+ writeChildren(oldParent, Array.from(oldParent.children ?? []).filter((item, at) => at !== prevIdx));
1774
+ }
1775
+ }
1776
+
1777
+ node.root = null;
1778
+ }
1779
+
1780
+ const merged = current.slice(0, spliceIdx).concat(newElems, current.slice(spliceIdx + spliceCount));
1781
+ writeChildren(parent, merged);
1782
+ }
1783
+
1784
+ /*
1785
+ * api/css.js
1786
+ */
1787
+
1788
+ const cssApi: CheerioPrototype = {
1789
+ css(this: CheerioInstance, prop?: any, val?: any) {
1790
+ if (arguments.length === 2 || (Object.prototype.toString.call(prop) === '[object Object]')) {
1791
+ return domEach(this, function (idx, el) {
1792
+ setCss(el, prop, val, idx);
1793
+ });
1794
+ } else {
1795
+ return getCss(this[0], prop);
1796
+ }
1797
+ },
1798
+ };
1799
+
1800
+ /*
1801
+ * api/forms.js
1802
+ */
1803
+
1804
+ const submittableSelector = 'input,select,textarea,keygen';
1805
+ const r20 = /%20/g;
1806
+ const rCRLF = /\r?\n/g;
1807
+
1808
+ const formsApi: CheerioPrototype = {
1809
+ serialize(this: CheerioInstance): string {
1810
+ // Convert form elements into name/value objects
1811
+ const arr = formsApi.serializeArray.call(this);
1812
+
1813
+ // Serialize each element into a key/value string
1814
+ const retArr = arr.map((data: { name: string; value: string }) => `${encodeURIComponent(data.name)}=${encodeURIComponent(data.value)}`);
1815
+
1816
+ // Return the resulting serialization
1817
+ return retArr.join('&').replace(r20, '+');
1818
+ },
1819
+
1820
+ serializeArray(this: CheerioInstance): Array<{ name: string; value: string }> {
1821
+ // Resolve all form elements from either forms or collections of form elements
1822
+ const Cheerio = this.constructor as CheerioConstructor;
1823
+ return (this.map(function (this: LegacyNode) {
1824
+ const elem = this;
1825
+ const $elem = Cheerio(elem);
1826
+ if (elem.name === 'form') {
1827
+ return ($elem.find(submittableSelector) as CheerioInstance).toArray();
1828
+ } else {
1829
+ return $elem.filter(submittableSelector).toArray();
1830
+ }
1831
+ }) as CheerioInstance)
1832
+ .filter(
1833
+ // Verify elements have a name (`attr.name`) and are not disabled (`:disabled`)
1834
+ '[name!=""]:not(:disabled)'
1835
+ // and cannot be clicked (`[type=submit]`) or are used in `x-www-form-urlencoded` (`[type=file]`)
1836
+ + ':not(:submit, :button, :image, :reset, :file)'
1837
+ // and are either checked/don't have a checkable state
1838
+ + ':matches([checked], :not(:checkbox, :radio))')
1839
+ .map(function (_i: number, elem: LegacyNode) {
1840
+ const $elem = Cheerio(elem);
1841
+ const name = $elem.attr('name') as string;
1842
+ const val = $elem.val();
1843
+
1844
+ // If there is no value set (e.g. `undefined`, `null`), then return nothing
1845
+ if (val == null) {
1846
+ return null;
1847
+ } else {
1848
+ // If we have an array of values (e.g. `<select multiple>`), return an array of key/value pairs
1849
+ if (Array.isArray(val)) {
1850
+ return val.map((value: string) => ({
1851
+ name,
1852
+ value: value.replace(rCRLF, '\r\n'),
1853
+ }));
1854
+ // Otherwise (e.g. `<input type="text">`, return only one key/value pair
1855
+ } else {
1856
+ return { name, value: (val as string).replace(rCRLF, '\r\n') };
1857
+ }
1858
+ }
1859
+ })
1860
+ .get() as Array<{ name: string; value: string }>;
1861
+ },
1862
+ };
1863
+
1864
+ /*
1865
+ * lib/static.js
1866
+ */
1867
+
1868
+ function render(that: { _root?: CheerioInstance }, dom: any, options: LegacyOptions): string {
1869
+ if (!dom) {
1870
+ if (that._root && (that._root as unknown as LegacyNode).children) {
1871
+ dom = (that._root as unknown as LegacyNode).children;
1872
+ } else {
1873
+ return '';
1874
+ }
1875
+ } else if (typeof dom === 'string') {
1876
+ const roots = ((that._root ?? {}) as unknown as LegacyNode).children ?? [];
1877
+ dom = scopedSelect(dom, roots, { ...options, context: roots });
1878
+ }
1879
+
1880
+ return renderWith(options, dom);
1881
+ }
1882
+
1883
+ /** $.html([selector | dom], [options]) */
1884
+ function staticHtml(this: any, dom?: any, options?: LegacyOptions): string {
1885
+ const Cheerio = moduleCheerio;
1886
+
1887
+ // be flexible about parameters, sometimes we call html(),
1888
+ // with options as only parameter
1889
+ if (Object.prototype.toString.call(dom) === '[object Object]' && !options && !('length' in dom) && !('type' in dom)) {
1890
+ options = dom;
1891
+ dom = undefined;
1892
+ }
1893
+
1894
+ // sometimes $.html() used without preloading html
1895
+ // so fallback non existing options to the default ones
1896
+ options = defaults(options ?? {}, this._options, Cheerio.prototype.options) as LegacyOptions;
1897
+
1898
+ return render(this, dom, options);
1899
+ }
1900
+
1901
+ /** $.xml([selector | dom]) */
1902
+ function staticXml(this: any, dom?: any): string {
1903
+ const options = defaults({ xmlMode: true } as LegacyOptions, this._options);
1904
+ return render(this, dom, options);
1905
+ }
1906
+
1907
+ /** $.text(dom) */
1908
+ function staticText(this: any, elems?: ArrayLike<LegacyNode>): string {
1909
+ if (!elems) {
1910
+ elems = staticRoot.call(this) as unknown as ArrayLike<LegacyNode>;
1911
+ }
1912
+ const src = (elems ?? []) as ArrayLike<LegacyNode>;
1913
+ const len = (src as any).length >>> 0;
1914
+ if (len > 0) {
1915
+ const first = (src as any)[0] as LegacyNode | undefined;
1916
+ const document = bindingOf(first)?.document;
1917
+ if (document) {
1918
+ const ids = new Array<number>(len);
1919
+ let ok = true;
1920
+ for (let i = 0; i < len; i++) {
1921
+ const id = viewIdIn(document, (src as any)[i]);
1922
+ if (id === undefined) { ok = false; break; }
1923
+ ids[i] = id;
1924
+ }
1925
+ if (ok) {
1926
+ const text = document.text(ids);
1927
+ if (typeof text === 'string') return text;
1928
+ }
1929
+ }
1930
+ }
1931
+ let ret = '';
1932
+ for (let i = 0; i < len; i++) {
1933
+ const elem = (src as any)[i] as LegacyNode;
1934
+ if (elem.type === 'text') ret += elem.data;
1935
+ else if (elem.children && elem.type !== 'comment') {
1936
+ ret += staticText(elem.children);
1937
+ }
1938
+ }
1939
+ return ret;
1940
+ }
1941
+
1942
+ /** $.parseHTML(data [, context ] [, keepScripts ]) */
1943
+ function staticParseHTML(this: { load: typeof load }, data?: string | null, context?: unknown, keepScripts = typeof context === 'boolean' ? context : false): LegacyNode[] | null {
1944
+ let parsed: CheerioInstance;
1945
+
1946
+ if (!data || typeof data !== 'string') {
1947
+ return null;
1948
+ }
1949
+
1950
+ if (typeof context === 'boolean') {
1951
+ keepScripts = context as boolean;
1952
+ }
1953
+
1954
+ parsed = this.load(data) as unknown as CheerioInstance;
1955
+ if (!keepScripts) {
1956
+ (parsed as any)('script').remove();
1957
+ }
1958
+
1959
+ // The `children` array is used by Cheerio internally to group elements that
1960
+ // share the same parents. When nodes created through `parseHTML` are
1961
+ // inserted into previously-existing DOM structures, they will be removed
1962
+ // from the `children` array. The results of `parseHTML` should remain
1963
+ // constant across these operations, so a shallow copy should be returned.
1964
+ return (parsed.root()[0] as LegacyNode).children!.slice();
1965
+ }
1966
+
1967
+ /** $.root() */
1968
+ function staticRoot(this: any): CheerioInstance {
1969
+ return (this as unknown as CheerioConstructor)(this._root);
1970
+ }
1971
+
1972
+ /** $.contains(container, contained) */
1973
+ function staticContains(container?: LegacyNode, contained?: LegacyNode): boolean {
1974
+ // According to the jQuery API, an element does not "contain" itself
1975
+ if (contained === container) {
1976
+ return false;
1977
+ }
1978
+
1979
+ // Step up the descendants, stopping when the root element is reached
1980
+ // (signaled by `.parent` returning a reference to the same object)
1981
+ while (contained && contained !== contained.parent) {
1982
+ contained = contained.parent as LegacyNode;
1983
+ if (contained === container) {
1984
+ return true;
1985
+ }
1986
+ }
1987
+
1988
+ return false;
1989
+ }
1990
+
1991
+ /** $.load(str) */
1992
+ function load(content: string | Buffer | ArrayLike<LegacyNode> | LegacyNode, options?: LegacyOptions | null): CheerioStatic {
1993
+ const Cheerio = moduleCheerio;
1994
+
1995
+ options = defaults({ ...(options ?? {}) }, Cheerio.prototype.options) as LegacyOptions;
1996
+
1997
+ const root = parse(content as string | Buffer, options);
1998
+
1999
+ const initialize = function (this: CheerioInstance, selector?: any, context?: any, r?: any, opts?: LegacyOptions) {
2000
+ if (!(this instanceof initialize)) {
2001
+ return new (initialize as unknown as CheerioConstructor)(selector, context, r, opts);
2002
+ }
2003
+ opts = defaults(opts || {}, options);
2004
+ return Cheerio.call(this, selector, context, r || root, opts);
2005
+ } as unknown as CheerioStatic;
2006
+
2007
+ // Ensure that selections created by the "loaded" `initialize` function are
2008
+ // true Cheerio instances.
2009
+ initialize.prototype = Object.create(Cheerio.prototype) as CheerioPrototype;
2010
+ initialize.prototype.constructor = initialize;
2011
+
2012
+ // Mimic jQuery's prototype alias for plugin authors.
2013
+ (initialize as any).fn = initialize.prototype;
2014
+
2015
+ // Keep a reference to the top-level scope so we can chain methods that
2016
+ // implicitly resolve selectors; e.g. $("<span>").(".bar"), which otherwise
2017
+ // loses ._root
2018
+ initialize.prototype._originalRoot = root;
2019
+
2020
+ // Add in the static methods
2021
+ Object.assign(initialize, staticExports);
2022
+
2023
+ // Add in the root
2024
+ (initialize as any)._root = root;
2025
+ // store options
2026
+ (initialize as any)._options = options;
2027
+
2028
+ return initialize;
2029
+ }
2030
+
2031
+ const staticExports = {
2032
+ load,
2033
+ html: staticHtml,
2034
+ xml: staticXml,
2035
+ text: staticText,
2036
+ parseHTML: staticParseHTML,
2037
+ root: staticRoot,
2038
+ contains: staticContains,
2039
+ };
2040
+
2041
+ /*
2042
+ * Module assembly — the callable 0.22.0 module export.
2043
+ */
2044
+
2045
+ const moduleCheerio = makeCheerio() as unknown as CheerioStatic;
2046
+ for (const api of [attributesApi, traversingApi, manipulationApi, cssApi, formsApi]) {
2047
+ Object.assign(moduleCheerio.prototype, api);
2048
+ }
2049
+ Object.assign(moduleCheerio, staticExports);
2050
+ moduleCheerio.version = packageVersion;
2051
+
2052
+ export default moduleCheerio;
2053
+ export { moduleCheerio as cheerio, load, staticHtml as html, staticXml as xml, staticText as text, staticParseHTML as parseHTML, staticRoot as root, staticContains as contains };
2054
+ export { staticExports as legacyStatics };
2055
+ export type { CheerioInstance, CheerioConstructor, CheerioPrototype, LegacyNode, LegacyOptions };