@dvaji/cheerox 0.0.0-stage → 0.1.2

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 (268) hide show
  1. package/CONTRIBUTING.md +74 -0
  2. package/Cargo.lock +1091 -0
  3. package/Cargo.toml +47 -0
  4. package/LICENSE +21 -0
  5. package/README.md +121 -2
  6. package/RELEASING.md +114 -0
  7. package/THIRD_PARTY_NOTICES.md +7581 -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-BKkfJEAr.mjs +1648 -0
  18. package/dist/cheerio-compat-BKkfJEAr.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-DcnYK9OB.cjs +1719 -0
  23. package/dist/cheerio-compat-DcnYK9OB.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 +4120 -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 +35 -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/native/vendor/scraper-0.24.0/Cargo.toml +52 -0
  167. package/native/vendor/scraper-0.24.0/LICENSE +15 -0
  168. package/native/vendor/scraper-0.24.0/src/element_ref/element.rs +212 -0
  169. package/native/vendor/scraper-0.24.0/src/element_ref/mod.rs +236 -0
  170. package/native/vendor/scraper-0.24.0/src/element_ref/serializable.rs +15 -0
  171. package/native/vendor/scraper-0.24.0/src/error/utils.rs +91 -0
  172. package/native/vendor/scraper-0.24.0/src/error.rs +118 -0
  173. package/native/vendor/scraper-0.24.0/src/html/mod.rs +270 -0
  174. package/native/vendor/scraper-0.24.0/src/html/serializable.rs +27 -0
  175. package/native/vendor/scraper-0.24.0/src/html/tree_sink.rs +285 -0
  176. package/native/vendor/scraper-0.24.0/src/lib.rs +180 -0
  177. package/native/vendor/scraper-0.24.0/src/node/serializable.rs +52 -0
  178. package/native/vendor/scraper-0.24.0/src/node.rs +465 -0
  179. package/native/vendor/scraper-0.24.0/src/selectable.rs +70 -0
  180. package/native/vendor/scraper-0.24.0/src/selector.rs +290 -0
  181. package/package.json +167 -4
  182. package/scripts/check-native.mjs +15 -0
  183. package/scripts/check-release.mjs +234 -0
  184. package/scripts/fix-declarations.mjs +39 -0
  185. package/scripts/generate-notices.mjs +194 -0
  186. package/scripts/notices/README.md +13 -0
  187. package/scripts/notices/cheerio-MIT.txt +21 -0
  188. package/scripts/notices/html5ever-AUTHORS.txt +20 -0
  189. package/scripts/notices/html5ever-COPYRIGHT.txt +8 -0
  190. package/scripts/notices/html5ever-LICENSE-APACHE.txt +201 -0
  191. package/scripts/notices/html5ever-LICENSE-MIT.txt +25 -0
  192. package/scripts/notices/htmlparser2-MIT.txt +18 -0
  193. package/scripts/notices/napi-rs-MIT.txt +43 -0
  194. package/scripts/notices/neon-MIT.txt +19 -0
  195. package/scripts/notices/runtime-01c266bced4a434da005.txt +3 -0
  196. package/scripts/notices/runtime-0a54e647fe54104658b5.txt +14 -0
  197. package/scripts/notices/runtime-0b74dfa0bcee5c420c6b.txt +25 -0
  198. package/scripts/notices/runtime-0d542e0c8804e39aa7f3.txt +177 -0
  199. package/scripts/notices/runtime-0f96a83840e146e43c0e.txt +21 -0
  200. package/scripts/notices/runtime-123a331b5dbf04c30097.txt +25 -0
  201. package/scripts/notices/runtime-172020dbfd5b53a226df.txt +34 -0
  202. package/scripts/notices/runtime-209fbbe0ad52d9235e37.txt +26 -0
  203. package/scripts/notices/runtime-23f18e03dc49df91622f.txt +23 -0
  204. package/scripts/notices/runtime-268872b9816f90fd8e85.txt +220 -0
  205. package/scripts/notices/runtime-35242e7a83f69875e6ed.txt +176 -0
  206. package/scripts/notices/runtime-378f5840b258e2779c39.txt +25 -0
  207. package/scripts/notices/runtime-4108245a1f2df9d4e94d.txt +25 -0
  208. package/scripts/notices/runtime-4455bf75a91154108304.txt +21 -0
  209. package/scripts/notices/runtime-553fffcd9b1cb158bc3e.txt +13 -0
  210. package/scripts/notices/runtime-62c7a1e35f56406896d7.txt +176 -0
  211. package/scripts/notices/runtime-6485b8ed310d3f0340bf.txt +25 -0
  212. package/scripts/notices/runtime-69fef7b0f322a6555415.txt +201 -0
  213. package/scripts/notices/runtime-6df43f6f4b5d4587f3d8.txt +187 -0
  214. package/scripts/notices/runtime-799e9ca9d179295ef372.txt +24 -0
  215. package/scripts/notices/runtime-7b63ecd5f1902af1b637.txt +25 -0
  216. package/scripts/notices/runtime-7bc7d5de2a0b793d4e1a.txt +21 -0
  217. package/scripts/notices/runtime-7e12e5df4bae12cb2158.txt +24 -0
  218. package/scripts/notices/runtime-861399f8c21c042b1105.txt +12 -0
  219. package/scripts/notices/runtime-8ada45cd9f843acf64e4.txt +201 -0
  220. package/scripts/notices/runtime-90eb64f0279b0d9432ac.txt +12 -0
  221. package/scripts/notices/runtime-a60eea817514531668d7.txt +201 -0
  222. package/scripts/notices/runtime-a7c936ff1ed8fa340172.txt +25 -0
  223. package/scripts/notices/runtime-ab6eec6caf0fa5775e41.txt +275 -0
  224. package/scripts/notices/runtime-b1181a40b2a7b25cf66f.txt +19 -0
  225. package/scripts/notices/runtime-b71bd43a069ca0641a9e.txt +25 -0
  226. package/scripts/notices/runtime-c16f8dcf1a368b83be78.txt +201 -0
  227. package/scripts/notices/runtime-c2cfccb812fe482101a8.txt +21 -0
  228. package/scripts/notices/runtime-e99d88d232bf57d70f0f.txt +25 -0
  229. package/scripts/notices/runtime-f32fb3b417a194167cfa.txt +9 -0
  230. package/scripts/notices/runtime-f5062c9a188d81dfe66b.txt +39 -0
  231. package/scripts/notices/runtime-f9070a832833fa7488fd.txt +4 -0
  232. package/scripts/notices/runtime-fab3dd6bdab226f1c086.txt +373 -0
  233. package/scripts/notices/runtime-fba3318d0c600380177e.txt +62 -0
  234. package/scripts/notices/runtime-ff8f68cb076caf8cefe7.txt +25 -0
  235. package/scripts/notices/runtime-ff92bed461f50338dd70.txt +74 -0
  236. package/scripts/notices/runtime.json +1632 -0
  237. package/scripts/notices/sources.json +561 -0
  238. package/scripts/notices/xray-MIT.txt +21 -0
  239. package/src/attribute-object.ts +71 -0
  240. package/src/attributes.ts +308 -0
  241. package/src/cheerio-compat/css.ts +58 -0
  242. package/src/cheerio-compat/render.ts +106 -0
  243. package/src/cheerio-compat/selectors.ts +51 -0
  244. package/src/cheerio-compat/types.ts +52 -0
  245. package/src/cheerio-compat.ts +2055 -0
  246. package/src/codec.ts +96 -0
  247. package/src/dom.ts +87 -0
  248. package/src/extract-plan.ts +97 -0
  249. package/src/extract.ts +322 -0
  250. package/src/hooks.ts +369 -0
  251. package/src/index.ts +48 -0
  252. package/src/io.ts +491 -0
  253. package/src/match.ts +207 -0
  254. package/src/modern.ts +259 -0
  255. package/src/native.ts +149 -0
  256. package/src/nodes.ts +831 -0
  257. package/src/parse.ts +53 -0
  258. package/src/parser-types.ts +157 -0
  259. package/src/router.ts +1129 -0
  260. package/src/selection.ts +682 -0
  261. package/src/slim.ts +12 -0
  262. package/src/snapshot.ts +291 -0
  263. package/src/transport.ts +113 -0
  264. package/src/types.ts +186 -0
  265. package/src/utils.ts +29 -0
  266. package/src/workers.ts +21 -0
  267. package/tsconfig.json +15 -0
  268. package/tsdown.config.mjs +17 -0
