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
use hashbrown::HashSet;
use iref::{Iri, IriBuf};
use mime::Mime;
use rdf_types::vocabulary::{IriVocabulary, IriVocabularyMut};
use static_iref::iri;
use std::borrow::Cow;

pub mod chain;
pub mod fs;
pub mod map;
pub mod none;

pub use chain::ChainLoader;
pub use fs::FsLoader;
pub use none::NoLoader;

#[cfg(feature = "reqwest")]
pub mod reqwest;

#[cfg(feature = "reqwest")]
pub use self::reqwest::ReqwestLoader;

pub type LoadingResult<I, E> = Result<RemoteDocument<I>, E>;

pub type RemoteContextReference<I = IriBuf> = RemoteDocumentReference<I, json_ld_syntax::Context>;

/// Remote document, loaded or not.
///
/// Either an IRI or the actual document content.
#[derive(Clone)]
pub enum RemoteDocumentReference<I = IriBuf, T = json_syntax::Value> {
	/// IRI to the remote document.
	Iri(I),

	/// Remote document content.
	Loaded(RemoteDocument<I, T>),
}

impl<I, T> RemoteDocumentReference<I, T> {
	/// Creates an IRI to a `json_syntax::Value` JSON document.
	///
	/// This method can replace `RemoteDocumentReference::Iri` to help the type
	/// inference in the case where `T = json_syntax::Value`.
	pub fn iri(iri: I) -> Self {
		Self::Iri(iri)
	}
}

impl<I> RemoteDocumentReference<I> {
	/// Loads the remote document with the given `vocabulary` and `loader`.
	///
	/// If the document is already [`Self::Loaded`], simply returns the inner
	/// [`RemoteDocument`].
	pub async fn load_with<V, L: Loader<I>>(
		self,
		vocabulary: &mut V,
		loader: &mut L,
	) -> Result<RemoteDocument<I>, L::Error>
	where
		V: IriVocabularyMut<Iri = I>,
	{
		match self {
			Self::Iri(r) => Ok(loader.load_with(vocabulary, r).await?.map(Into::into)),
			Self::Loaded(doc) => Ok(doc),
		}
	}

	/// Loads the remote document with the given `vocabulary` and `loader`.
	///
	/// For [`Self::Iri`] returns an owned [`RemoteDocument`] with
	/// [`Cow::Owned`].
	/// For [`Self::Loaded`] returns a reference to the inner [`RemoteDocument`]
	/// with [`Cow::Borrowed`].
	pub async fn loaded_with<V, L: Loader<I>>(
		&self,
		vocabulary: &mut V,
		loader: &mut L,
	) -> Result<Cow<'_, RemoteDocument<I>>, L::Error>
	where
		V: IriVocabularyMut<Iri = I>,
		I: Clone,
	{
		match self {
			Self::Iri(r) => Ok(Cow::Owned(
				loader
					.load_with(vocabulary, r.clone())
					.await?
					.map(Into::into),
			)),
			Self::Loaded(doc) => Ok(Cow::Borrowed(doc)),
		}
	}
}

#[derive(Debug, thiserror::Error)]
pub enum ContextLoadError<E> {
	#[error("loading document failed: {0}")]
	LoadingDocumentFailed(E),

	#[error("context extraction failed")]
	ContextExtractionFailed(#[from] ExtractContextError),
}

impl<I> RemoteContextReference<I> {
	/// Loads the remote context with the given `vocabulary` and `loader`.
	///
	/// If the context is already [`Self::Loaded`], simply returns the inner
	/// [`RemoteContext`].
	pub async fn load_context_with<V, L: Loader<I>>(
		self,
		vocabulary: &mut V,
		loader: &mut L,
	) -> Result<RemoteContext<I>, ContextLoadError<L::Error>>
	where
		V: IriVocabularyMut<Iri = I>,
	{
		match self {
			Self::Iri(r) => Ok(loader
				.load_with(vocabulary, r)
				.await
				.map_err(ContextLoadError::LoadingDocumentFailed)?
				.try_map(|d| d.into_ld_context())?),
			Self::Loaded(doc) => Ok(doc),
		}
	}

