oxirs-wasm 0.2.4

WebAssembly bindings for OxiRS - Run RDF/SPARQL 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
//! JSON-LD output format for OxiRS WASM
//!
//! Converts an RDF graph into JSON-LD compact form.
//!
//! Supports:
//! - `@context` with namespace prefix bindings
//! - `@id` for subject IRIs
//! - `@type` for `rdf:type` predicate
//! - `@language` for lang-tagged literals
//! - `@value` / `@type` for typed literals
//! - Grouping: multiple triples with the same subject are merged into one JSON object
//! - Array values when a property has multiple objects

use crate::store::{InternalTriple, OxiRSStore};
use std::collections::HashMap;

/// The rdf:type IRI
const RDF_TYPE: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";

/// Standard namespace prefixes included in every @context
static DEFAULT_PREFIXES: &[(&str, &str)] = &[
    ("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"),
    ("rdfs", "http://www.w3.org/2000/01/rdf-schema#"),
    ("xsd", "http://www.w3.org/2001/XMLSchema#"),
    ("owl", "http://www.w3.org/2002/07/owl#"),
    ("schema", "https://schema.org/"),
    ("foaf", "http://xmlns.com/foaf/0.1/"),
    ("dc", "http://purl.org/dc/elements/1.1/"),
    ("dcterms", "http://purl.org/dc/terms/"),
];

// -----------------------------------------------------------------------
// Public API
// -----------------------------------------------------------------------

/// Serialize all triples in the store to a JSON-LD document string.
///
/// The output is a compact JSON-LD document with:
/// - `@context` containing standard namespace prefix bindings
/// - `@graph` array of subject-grouped RDF objects
///
/// # Example output
/// ```json
/// {
///   "@context": { "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#", ... },
///   "@graph": [
///     {
///       "@id": "http://example.org/alice",
///       "http://example.org/name": [{"@value": "Alice"}],
///       "http://example.org/knows": [{"@id": "http://example.org/bob"}]
///     }
///   ]
/// }
/// ```
pub fn serialize_jsonld(store: &OxiRSStore) -> String {
    let triples: Vec<&InternalTriple> = store.all_triples().collect();
    serialize_triples_jsonld(&triples, &[])
}

/// Serialize with additional custom prefix bindings.
///
/// `extra_prefixes` is a slice of `("prefix", "IRI")` pairs.
pub fn serialize_jsonld_with_prefixes(
    store: &OxiRSStore,
    extra_prefixes: &[(&str, &str)],
) -> String {
    let triples: Vec<&InternalTriple> = store.all_triples().collect();
    serialize_triples_jsonld(&triples, extra_prefixes)
}

/// Core serialization: given a list of triples, produce JSON-LD text.
pub(crate) fn serialize_triples_jsonld(
    triples: &[&InternalTriple],
    extra_prefixes: &[(&str, &str)],
) -> String {
    // Build prefix map
    let mut prefixes: HashMap<String, String> = DEFAULT_PREFIXES
        .iter()
        .map(|(k, v)| (k.to_string(), v.to_string()))
        .collect();
    for (k, v) in extra_prefixes {
        prefixes.insert(k.to_string(), v.to_string());
    }

    // Group triples by subject
    let mut subject_map: HashMap<String, Vec<&InternalTriple>> = HashMap::new();
    let mut subject_order: Vec<String> = Vec::new();
    for triple in triples {
        let entry = subject_map
            .entry(triple.subject.clone())
            .or_insert_with(|| {
                subject_order.push(triple.subject.clone());
                Vec::new()
            });
        entry.push(triple);
    }

    // Build @context
    let context_str = build_context(&prefixes);

    // Build @graph
    let mut graph_items: Vec<String> = Vec::new();
    for subject in &subject_order {
        if let Some(group) = subject_map.get(subject) {
            let item = build_subject_object(subject, group, &prefixes);
            graph_items.push(item);
        }
    }

    if graph_items.is_empty() {
        format!("{{\n  \"@context\": {context_str},\n  \"@graph\": []\n}}")
    } else {
        let graph_str = graph_items.join(",\n    ");
        format!("{{\n  \"@context\": {context_str},\n  \"@graph\": [\n    {graph_str}\n  ]\n}}")
    }
}

// -----------------------------------------------------------------------
// Helpers
// -----------------------------------------------------------------------

/// Build the `@context` JSON object string
fn build_context(prefixes: &HashMap<String, String>) -> String {
    let mut pairs: Vec<String> = prefixes
        .iter()
        .map(|(k, v)| format!("    \"{k}\": \"{v}\""))
        .collect();
    pairs.sort(); // deterministic output
    format!("{{\n{}\n  }}", pairs.join(",\n"))
}

