oxml-wasm 0.0.11

WebAssembly bindings for oxml: XML parsing and XPath in the browser
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
// SPDX-License-Identifier: MIT OR Apache-2.0
// Copyright (c) 2026 oxml. All rights reserved.

//! The binding logic, free of `wasm-bindgen`.
//!
//! Everything the bindings actually *do* lives here, returning `String`
//! errors. `JsError` can only be constructed meaningfully against a
//! JavaScript runtime, so a test that had to build one could not run
//! under `cargo test` — keeping the logic on this side means the
//! behaviour is covered natively and the `#[wasm_bindgen]` layer above
//! is a one-line map per function, with nothing left in it to get wrong.

/// Parse a document, or describe why it is not well-formed.
///
/// # Errors
///
/// The message names the line and column, because it crosses into
/// JavaScript where a caller has no other way to locate the fault.
pub fn parse(source: &str) -> Result<oxml::Document, String> {
    oxml::parse_with(source, oxml::Limits::strict()).map_err(|e| {
        let (line, column) = e.line_column(source);
        format!("{line}:{column}: {e}")
    })
}

/// The local name of the root element, if there is one.
#[must_use]
pub fn root_name(doc: &oxml::Document) -> Option<String> {
    doc.root_element()
        .and_then(|r| doc.element_name(r))
        .map(|n| n.local.clone())
}

/// Bindings written as `PREFIX=URI`, the same spelling `oxml-cli`
/// takes for `--ns`, so the two are learned once.
///
/// From oxml 0.0.4 a prefix in an expression resolves against bindings
/// supplied with the query rather than against the document, and an
/// unbound prefix is an error. Without a way to pass them, `//m:item`
/// would have become unanswerable from JavaScript.
fn parse_bindings(namespaces: &[String]) -> Result<Vec<(&str, &str)>, String> {
    let mut out: Vec<(&str, &str)> = Vec::new();
    for entry in namespaces {
        let Some((prefix, uri)) = entry.split_once('=') else {
            return Err(format!(
                "`{entry}` is not a namespace binding; write PREFIX=URI"
            ));
        };
        if prefix.is_empty() {
            return Err("a namespace binding needs a prefix".to_owned());
        }
        if prefix == "xml" {
            return Err(
                "`xml` is bound by the specification and may not be rebound"
                    .to_owned(),
            );
        }
        // Later bindings win, so a caller can layer defaults.
        out.retain(|(p, _)| *p != prefix);
        out.push((prefix, uri));
    }
    Ok(out)
}

fn compile(
    expression: &str,
    namespaces: &[String],
) -> Result<oxml::XPath, String> {
    let bindings = parse_bindings(namespaces)?;
    // Expressions arrive from JavaScript, which may be running on
    // somebody else's input. `Limits::strict()` bounds nesting and
    // operator count so the worst case is an error, not a stack
    // overflow in the page.
    oxml::XPath::compile_with_namespaces_and_limits(
        expression,
        &bindings,
        &oxml::Limits::strict(),
    )
    .map_err(|e| e.to_string())
}

/// The text of every matched node.
///
/// # Errors
///
/// If the expression does not compile, or names a namespace prefix
/// that `namespaces` does not bind. An unbound prefix is an error
/// rather than a silent non-match: it would otherwise look like a
/// document that simply contains nothing.
pub fn query_text(
    doc: &oxml::Document,
    expression: &str,
    namespaces: &[String],
) -> Result<Vec<String>, String> {
    let value = evaluate(doc, expression, namespaces)?;
    let Some(nodes) = value.nodes() else {
        return Ok(vec![value.to_str(doc)]);
    };
    let mut remaining = oxml::xpath::EvalLimits::default().max_string_bytes;
    nodes
        .iter()
        .map(|node| crate::output::text(doc, *node, &mut remaining, false))
        .collect()
}

/// The expression's value as a string.
///
/// # Errors
///
/// As [`query_text`].
pub fn query_value(
    doc: &oxml::Document,
    expression: &str,
    namespaces: &[String],
) -> Result<String, String> {
    let value = evaluate(doc, expression, namespaces)?;
    let mut remaining = oxml::xpath::EvalLimits::default().max_string_bytes;
    if let Some(node) = value.nodes().and_then(|nodes| nodes.first()) {
        return crate::output::text(doc, *node, &mut remaining, true);
    }
    Ok(value.to_str(doc))
}