@@ -0,0 +1,946 @@
1
+ //! Cheerio attribute, property, style, data, class and form semantics.
2
+ //! JavaScript only supplies callbacks and preserves opaque JS value identities.
3
+ use crate::arena::{value_ids, DomArena};
4
+ use crate::codec;
5
+ use serde_json::{json, Map, Number, Value};
6
+ use std::collections::HashSet;
7
+
8
+ fn element(arena: &DomArena, id: u32) -> bool {
9
+ arena.node(id).is_some_and(|node| node.is_element())
10
+ }
11
+
12
+ fn boolean_attribute(name: &str) -> bool {
13
+ matches!(
14
+ name.to_ascii_lowercase().as_str(),
15
+ "autofocus"
16
+ | "autoplay"
17
+ | "async"
18
+ | "checked"
19
+ | "controls"
20
+ | "defer"
21
+ | "disabled"
22
+ | "hidden"
23
+ | "loop"
24
+ | "multiple"
25
+ | "open"
26
+ | "readonly"
27
+ | "required"
28
+ | "scoped"
29
+ | "selected"
30
+ )
31
+ }
32
+
33
+ fn js_string(value: &Value) -> String {
34
+ match value {
35
+ Value::String(value) => value.clone(),
36
+ Value::Null => "null".into(),
37
+ Value::Array(values) => values
38
+ .iter()
39
+ .map(|value| {
40
+ if value.is_null() {
41
+ String::new()
42
+ } else {
43
+ js_string(value)
44
+ }
45
+ })
46
+ .collect::<Vec<_>>()
47
+ .join(","),
48
+ Value::Object(value)
49
+ if value.get("__undefinedJavaScriptValue") == Some(&Value::Bool(true)) =>
50
+ {
51
+ "undefined".into()
52
+ }
53
+ Value::Object(_) => "[object Object]".into(),
54
+ Value::Number(number) => number
55
+ .as_f64()
56
+ .map(js_number)
57
+ .unwrap_or_else(|| number.to_string()),
58
+ Value::Bool(value) => value.to_string(),
59
+ }
60
+ }
61
+
62
+ fn js_number(number: f64) -> String {
63
+ if number == 0.0 {
64
+ return "0".into();
65
+ }
66
+ if number.abs() >= 1e21 || number.abs() < 1e-6 {
67
+ let scientific = format!("{number:e}");
68
+ if let Some((mantissa, exponent)) = scientific.split_once('e') {
69
+ if let Ok(exponent) = exponent.parse::<i32>() {
70
+ return format!(
71
+ "{mantissa}e{}{exponent}",
72
+ if exponent >= 0 { "+" } else { "" }
73
+ );
74
+ }
75
+ }
76
+ scientific
77
+ } else {
78
+ number.to_string()
79
+ }
80
+ }
81
+
82
+ fn truthy(value: &Value) -> bool {
83
+ match value {
84
+ Value::Null => false,
85
+ Value::Bool(value) => *value,
86
+ Value::String(value) => !value.is_empty(),
87
+ Value::Number(value) => value.as_f64().is_some_and(|value| value != 0.0),
88
+ _ => true,
89
+ }
90
+ }
91
+
92
+ fn get_attr(arena: &DomArena, id: u32, name: &str) -> Value {
93
+ let Some(node) = arena.node(id).filter(|node| node.is_element()) else {
94
+ return Value::Null;
95
+ };
96
+ if name.is_empty() {
97
+ return Value::Object(node.attribs.to_map());
98
+ }
99
+ if let Some(value) = node.attribs.get(name) {
100
+ return if !arena.xml_mode() && boolean_attribute(name) {
101
+ json!(name)
102
+ } else {
103
+ value.clone()
104
+ };
105
+ }
106
+ if name == "value" {
107
+ if node.name.as_deref() == Some("option") {
108
+ return json!(arena.text(&node.children));
109
+ }
110
+ if node.name.as_deref() == Some("input")
111
+ && matches!(arena.attr(id, "type"), Some("radio" | "checkbox"))
112
+ {
113
+ return json!("on");
114
+ }
115
+ }
116
+ Value::Null
117
+ }
118
+
119
+ fn inner_text(arena: &DomArena, id: u32) -> String {
120
+ let mut output = String::new();
121
+ let mut stack = vec![id];
122
+ let mut seen = HashSet::new();
123
+ while let Some(id) = stack.pop() {
124
+ if !seen.insert(id) {
125
+ continue;
126
+ }
127
+ let Some(node) = arena.node(id) else {
128
+ continue;
129
+ };
130
+ if matches!(node.name.as_deref(), Some("script" | "style")) || node.kind == "comment" {
131
+ continue;
132
+ }
133
+ if node.kind == "text" {
134
+ output.push_str(node.data.as_deref().unwrap_or(""));
135
+ } else if node.name.as_deref() == Some("br") {
136
+ output.push('\n');
137
+ } else {
138
+ stack.extend(node.children.iter().rev().copied());
139
+ }
140
+ }
141
+ output
142
+ }
143
+
144
+ fn parse_css(style: &str) -> Map<String, Value> {
145
+ let mut properties = Map::new();
146
+ let mut previous: Option<String> = None;
147
+ for segment in style.trim().split(';') {
148
+ let colon = segment.find(':');
149
+ if colon.is_none_or(|index| index == 0 || index + 1 == segment.len()) {
150
+ let continuation = segment.trim_end();
151
+ if !continuation.is_empty() {
152
+ if let Some(key) = &previous {
153
+ let mut value = properties.get(key).map(js_string).unwrap_or_default();
154
+ value.push(';');
155
+ value.push_str(continuation);
156
+ properties.insert(key.clone(), json!(value));
157
+ }
158
+ }
159
+ } else if let Some(colon) = colon {
160
+ let key = segment[..colon].trim().to_owned();
161
+ let value = segment[colon + 1..].trim();
162
+ properties.insert(key.clone(), json!(value));
163
+ previous = Some(key);
164
+ }
165
+ }
166
+ properties
167
+ }
168
+
169
+ fn set_css(arena: &mut DomArena, ids: &[u32], name: &str, value: &Value) {
170
+ for id in ids {
171
+ if !element(arena, *id) {
172
+ continue;
173
+ }
174
+ let mut properties = parse_css(arena.attr(*id, "style").unwrap_or(""));
175
+ if value.as_str() == Some("") {
176
+ properties.shift_remove(name);
177
+ } else if !value.is_null() {
178
+ properties.insert(name.into(), json!(js_string(value)));
179
+ }
180
+ let style = properties
181
+ .iter()
182
+ .map(|(key, value)| format!("{key}: {};", js_string(value)))
183
+ .collect::<Vec<_>>()
184
+ .join(" ");
185
+ arena.set_attr(&[*id], "style", Some(&style));
186
+ }
187
+ }
188
+
189
+ fn node_property(arena: &DomArena, id: u32, name: &str) -> bool {
190
+ matches!(
191
+ name,
192
+ "attribs"
193
+ | "children"
194
+ | "childNodes"
195
+ | "parent"
196
+ | "parentNode"
197
+ | "prev"
198
+ | "previousSibling"
199
+ | "next"
200
+ | "nextSibling"
201
+ | "firstChild"
202
+ | "lastChild"
203
+ | "nodeType"
204
+ | "nodeValue"
205
+ | "name"
206
+ | "tagName"
207
+ | "type"
208
+ | "startIndex"
209
+ | "endIndex"
210
+ ) || arena.node(id).is_some_and(|node| {
211
+ node.extras.contains_key(name)
212
+ || match name {
213
+ "namespace" => node.namespace.is_some(),
214
+ "attribsNamespace" => node.attribs_namespace.is_some(),
215
+ "attribsPrefix" => node.attribs_prefix.is_some(),
216
+ _ => false,
217
+ }
218
+ })
219
+ }
220
+
221
+ fn get_prop(arena: &mut DomArena, id: u32, name: &str) -> napi::Result<Value> {
222
+ let Some(node) = arena.node(id) else {
223
+ return Ok(Value::Null);
224
+ };
225
+ Ok(match name {
226
+ "style" if node.is_element() => {
227
+ let mut properties = parse_css(arena.attr(id, "style").unwrap_or(""));
228
+ let names: Vec<_> = properties.keys().cloned().collect();
229
+ for (index, name) in names.iter().enumerate() {
230
+ properties.insert(index.to_string(), json!(name));
231
+ }
232
+ properties.insert("length".into(), json!(names.len()));
233
+ Value::Object(properties)
234
+ }
235
+ "tagName" | "nodeName" if node.is_element() => {
236
+ json!(node.name.as_deref().unwrap_or("").to_uppercase())
237
+ }
238
+ "textContent" => json!(arena.text(&[id])),
239
+ "innerText" => json!(if arena.xml_mode() {
240
+ arena.text(&[id])
241
+ } else {
242
+ inner_text(arena, id)
243
+ }),
244
+ "outerHTML" => json!(arena.serialize_mut(&[id], &arena.options.clone())),
245
+ "innerHTML" => json!(arena.inner_html_mut(id)),
246
+ "href" | "src" if node.is_element() => {
247
+ let value = arena.attr(id, name);
248
+ let tag = node.name.as_deref().unwrap_or("");
249
+ let resolves = name == "href" && matches!(tag, "a" | "link")
250
+ || name == "src" && matches!(tag, "img" | "iframe" | "audio" | "video" | "source");
251
+ match (value, arena.options.get("baseURI").and_then(Value::as_str)) {
252
+ (Some(value), Some(base)) if resolves => json!(crate::codec::encode_literal(
253
+ url::Url::parse(&crate::codec::to_usv(base))
254
+ .and_then(|base| base.join(&crate::codec::to_usv(value)))
255
+ .map_err(|error| napi::Error::from_reason(error.to_string()))?
256
+ .as_str()
257
+ )),
258
+ (Some(value), _) => json!(value),
259
+ _ => Value::Null,
260
+ }
261
+ }
262
+ _ if !node.is_element() => Value::Null,
263
+ _ if node_property(arena, id, name) => json!({"__nativeNodeProperty": name}),
264
+ _ if !arena.xml_mode() && boolean_attribute(name) => json!(node.attribs.contains_key(name)),
265
+ _ => get_attr(arena, id, name),
266
+ })
267
+ }
268
+
269
+ fn set_prop(arena: &mut DomArena, ids: &[u32], name: &str, value: &Value) -> napi::Result<()> {
270
+ for id in ids {
271
+ if !element(arena, *id) {
272
+ continue;
273
+ }
274
+ if node_property(arena, *id, name) || matches!(name, "namespace" | "prefix") {
275
+ let field = match name {
276
+ "childNodes" => "children",
277
+ "parentNode" => "parent",
278
+ "previousSibling" => "prev",
279
+ "nextSibling" => "next",
280
+ _ => name,
281
+ };
282
+ arena.set_node(*id, field, value)?;
283
+ } else if !arena.xml_mode() && boolean_attribute(name) {
284
+ arena.set_attr(&[*id], name, if truthy(value) { Some("") } else { None });
285
+ } else {
286
+ arena.set_attr(&[*id], name, Some(&js_string(value)));
287
+ }
288
+ }
289
+ Ok(())
290
+ }
291
+
292
+ fn camel_case(value: &str) -> String {
293
+ let mut result = String::new();
294
+ let mut chars = value.chars().peekable();
295
+ while let Some(character) = chars.next() {
296
+ if matches!(character, '.' | '_' | '-') {
297
+ if chars.peek().is_none() {
298
+ continue;
299
+ }
300
+ if chars
301
+ .peek()
302
+ .is_some_and(|character| character.is_ascii_alphanumeric() || *character == '_')
303
+ {
304
+ result.push(chars.next().unwrap().to_ascii_uppercase());
305
+ continue;
306
+ }
307
+ }
308
+ result.push(character);
309
+ }
310
+ result
311
+ }
312
+
313
+ fn css_case(value: &str) -> String {
314
+ let mut result = String::new();
315
+ for character in value.chars() {
316
+ if character.is_ascii_uppercase() {
317
+ result.push('-');
318
+ }
319
+ result.push(character.to_ascii_lowercase());
320
+ }
321
+ result
322
+ }
323
+
324
+ fn data_value(value: &str) -> Value {
325
+ match value {
326
+ "null" => return Value::Null,
327
+ "true" => return json!(true),
328
+ "false" => return json!(false),
329
+ "NaN" | "Infinity" | "-Infinity" => return json!({"__nativeNumber": value}),
330
+ _ => {}
331
+ }
332
+ if let Ok(number) = value.parse::<f64>() {
333
+ let rendered = js_number(number);
334
+ if rendered == value {
335
+ if let Some(number) = Number::from_f64(number) {
336
+ return Value::Number(number);
337
+ }
338
+ }
339
+ }
340
+ if value.starts_with('{') && value.ends_with('}')
341
+ || value.starts_with('[') && value.ends_with(']')
342
+ {
343
+ if let Ok(value) = crate::codec::parse_json(value) {
344
+ return value;
345
+ }
346
+ }
347
+ json!(value)
348
+ }
349
+
350
+ fn read_data(arena: &mut DomArena, id: u32, name: Option<&str>) -> Value {
351
+ if !element(arena, id) {
352
+ return json!({"found":false});
353
+ }
354
+ let node = &mut arena.nodes[id as usize];
355
+ let attributes = node.attribs.clone();
356
+ let entry = node.extras.entry("data").or_insert_with(|| json!({}));
357
+ if !entry.is_object() {
358
+ *entry = json!({});
359
+ }
360
+ let data = entry.as_object_mut().unwrap();
361
+ if let Some(name) = name {
362
+ if !data.contains_key(name) {
363
+ if let Some(value) = attributes
364
+ .get(&format!("data-{}", css_case(name)))
365
+ .and_then(Value::as_str)
366
+ {
367
+ data.insert(name.into(), data_value(value));
368
+ }
369
+ }
370
+ match data.get(name) {
371
+ Some(value) => json!({"found":true,"value":value}),
372
+ None => json!({"found":false}),
373
+ }
374
+ } else {
375
+ for (key, value) in attributes {
376
+ if let Some(key) = key.strip_prefix("data-") {
377
+ data.entry(camel_case(key))
378
+ .or_insert_with(|| data_value(value.as_str().unwrap_or("")));
379
+ }
380
+ }
381
+ json!({"found":true,"value":data})
382
+ }
383
+ }
384
+
385
+ fn descendants(arena: &DomArena, roots: &[u32], tag: Option<&str>) -> Vec<u32> {
386
+ let mut output = Vec::new();
387
+ for root in roots {
388
+ let mut stack = arena
389
+ .node(*root)
390
+ .map(|node| node.children.iter().rev().copied().collect::<Vec<_>>())
391
+ .unwrap_or_default();
392
+ let mut seen = HashSet::new();
393
+ while let Some(id) = stack.pop() {
394
+ if !seen.insert(id) {
395
+ continue;
396
+ }
397
+ let Some(node) = arena.node(id) else {
398
+ continue;
399
+ };
400
+ if node.is_element() && tag.is_none_or(|tag| node.name.as_deref() == Some(tag)) {
401
+ output.push(id);
402
+ }
403
+ stack.extend(node.children.iter().rev().copied());
404
+ }
405
+ }
406
+ output
407
+ }
408
+
409
+ fn selected_options(arena: &DomArena, select: u32) -> Vec<u32> {
410
+ let options = descendants(arena, &[select], Some("option"));
411
+ let selected: Vec<_> = options
412
+ .iter()
413
+ .copied()
414
+ .filter(|id| arena.attr(*id, "selected").is_some())
415
+ .collect();
416
+ if selected.is_empty() && arena.attr(select, "multiple").is_none() {
417
+ options.into_iter().take(1).collect()
418
+ } else {
419
+ selected
420
+ }
421
+ }
422
+
423
+ fn get_value(arena: &DomArena, ids: &[u32]) -> Value {
424
+ let Some(id) = ids.first().copied() else {
425
+ return Value::Null;
426
+ };
427
+ let Some(node) = arena.node(id).filter(|node| node.is_element()) else {
428
+ return Value::Null;
429
+ };
430
+ match node.name.as_deref() {
431
+ Some("textarea") => json!(arena.text(ids)),
432
+ Some("input" | "option" | "button") => get_attr(arena, id, "value"),
433
+ Some("select") => {
434
+ let selected = selected_options(arena, id);
435
+ if get_attr(arena, id, "multiple")
436
+ .as_str()
437
+ .is_some_and(|value| !value.is_empty())
438
+ {
439
+ json!(selected
440
+ .iter()
441
+ .map(|id| arena.text(&[*id]))
442
+ .collect::<Vec<_>>())
443
+ } else {
444
+ selected
445
+ .first()
446
+ .map(|id| get_attr(arena, *id, "value"))
447
+ .unwrap_or(Value::Null)
448
+ }
449
+ }
450
+ _ => Value::Null,
451
+ }
452
+ }
453
+
454
+ fn set_value(arena: &mut DomArena, ids: &[u32], value: &Value) -> bool {
455
+ let Some(id) = ids.first().copied() else {
456
+ return true;
457
+ };
458
+ let Some(node) = arena.node(id).filter(|node| node.is_element()) else {
459
+ return true;
460
+ };
461
+ match node.name.as_deref() {
462
+ Some("textarea") => arena.set_text(ids, &js_string(value)),
463
+ Some("input" | "option" | "button") => {
464
+ if value.get("__undefinedJavaScriptValue") == Some(&Value::Bool(true)) {
465
+ return true;
466
+ }
467
+ let string = js_string(value);
468
+ arena.set_attr(
469
+ ids,
470
+ "value",
471
+ if value.is_null() { None } else { Some(&string) },
472
+ );
473
+ }
474
+ Some("select") => {
475
+ if arena.attr(id, "multiple").is_none() && value.is_array() {
476
+ return true;
477
+ }
478
+ let values = value
479
+ .as_array()
480
+ .cloned()
481
+ .unwrap_or_else(|| vec![value.clone()])
482
+ .iter()
483
+ .map(js_string)
484
+ .collect::<HashSet<_>>();
485
+ let options = descendants(arena, ids, Some("option"));
486
+ for id in options {
487
+ let selected = arena
488
+ .attr(id, "value")
489
+ .is_some_and(|value| values.contains(value));
490
+ arena.set_attr(&[id], "selected", if selected { Some("") } else { None });
491
+ }
492
+ }
493
+ _ => return false,
494
+ }
495
+ true
496
+ }
497
+
498
+ fn disabled(arena: &DomArena, id: u32) -> bool {
499
+ // Cheerio's selector alias checks the control's own attribute. It does not
500
+ // propagate a disabled fieldset to descendants as a browser does.
501
+ arena.attr(id, "disabled").is_some()
502
+ }
503
+
504
+ fn serialize_array(arena: &DomArena, ids: &[u32]) -> Value {
505
+ let mut controls = Vec::new();
506
+ for id in ids {
507
+ if arena
508
+ .node(*id)
509
+ .is_some_and(|node| node.name.as_deref() == Some("form"))
510
+ {
511
+ controls.extend(descendants(arena, &[*id], None));
512
+ } else {
513
+ controls.push(*id);
514
+ }
515
+ }
516
+ let mut output = Vec::new();
517
+ for id in controls {
518
+ let Some(node) = arena.node(id) else {
519
+ continue;
520
+ };
521
+ if !matches!(
522
+ node.name.as_deref(),
523
+ Some("input" | "select" | "textarea" | "keygen")
524
+ ) || disabled(arena, id)
525
+ {
526
+ continue;
527
+ }
528
+ let Some(name) = arena.attr(id, "name").filter(|name| !name.is_empty()) else {
529
+ continue;
530
+ };
531
+ let control_type = arena.attr(id, "type").unwrap_or("").to_ascii_lowercase();
532
+ if matches!(
533
+ control_type.as_str(),
534
+ "submit" | "button" | "image" | "reset" | "file"
535
+ ) || matches!(control_type.as_str(), "checkbox" | "radio")
536
+ && arena.attr(id, "checked").is_none()
537
+ {
538
+ continue;
539
+ }
540
+ let value = get_value(arena, &[id]);
541
+ let values = value
542
+ .as_array()
543
+ .cloned()
544
+ .unwrap_or_else(|| vec![if value.is_null() { json!("") } else { value }]);
545
+ for value in values {
546
+ output.push(json!({"name":name,"value":js_string(&value).replace("\r\n", "\n").replace('\n', "\r\n")}));
547
+ }
548
+ }
549
+ Value::Array(output)
550
+ }
551
+
552
+ fn encode_component(value: &str, encoded: bool) -> Result<String, ()> {
553
+ let decoded;
554
+ let value = if encoded && codec::has_encoding(value) {
555
+ decoded = String::from_utf16(&codec::to_units(value)).map_err(|_| ())?;
556
+ decoded.as_str()
557
+ } else {
558
+ value
559
+ };
560
+ let mut output = String::new();
561
+ for byte in value.bytes() {
562
+ if byte.is_ascii_alphanumeric() || b"-_.!~*'()".contains(&byte) {
563
+ output.push(byte as char);
564
+ } else if byte == b' ' {
565
+ output.push('+');
566
+ } else {
567
+ output.push_str(&format!("%{byte:02X}"));
568
+ }
569
+ }
570
+ Ok(output)
571
+ }
572
+
573
+ pub(crate) fn keeps_element_names(command: &str) -> bool {
574
+ matches!(
575
+ command,
576
+ "attr"
577
+ | "removeAttr"
578
+ | "css"
579
+ | "data"
580
+ | "removeData"
581
+ | "hasClass"
582
+ | "addClass"
583
+ | "removeClass"
584
+ | "toggleClass"
585
+ | "serializeArray"
586
+ | "serialize"
587
+ )
588
+ }
589
+
590
+ pub(crate) fn execute(
591
+ arena: &mut DomArena,
592
+ command: &str,
593
+ args: &Value,
594
+ ) -> napi::Result<Option<Value>> {
595
+ let ids = value_ids(&args["ids"]);
596
+ let first = ids.first().copied();
597
+ let name = args.get("name").and_then(Value::as_str);
598
+ let value = args.get("value");
599
+ let result = match command {
600
+ "attr" => {
601
+ if let Some(value) = value {
602
+ if let Some(name) = name {
603
+ let string = js_string(value);
604
+ arena.set_attr(
605
+ &ids,
606
+ name,
607
+ if value.is_null() { None } else { Some(&string) },
608
+ );
609
+ }
610
+ Value::Null
611
+ } else {
612
+ first
613
+ .map(|id| get_attr(arena, id, name.unwrap_or("")))
614
+ .unwrap_or(Value::Null)
615
+ }
616
+ }
617
+ "removeAttr" => {
618
+ for name in name.unwrap_or("").split_whitespace() {
619
+ arena.set_attr(&ids, name, None);
620
+ }
621
+ Value::Null
622
+ }
623
+ "prop" => {
624
+ if let Some(value) = value {
625
+ if let Some(name) = name {
626
+ set_prop(arena, &ids, name, value)?;
627
+ }
628
+ Value::Null
629
+ } else if let (Some(id), Some(name)) = (first, name) {
630
+ if args.get("raw").and_then(Value::as_bool) == Some(true) {
631
+ if !element(arena, id) {
632
+ Value::Null
633
+ } else if node_property(arena, id, name) {
634
+ json!({"__nativeNodeProperty":name})
635
+ } else if !arena.xml_mode() && boolean_attribute(name) {
636
+ json!(arena.attr(id, name).is_some())
637
+ } else {
638
+ get_attr(arena, id, name)
639
+ }
640
+ } else {
641
+ get_prop(arena, id, name)?
642
+ }
643
+ } else {
644
+ Value::Null
645
+ }
646
+ }
647
+ "css" => {
648
+ if let (Some(name), Some(value)) = (name, value) {
649
+ set_css(arena, &ids, name, value);
650
+ Value::Null
651
+ } else if let Some(id) = first.filter(|id| element(arena, *id)) {
652
+ let properties = parse_css(arena.attr(id, "style").unwrap_or(""));
653
+ if let Some(name) = name {
654
+ properties.get(name).cloned().unwrap_or(Value::Null)
655
+ } else if let Some(names) = args.get("name").and_then(Value::as_array) {
656
+ Value::Object(
657
+ names
658
+ .iter()
659
+ .filter_map(|name| name.as_str())
660
+ .filter_map(|name| {
661
+ properties
662
+ .get(name)
663
+ .map(|value| (name.into(), value.clone()))
664
+ })
665
+ .collect(),
666
+ )
667
+ } else {
668
+ Value::Object(properties)
669
+ }
670
+ } else {
671
+ Value::Null
672
+ }
673
+ }
674
+ "data" => {
675
+ if let (Some(name), Some(value)) = (name, value) {
676
+ for id in &ids {
677
+ if !element(arena, *id) {
678
+ continue;
679
+ }
680
+ let entry = arena.nodes[*id as usize]
681
+ .extras
682
+ .entry("data")
683
+ .or_insert_with(|| json!({}));
684
+ if !entry.is_object() {
685
+ *entry = json!({});
686
+ }
687
+ entry
688
+ .as_object_mut()
689
+ .unwrap()
690
+ .insert(name.into(), value.clone());
691
+ }
692
+ Value::Null
693
+ } else {
694
+ first
695
+ .map(|id| read_data(arena, id, name))
696
+ .unwrap_or_else(|| json!({"found":false}))
697
+ }
698
+ }
699
+ "removeData" => {
700
+ if let Some(name) = name {
701
+ for id in &ids {
702
+ if let Some(data) = arena
703
+ .nodes
704
+ .get_mut(*id as usize)
705
+ .and_then(|node| node.extras.get_mut("data"))
706
+ .and_then(Value::as_object_mut)
707
+ {
708
+ data.shift_remove(name);
709
+ }
710
+ }
711
+ }
712
+ Value::Null
713
+ }
714
+ "hasClass" => {
715
+ let needle = name.unwrap_or("");
716
+ json!(
717
+ !needle.is_empty()
718
+ && ids.iter().any(|id| element(arena, *id)
719
+ && arena.attr(*id, "class").is_some_and(|classes| classes
720
+ .match_indices(needle)
721
+ .any(|(index, _)| {
722
+ (index == 0
723
+ || classes[..index]
724
+ .chars()
725
+ .next_back()
726
+ .is_some_and(char::is_whitespace))
727
+ && (index + needle.len() == classes.len()
728
+ || classes[index + needle.len()..]
729
+ .chars()
730
+ .next()
731
+ .is_some_and(char::is_whitespace))
732
+ })))
733
+ )
734
+ }
735
+ "addClass" | "removeClass" | "toggleClass" => {
736
+ let names: Vec<_> = name.unwrap_or("").split_whitespace().collect();
737
+ for id in &ids {
738
+ if !element(arena, *id) {
739
+ continue;
740
+ }
741
+ let old = arena.attr(*id, "class").unwrap_or("").to_owned();
742
+ if command == "addClass" && !names.is_empty() {
743
+ let mut classes = format!(" {old} ");
744
+ for name in &names {
745
+ if !classes.contains(&format!(" {name} ")) {
746
+ classes.push_str(name);
747
+ classes.push(' ');
748
+ }
749
+ }
750
+ arena.set_attr(&[*id], "class", Some(classes.trim()));
751
+ continue;
752
+ }
753
+ let mut classes: Vec<String> = old.split_whitespace().map(str::to_owned).collect();
754
+ let mut changed = false;
755
+ if command == "removeClass"
756
+ && args.get("all").and_then(Value::as_bool) == Some(true)
757
+ {
758
+ classes.clear();
759
+ changed = true;
760
+ }
761
+ for name in &names {
762
+ let present = classes.iter().any(|class| class == name);
763
+ let add = if command == "addClass" {
764
+ true
765
+ } else if command == "removeClass" {
766
+ false
767
+ } else {
768
+ args.get("state")
769
+ .and_then(Value::as_bool)
770
+ .unwrap_or(!present)
771
+ };
772
+ if add && !present {
773
+ classes.push((*name).into());
774
+ changed = true;
775
+ } else if !add && present {
776
+ classes.retain(|class| class != name);
777
+ changed = true;
778
+ }
779
+ }
780
+ if changed || command == "toggleClass" && !names.is_empty() {
781
+ arena.set_attr(&[*id], "class", Some(&classes.join(" ")));
782
+ }
783
+ }
784
+ Value::Null
785
+ }
786
+ "val" => {
787
+ if let Some(value) = value {
788
+ if value.get("__undefinedJavaScriptValue") == Some(&Value::Bool(true))
789
+ && first
790
+ .and_then(|id| arena.node(id))
791
+ .is_some_and(|node| node.name.as_deref() == Some("textarea"))
792
+ {
793
+ json!({"chain":false,"returnValue":get_value(arena,&ids)})
794
+ } else {
795
+ json!(set_value(arena, &ids, value))
796
+ }
797
+ } else {
798
+ get_value(arena, &ids)
799
+ }
800
+ }
801
+ "serializeArray" => serialize_array(arena, &ids),
802
+ "serialize" => {
803
+ let fields = serialize_array(arena, &ids);
804
+ let encoded = arena.options.get("__utf16Codec") == Some(&Value::Bool(true));
805
+ let result = fields
806
+ .as_array()
807
+ .unwrap()
808
+ .iter()
809
+ .map(|field| {
810
+ Ok(format!(
811
+ "{}={}",
812
+ encode_component(field["name"].as_str().unwrap_or(""), encoded)?,
813
+ encode_component(field["value"].as_str().unwrap_or(""), encoded)?
814
+ ))
815
+ })
816
+ .collect::<Result<Vec<_>, ()>>();
817
+ match result {
818
+ Ok(fields) => json!(fields.join("&")),
819
+ Err(()) => json!({"__nativeError":{"name":"URIError","message":"URI malformed"}}),
820
+ }
821
+ }
822
+ _ => return Ok(None),
823
+ };
824
+ Ok(Some(result))
825
+ }
826
+
827
+ #[cfg(test)]
828
+ mod tests {
829
+ use super::*;
830
+
831
+ fn fixture(source: &str) -> DomArena {
832
+ crate::arena::parse_xml(
833
+ source,
834
+ json!({"xmlMode":false,"baseURI":"https://example.com/path/page"}),
835
+ )
836
+ }
837
+
838
+ fn tag(arena: &DomArena, name: &str) -> u32 {
839
+ arena
840
+ .nodes
841
+ .iter()
842
+ .position(|node| node.name.as_deref() == Some(name))
843
+ .unwrap() as u32
844
+ }
845
+
846
+ fn run(arena: &mut DomArena, command: &str, args: Value) -> Value {
847
+ execute(arena, command, &args).unwrap().unwrap()
848
+ }
849
+
850
+ #[test]
851
+ fn form_serialization_matches_cheerio_fieldset_and_control_semantics() {
852
+ let mut arena = fixture("<form><fieldset disabled><legend><input name='allowed' value='yes'></legend><input name='child' value='no'></fieldset><input name='own' disabled value='gone'><input name='space' value='a b!'><input name='tick' type='checkbox' checked><textarea name='lines'>one\ntwo</textarea></form>");
853
+ let form = tag(&arena, "form");
854
+ assert_eq!(
855
+ run(&mut arena, "serialize", json!({"ids":[form]})),
856
+ json!("allowed=yes&child=no&space=a+b!&tick=on&lines=one%0D%0Atwo")
857
+ );
858
+ }
859
+
860
+ #[test]
861
+ fn form_percent_encoding_uses_original_unicode_and_rejects_lone_surrogates() {
862
+ let mut arena = fixture("<form><input name='value'></form>");
863
+ arena.options["__utf16Codec"] = Value::Bool(true);
864
+ let form = tag(&arena, "form");
865
+ let input = tag(&arena, "input");
866
+ arena.set_attr(
867
+ &[input],
868
+ "value",
869
+ Some(&codec::from_units(&[0xe000, 0xd83d, 0xde00])),
870
+ );
871
+ assert_eq!(
872
+ run(&mut arena, "serialize", json!({"ids":[form]})),
873
+ json!("value=%EE%80%80%F0%9F%98%80")
874
+ );
875
+ arena.set_attr(&[input], "value", Some(&codec::from_units(&[0xd800])));
876
+ assert_eq!(
877
+ run(&mut arena, "serialize", json!({"ids":[form]})),
878
+ json!({"__nativeError":{"name":"URIError","message":"URI malformed"}})
879
+ );
880
+ assert_eq!(
881
+ run(&mut arena, "serializeArray", json!({"ids":[form]}))[0]["value"],
882
+ codec::from_units(&[0xd800])
883
+ );
884
+ }
885
+
886
+ #[test]
887
+ fn data_values_are_typed_cached_and_keep_canonical_number_rules() {
888
+ let mut arena = fixture("<div data-null='null' data-ok='true' data-number='23' data-sci='1E10' data-json='[1,2]'></div>");
889
+ let id = tag(&arena, "div");
890
+ assert_eq!(
891
+ run(&mut arena, "data", json!({"ids":[id],"name":"null"})),
892
+ json!({"found":true,"value":null})
893
+ );
894
+ assert_eq!(
895
+ run(&mut arena, "data", json!({"ids":[id],"name":"number"}))["value"],
896
+ json!(23.0)
897
+ );
898
+ arena.set_attr(&[id], "data-number", Some("99"));
899
+ let values = run(&mut arena, "data", json!({"ids":[id]}));
900
+ assert_eq!(values["value"]["number"], json!(23.0));
901
+ assert_eq!(values["value"]["sci"], json!("1E10"));
902
+ assert_eq!(values["value"]["json"], json!([1, 2]));
903
+ }
904
+
905
+ #[test]
906
+ fn styles_preserve_data_uri_semicolons_and_class_changes_preserve_whitespace() {
907
+ let mut arena = fixture("<div class='one\ttwo' style='background: url(data:image/png;base64,AAA); margin: 0;'></div>");
908
+ let id = tag(&arena, "div");
909
+ assert_eq!(
910
+ run(&mut arena, "css", json!({"ids":[id],"name":"background"})),
911
+ json!("url(data:image/png;base64,AAA)")
912
+ );
913
+ run(&mut arena, "addClass", json!({"ids":[id],"name":"three"}));
914
+ assert_eq!(arena.attr(id, "class"), Some("one\ttwo three"));
915
+ run(
916
+ &mut arena,
917
+ "css",
918
+ json!({"ids":[id],"name":"margin","value":""}),
919
+ );
920
+ assert_eq!(
921
+ arena.attr(id, "style"),
922
+ Some("background: url(data:image/png;base64,AAA);")
923
+ );
924
+ }
925
+
926
+ #[test]
927
+ fn properties_resolve_urls_and_boolean_attributes_stay_mode_specific() {
928
+ let mut arena = fixture("<a href='../result'>Result</a><input checked>");
929
+ let link = tag(&arena, "a");
930
+ let input = tag(&arena, "input");
931
+ assert_eq!(
932
+ run(&mut arena, "prop", json!({"ids":[link],"name":"href"})),
933
+ json!("https://example.com/result")
934
+ );
935
+ assert_eq!(
936
+ run(&mut arena, "prop", json!({"ids":[input],"name":"checked"})),
937
+ json!(true)
938
+ );
939
+ run(
940
+ &mut arena,
941
+ "prop",
942
+ json!({"ids":[input],"name":"checked","value":false}),
943
+ );
944
+ assert_eq!(arena.attr(input, "checked"), None);
945
+ }
946
+ }