jsonld-compaction 0.23.0

JSON-LD document compaction implementation
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
use crate::{Error, Options, add_value, compact_iri, compact_property, iri::keyword_alias};
use contextual::WithContext;
use jsonld_context_processing::{Options as ProcessingOptions, Process, ProcessingMode};
use jsonld_core::{Container, ContainerKind, Context, ContextRef, Id, Loader, Node, Term, Type};
use jsonld_syntax::Keyword;
use rdfx::vocabulary::VocabularyMut;
use std::hash::Hash;

/// Turns an optional string into a JSON string, or JSON `null` when absent.
///
/// IRI compaction returns `None` for a null term, which the specification
/// requires to be written out as `null` rather than omitted.
fn optional_string(s: Option<&str>) -> jstrict::Value {
    s.map_or(jstrict::Value::Null, |s| jstrict::Value::String(s.into()))
}

/// Compacts a node object, following the [compaction algorithm][1]'s node
/// object case.
///
/// Emits `@id`, `@type`, `@reverse`, `@index`, `@graph`, `@included` and every
/// ordinary property into a single JSON object, keyed by whatever each expanded
/// property compacts to. `index` is the `@index` the node was reached through,
/// and is dropped when the active property's container mapping already turned it
/// into a map key.
///
/// A node object consisting of nothing but an `@id` may compact to a bare
/// string instead of an object, when the active property's type mapping is `@id`
/// or `@vocab`.
///
/// [1]: https://www.w3.org/TR/json-ld-api/#compaction-algorithm
pub async fn compact_indexed_node_with<N, L>(
    vocabulary: &mut N,
    node: &Node<N::Iri, N::BlankId>,
    index: Option<&str>,
    mut active_context: &Context<N::Iri, N::BlankId>,
    type_scoped_context: &Context<N::Iri, N::BlankId>,
    active_property: Option<&str>,
    loader: &L,
    options: Options,
) -> Result<jstrict::Value, Error<L::Error>>
where
    N: VocabularyMut,
    N::Iri: Clone + Hash + Eq,
    N::BlankId: Clone + Hash + Eq,
    L: Loader,
{
    // If active context has a previous context, the active context is not propagated.
    // If element does not contain an @value entry, and element does not consist of
    // a single @id entry, set active context to previous context from active context,
    // as the scope of a term-scoped context does not apply when processing new node objects.
    if !(node.is_empty() && node.id.is_some()) {
        // does not consist of a single @id entry
        if let Some(previous_context) = active_context.previous_context() {
            active_context = previous_context;
        }
    }

    // If the term definition for active property in active context has a local context:
    //
    // Known deviation from the specification text, which says to look the term
    // definition up in the active context. This looks it up in
    // `type_scoped_context` instead, which is what makes the W3C compaction test
    // suite pass; the spec text is believed to be in error. See
    // https://github.com/w3c/json-ld-api/issues/502.
    let mut active_context = ContextRef::Borrowed(active_context);
    if let Some(active_property) = active_property
        && let Some(active_property_definition) = type_scoped_context.get(active_property)
        && let Some(local_context) = active_property_definition.context()
    {
        active_context = ContextRef::owned(
            local_context
                .process_with(
                    vocabulary,
                    active_context.as_ref(),
                    loader,
                    active_property_definition.base_url().cloned(),
                    ProcessingOptions::from(options).with_override(),
                )
                .await?
                .into_processed(),
        );
    }

    let mut result = jstrict::Object::default();

    if !node.types().is_empty() {
        // If element has an @type entry, create a new array compacted types initialized by
        // transforming each expanded type of that entry into its compacted form by IRI
        // compacting expanded type. Then, for each term in compacted types ordered
        // lexicographically:
        let mut compacted_types = Vec::new();
        for ty in node.types() {
            let compacted_ty = compact_iri(vocabulary, type_scoped_context, &ty.clone().into_term(), true, false, options)?;
            compacted_types.push(compacted_ty);
        }

        compacted_types.sort_by(|a, b| a.as_deref().cmp(&b.as_deref()));

        for term in compacted_types.iter().flatten() {
            if let Some(term_definition) = type_scoped_context.get(&**term)
                && let Some(local_context) = term_definition.context()
            {
                let processing_options = ProcessingOptions::from(options).without_propagation();
                active_context = ContextRef::owned(
                    local_context
                        .process_with(
                            vocabulary,
                            active_context.as_ref(),
                            loader,
                            term_definition.base_url().cloned(),
                            processing_options,
                        )
                        .await?
                        .into_processed(),
                );
            }
        }
    }

    // For each key expanded property and value expanded value in element, ordered
    // lexicographically by expanded property if ordered is true:
    let expanded_entries: Vec<_> = if options.ordered {
        // Decorate-sort-undecorate: cache `as_str()` so the comparator does
        // not call `with(vocabulary).as_str()` O(P log P) times. The cached
        // `&str` borrows from `entry.0` (which lives in `node.properties()`)
        // and `vocabulary`, both of which outlive `decorated`, so we avoid
        // the per-entry `to_string()` allocation.
        let vocabulary: &N = vocabulary;
        let mut decorated: Vec<(&str, _)> = node.properties().iter().map(|entry| (entry.0.with(vocabulary).as_str(), entry)).collect();
        decorated.sort_by(|a, b| a.0.cmp(b.0));
        decorated.into_iter().map(|(_, entry)| entry).collect()
    } else {
        node.properties().iter().collect()
    };

    // If expanded property is @id:
    if let Some(id_entry) = &node.id {
        let id = id_entry.clone().into_term();

        if node.is_empty() {
            // This covers step 7 of the compaction algorithm:
            // If element has an @value or @id entry and the result of using the
            // Value Compaction algorithm, passing active context, active property,
            // and element as value is a scalar, or the term definition for active property
            // has a type mapping of @json, return that result.
            //
            // together with step 7 of the value compaction algorithm:
            // If value has an @id entry and has no other entries other than @index:
            //
            // If the type mapping of active property is set to @id,
            // set result to the result of IRI compacting the value associated with the
            // @id entry using false for vocab.
            let type_mapping = match active_property {
                Some(prop) => match active_context.get(prop) {
                    Some(def) => def.typ(),
                    None => None,
                },
                None => None,
            };

            if type_mapping == Some(&Type::Id) {
                let compacted_value = compact_iri(vocabulary, active_context.as_ref(), &id, false, false, options)?;
                return Ok(optional_string(compacted_value.as_deref()));
            }

            // Otherwise, if the type mapping of active property is set to @vocab,
            // set result to the result of IRI compacting the value associated with the @id entry.
            if type_mapping == Some(&Type::Vocab) {
                let compacted_value = compact_iri(vocabulary, active_context.as_ref(), &id, true, false, options)?;
                return Ok(optional_string(compacted_value.as_deref()));
            }
        }

        // If expanded value is a string, then initialize compacted value by IRI
        // compacting expanded value with vocab set to false.
        let compacted_value = compact_iri(vocabulary, active_context.as_ref(), &id, false, false, options)?;

        // Initialize alias by IRI compacting expanded property.
        let alias = keyword_alias(vocabulary, active_context.as_ref(), options, Keyword::Id);
        result.insert(alias.into(), optional_string(compacted_value.as_deref()));
    }

    compact_types(
        vocabulary,
        &mut result,
        node.types.as_deref(),
        active_context.as_ref(),
        type_scoped_context,
        options,
    )?;

    // If expanded property is @reverse:
    if let Some(reverse_properties) = node.reverse_properties_entry()
        && !reverse_properties.is_empty()
    {
        // Initialize compacted value to the result of using this algorithm recursively,
        // passing active context, @reverse for active property,
        // expanded value for element, and the compactArrays and ordered flags.
        let active_property = "@reverse";
        if let Some(active_property_definition) = active_context.get(active_property)
            && let Some(local_context) = active_property_definition.context()
        {
            active_context = ContextRef::owned(
                local_context
                    .process_with(
                        vocabulary,
                        active_context.as_ref(),
                        loader,
                        active_property_definition.base_url().cloned(),
                        ProcessingOptions::from(options).with_override(),
                    )
                    .await?
                    .into_processed(),
            );
        }

        // Every property compacts into one shared object, deliberately. Giving
        // each property its own object and merging afterwards — the obvious way
        // to make these iterations independent of one another — does not
        // reproduce the same output: `add_value` cannot merge the fragments
        // that `compact_property` produces for `@nest` sub-objects, for
        // `@index`/`@id`/`@type`/`@language` container maps, or for graph
        // fragments, because those are objects that have to be merged key by
        // key rather than appended. Doing it correctly would mean either
        // restructuring `compact_property` to emit a flat log of insertions, or
        // consulting the active context per key to decide between a recursive
        // merge and `add_value`.
        let mut reverse_result = jstrict::Object::default();
        for (expanded_property, expanded_value) in reverse_properties {
            compact_property(
                vocabulary,
                &mut reverse_result,
                expanded_property.clone().into(),
                expanded_value.iter(),
                active_context.as_ref(),
                loader,
                true,
                options,
            )
            .await?;
        }

        // For each property and value in compacted value:
        let mut reverse_map = jstrict::Object::default();
        for (property, mapped_value) in &mut reverse_result {
            let mut value = jstrict::Value::Null;
            std::mem::swap(&mut value, &mut *mapped_value);

            // If the term definition for property in the active context indicates that
            // property is a reverse property
            if let Some(term_definition) = active_context.get(property.as_str())
                && term_definition.reverse_property()
            {
                // Initialize as array to true if the container mapping for property in
                // the active context includes @set, otherwise the negation of compactArrays.
                let as_array = term_definition.container().contains(ContainerKind::Set) || !options.compact_arrays;

                // Use add value to add value to the property entry in result using as array.
                add_value(&mut result, property, value, as_array);
                continue;
            }

            reverse_map.insert(property.clone(), value);
        }

        if !reverse_map.is_empty() {
            // Initialize alias by IRI compacting @reverse.
            let alias = keyword_alias(vocabulary, active_context.as_ref(), options, Keyword::Reverse);

            // Set the value of the alias entry of result to compacted value.
            result.insert(alias.into(), reverse_map.into());
        }
    }

    // If expanded property is @index and active property has a container mapping in
    // active context that includes @index,
    if let Some(index_entry) = index {
        let mut index_container = false;
        if let Some(active_property) = active_property
            && let Some(active_property_definition) = active_context.get(active_property)
            && active_property_definition.container().contains(ContainerKind::Index)
        {
            // then the compacted result will be inside of an @index container,
            // drop the @index entry by continuing to the next expanded property.
            index_container = true;
        }

        if !index_container {
            // Initialize alias by IRI compacting expanded property.
            let alias = keyword_alias(vocabulary, active_context.as_ref(), options, Keyword::Index);

            // Add an entry alias to result whose value is set to expanded value and continue with the next expanded property.
            result.insert(alias.into(), index_entry.into());
        }
    }

    if let Some(graph_entry) = node.graph_entry() {
        compact_property(
            vocabulary,
            &mut result,
            Term::Keyword(Keyword::Graph),
            graph_entry.iter(),
            active_context.as_ref(),
            loader,
            false,
            options,
        )
        .await?;
    }

    for (expanded_property, expanded_value) in expanded_entries {
        compact_property(
            vocabulary,
            &mut result,
            expanded_property.clone().into(),
            expanded_value.iter(),
            active_context.as_ref(),
            loader,
            false,
            options,
        )
        .await?;
    }

    if let Some(included_entry) = node.included_entry() {
        compact_property(
            vocabulary,
            &mut result,
            Term::Keyword(Keyword::Included),
            included_entry.iter(),
            active_context.as_ref(),
            loader,
            false,
            options,
        )
        .await?;
    }

    Ok(result.into())
}