	/// Loads the remote context with the given `vocabulary` and `loader`.
	///
	/// For [`Self::Iri`] returns an owned [`RemoteContext`] with
	/// [`Cow::Owned`].
	/// For [`Self::Loaded`] returns a reference to the inner [`RemoteContext`]
	/// with [`Cow::Borrowed`].
	pub async fn loaded_context_with<V, L: Loader<I>>(
		&self,
		vocabulary: &mut V,
		loader: &mut L,
	) -> Result<Cow<'_, RemoteContext<I>>, ContextLoadError<L::Error>>
	where
		V: IriVocabularyMut<Iri = I>,
		I: Clone,
	{
		match self {
			Self::Iri(r) => Ok(Cow::Owned(
				loader
					.load_with(vocabulary, r.clone())
					.await
					.map_err(ContextLoadError::LoadingDocumentFailed)?
					.try_map(|d| d.into_ld_context())?,
			)),
			Self::Loaded(doc) => Ok(Cow::Borrowed(doc)),
		}
	}
}

/// Remote document.
///
/// Stores the content of a loaded remote document along with its original URL.
#[derive(Debug, Clone)]
pub struct RemoteDocument<I = IriBuf, T = json_syntax::Value> {
	/// The final URL of the loaded document, after eventual redirection.
	url: Option<I>,

	/// The HTTP `Content-Type` header value of the loaded document, exclusive
	/// of any optional parameters.
	content_type: Option<Mime>,

	/// If available, the value of the HTTP `Link Header` [RFC 8288] using the
	/// `http://www.w3.org/ns/json-ld#context` link relation in the response.
	///
	/// If the response's `Content-Type` is `application/ld+json`, the HTTP
	/// `Link Header` is ignored. If multiple HTTP `Link Headers` using the
	/// `http://www.w3.org/ns/json-ld#context` link relation are found, the
	/// loader fails with a `multiple context link headers` error.
	///
	/// [RFC 8288]: https://www.rfc-editor.org/rfc/rfc8288
	context_url: Option<I>,

	profile: HashSet<Profile<I>>,

	/// The retrieved document.
	document: T,
}

pub type RemoteContext<I = IriBuf> = RemoteDocument<I, json_ld_syntax::context::Context>;

impl<I, T> RemoteDocument<I, T> {
	/// Creates a new remote document.
	///
	/// `url` is the final URL of the loaded document, after eventual
	/// redirection.
	/// `content_type` is the HTTP `Content-Type` header value of the loaded
	/// document, exclusive of any optional parameters.
	pub fn new(url: Option<I>, content_type: Option<Mime>, document: T) -> Self {
		Self::new_full(url, content_type, None, HashSet::new(), document)
	}

	/// Creates a new remote document.
	///
	/// `url` is the final URL of the loaded document, after eventual
	/// redirection.
	/// `content_type` is the HTTP `Content-Type` header value of the loaded
	/// document, exclusive of any optional parameters.
	/// `context_url` is the value of the HTTP `Link Header` [RFC 8288] using the
	/// `http://www.w3.org/ns/json-ld#context` link relation in the response,
	/// if any.
	/// `profile` is the value of any profile parameter retrieved as part of the
	/// original contentType.
	///
	/// [RFC 8288]: https://www.rfc-editor.org/rfc/rfc8288
	pub fn new_full(
		url: Option<I>,
		content_type: Option<Mime>,
		context_url: Option<I>,
		profile: HashSet<Profile<I>>,
		document: T,
	) -> Self {
		Self {
			url,
			content_type,
			context_url,
			profile,
			document,
		}
	}

	/// Maps the content of the remote document.
	pub fn map<U>(self, f: impl Fn(T) -> U) -> RemoteDocument<I, U> {
		RemoteDocument {
			url: self.url,
			content_type: self.content_type,
			context_url: self.context_url,
			profile: self.profile,
			document: f(self.document),
		}
	}

	/// Tries to map the content of the remote document.
	pub fn try_map<U, E>(self, f: impl Fn(T) -> Result<U, E>) -> Result<RemoteDocument<I, U>, E> {
		Ok(RemoteDocument {
			url: self.url,
			content_type: self.content_type,
			context_url: self.context_url,
			profile: self.profile,
			document: f(self.document)?,
		})
	}