/// How many nodes an expression matches.
///
/// # Errors
///
/// As [`query_text`].
pub fn query_count(
    doc: &oxml::Document,
    expression: &str,
    namespaces: &[String],
) -> Result<usize, String> {
    Ok(evaluate(doc, expression, namespaces)?
        .nodes()
        .map_or(0, <[oxml::NodeId]>::len))
}

/// Whether a document is well-formed, without keeping it.
///
/// This parses and discards. Reading the document as events instead
/// would hold far less at once, and is *slower* -- about 1.9 times --
/// because an event owns its text where the tree keeps ranges into
/// the input. For an answer this small the tree is the cheaper route;
/// see `oxml`'s `stream` module for when it is not.
#[must_use]
pub fn is_well_formed(source: &str) -> bool {
    oxml::parse_with(source, oxml::Limits::strict()).is_ok()
}

fn evaluate(
    doc: &oxml::Document,
    expression: &str,
    namespaces: &[String],
) -> Result<oxml::xpath::Value, String> {
    let context = oxml::xpath::EvalContext::new()
        .with_limits(oxml::xpath::EvalLimits::default());
    compile(expression, namespaces)?
        .evaluate_with(doc, &context)
        .map_err(|e| e.to_string())
}

/// The document as XML.
///
/// The counterpart to [`parse`]. `oxml` gained serialisation in 0.0.8
/// and these bindings did not expose it, so a caller could read a
/// document but not write one back and had to reach for
/// `XMLSerializer`, holding two representations of the same thing.
///
/// Escaping is applied where it changes meaning rather than
/// everywhere: `&`, `<` and `>` in text, and additionally `"`, tab,
/// newline and carriage return inside attribute values, where an
/// unescaped newline would normalise to a space on the way back in
/// and the round trip would not be one.
#[must_use]
pub fn to_xml(doc: &oxml::Document) -> String {
    doc.to_xml()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn serialisation_is_a_fixed_point() {
        // Not byte-identical to the input: a document has more than
        // one valid spelling. The guarantee is that the output parses
        // to something that serialises the same way.
        let doc = parse(DOC).expect("well-formed");
        let once = to_xml(&doc);
        let twice = to_xml(&parse(&once).expect("the output parses"));
        assert_eq!(once, twice);
    }

    #[test]
    fn text_escaping_survives_the_round_trip() {
        // If `&` came back unescaped the second parse would read an
        // entity reference where the first read a character.
        let doc = parse("<a>p &amp; q</a>").expect("well-formed");
        let out = to_xml(&doc);
        assert!(out.contains("&amp;"), "{out}");
        let again = parse(&out).expect("reparses");
        assert_eq!(query_value(&again, "string(//a)", &[]).unwrap(), "p & q");
    }

    #[test]
    fn attribute_escaping_survives_the_round_trip() {
        // A `<` written literally in an attribute would make the
        // reparse see markup.
        let doc = parse(r#"<a note="x &lt; y"/>"#).expect("well-formed");
        let out = to_xml(&doc);
        assert!(out.contains("&lt;"), "{out}");
        let again = parse(&out).expect("reparses");
        assert_eq!(
            query_value(&again, "string(//a/@note)", &[]).unwrap(),
            "x < y"
        );
    }

    #[test]
    fn a_newline_in_an_attribute_is_escaped() {
        // An unescaped newline normalises to a space on the way back
        // in, so the round trip would silently change the value.
        let doc = parse("<a note=\"x&#10;y\"/>").expect("well-formed");
        let out = to_xml(&doc);
        let again = parse(&out).expect("reparses");
        assert_eq!(
            query_value(&again, "string(//a/@note)", &[]).unwrap(),
            "x\ny",
            "serialised as: {out}"
        );
    }

    #[test]
    fn namespaces_survive_the_round_trip() {
        let doc = parse(r#"<r xmlns:m="urn:x"><m:i>v</m:i></r>"#)
            .expect("well-formed");
        let out = to_xml(&doc);
        let again = parse(&out).expect("reparses");
        let ns = vec!["m=urn:x".to_owned()];
        assert_eq!(query_text(&again, "//m:i", &ns).unwrap(), ["v"]);
    }

    const DOC: &str = "<library count=\"2\">\
        <book lang=\"en\"><title>Dune</title></book>\
        <book lang=\"fr\"><title>Germinal</title></book>\
        </library>";

    fn doc() -> oxml::Document {
        parse(DOC).expect("well-formed")
    }

    #[test]
    fn parse_accepts_a_well_formed_document() {
        assert!(parse(DOC).is_ok());
        assert!(parse("<a/>").is_ok());
        assert!(parse("<?xml version=\"1.0\"?><a>é 😀</a>").is_ok());
    }

    #[test]
    fn a_parse_error_carries_a_position() {
        // In a browser this is the whole diagnostic the user sees, so
        // "failed" without a location would be useless.
        let e = parse("<a><b></a>").expect_err("not well-formed");
        assert!(e.contains(':'), "{e}");
        let (line, rest) = e.split_once(':').expect("line:column");
        assert!(line.parse::<u32>().is_ok(), "{e}");
        assert!(
            rest.split(':')
                .next()
                .and_then(|c| c.trim().parse::<u32>().ok())
                .is_some(),
            "{e}"
        );
    }

    #[test]
    fn root_name_reads_the_document_element() {
        assert_eq!(root_name(&doc()).as_deref(), Some("library"));
    }

    #[test]
    fn query_text_returns_one_entry_per_node() {
        let titles = query_text(&doc(), "//title", &[]).expect("valid");
        assert_eq!(titles, ["Dune", "Germinal"]);
    }

    #[test]
    fn query_text_on_a_non_node_set_returns_the_value() {
        // Not an error: JavaScript callers should not have to know
        // which expressions yield node-sets before calling.
        assert_eq!(
            query_text(&doc(), "count(//book)", &[]).expect("valid"),
            ["2"]
        );
    }

    #[test]
    fn query_text_reads_attributes() {
        assert_eq!(
            query_text(&doc(), "//book/@lang", &[]).expect("valid"),
            ["en", "fr"]
        );
    }

    #[test]
    fn query_value_formats_numbers_as_xpath_does() {
        let d = doc();
        assert_eq!(query_value(&d, "count(//book)", &[]).expect("valid"), "2");
        assert_eq!(query_value(&d, "1 div 4", &[]).expect("valid"), "0.25");
        assert_eq!(
            query_value(&d, "//book[1]/@lang", &[]).expect("valid"),
            "en"
        );
        assert_eq!(
            query_value(&d, "count(//book) = 2", &[]).expect("valid"),
            "true"
        );
    }

    #[test]
    fn query_count_counts_nodes_and_nothing_else() {
        let d = doc();
        assert_eq!(query_count(&d, "//book", &[]).expect("valid"), 2);
        assert_eq!(query_count(&d, "//missing", &[]).expect("valid"), 0);
        // A number is not a node-set; zero rather than an error.
        assert_eq!(query_count(&d, "count(//book)", &[]).expect("valid"), 0);
    }

    #[test]
    fn a_malformed_expression_is_an_error_on_every_entry_point() {
        let d = doc();
        for bad in ["//[", "count(", "1 +", "//book[", "@@x"] {
            assert!(query_text(&d, bad, &[]).is_err(), "query_text `{bad}`");
            assert!(query_value(&d, bad, &[]).is_err(), "query_value `{bad}`");
            assert!(query_count(&d, bad, &[]).is_err(), "query_count `{bad}`");
        }
    }

    #[test]
    fn is_well_formed_agrees_with_parse() {
        for src in [
            DOC,
            "<a/>",
            "<a><b/></a>",
            "<a><b></a>",
            "<a>",
            "",
            "not xml",
            "<a></a><b></b>",
        ] {
            assert_eq!(
                is_well_formed(src),
                parse(src).is_ok(),
                "disagreement on `{src}`"
            );
        }
    }
}

/// The README's JavaScript examples, checked against the logic they
/// describe.
///
/// The bindings layer is a one-line map per function, so anything the
/// README claims about behaviour is decidable here without a
/// WebAssembly toolchain. Two of its claims were wrong when written:
/// the error message carries a line and column *before* the library's
/// own byte offset, and `query_text` on an expression that is not a
/// node-set returns a one-element array rather than throwing.
#[cfg(test)]
mod readme {
    use super::*;

    const CATALOGUE: &str = r#"<catalogue>
        <book lang="en"><title>Dune</title><price>9.99</price></book>
        <book lang="fr"><title>Germinal</title><price>7.50</price></book>
    </catalogue>"#;

    #[test]
    fn the_quick_start_returns_what_the_readme_says() {
        let doc = parse(CATALOGUE).expect("well-formed");
        assert_eq!(root_name(&doc).as_deref(), Some("catalogue"));
        assert_eq!(
            query_text(&doc, "//title", &[]).expect("valid"),
            ["Dune", "Germinal"]
        );
        assert_eq!(query_count(&doc, "//book", &[]).expect("valid"), 2);
        assert_eq!(
            query_value(&doc, "sum(//price)", &[]).expect("valid"),
            "17.49"
        );
        assert!(!is_well_formed("<a>"));
    }

    #[test]
    fn query_text_on_a_non_node_set_returns_one_element() {
        // Not an error: the value is converted to a string and wrapped,
        // so a caller iterating the result still gets something useful.
        let doc = parse(CATALOGUE).expect("well-formed");
        assert_eq!(
            query_text(&doc, "count(//book)", &[]).expect("valid"),
            ["2"]
        );
        assert_eq!(query_count(&doc, "count(//book)", &[]).expect("valid"), 0);
    }

    #[test]
    fn a_parse_error_leads_with_line_and_column() {
        let message = parse("<a></b>").expect_err("mismatched tags");
        assert!(
            message.starts_with("1:4: "),
            "the README shows a leading line:column -- got {message:?}"
        );
        assert!(message.contains("</b> closes <a>"), "{message}");
    }

    #[test]
    fn an_invalid_expression_fails_at_query_time_not_parse_time() {
        let doc = parse(CATALOGUE).expect("well-formed");
        assert!(query_value(&doc, "//[", &[]).is_err());
        assert!(query_text(&doc, "//[", &[]).is_err());
        assert!(query_count(&doc, "//[", &[]).is_err());
    }
}

/// Namespace bindings, which arrive as `PREFIX=URI` strings.
#[cfg(test)]
mod bindings {
    use super::{parse, parse_bindings, query_count, query_text};

    const NS: &str =
        r#"<r xmlns:m="urn:u"><m:item>ns</m:item><item>plain</item></r>"#;

    #[test]
    fn a_bound_prefix_selects_only_that_namespace() {
        let doc = parse(NS).expect("well-formed");
        let bound = [String::from("m=urn:u")];
        assert_eq!(
            query_text(&doc, "//m:item", &bound).expect("valid"),
            ["ns"]
        );
    }

    #[test]
    fn only_the_uri_matters_never_the_prefix() {
        // The expression may spell the prefix differently from the
        // document, which is why bindings belong to the query.
        let doc = parse(NS).expect("well-formed");
        let bound = [String::from("q=urn:u")];
        assert_eq!(
            query_text(&doc, "//q:item", &bound).expect("valid"),
            ["ns"]
        );
    }

    #[test]
    fn an_unprefixed_name_matches_no_namespace_only() {
        let doc = parse(NS).expect("well-formed");
        assert_eq!(query_text(&doc, "//item", &[]).expect("valid"), ["plain"]);
    }

    #[test]
    fn an_unbound_prefix_is_an_error() {
        let doc = parse(NS).expect("well-formed");
        assert!(query_count(&doc, "//m:item", &[]).is_err());
    }

    #[test]
    fn later_bindings_win() {
        let entries = [String::from("a=urn:one"), String::from("a=urn:two")];
        let got = parse_bindings(&entries).expect("valid");
        assert_eq!(got, vec![("a", "urn:two")]);
    }

    #[test]
    fn a_malformed_binding_is_rejected() {
        for bad in ["bogus", "=urn:u", "xml=urn:u"] {
            let entries = [bad.to_owned()];
            assert!(
                parse_bindings(&entries).is_err(),
                "{bad} should be rejected"
            );
        }
    }

    #[test]
    fn a_uri_may_contain_an_equals_sign() {
        let entries = [String::from("m=urn:u?a=b")];
        let got = parse_bindings(&entries).expect("valid");
        assert_eq!(got[0].1, "urn:u?a=b");
    }
}