/// Compacts a node object's `@type` values and inserts them into `result` under
/// whatever `@type` itself compacts to.
///
/// Each type is compacted against `type_scoped_context`, as the specification
/// requires, while the key for `@type` comes from `active_context`. A single type
/// becomes a bare string unless the term for `@type` has an `@set` container (in
/// JSON-LD 1.1) or `compact_arrays` is off.
fn compact_types<N, E>(
    vocabulary: &mut N,
    result: &mut jstrict::Object,
    types: Option<&[Id<N::Iri, N::BlankId>]>,
    active_context: &Context<N::Iri, N::BlankId>,
    type_scoped_context: &Context<N::Iri, N::BlankId>,
    options: Options,
) -> Result<(), Error<E>>
where
    N: VocabularyMut,
    N::Iri: Clone + Hash + Eq,
    N::BlankId: Clone + Hash + Eq,
{
    // If expanded property is @type:
    if let Some(types) = types
        && !types.is_empty()
    {
        // If expanded value is a string,
        // then initialize compacted value by IRI compacting expanded value using
        // type-scoped context for active context.
        let compacted_value = if types.len() == 1 {
            let arc = compact_iri(vocabulary, type_scoped_context, &types[0].clone().into_term(), true, false, options)?;
            optional_string(arc.as_deref())
        } else {
            // Otherwise, expanded value must be a @type array:
            // Initialize compacted value to an empty array.
            let mut compacted_value = Vec::with_capacity(types.len());

            // For each item expanded type in expanded value:
            for ty in types {
                let ty = ty.clone().into_term();

                // Set term by IRI compacting expanded type using type-scoped context for active context.
                let compacted_ty = compact_iri(vocabulary, type_scoped_context, &ty, true, false, options)?;

                // Append term, to compacted value.
                compacted_value.push(optional_string(compacted_ty.as_deref()));
            }

            jstrict::Value::Array(compacted_value.into_iter().collect())
        };

        // Initialize alias by IRI compacting expanded property.
        let alias = keyword_alias(vocabulary, active_context, options, Keyword::Type);

        // Initialize as array to true if processing mode is json-ld-1.1 and the
        // container mapping for alias in the active context includes @set,
        // otherwise to the negation of compactArrays.
        let container_mapping = match active_context.get(alias) {
            Some(def) => def.container(),
            None => Container::None,
        };
        let as_array = (options.processing_mode == ProcessingMode::JsonLd1_1 && container_mapping.contains(ContainerKind::Set)) || !options.compact_arrays;

        // Use add value to add compacted value to the alias entry in result using as array.
        add_value(result, alias, compacted_value, as_array);
    }

    Ok(())
}