	/// Returns a reference to the final URL of the loaded document, after eventual redirection.
	pub fn url(&self) -> Option<&I> {
		self.url.as_ref()
	}

	/// Returns the HTTP `Content-Type` header value of the loaded document,
	/// exclusive of any optional parameters.
	pub fn content_type(&self) -> Option<&Mime> {
		self.content_type.as_ref()
	}

	/// Returns the value of the HTTP `Link Header` [RFC 8288] using the
	/// `http://www.w3.org/ns/json-ld#context` link relation in the response,
	/// if any.
	///
	/// If the response's `Content-Type` is `application/ld+json`, the HTTP
	/// `Link Header` is ignored. If multiple HTTP `Link Headers` using the
	/// `http://www.w3.org/ns/json-ld#context` link relation are found, the
	/// loader fails with a `multiple context link headers` error.
	///
	/// [RFC 8288]: https://www.rfc-editor.org/rfc/rfc8288
	pub fn context_url(&self) -> Option<&I> {
		self.context_url.as_ref()
	}

	/// Returns a reference to the content of the document.
	pub fn document(&self) -> &T {
		&self.document
	}

	/// Returns a mutable reference to the content of the document.
	pub fn document_mut(&mut self) -> &mut T {
		&mut self.document
	}

	/// Drops the original URL and returns the content of the document.
	pub fn into_document(self) -> T {
		self.document
	}

	/// Drops the content and returns the original URL of the document.
	pub fn into_url(self) -> Option<I> {
		self.url
	}

	/// Sets the URL of the document.
	pub fn set_url(&mut self, url: Option<I>) {
		self.url = url
	}
}

/// Standard `profile` parameter values defined for the `application/ld+json`.
///
/// See: <https://www.w3.org/TR/json-ld11/#iana-considerations>
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum StandardProfile {
	/// To request or specify expanded JSON-LD document form.
	Expanded,

	/// To request or specify compacted JSON-LD document form.
	Compacted,

	/// To request or specify a JSON-LD context document.
	Context,

	/// To request or specify flattened JSON-LD document form.
	Flattened,

	// /// To request or specify a JSON-LD frame document.
	// Frame,
	/// To request or specify a JSON-LD framed document.
	Framed,
}

impl StandardProfile {
	pub fn from_iri(iri: &Iri) -> Option<Self> {
		if iri == iri!("http://www.w3.org/ns/json-ld#expanded") {
			Some(Self::Expanded)
		} else if iri == iri!("http://www.w3.org/ns/json-ld#compacted") {
			Some(Self::Compacted)
		} else if iri == iri!("http://www.w3.org/ns/json-ld#context") {
			Some(Self::Context)
		} else if iri == iri!("http://www.w3.org/ns/json-ld#flattened") {
			Some(Self::Flattened)
		} else if iri == iri!("http://www.w3.org/ns/json-ld#framed") {
			Some(Self::Framed)
		} else {
			None
		}
	}

	pub fn iri(&self) -> &'static Iri {
		match self {
			Self::Expanded => iri!("http://www.w3.org/ns/json-ld#expanded"),
			Self::Compacted => iri!("http://www.w3.org/ns/json-ld#compacted"),
			Self::Context => iri!("http://www.w3.org/ns/json-ld#context"),
			Self::Flattened => iri!("http://www.w3.org/ns/json-ld#flattened"),
			Self::Framed => iri!("http://www.w3.org/ns/json-ld#framed"),
		}
	}
}

/// Value for the `profile` parameter defined for the `application/ld+json`.
///
/// Standard values defined by the JSON-LD specification are defined by the
/// [`StandardProfile`] type.
///
/// See: <https://www.w3.org/TR/json-ld11/#iana-considerations>
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Profile<I> {
	Standard(StandardProfile),
	Custom(I),
}

impl<I> Profile<I> {
	pub fn new(iri: &Iri, vocabulary: &mut impl IriVocabularyMut<Iri = I>) -> Self {
		match StandardProfile::from_iri(iri) {
			Some(p) => Self::Standard(p),
			None => Self::Custom(vocabulary.insert(iri)),
		}
	}