/// Build a single JSON-LD object for a subject and its predicate-object pairs
fn build_subject_object(
    subject: &str,
    triples: &[&InternalTriple],
    prefixes: &HashMap<String, String>,
) -> String {
    let id = compact_iri(subject, prefixes);
    let mut props: HashMap<String, Vec<String>> = HashMap::new();
    let mut prop_order: Vec<String> = Vec::new();

    for triple in triples {
        let pred_compact = compact_iri(&triple.predicate, prefixes);
        let obj_json = object_to_json(&triple.object, prefixes);

        let entry = props.entry(pred_compact.clone()).or_insert_with(|| {
            prop_order.push(pred_compact);
            Vec::new()
        });
        entry.push(obj_json);
    }

    let mut lines: Vec<String> = Vec::new();
    lines.push(format!("\"@id\": \"{id}\""));

    for key in &prop_order {
        if let Some(values) = props.get(key) {
            // rdf:type uses @type shorthand
            let json_key = if key == "rdf:type" || key == "a" || key == RDF_TYPE {
                "@type".to_string()
            } else {
                key.clone()
            };

            if values.len() == 1 {
                lines.push(format!("\"{json_key}\": {}", values[0]));
            } else {
                let arr = values.join(", ");
                lines.push(format!("\"{json_key}\": [{arr}]"));
            }
        }
    }

    let inner = lines.join(",\n      ");
    format!("{{\n      {inner}\n    }}")
}

/// Convert an RDF term to a compact IRI using prefix bindings
pub(crate) fn compact_iri(iri: &str, prefixes: &HashMap<String, String>) -> String {
    // Try each prefix
    for (prefix, base) in prefixes {
        if let Some(local) = iri.strip_prefix(base.as_str()) {
            if !local.is_empty() && !local.contains('/') && !local.contains('#') {
                return format!("{prefix}:{local}");
            }
        }
    }
    // No prefix matched — return as-is
    iri.to_string()
}

/// Convert an RDF object term to JSON-LD value notation
pub(crate) fn object_to_json(term: &str, prefixes: &HashMap<String, String>) -> String {
    if term.starts_with('"') {
        // Literal: "value", "value"@lang, or "value"^^<datatype>
        parse_literal_to_json(term)
    } else if let Some(id) = term.strip_prefix("_:") {
        // Blank node
        format!("{{\"@id\": \"_:{id}\"}}")
    } else {
        // IRI
        let compact = compact_iri(term, prefixes);
        format!("{{\"@id\": \"{compact}\"}}")
    }
}

/// Parse a literal RDF term and produce JSON-LD value notation
fn parse_literal_to_json(term: &str) -> String {
    // Find the closing quote
    let chars: Vec<char> = term.chars().collect();
    let mut pos = 1usize;
    while pos < chars.len() && chars[pos] != '"' {
        if chars[pos] == '\\' {
            pos += 1; // skip escape char
        }
        pos += 1;
    }

    let value: String = chars[1..pos].iter().collect();
    let value_escaped = escape_json_string(&value);

    if pos + 1 >= chars.len() {
        // Plain literal with no annotation
        return format!("{{\"@value\": \"{value_escaped}\"}}");
    }

    let rest: String = chars[pos + 1..].iter().collect();

    if let Some(lang) = rest.strip_prefix('@') {
        // Language-tagged literal
        format!("{{\"@value\": \"{value_escaped}\", \"@language\": \"{lang}\"}}")
    } else if let Some(dt_raw) = rest.strip_prefix("^^") {
        // Typed literal
        let datatype = if dt_raw.starts_with('<') && dt_raw.ends_with('>') {
            dt_raw[1..dt_raw.len() - 1].to_string()
        } else {
            dt_raw.to_string()
        };
        // Use compact datatype IRI for well-known types
        let short_dt = compact_xsd_type(&datatype);
        format!("{{\"@value\": \"{value_escaped}\", \"@type\": \"{short_dt}\"}}")
    } else {
        format!("{{\"@value\": \"{value_escaped}\"}}")
    }
}

/// Compact XSD datatypes to short form
fn compact_xsd_type(datatype: &str) -> String {
    let xsd = "http://www.w3.org/2001/XMLSchema#";
    if let Some(local) = datatype.strip_prefix(xsd) {
        format!("xsd:{local}")
    } else {
        datatype.to_string()
    }
}

/// Escape special JSON characters in a string
fn escape_json_string(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '"' => result.push_str("\\\""),
            '\\' => result.push_str("\\\\"),
            '\n' => result.push_str("\\n"),
            '\r' => result.push_str("\\r"),
            '\t' => result.push_str("\\t"),
            c => result.push(c),
        }
    }
    result
}

