1use crate::error::{JsonLdError, Result};
6use json_syntax::Value;
7use oxrdf::{GraphName, NamedNode};
8use sha2::{Digest, Sha256};
9use std::collections::BTreeMap;
10use std::fmt::Write;
11use std::sync::Arc;
12
13pub const CONTENT_HASH_PREFIX: &str = "urn:oxilite:doc:sha256:";
15
16#[derive(Debug, Clone, PartialEq, Eq, Default)]
18pub enum KeyStrategy {
19 #[default]
21 Id,
22 Pointer(String),
24 ContentHash,
26 Explicit,
28}
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
32pub enum MissingKey {
33 #[default]
35 Reject,
36 ContentHash,
38}
39
40#[derive(Debug, Clone, PartialEq, Eq, Default)]
42pub enum GraphStrategy {
43 #[default]
45 Key,
46 Template(String),
48 Fixed(NamedNode),
50 DefaultGraph,
52}
53
54impl GraphStrategy {
55 pub fn owns_target(&self) -> bool {
57 matches!(self, Self::Key | Self::Template(_))
58 }
59}
60
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub enum RdfDirection {
64 I18nDatatype,
66 CompoundLiteral,
68}
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
72pub enum ProcessingMode {
73 JsonLd10,
75 #[default]
77 JsonLd11,
78}
79
80pub type ContextFetcher = Arc<dyn Fn(&str) -> Result<String> + Send + Sync>;
82
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub struct MetadataIndexes {
86 pub issuer: bool,
87 pub subject: bool,
88 pub valid_until: bool,
89}
90
91impl Default for MetadataIndexes {
92 fn default() -> Self {
93 Self {
94 issuer: true,
95 subject: true,
96 valid_until: true,
97 }
98 }
99}
100
101impl MetadataIndexes {
102 pub fn none() -> Self {
104 Self {
105 issuer: false,
106 subject: false,
107 valid_until: false,
108 }
109 }
110}
111
112#[derive(Clone, Default)]
114pub struct JsonLdOptions {
115 pub key: KeyStrategy,
116 pub on_missing_key: MissingKey,
117 pub graph: GraphStrategy,
118 pub base_iri: Option<String>,
120 pub rdf_direction: Option<RdfDirection>,
121 pub processing_mode: ProcessingMode,
122 pub contexts: BTreeMap<String, String>,
124 pub fetcher: Option<ContextFetcher>,
126 pub cache_fetched: bool,
128 pub indexes: MetadataIndexes,
130}
131
132impl std::fmt::Debug for JsonLdOptions {
133 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
134 f.debug_struct("JsonLdOptions")
135 .field("key", &self.key)
136 .field("on_missing_key", &self.on_missing_key)
137 .field("graph", &self.graph)
138 .field("base_iri", &self.base_iri)
139 .field("rdf_direction", &self.rdf_direction)
140 .field("processing_mode", &self.processing_mode)
141 .field("contexts", &self.contexts.keys().collect::<Vec<_>>())
142 .field("fetcher", &self.fetcher.is_some())
143 .field("cache_fetched", &self.cache_fetched)
144 .field("indexes", &self.indexes)
145 .finish()
146 }
147}
148
149impl JsonLdOptions {
150 pub fn with_context(mut self, iri: impl Into<String>, json: impl Into<String>) -> Self {
152 self.contexts.insert(iri.into(), json.into());
153 self
154 }
155
156 pub fn key_for(&self, raw: &str, doc: &Value, explicit: Option<&str>) -> Result<String> {
158 if let Some(k) = explicit {
159 return Ok(k.to_owned());
160 }
161 let found = match &self.key {
162 KeyStrategy::Id => top_level_id(doc),
163 KeyStrategy::Pointer(p) => pointer(doc, p).and_then(|v| v.as_str().map(str::to_owned)),
164 KeyStrategy::ContentHash => return Ok(content_hash_key(raw)),
165 KeyStrategy::Explicit => None,
166 };
167 match found {
168 Some(k) if !k.is_empty() => Ok(k),
169 _ => match self.on_missing_key {
170 MissingKey::ContentHash => Ok(content_hash_key(raw)),
171 MissingKey::Reject => Err(JsonLdError::MissingKey(match &self.key {
172 KeyStrategy::Id => "no top-level @id or id".into(),
173 KeyStrategy::Pointer(p) => format!("no string at {p}"),
174 _ => "no key was passed".into(),
175 })),
176 },
177 }
178 }
179
180 pub fn graph_for(&self, key: &str) -> Result<GraphName> {
182 Ok(match &self.graph {
183 GraphStrategy::Key => GraphName::NamedNode(parse_iri(key)?),
184 GraphStrategy::Template(t) => {
185 GraphName::NamedNode(parse_iri(&t.replace("{key}", &percent_encode(key)))?)
186 }
187 GraphStrategy::Fixed(g) => GraphName::NamedNode(g.clone()),
188 GraphStrategy::DefaultGraph => GraphName::DefaultGraph,
189 })
190 }
191}
192
193fn parse_iri(s: &str) -> Result<NamedNode> {
194 NamedNode::new(s).map_err(|e| JsonLdError::InvalidGraphName(format!("{s}: {e}")))
195}
196
197pub fn top_level_id(doc: &Value) -> Option<String> {
199 let o = doc.as_object()?;
200 for k in ["@id", "id"] {
201 if let Some(v) = o.get_unique(k).ok().flatten() {
202 return v.as_str().map(str::to_owned);
203 }
204 }
205 None
206}
207
208pub fn pointer<'a>(doc: &'a Value, pointer: &str) -> Option<&'a Value> {
210 if pointer.is_empty() {
211 return Some(doc);
212 }
213 let mut cur = doc;
214 for token in pointer.strip_prefix('/')?.split('/') {
215 let token = token.replace("~1", "/").replace("~0", "~");
216 cur = match cur {
217 Value::Object(o) => o.get_unique(token.as_str()).ok().flatten()?,
218 Value::Array(a) => a.get(token.parse::<usize>().ok()?)?,
219 _ => return None,
220 };
221 }
222 Some(cur)
223}
224
225pub fn sha256(raw: &str) -> [u8; 32] {
227 Sha256::digest(raw.as_bytes()).into()
228}
229
230pub fn hex(bytes: &[u8]) -> String {
232 let mut s = String::with_capacity(bytes.len() * 2);
233 for b in bytes {
234 let _ = write!(s, "{b:02x}");
235 }
236 s
237}
238
239pub fn content_hash_key(raw: &str) -> String {
241 format!("{CONTENT_HASH_PREFIX}{}", hex(&sha256(raw)))
242}
243
244pub fn percent_encode(s: &str) -> String {
246 let mut out = String::with_capacity(s.len());
247 for b in s.bytes() {
248 if b.is_ascii_alphanumeric() || b"-._~!$&'()*+,;=:@/".contains(&b) {
249 out.push(b as char);
250 } else {
251 let _ = write!(out, "%{b:02X}");
252 }
253 }
254 out
255}
256
257#[cfg(test)]
258mod tests {
259 use super::*;
260 use json_syntax::Parse;
261
262 fn parse(s: &str) -> Value {
263 Value::parse_str(s).unwrap().0
264 }
265
266 #[test]
267 fn keys() {
268 let raw =
269 r#"{"id": "https://example.org/docs/1", "credentialSubject": {"id": "did:ex:1"}}"#;
270 let doc = parse(raw);
271 let o = JsonLdOptions::default();
272 assert_eq!(
273 o.key_for(raw, &doc, None).unwrap(),
274 "https://example.org/docs/1"
275 );
276 let o = JsonLdOptions {
277 key: KeyStrategy::Pointer("/credentialSubject/id".into()),
278 ..Default::default()
279 };
280 assert_eq!(o.key_for(raw, &doc, None).unwrap(), "did:ex:1");
281 let o = JsonLdOptions {
282 key: KeyStrategy::Pointer("/nope".into()),
283 ..Default::default()
284 };
285 assert!(matches!(
286 o.key_for(raw, &doc, None),
287 Err(JsonLdError::MissingKey(_))
288 ));
289 }
290
291 #[test]
292 fn templates() {
293 let o = JsonLdOptions {
294 graph: GraphStrategy::Template("https://example.org/g/{key}".into()),
295 ..Default::default()
296 };
297 assert_eq!(
298 o.graph_for("a b").unwrap(),
299 GraphName::NamedNode(NamedNode::new_unchecked("https://example.org/g/a%20b"))
300 );
301 assert!(matches!(
302 JsonLdOptions::default().graph_for("not an iri"),
303 Err(JsonLdError::InvalidGraphName(_))
304 ));
305 }
306}