	pub fn iri<'a>(&'a self, vocabulary: &'a impl IriVocabulary<Iri = I>) -> &'a Iri {
		match self {
			Self::Standard(s) => s.iri(),
			Self::Custom(c) => vocabulary.iri(c).unwrap(),
		}
	}
}

/// Document loader.
///
/// A document loader is required by most processing functions to fetch remote
/// documents identified by an IRI. In particular, the loader is in charge of
/// fetching all the remote contexts imported in a `@context` entry.
///
/// This library provides a few default loader implementations:
///   - [`NoLoader`] dummy loader that always fail. Perfect if you are certain
///     that the processing will not require any loading.
///   - Standard [`HashMap`](std::collection::HashMap) and
///     [`BTreeMap`](std::collection::BTreeMap) mapping IRIs to pre-loaded
///     documents. This way no network calls are performed and the loaded
///     content can be trusted.
///   - [`FsLoader`] that redirecting registered IRI prefixes to a local
///     directory on the file system. This also avoids network calls. The loaded
///     content can be trusted as long as the file system is trusted.
///   - `ReqwestLoader` actually downloading the remote documents using the
///     [`reqwest`](https://crates.io/crates/reqwest) library.
///     This requires the `reqwest` feature to be enabled.
pub trait Loader<I = IriBuf> {
	/// Error type.
	type Error;

	/// Loads the document behind the given IRI, using the given vocabulary.
	#[allow(async_fn_in_trait)]
	async fn load_with<V>(&mut self, vocabulary: &mut V, url: I) -> LoadingResult<I, Self::Error>
	where
		V: IriVocabularyMut<Iri = I>;

	/// Loads the document behind the given IRI.
	#[allow(async_fn_in_trait)]
	async fn load(&mut self, url: I) -> Result<RemoteDocument<I>, Self::Error>
	where
		(): IriVocabulary<Iri = I>,
	{
		self.load_with(rdf_types::vocabulary::no_vocabulary_mut(), url)
			.await
	}
}

impl<'l, I, L: Loader<I>> Loader<I> for &'l mut L {
	type Error = L::Error;

	async fn load_with<V>(&mut self, vocabulary: &mut V, url: I) -> LoadingResult<I, Self::Error>
	where
		V: IriVocabularyMut<Iri = I>,
	{
		L::load_with(self, vocabulary, url).await
	}

	async fn load(&mut self, url: I) -> Result<RemoteDocument<I>, Self::Error>
	where
		(): IriVocabulary<Iri = I>,
	{
		L::load(self, url).await
	}
}

/// Context extraction error.
#[derive(Debug, thiserror::Error)]
pub enum ExtractContextError {
	/// Unexpected JSON value.
	#[error("unexpected {0}")]
	Unexpected(json_syntax::Kind),

	/// No context definition found.
	#[error("missing `@context` entry")]
	NoContext,

	/// Multiple context definitions found.
	#[error("duplicate `@context` entry")]
	DuplicateContext,

	/// JSON syntax error.
	#[error("JSON-LD context syntax error: {0}")]
	Syntax(json_ld_syntax::context::InvalidContext),
}

impl ExtractContextError {
	fn duplicate_context(
		json_syntax::object::Duplicate(_, _): json_syntax::object::Duplicate<
			json_syntax::object::Entry,
		>,
	) -> Self {
		Self::DuplicateContext
	}
}

pub trait ExtractContext {
	fn into_ld_context(self) -> Result<json_ld_syntax::context::Context, ExtractContextError>;
}

impl ExtractContext for json_syntax::Value {
	fn into_ld_context(self) -> Result<json_ld_syntax::context::Context, ExtractContextError> {
		match self {
			Self::Object(mut o) => match o
				.remove_unique("@context")
				.map_err(ExtractContextError::duplicate_context)?
			{
				Some(context) => {
					use json_ld_syntax::TryFromJson;
					json_ld_syntax::context::Context::try_from_json(context.value)
						.map_err(ExtractContextError::Syntax)
				}
				None => Err(ExtractContextError::NoContext),
			},
			other => Err(ExtractContextError::Unexpected(other.kind())),
		}
	}
}