// -----------------------------------------------------------------------
// Tests
// -----------------------------------------------------------------------

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

    fn make_store() -> OxiRSStore {
        let mut store = OxiRSStore::new();
        store.insert(
            "http://example.org/alice",
            "http://example.org/name",
            "\"Alice\"",
        );
        store.insert(
            "http://example.org/alice",
            "http://example.org/knows",
            "http://example.org/bob",
        );
        store.insert(
            "http://example.org/bob",
            "http://example.org/name",
            "\"Bob\"",
        );
        store
    }

    #[test]
    fn test_jsonld_contains_context() {
        let store = make_store();
        let output = serialize_jsonld(&store);
        assert!(output.contains("\"@context\""));
        assert!(output.contains("\"rdf\""));
    }

    #[test]
    fn test_jsonld_contains_graph() {
        let store = make_store();
        let output = serialize_jsonld(&store);
        assert!(output.contains("\"@graph\""));
    }

    #[test]
    fn test_jsonld_contains_subject_ids() {
        let store = make_store();
        let output = serialize_jsonld(&store);
        assert!(output.contains("alice"));
        assert!(output.contains("bob"));
    }

    #[test]
    fn test_jsonld_literal_value() {
        let store = make_store();
        let output = serialize_jsonld(&store);
        assert!(output.contains("\"@value\""));
        assert!(output.contains("Alice"));
    }

    #[test]
    fn test_jsonld_iri_object() {
        let store = make_store();
        let output = serialize_jsonld(&store);
        assert!(output.contains("\"@id\""));
    }

    #[test]
    fn test_jsonld_lang_literal() {
        let mut store = OxiRSStore::new();
        store.insert(
            "http://example.org/s",
            "http://example.org/p",
            "\"hello\"@en",
        );
        let output = serialize_jsonld(&store);
        assert!(output.contains("\"@language\""));
        assert!(output.contains("\"en\""));
    }

    #[test]
    fn test_jsonld_typed_literal() {
        let mut store = OxiRSStore::new();
        store.insert(
            "http://example.org/s",
            "http://example.org/age",
            "\"42\"^^<http://www.w3.org/2001/XMLSchema#integer>",
        );
        let output = serialize_jsonld(&store);
        assert!(output.contains("\"@type\""));
        assert!(output.contains("xsd:integer"));
    }

    #[test]
    fn test_jsonld_empty_store() {
        let store = OxiRSStore::new();
        let output = serialize_jsonld(&store);
        assert!(output.contains("\"@graph\""));
        assert!(output.contains("[]"));
    }

    #[test]
    fn test_jsonld_with_rdf_type() {
        let mut store = OxiRSStore::new();
        store.insert(
            "http://example.org/alice",
            "http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
            "http://xmlns.com/foaf/0.1/Person",
        );
        let output = serialize_jsonld(&store);
        assert!(output.contains("@type") || output.contains("rdf:type"));
    }

    #[test]
    fn test_jsonld_blank_node() {
        let mut store = OxiRSStore::new();
        store.insert("http://example.org/s", "http://example.org/p", "_:b0");
        let output = serialize_jsonld(&store);
        assert!(output.contains("_:b0") || output.contains("b0"));
    }

    #[test]
    fn test_jsonld_with_custom_prefixes() {
        let mut store = OxiRSStore::new();
        store.insert(
            "http://example.org/alice",
            "http://example.org/name",
            "\"Alice\"",
        );
        let output = serialize_jsonld_with_prefixes(&store, &[("ex", "http://example.org/")]);
        assert!(output.contains("\"ex\""));
    }

    #[test]
    fn test_compact_iri_standard_prefix() {
        let mut prefixes = HashMap::new();
        prefixes.insert("ex".to_string(), "http://example.org/".to_string());
        let compact = compact_iri("http://example.org/alice", &prefixes);
        assert_eq!(compact, "ex:alice");
    }

    #[test]
    fn test_compact_iri_no_match() {
        let prefixes = HashMap::new();
        let compact = compact_iri("http://unknown.org/foo", &prefixes);
        assert_eq!(compact, "http://unknown.org/foo");
    }

    #[test]
    fn test_escape_json_string() {
        let s = "Hello \"World\"\nTab\there";
        let escaped = escape_json_string(s);
        assert!(escaped.contains("\\\""));
        assert!(escaped.contains("\\n"));
        assert!(escaped.contains("\\t"));
    }

    #[test]
    fn test_jsonld_valid_json_structure() {
        let store = make_store();
        let output = serialize_jsonld(&store);
        // Basic JSON structure checks
        assert!(output.starts_with('{'));
        assert!(output.ends_with('}'));
        assert!(output.contains("@context"));
        assert!(output.contains("@graph"));
    }

    #[test]
    fn test_jsonld_multiple_objects_same_predicate() {
        let mut store = OxiRSStore::new();
        store.insert(
            "http://example.org/alice",
            "http://example.org/knows",
            "http://example.org/bob",
        );
        store.insert(
            "http://example.org/alice",
            "http://example.org/knows",
            "http://example.org/carol",
        );
        let output = serialize_jsonld(&store);
        // Both bob and carol should appear
        assert!(output.contains("bob"));
        assert!(output.contains("carol"));
    }
}