ikigai_shacl/lib.rs
1//! `ikigai-shacl` — SHACL validation as an ikigai resource.
2//!
3//! `urn:shacl:validate` validates a piped RDF `data` graph against a SHACL `shapes` graph. The
4//! validation **report is itself an RDF graph**: the default `text/turtle` output is the SHACL
5//! ValidationReport (conforms + a node per violation), skolemized under a content address of the
6//! report so it carries no blank node (every one is named under [`REPORT_SCHEME`]), and
7//! `application/json` gives a structured
8//! [`Report`] — `{conforms, violations: [{focus_node, path, component, message, value}]}` —
9//! content-negotiated structured errors for free. Both faces carry the same facts: the
10//! `sh:resultMessage` with its `{?value}`-style template resolved, the offending `sh:value`,
11//! and the `sh:resultPath`.
12//!
13//! `shapes` is taken **by reference** (the ROC-idiomatic form: a shapes graph is a resource
14//! you point at, sourced through the kernel — cacheable, golden-threaded); inline Turtle is
15//! also accepted. So the endpoint is `async` (the one await is the shapes resolution).
16//!
17//! ## Two validators, one resource (ledger #1176)
18//!
19//! - **`rudof`** (the default feature): rudof's consolidated `shacl` crate, all of SHACL Core
20//! and SHACL-SPARQL's `sh:select`, behind the bounds in `rudof_engine`. A heavy dependency
21//! tree, and one that cannot be built without a network stack on native (rudof's IRI crate
22//! links reqwest, and its RDF crate turns on tokio).
23//! - **[`core_shacl`]**, always compiled: a subset validator with no rudof, no network stack and
24//! no recursion over either graph, for a host that turns `rudof` off. It REFUSES, by name, every SHACL
25//! term outside that subset rather than skip a constraint it does not understand. Vocab 0.5.7
26//! shapes use `sh:or` and require rudof. Its
27//! `sh:sparql` / `sh:select` constraints come with the **`sparql`** feature (which `rudof`
28//! implies), and with it oxigraph's store and ikigai-store's guards and time budget. With
29//! default features off it is the CORE constraints alone, on oxrdf and oxttl (ledger #2107):
30//! small enough for an in-page wasm kernel, bounded by work rather than time
31//! ([`core_shacl::MAX_VALIDATION_WORK`]), and refusing a SHACL-SPARQL construct by name.
32//!
33//! With both compiled the endpoint uses rudof; `tests/differential.rs` runs both over one corpus
34//! and requires the same verdicts. The `module` feature (a lazy-loadable WASM module) implies
35//! `rudof`. The JavaScript `shacl-engine` remains a third implementation of the same
36//! `urn:shacl:validate` resource, held to the parity corpus (see `js-parity/`).
37
38#![forbid(unsafe_code)]
39
40use async_trait::async_trait;
41use ikigai_core::{
42 space_iri, ArgRef, ArgSpec, Description, Endpoint, EndpointSpace, Error, Exact, Invocation,
43 Iri, ReprType, Representation, Request, Result, Verb,
44};
45
46pub mod core_shacl;
47mod depth;
48mod naming;
49#[cfg(feature = "rudof")]
50mod rudof_engine;
51pub use depth::{MAX_DATA_RECURSION, MAX_SHAPE_DEPTH, MAX_TURTLE_NESTING};
52
53/// The name [`space`] claims: `urn:iki:space:shacl`.
54pub const SPACE_ID: &str = "urn:iki:space:shacl";
55
56/// The space binding `urn:shacl:validate`. It is configuration-free (no parameters, nothing
57/// read while building it), so it names itself [`SPACE_ID`]; the name goes on LAST, because
58/// binding a door after naming drops the name (core 0.1.89).
59pub fn space() -> EndpointSpace {
60 EndpointSpace::new()
61 .bind(Exact::new("urn:shacl:validate"), ValidateEndpoint)
62 .named(space_iri("shacl"))
63}
64
65/// The argument every refusal names: the SPARQL arrived inside the shapes graph.
66pub(crate) const SHAPES_ARG: &str = "shapes";
67
68/// Is `s` an inline Turtle shapes graph rather than a resource reference? Turtle opens with
69/// `@prefix`/`@base`, a `<…>` IRI, a `_:` blank node, or a `#` comment — or spans lines; a
70/// bare `urn:`/`http(s)` IRI with no whitespace is the by-reference case.
71fn is_inline_shapes(s: &str) -> bool {
72 let t = s.trim_start();
73 t.starts_with('@')
74 || t.starts_with('<')
75 || t.starts_with('#')
76 || t.starts_with("_:")
77 || t.chars().any(char::is_whitespace)
78}
79
80/// Resolve a `shapes` reference through the kernel — `urn:`/`file:` via `inv.source`, http(s)
81/// via `urn:httpGet` — recording it as a dependency so a result is cacheable and invalidates
82/// when the shapes change. (Mirrors the jsonld compact context-by-reference.)
83async fn resolve_shapes(inv: &Invocation<'_>, uri: &str) -> Result<Representation> {
84 if uri.starts_with("http://") || uri.starts_with("https://") {
85 let get = Iri::parse("urn:httpGet").expect("urn:httpGet is a valid IRI");
86 let request = Request::new(Verb::Source, get)
87 .with_arg("url", ArgRef::Inline(uri.as_bytes().to_vec()));
88 inv.issue(request).await
89 } else {
90 let iri = Iri::parse(uri).map_err(|e| {
91 Error::Endpoint(format!("urn:shacl:validate: bad shapes IRI `{uri}`: {e}"))
92 })?;
93 inv.source(&iri).await
94 }
95}
96
97/// One conformance violation, reduced to its **implementation-independent signature** — the
98/// spec-defined parts every SHACL validator agrees on. (Deliberately omits `sh:resultMessage`
99/// and blank-node ids, which legitimately differ between validators.) This is the cross-impl
100/// **parity contract**: rudof (native) and shacl-engine (browser) must produce the same set.
101/// The endpoint's JSON face is the richer [`ReportResult`]; a signature is its first three
102/// keys.
103#[derive(serde::Serialize, serde::Deserialize, PartialEq, Eq, PartialOrd, Ord, Clone, Debug)]
104pub struct Violation {
105 /// The focus node that failed (IRI / blank-node id).
106 pub focus_node: String,
107 /// The `sh:resultPath`, if any, rendered as [`ReportResult::path`] says: an IRI only for a
108 /// predicate path, and otherwise a path expression that is not an IRI.
109 pub path: Option<String>,
110 /// The `sh:sourceConstraintComponent` IRI (e.g. `…#MinCountConstraintComponent`).
111 pub component: String,
112}
113
114/// The portable validation outcome: `conforms` + the sorted violation signatures. This is
115/// the parity contract in `tests/corpus/*/expected.json` (see `tests/parity.rs`); the
116/// endpoint's `application/json` face is the richer [`Report`].
117#[derive(serde::Serialize, serde::Deserialize, PartialEq, Eq, Clone, Debug)]
118pub struct ValidationOutcome {
119 pub conforms: bool,
120 pub violations: Vec<Violation>,
121}
122
123/// An RDF term in the SPARQL 1.1 Query Results JSON encoding — `{"type": "uri" | "bnode" |
124/// "literal", "value": …}`, a literal carrying `"xml:lang"` when language-tagged and
125/// `"datatype"` when typed (a plain `xsd:string` carries neither, as in that spec). An
126/// RDF-star quoted triple is `{"type": "triple", "value": {subject, predicate, object}}`
127/// (the SPARQL 1.2 form).
128#[derive(serde::Serialize, serde::Deserialize, PartialEq, Eq, PartialOrd, Ord, Clone, Debug)]
129#[serde(tag = "type", rename_all = "lowercase")]
130pub enum Term {
131 Uri {
132 value: String,
133 },
134 Bnode {
135 value: String,
136 },
137 Literal {
138 value: String,
139 #[serde(rename = "xml:lang", default, skip_serializing_if = "Option::is_none")]
140 lang: Option<String>,
141 #[serde(default, skip_serializing_if = "Option::is_none")]
142 datatype: Option<String>,
143 },
144 Triple {
145 value: Box<QuotedTriple>,
146 },
147}
148
149/// The value of a [`Term::Triple`]: an RDF-star quoted triple.
150#[derive(serde::Serialize, serde::Deserialize, PartialEq, Eq, PartialOrd, Ord, Clone, Debug)]
151pub struct QuotedTriple {
152 pub subject: Term,
153 pub predicate: Term,
154 pub object: Term,
155}
156
157impl Term {
158 /// The string a SHACL message template substitutes for this term (spec §5.3.2 / §6.5.3
159 /// semantics): an IRI as itself, a literal as its lexical form, a blank node as `_:id`.
160 pub fn lexical(&self) -> String {
161 match self {
162 Term::Uri { value } | Term::Literal { value, .. } => value.clone(),
163 Term::Bnode { value } => format!("_:{value}"),
164 Term::Triple { value } => format!(
165 "<< {} {} {} >>",
166 value.subject.lexical(),
167 value.predicate.lexical(),
168 value.object.lexical()
169 ),
170 }
171 }
172}
173
174pub(crate) const XSD_STRING: &str = "http://www.w3.org/2001/XMLSchema#string";
175
176/// The two faces of the report, which are also the two values `as` accepts and the
177/// two declared outputs — one list, so `as`'s `one_of` and `outputs` cannot drift.
178pub(crate) const TURTLE: &str = "text/turtle";
179pub(crate) const JSON: &str = "application/json";
180
181/// One validation result as the `application/json` face reports it. The first three keys are
182/// the parity [`Violation`] signature and keep their names and order; `message` and `value`
183/// follow. Sorted by these fields in this order, so a report is deterministic.
184#[derive(serde::Serialize, serde::Deserialize, PartialEq, Eq, PartialOrd, Ord, Clone, Debug)]
185pub struct ReportResult {
186 /// The focus node that failed (IRI / blank-node id).
187 pub focus_node: String,
188 /// The `sh:resultPath`, if the result has one, as a string. A constraint on a **node**
189 /// shape has none unless it binds `?path` itself — a `sh:sparql` on a node shape reports
190 /// `null` here by the SHACL spec, not by omission.
191 ///
192 /// **It is an IRI only when the path is a single predicate** (ledger #204):
193 ///
194 /// - A predicate path is its IRI, bare: `http://example.org/name`.
195 /// - Any other path is rudof's rendering of the path expression, which is **not an IRI**
196 /// and not SPARQL either, since its IRIs are unbracketed: every compound is in
197 /// parentheses, an alternative `(a | b)`, a sequence `(a / b)`, an inverse `^(a)`, and
198 /// `(a)*`, `(a)+`, `(a)?` for zero-or-more, one-or-more and zero-or-one, nesting as the
199 /// path does. A predicate IRI never begins with `(` or `^`, so that tells the two apart.
200 /// - With the `rudof` feature off, the subset validator refuses a shapes graph whose path
201 /// is not a predicate, so it only ever reports the first form.
202 ///
203 /// The parity case `tests/corpus/complex-paths` holds shacl-engine to the same strings, and
204 /// this pins both forms, so a rudof release that renders a path differently fails here:
205 ///
206 /// ```
207 /// let shapes = r#"@prefix sh: <http://www.w3.org/ns/shacl#> .
208 /// @prefix : <http://example.org/> .
209 /// :S a sh:NodeShape ; sh:targetNode :dave ;
210 /// sh:property [ sh:path :name ; sh:minCount 1 ] ;
211 /// sh:property [ sh:path [ sh:alternativePath ( :email :phone ) ] ; sh:minCount 1 ] ;
212 /// sh:property [ sh:path ( :employer :name ) ; sh:minCount 1 ] ;
213 /// sh:property [ sh:path [ sh:inversePath :member ] ; sh:minCount 1 ] ."#;
214 ///
215 /// let report = ikigai_shacl::validate_report("", shapes);
216 /// if cfg!(feature = "rudof") {
217 /// let paths: Vec<String> = report
218 /// .unwrap()
219 /// .violations
220 /// .into_iter()
221 /// .map(|v| v.path.unwrap())
222 /// .collect();
223 /// assert_eq!(
224 /// paths,
225 /// [
226 /// "(http://example.org/email | http://example.org/phone)",
227 /// "(http://example.org/employer / http://example.org/name)",
228 /// "^(http://example.org/member)",
229 /// "http://example.org/name",
230 /// ]
231 /// );
232 /// } else {
233 /// assert!(report.is_err(), "the subset refuses a complex path");
234 /// }
235 /// ```
236 pub path: Option<String>,
237 /// The `sh:sourceConstraintComponent` IRI (e.g. `…#MinCountConstraintComponent`).
238 pub component: String,
239 /// The `sh:resultMessage`, with `{?value}`/`{$value}`, `{?this}` and `{?path}` resolved
240 /// against this result (SHACL §6.5.3 semantics). Language-tagged when the shape's
241 /// `sh:message` is. The shape's own message beats the validator's default, which is
242 /// never tagged; among several tagged messages the lowest language tag is reported.
243 pub message: Option<Term>,
244 /// The `sh:value` — the offending value node — as a term.
245 pub value: Option<Term>,
246}
247
248impl ReportResult {
249 /// The parity signature: this result minus what legitimately differs between validators.
250 pub fn signature(&self) -> Violation {
251 Violation {
252 focus_node: self.focus_node.clone(),
253 path: self.path.clone(),
254 component: self.component.clone(),
255 }
256 }
257}
258
259/// The `application/json` face of `urn:shacl:validate`: `conforms` + one [`ReportResult`]
260/// per `sh:result`, sorted. The exact shape, pinned — this is what a consumer parses:
261///
262/// ```
263/// let shapes = r#"@prefix sh: <http://www.w3.org/ns/shacl#> .
264/// @prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
265/// @prefix : <http://example.org/> .
266/// :PersonShape a sh:NodeShape ;
267/// sh:targetClass :Person ;
268/// sh:property [ sh:path :name ; sh:datatype xsd:string ;
269/// sh:message "{?value} is not a string"@en ] ."#;
270/// let data = r#"@prefix : <http://example.org/> .
271/// :carol a :Person ; :name 42 ."#;
272///
273/// let report = ikigai_shacl::validate_report(data, shapes).unwrap();
274/// assert_eq!(
275/// serde_json::to_string_pretty(&report).unwrap(),
276/// r#"{
277/// "conforms": false,
278/// "violations": [
279/// {
280/// "focus_node": "http://example.org/carol",
281/// "path": "http://example.org/name",
282/// "component": "http://www.w3.org/ns/shacl#DatatypeConstraintComponent",
283/// "message": {
284/// "type": "literal",
285/// "value": "42 is not a string",
286/// "xml:lang": "en"
287/// },
288/// "value": {
289/// "type": "literal",
290/// "value": "42",
291/// "datatype": "http://www.w3.org/2001/XMLSchema#integer"
292/// }
293/// }
294/// ]
295/// }"#
296/// );
297/// ```
298#[derive(serde::Serialize, serde::Deserialize, PartialEq, Eq, Clone, Debug)]
299pub struct Report {
300 pub conforms: bool,
301 pub violations: Vec<ReportResult>,
302}
303
304impl Report {
305 /// Reduce to the parity [`ValidationOutcome`] (sorted signatures).
306 pub fn outcome(&self) -> ValidationOutcome {
307 let mut violations: Vec<Violation> = self
308 .violations
309 .iter()
310 .map(ReportResult::signature)
311 .collect();
312 violations.sort();
313 ValidationOutcome {
314 conforms: self.conforms,
315 violations,
316 }
317 }
318}
319
320/// Validate `data_ttl` against `shapes_ttl`, returning the full [`Report`] — what the
321/// `application/json` face serializes. rudof with the `rudof` feature, else [`core_shacl`].
322/// With `sparql` (which `rudof` implies), within the base time budget (5 s), past which it is
323/// refused with a typed `Error::OverBudget` (a library call carries no capability to grant more);
324/// without it, within [`core_shacl::MAX_VALIDATION_WORK`], past which it is refused with a typed
325/// `Error::InvalidArgument`.
326pub fn validate_report(data_ttl: &str, shapes_ttl: &str) -> Result<Report> {
327 #[cfg(feature = "rudof")]
328 {
329 rudof_engine::validate_report(data_ttl, shapes_ttl)
330 }
331 #[cfg(not(feature = "rudof"))]
332 {
333 core_shacl::validate_report(data_ttl, shapes_ttl)
334 }
335}
336
337/// Validate `data_ttl` against `shapes_ttl`, returning the portable [`ValidationOutcome`] —
338/// the parity contract.
339pub fn validate_outcome(data_ttl: &str, shapes_ttl: &str) -> Result<ValidationOutcome> {
340 Ok(validate_report(data_ttl, shapes_ttl)?.outcome())
341}
342
343/// Validate `data_ttl` against `shapes_ttl`, returning the report graph as Turtle — what the
344/// default `text/turtle` face serves. rudof with the `rudof` feature, else [`core_shacl`];
345/// within the same bound as [`validate_report`].
346pub fn validate_turtle(data_ttl: &str, shapes_ttl: &str) -> Result<String> {
347 #[cfg(feature = "rudof")]
348 {
349 rudof_engine::validate_turtle(data_ttl, shapes_ttl)
350 }
351 #[cfg(not(feature = "rudof"))]
352 {
353 core_shacl::validate_turtle(data_ttl, shapes_ttl)
354 }
355}
356
357/// Validate, rendering per `as_type`: `application/json` → the [`Report`]; else the SHACL
358/// report graph as Turtle (the report *is* RDF). Same results, same resolved messages, on
359/// both faces. `capability` is the caller's, which decides the time budget either validator
360/// runs under (ledger #1735 gave the rudof path the subset path's).
361fn validate(
362 data_ttl: &str,
363 shapes_ttl: &str,
364 as_type: &str,
365 capability: &ikigai_core::Capability,
366) -> Result<Representation> {
367 #[cfg(feature = "rudof")]
368 {
369 rudof_engine::validate(data_ttl, shapes_ttl, as_type, capability)
370 }
371 #[cfg(not(feature = "rudof"))]
372 {
373 core_shacl::validate(data_ttl, shapes_ttl, as_type, capability)
374 }
375}
376
377/// The prefix every node of the report graph is named under:
378/// `urn:ikigai:shacl:report:<content id of the report graph>:<blank-node label>`. A consumer
379/// can recognize a node this crate minted by this prefix, and nothing else in a report carries
380/// it.
381///
382/// Every part is a function of the inputs, never of the run that made it (ledger #1565): the
383/// content id is that of the report graph, and the label is stable too. A node from an input
384/// graph is labeled by order of first appearance in that document, `data.b<N>` or
385/// `shapes.b<N>` (the parser's own label for `[ … ]` is random, so it is never used, and an
386/// explicit `_:alice` is renamed alike); a node the validator mints is `report`, or a name
387/// derived from its content. The JSON face and `sh:message` templates use the same labels
388/// (`_:data.b0`). Pinned:
389///
390/// ```
391/// let shapes = r#"@prefix sh: <http://www.w3.org/ns/shacl#> .
392/// @prefix : <http://example.org/> .
393/// :PersonShape a sh:NodeShape ; sh:targetClass :Person ;
394/// sh:property [ sh:path :name ; sh:minCount 1 ] ."#;
395/// let data = "@prefix : <http://example.org/> . [] a :Person .";
396///
397/// let turtle = ikigai_shacl::validate_turtle(data, shapes).unwrap();
398/// let mut nodes: Vec<&str> = turtle
399/// .split(['<', '>'])
400/// .filter(|s| s.starts_with(ikigai_shacl::REPORT_SCHEME))
401/// .collect();
402/// nodes.sort_unstable();
403/// nodes.dedup();
404/// // The report, its one result, the blank property shape and the blank focus node, each
405/// // `<scheme><content id>:<label>`, and no blank node left.
406/// assert_eq!(nodes.len(), 4, "{turtle}");
407/// let labels: Vec<&str> = nodes
408/// .iter()
409/// .map(|n| n.strip_prefix(ikigai_shacl::REPORT_SCHEME).unwrap())
410/// .map(|rest| {
411/// let (content_id, label) = rest.rsplit_once(':').unwrap();
412/// assert!(content_id.starts_with("b3:"), "{content_id}");
413/// label
414/// })
415/// .collect();
416/// for label in ["report", "data.b0", "shapes.b0"] {
417/// assert!(labels.contains(&label), "{label} in {labels:?}");
418/// }
419/// assert!(!turtle.contains("_:"));
420/// // And the same inputs give the same bytes, every time.
421/// assert_eq!(turtle, ikigai_shacl::validate_turtle(data, shapes).unwrap());
422/// ```
423pub const REPORT_SCHEME: &str = "urn:ikigai:shacl:report:";
424
425/// A representation from a media type + body.
426pub(crate) fn repr(media: &str, body: String) -> Representation {
427 Representation::new(
428 ReprType::new(media).with_param("charset", "utf-8"),
429 body.into_bytes(),
430 )
431 .cacheable()
432}
433
434/// `urn:shacl:validate` — async because `shapes` may be a resource to resolve (inline Turtle
435/// is used directly). Validates the piped `data` graph against it.
436struct ValidateEndpoint;
437
438#[async_trait]
439impl Endpoint for ValidateEndpoint {
440 async fn invoke(&self, inv: &Invocation<'_>) -> Result<Representation> {
441 // Core's own refusal, unchanged: `MissingArgument` when the argument is absent,
442 // `InvalidArgument` when it is not inline or not UTF-8. These used to be rewritten as an
443 // untyped `Error::Endpoint` with a friendlier sentence, which made a caller's omission
444 // indistinguishable from a failure of the endpoint (ikigai-conformance's REQUIRED). The
445 // sentence lives on in the ArgSpecs: `data` is the Turtle graph, usually piped in;
446 // `shapes` is inline Turtle or a resolvable resource IRI.
447 let data = inv.inline_str("data")?.to_string();
448 let shapes_arg = inv.inline_str("shapes")?;
449 let as_type = inv.inline_str("as").unwrap_or(TURTLE).to_string();
450
451 // Inline Turtle used directly; anything else is a resource reference resolved through
452 // the kernel (the one await — no rudof value is live across it).
453 let shapes_ttl = if is_inline_shapes(shapes_arg) {
454 shapes_arg.to_string()
455 } else {
456 let repr = resolve_shapes(inv, shapes_arg).await?;
457 String::from_utf8(repr.bytes).map_err(|e| {
458 Error::Endpoint(format!("urn:shacl:validate: shapes not UTF-8: {e}"))
459 })?
460 };
461
462 validate(&data, &shapes_ttl, &as_type, inv.capability)
463 }
464
465 fn name(&self) -> &str {
466 "shacl-validate"
467 }
468
469 fn describe(&self) -> Description {
470 Description::new("shacl-validate")
471 .title("SHACL validate")
472 .summary(
473 "Validate an RDF data graph against a SHACL shapes graph. The report is itself \
474 a graph (text/turtle) — or application/json {conforms, violations: \
475 [{focus_node, path, component, message, value}]}.",
476 )
477 .verb(Verb::Source)
478 .verb(Verb::Meta)
479 // ⚠ All three inputs are `xsd:string`, and for two of them that is the type
480 // of the WIRE, not of the value. `data` and `shapes` are RDF *documents*;
481 // `shapes` is additionally a union (inline Turtle OR a resource IRI, told
482 // apart by `is_inline_shapes`). An `ArgSpec` has `class`, `one_of` and
483 // `default` and no `example`, `pattern` or `any_of`, so the only class that
484 // is TRUE of every accepted value is the string the wire carries. Reported
485 // for ikigai-core (conformance PENDING #7/#25).
486 .input(
487 ArgSpec::new("data")
488 .summary(
489 "the RDF data graph to validate, as Turtle — piped in: with `shapes` \
490 named it is the sole unnamed required input, which is where the engine \
491 routes a piped value",
492 )
493 .class(XSD_STRING),
494 )
495 .input(
496 ArgSpec::new("shapes")
497 .summary(
498 "the SHACL shapes graph: inline Turtle, or a resolvable resource IRI \
499 sourced through the kernel (the report is then as cacheable as it is)",
500 )
501 .class(XSD_STRING),
502 )
503 .input(
504 ArgSpec::new("as")
505 .summary(
506 "report representation: text/turtle (default, the report graph) or \
507 application/json",
508 )
509 .class(XSD_STRING)
510 .one_of([TURTLE, JSON])
511 .default_value(TURTLE)
512 .optional(),
513 )
514 .output("text/turtle;charset=utf-8")
515 .output("application/json;charset=utf-8")
516 }
517}
518
519#[cfg(test)]
520mod tests {
521 use super::*;
522
523 const SHAPES: &str = r#"@prefix sh: <http://www.w3.org/ns/shacl#> .
524@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
525@prefix : <http://example.org/> .
526:PersonShape a sh:NodeShape ;
527 sh:targetClass :Person ;
528 sh:property [ sh:path :name ; sh:minCount 1 ; sh:datatype xsd:string ] ."#;
529
530 fn json(data: &str, shapes: &str) -> String {
531 String::from_utf8(
532 validate(
533 data,
534 shapes,
535 "application/json",
536 &ikigai_core::Capability::root(),
537 )
538 .unwrap()
539 .bytes,
540 )
541 .unwrap()
542 }
543
544 #[test]
545 fn conforming_data_conforms() {
546 let data = r#"@prefix : <http://example.org/> .
547:alice a :Person ; :name "Alice" ."#;
548 let body = json(data, SHAPES);
549 assert!(body.contains("\"conforms\": true"), "{body}");
550 }
551
552 #[test]
553 fn violating_data_reports() {
554 // :bob is a Person with no :name → violates sh:minCount 1.
555 let data = r#"@prefix : <http://example.org/> .
556:bob a :Person ."#;
557 let body = json(data, SHAPES);
558 assert!(body.contains("\"conforms\": false"), "{body}");
559 }
560
561 #[test]
562 fn report_is_a_turtle_graph() {
563 let data = r#"@prefix : <http://example.org/> .
564:bob a :Person ."#;
565 let ttl = String::from_utf8(
566 validate(
567 data,
568 SHAPES,
569 "text/turtle",
570 &ikigai_core::Capability::root(),
571 )
572 .unwrap()
573 .bytes,
574 )
575 .unwrap();
576 // The SHACL report is itself RDF — it carries the shacl namespace.
577 assert!(
578 ttl.contains("shacl#") || ttl.contains("sh:"),
579 "report graph: {ttl}"
580 );
581 }
582
583 /// The shape the ikigai-core process vocabulary authors: a `sh:sparql` on a NODE shape
584 /// with a `{?value}` message template. The report must name the value; the path is
585 /// `null` because a node-shape constraint has none (the spec, not a dropped field).
586 const KNOWS_SHAPES: &str = r#"@prefix sh: <http://www.w3.org/ns/shacl#> .
587@prefix : <http://example.org/> .
588:PersonShape a sh:NodeShape ;
589 sh:targetClass :Person ;
590 sh:sparql [
591 sh:message "{?this} knows itself via {?value}" ;
592 sh:prefixes <http://example.org/> ;
593 sh:select """
594 PREFIX : <http://example.org/>
595 SELECT $this ?value WHERE { $this :knows ?value . FILTER(?value = $this) }
596 """ ] ."#;
597
598 const KNOWS_DATA: &str = r#"@prefix : <http://example.org/> .
599:bob a :Person ; :knows :bob ."#;
600
601 #[cfg(feature = "sparql")]
602 #[test]
603 fn sparql_node_constraint_resolves_the_message_and_carries_the_value() {
604 let report = validate_report(KNOWS_DATA, KNOWS_SHAPES).unwrap();
605 assert!(!report.conforms);
606 assert_eq!(report.violations.len(), 1, "{report:?}");
607 let r = &report.violations[0];
608 assert_eq!(r.focus_node, "http://example.org/bob");
609 assert_eq!(r.path, None, "a node-shape sh:sparql has no sh:resultPath");
610 assert_eq!(
611 r.component,
612 "http://www.w3.org/ns/shacl#SPARQLConstraintComponent"
613 );
614 assert_eq!(
615 r.message,
616 Some(Term::Literal {
617 value: "http://example.org/bob knows itself via http://example.org/bob".into(),
618 lang: None,
619 datatype: None,
620 })
621 );
622 assert_eq!(
623 r.value,
624 Some(Term::Uri {
625 value: "http://example.org/bob".into()
626 })
627 );
628 }
629
630 #[cfg(feature = "sparql")]
631 #[test]
632 fn sparql_constraint_that_binds_path_fills_path() {
633 let shapes = KNOWS_SHAPES.replace(
634 "SELECT $this ?value WHERE {",
635 "SELECT $this ?value ?path WHERE { BIND(:knows AS ?path)",
636 );
637 let report = validate_report(KNOWS_DATA, &shapes).unwrap();
638 assert_eq!(report.violations.len(), 1, "{report:?}");
639 assert_eq!(
640 report.violations[0].path.as_deref(),
641 Some("http://example.org/knows"),
642 "a bound ?path becomes sh:resultPath"
643 );
644 }
645
646 #[cfg(feature = "sparql")]
647 #[test]
648 fn sparql_constraint_without_a_message_reports_null_message() {
649 let shapes =
650 KNOWS_SHAPES.replace("sh:message \"{?this} knows itself via {?value}\" ;\n", "");
651 let report = validate_report(KNOWS_DATA, &shapes).unwrap();
652 assert_eq!(report.violations.len(), 1, "{report:?}");
653 assert_eq!(report.violations[0].message, None);
654 }
655
656 /// Without `sparql`, the same shapes are refused, naming the construct and the feature that
657 /// would validate them, never answered as if the constraint were not there.
658 #[cfg(not(feature = "sparql"))]
659 #[test]
660 fn without_sparql_a_sparql_constraint_is_refused_naming_the_feature() {
661 match validate_report(KNOWS_DATA, KNOWS_SHAPES) {
662 Err(Error::InvalidArgument { name, detail }) => {
663 assert_eq!(name, "shapes");
664 assert!(detail.contains("`sh:sparql`"), "{detail}");
665 assert!(detail.contains("`sparql` feature"), "{detail}");
666 }
667 other => panic!("not refused: {other:?}"),
668 }
669 }
670
671 #[test]
672 fn tagged_shape_message_beats_the_validator_default_and_lowest_tag_wins() {
673 // Core-constraint results carry rudof's own untagged default message merged with the
674 // shape's; a shape author's tagged message must be what the JSON reports.
675 let shapes = SHAPES.replace(
676 "sh:datatype xsd:string ]",
677 "sh:datatype xsd:string ; sh:message \"nom {?value} invalide\"@fr, \
678 \"name {?value} is not a string\"@en ]",
679 );
680 let data = r#"@prefix : <http://example.org/> .
681:carol a :Person ; :name 42 ."#;
682 let report = validate_report(data, &shapes).unwrap();
683 assert_eq!(report.violations.len(), 1, "{report:?}");
684 assert_eq!(
685 report.violations[0].message,
686 Some(Term::Literal {
687 value: "name 42 is not a string".into(),
688 lang: Some("en".into()),
689 datatype: None,
690 })
691 );
692 }
693
694 #[cfg(feature = "sparql")]
695 #[test]
696 fn json_keeps_the_signature_keys_first_and_in_order() {
697 let body = json(KNOWS_DATA, KNOWS_SHAPES);
698 let keys: Vec<usize> = [
699 "\"focus_node\"",
700 "\"path\"",
701 "\"component\"",
702 "\"message\"",
703 "\"value\"",
704 ]
705 .iter()
706 .map(|k| {
707 body.find(k)
708 .unwrap_or_else(|| panic!("{k} missing in {body}"))
709 })
710 .collect();
711 assert!(keys.windows(2).all(|w| w[0] < w[1]), "key order in {body}");
712 // And the JSON face round-trips through the public type.
713 let parsed: Report = serde_json::from_str(&body).unwrap();
714 assert_eq!(parsed, validate_report(KNOWS_DATA, KNOWS_SHAPES).unwrap());
715 }
716
717 #[test]
718 fn turtle_face_carries_the_same_resolved_message_value_and_path() {
719 let shapes = SHAPES.replace(
720 "sh:datatype xsd:string ]",
721 "sh:datatype xsd:string ; sh:message \"{?value} is not a string\" ]",
722 );
723 let data = r#"@prefix : <http://example.org/> .
724:carol a :Person ; :name 42 ."#;
725 let ttl = String::from_utf8(
726 validate(
727 data,
728 &shapes,
729 "text/turtle",
730 &ikigai_core::Capability::root(),
731 )
732 .unwrap()
733 .bytes,
734 )
735 .unwrap();
736 for needle in [
737 "sh:resultMessage \"42 is not a string\"",
738 "sh:value 42",
739 "sh:resultPath <http://example.org/name>",
740 "sh:focusNode <http://example.org/carol>",
741 ] {
742 assert!(
743 ttl.contains(needle),
744 "missing `{needle}` in report graph:\n{ttl}"
745 );
746 }
747 // The template is resolved on this face too — not copied through verbatim.
748 assert!(!ttl.contains("{?value}"), "unresolved template in:\n{ttl}");
749 }
750
751 #[test]
752 fn inline_shapes_detected() {
753 assert!(is_inline_shapes("@prefix : <x> .\n:S a sh:NodeShape ."));
754 assert!(is_inline_shapes("<http://x> a sh:NodeShape ."));
755 assert!(!is_inline_shapes("urn:data:shapes"));
756 assert!(!is_inline_shapes("https://example.org/shapes.ttl"));
757 }
758
759 /// A call missing a required input, or carrying one that is not UTF-8, is refused with
760 /// core's TYPED error naming the input, never an untyped `Error::Endpoint`: a caller (an
761 /// agent, `urn:kernel:validate`) must be able to tell its own omission from a failure of
762 /// the endpoint. ikigai-conformance's REQUIRED check walks the same drops.
763 #[test]
764 fn a_missing_or_undecodable_input_is_refused_typed() {
765 let kernel = ikigai_core::Kernel::new(std::sync::Arc::new(space()));
766 let call = |args: &[(&str, &[u8])]| {
767 let request = args.iter().fold(
768 Request::new(
769 Verb::Source,
770 Iri::parse("urn:shacl:validate").expect("a valid IRI"),
771 ),
772 |request, (name, value)| request.with_arg(*name, ArgRef::Inline(value.to_vec())),
773 );
774 futures::executor::block_on(kernel.issue(request, &ikigai_core::Capability::root()))
775 .expect_err("the call is refused")
776 };
777 let data: &[u8] = b"@prefix : <http://example.org/> .\n:bob a :Person .";
778
779 let err = call(&[("shapes", SHAPES.as_bytes())]);
780 assert!(
781 matches!(&err, Error::MissingArgument(name) if name == "data"),
782 "{err:?}"
783 );
784 let err = call(&[("data", data)]);
785 assert!(
786 matches!(&err, Error::MissingArgument(name) if name == "shapes"),
787 "{err:?}"
788 );
789 let err = call(&[("data", &[0xff, 0xfe]), ("shapes", SHAPES.as_bytes())]);
790 assert!(
791 matches!(&err, Error::InvalidArgument { name, .. } if name == "data"),
792 "{err:?}"
793 );
794 let err = call(&[("data", data), ("shapes", &[0xff, 0xfe])]);
795 assert!(
796 matches!(&err, Error::InvalidArgument { name, .. } if name == "shapes"),
797 "{err:?}"
798 );
799 }
800}
801
802// ---------------------------------------------------------------------------
803// This library *as* a dynamically-loadable WASM module (`--features module`).
804// ---------------------------------------------------------------------------
805#[cfg(feature = "module")]
806ikigai_module::wasm_module!(crate::space);
807
808/// Surface a Rust panic in the browser console (module builds only).
809#[cfg(feature = "module")]
810#[wasm_bindgen::prelude::wasm_bindgen(start)]
811pub fn __module_start() {
812 console_error_panic_hook::set_once();
813}