Copyright © 2017W3C® (MIT,ERCIM,Keio,Beihang).W3Cliability,trademark anddocument use rules apply.
This document defines a JavaScript-based extension mechanism for the Shapes Constraint Language (SHACL). It defines a syntax for declaring constraints, constraint components, functions, rules and targets in JavaScript. Using this syntax, SHACL shapes can benefit from the rich expressive power of JavaScript. In order to ensure that the resulting JavaScript code can be executed across platforms, this document defines a (minimalistic) JavaScript API that needs to be implemented by supporting engines.
This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of currentW3C publications and the latest revision of this technical report can be found in theW3C technical reports index at https://www.w3.org/TR/.
Future revisions of this document may be produced by a SHACLW3C Community Group.
This document was published by theRDF Data Shapes Working Group as a First Public Working Group Note. Comments regarding this document are welcome. Please send them topublic-rdf-shapes@w3.org (subscribe,archives).
Publication as a Working Group Note does not imply endorsement by theW3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.
This document was produced by a group operating under the5 February 2004W3C Patent Policy.W3C maintains apublic list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes containsEssential Claim(s) must disclose the information in accordance withsection 6 of theW3C Patent Policy.
This document is governed by the1 March 2017W3C Process Document.
Some examples in this document use Turtle [turtle]. The reader is expected to be familiar with SHACL [shacl] and the SHACL Advanced Features [shacl-af].
Within this document, the following namespace prefix bindings are used:
Prefix | Namespace |
---|---|
rdf: | http://www.w3.org/1999/02/22-rdf-syntax-ns# |
rdfs: | http://www.w3.org/2000/01/rdf-schema# |
sh: | http://www.w3.org/ns/shacl# |
xsd: | http://www.w3.org/2001/XMLSchema# |
ex: | http://example.com/ns# |
Throughout the document, color-coded boxes containing RDF graphs in Turtle will appear. These fragments of Turtle documents use the prefix bindings given above.
# This box represents a shapes graph<s> <p> <o> .
// This box contains JavaScript code
# This box represents a data graph.
# This box represents an output results graph
Formal definitions appear in blue boxes:
# This box contains textual definitions.
Grey boxes such as this include syntax rules that apply to the shapes graph.
true
denotes the RDF term"true"^^xsd:boolean
.false
denotes the RDF term"false"^^xsd:boolean
.
The terminology used throughout this document is consistent with the definitions in the main SHACL [shacl] specification, which references terms from RDF [rdf11-concepts]. This includes the termsblank node,conformance,constraint,constraint component,data graph,datatype,failure,focus node,RDF graph,ill-formed,IRI,literal,local name,node,node shape,object,parameter,predicate,property shape,RDF term,SHACL instance,shape,shapes graph,subject,target,triple,validation,validation report,validation result,validator,value,value node. Additional terms are defined in the SHACL Advanced Features document [shacl-af]:custom target,rule type,rule,SHACL function.
The Shapes Constraint Language (SHACL) [shacl] is a language for validatingRDF graphs against a set of conditions. These conditions are provided asshapes and other constructs expressed in the form of an RDF graph. SHACL is represented in RDF and consists of a SHACL Core RDF vocabulary with terms such assh:minCount
to express the most frequently neededconstraint kinds. However, in order to express more complex constraints, the SHACL Core vocabulary is often not sufficient. SHACL-SPARQL [shacl] is one extension mechanism for SHACL to express constraints in SPARQL, allowing shape definitions to point at executable SPARQL [sparql11-query] queries to perform the validation checks. This document defines theSHACL JavaScript Extensions (SHACL-JS), allowing users to express SHACL constraints and the advanced features of custom targets, functions and rules with the help of JavaScript.
SHACL-JS is based on a similar design to SHACL-SPARQL, but for JavaScript instead of SPARQL. The basic idea is that SHACL shapes can point at JavaScript functions in specified JavaScript files that can be resolved from the web. When shapes get evaluated, a SHACL-JS engine calls those functions with a predefined set of arguments and constructs validation results from the values and objects returned by these JavaScript function calls. The JavaScript code can access RDF triples from both theshapes graph and thedata graph where needed, through theJavaScript API that is defined in this document, or a higher-level JavaScript API that uses the specified API under the hood.
As a result of this design, SHACL shape definitions can be augmented with JavaScript and executed either within web browsers (assuming the SHACL engine operates on the client), or on servers that support JavaScript execution.
As well as sections marked as non-normative, all authoring guidelines, diagrams, examples, and notes in this specification are non-normative. Everything else in this specification is normative.
The key wordsMUST andMUST NOT are to be interpreted as described in [RFC2119].
This section defines an API that JavaScript-based SHACL functions can use to operate onRDF terms and to querytriples ingraphs. The JavaScript code behind SHACL-JSconstraints andconstraint components can directly access those functions or go through a higher-level layer of convenience functions that use these functions under the hood.
Note that the API expects these JavaScript Objects to be immutable, i.e. neither the values of anRDF term nortriples norgraphs can be modified during SHACLvalidation.
AllRDF terms (IRIs,blank nodes andliterals) are represented using JavaScript Objects that have attributes as described in the following three subsections. The following table summarizes key functions to create and operate on RDF term Objects:
Node Kind | Factory Function | Test Function | Attributes |
---|---|---|---|
IRIs | TermFactory.namedNode(uri) | .isURI() | uri |
Blank Nodes | TermFactory.blankNode(id) orTermFactory.blankNode() | .isBlankNode() | id |
Literals | TermFactory.literal(lex, languageOrDatatype) | .isLiteral() | datatype ,language ,lex |
Note that the attributes in the table above are only defined for Objects that have matching types. For example, the result of querying theuri
of ablank node is undefined.
Each of these Objects must have a function.equals(other)
that takes another term Object as its only parameter and returnstrue
exactly if the underlyingRDF terms are equal, andfalse
otherwise.
AnIRI is represented by a JavaScriptNamedNode
Object where.isURI()
returnstrue
while.isBlankNode()
and.isLiteral()
returnfalse
. The value of the read-only attributeuri
is theIRI string.
Ablank node is represented by a JavaScriptBlankNode
Object where.isBlankNode()
returnstrue
while.isURI()
and.isLiteral()
returnfalse
. The value of the read-only attributeid
is the blank node identifier as a string. That string is must be consistent for the same RDF node for the duration of a SHACL validation and processing of validation results.
Aliteral is represented by a JavaScriptLiteral
Object where.isLiteral()
returnstrue
while.isURI()
and.isBlankNode()
returnfalse
. The value of the read-only attributelanguage
is a lowercase BCP-47 [BCP47] string (for example,en
,en-gb
), or an empty string if the literal has no language. The value of the read-only attributedatatype
is aNamedNode representing the datatype IRI of the literal. Note that thisdatatype
is never undefined, and language-tagged strings haverdf:langString
as their datatype. The value of the read-only attributelex
is the lexical form of the literal, e.g."042"
for the RDF node"042"^^xsd:integer
.
During the execution of JavaScript code, the SHACL engineMUST provide an Object accessible via the variableTermFactory
that can be used to create JavaScript Objects for RDF terms. TheTermFactory
provides the following three functions:
namedNode(uri)
returns aNamedNode with theIRI provided as a string viauri
.blankNode(id)
returns aBlankNode with an optional identifier provided as a string viaid
. If theid
is omitted then the system generates a unique identifier.literal(lex, languageOrDatatype)
returns aLiteral with the lexical form provided as a string vialex
. The second argumentlanguageOrDatatype
must be either a non-empty string, in which case the literal will have that value as its language tag, or a JavaScriptNamedNode Object representing a datatype other thanrdf:langString
. An RDFtriple is represented by a JavaScriptTriple
Object with three read-only attributessubject
,predicate
andobject
, each of which has exactly one RDF term as its value. Furthermore, triples must provide anequals
function that takes an Objectother
as its only parameter and returns a boolean.equals
returnstrue
exactly ifother
has values for its attributessubject
,predicate
andobject
that returntrue
when compared usingequals()
against the corresponding attribute values of the first triple, andfalse
otherwise.
An RDF graph is represented by a JavaScriptGraph
Object that has a functionfind
which takes three parameters of type Object, all of which are optional. The result of thefind
function is anIterator object with two functions:
next()
either returns aTriple
ornull
if the iteration has been exhausted.close()
terminates theIterator and releases any resources allocated by it. Onceclose()
has been called, further calls tonext()
cause an exception. Theclose()
functionMUST always be called unless the iterator has already been walked to completion. The following JavaScript snippet assumes that the currentdata graph is represented by the variable$data
and gets the first label of a given resource where the label is an english literal.
function getEnglishLabel(resource) {var labelProperty = TermFactory.namedNode("http://www.w3.org/2000/01/rdf-schema#label");var labels = $data.find(resource, labelProperty, null);for(;;) {var labelTriple = labels.next();if(!labelTriple) {return null;}var label = labelTriple.object;if(label.isLiteral() && label.language.startsWith("en")) {labels.close();return label.value;}}}
During avalidation process, the variable$data
points at the JavaScriptGraph
Object representing the SHACLdata graph.
During a validation process, the variable$shapes
points at the JavaScriptGraph Object representing the SHACLshapes graph. This may be identical to thedata graph.
This section is non-normative.
The iterators produced by thefind
function described in this section are expected to be operating synchronously, i.e. the triples are available immediately to the caller. Since many of the constraints that users want to express in SHACL can be quite complex, a synchronous API contract typically leads to more maintainable code than an asynchronous one (with callbacks or promises). If data needs to be loaded on demand from a remote server, then solutions such as pre-caching or theawait
keyword may be used as a work-around. More sophisticated handling of asynchronous query scenarios may be defined by future versions of SHACL-JS.
SHACL-JS processors must provide a JavaScript function with the following signature:
SHACL.nodeConformsToShape(node, shape)
node
: TheRDF term Object of thenode to validateshape
: TheRDF term Object of theshape to validate thenode against The result of this function istrue
if and only ifnode
conforms to theshape
, andfalse
otherwise.
This function is needed because the implementation of some of theconstraint components such assh:NotConstraintComponent
requires the ability to spawn off a new SHACL validation process. It may also be used as entry point into the validation engine by custom code.
This section defines some generalRDF terms used by SHACL-JS to represent JavaScript code and libraries as part of a declarativeshapes graph.
The SHACL-JS vocabulary includes the classsh:JSExecutable
. SHACL instances of this class are calledJavaScript executables and may have values for the propertiessh:jsFunctionName
andsh:jsLibrary
.
EveryJavaScript executable must have exactly onevalue for the propertysh:jsFunctionName
.The values ofsh:jsFunctionName
areliterals withdatatypexsd:string
.
The semantics of how arguments are passed into the provided function depend on the specific type of executable, as described in later sections.
EveryJavaScript executable must have at least onevalue for the propertysh:jsLibrary
.Thevalues of the propertysh:jsLibrary
areIRIs orblank nodes.Thevalues of the propertysh:jsLibrary
are well-formed SHACL instances of the classsh:JSLibrary
.
The classsh:JSLibrary
can be used to declareJavaScript libraries. A library can be understood as a pointer to zero or more JavaScript files that need to be executed before aJavaScript executable can be evaluated. Libraries may depend on each other by declaring furthersh:jsLibrary
triples.
The values of the propertysh:jsLibraryURL
areliterals withdatatypexsd:anyURI
.
This section defines general rules for the execution of JavaScript declared in RDF, by a SHACL engine.
args
be a mapping of variable names to RDF nodes. The result of theexecution of a JavaScript function usingargs
is the result of the invocation of the JavaScript function, matching each variable name inargs
to parameter values in the function's signature. A JavaScript parameter matches a variable name if its name is equal to the concatenation of"$"
and the variable name. For the above definition, consider an example functionmyFunction($arg1, $arg2, $arg3) { ... }
and a variable mapping{ "arg1" : ex:Instance1, "arg2" : 42 }
. The JavaScript function would be called with the JavaScriptNamedNode
object representingex:Instance1
as value for$arg1
, the JavaScriptLiteral
object representing42
as value for$arg2
, andundefined
as value for$arg3
.
sh:jsLibrary
(including the libraries referenced by those libraries), followed by theexecution of the JavaScript function that has the same name as thevalue ofsh:jsFunctionName
. The result of the latter is the result of executing the executable.sh:jsLibraryURL
must be resolved into JavaScript code. By default this resolution mechanismMUST be performing an HTTP GET request against the given script URL. AfailureMUST be reported if the SHACL processor encounters a cyclic dependency between libraries.In practice, SHACL implementations may redirect the resolution of URLs to local files or cached copies.
SHACL-JS supports constraints that can be used to express restrictions based on JavaScript. In a nutshell, whenever a SHACL validation engine encounters ashape with ash:js
constraint, it will execute the provided JavaScript function and use the returned result to createvalidation results.
Constraint Component IRI:sh:JSConstraintComponent
Property | Summary |
---|---|
sh:js | AJavaScript-based constraint declaring the JavaScript function to evaluate. |
Thevalues ofsh:js
at ashape are calledJavaScript-based constraints. Each JavaScript-based constraint is also aJavaScript executable. The syntax rules and validation process for JavaScript-based constraints are defined in the rest of this section.
This section is non-normative.
The following example illustrates the syntax of aJavaScript-based constraint.
ex:ValidCountry a ex:Country ;ex:germanLabel "Spanien"@de .ex:InvalidCountry a ex:Country ;ex:germanLabel "Spain"@en .
function validateGermanLabel($this) {var results = [];var p = TermFactory.namedNode("http://example.org/ns#germanLabel");var s = $data.find($this, p, null);for(var t = s.next(); t; t = s.next()) {var object = t.object;if(!object.isLiteral() || !object.language.startsWith("de")) {results.push({value : object});}}return results;}
ex:LanguageExampleShapea sh:NodeShape ;sh:targetClass ex:Country ;sh:js [ # _:b1a sh:JSConstraint ; # This triple is optionalsh:message "Values are literals with German language tag." ;sh:jsLibrary [ sh:jsLibraryURL "http://example.org/js/germanLabel.js" ] ;sh:jsFunctionName "validateGermanLabel" ;] .
Thetarget of theshape above includes allSHACL instances ofex:Country
. For those nodes (represented by the variable$this
), the JavaScript code walks through thevalues of the propertyex:germanLabel
at$this
and verifies that they areliterals with a German language tag. Thevalidation report for the aforementioneddata graph is shown below:
[a sh:ValidationReport ;sh:conforms false ;sh:result [a sh:ValidationResult ;sh:resultSeverity sh:Violation ;sh:focusNode ex:InvalidCountry ;sh:resultMessage "Values are literals with German language tag." ;sh:resultPath ex:germanLabel ;sh:value "Spain"@en ;sh:sourceConstraint _:b1 ;sh:sourceConstraintComponent sh:JSConstraintComponent ;sh:sourceShape ex:LanguageExampleShape ;]] .
This section defines the validator ofsh:JSConstraintComponent
.
true
as avalue for the propertysh:deactivated
. Otherwise, for eachfocus nodeF
and eachvalue nodeV
forF
,execute the constraint's JavaScript function using the argument mapping{ "this" : F, "value" : V }
.Construct validation results for each result returned by these function calls. Report afailure if the execution of the JavaScript function results in an exception. The following rules define how to constructvalidation results from a given JavaScript function resultR
in the context of a givenconstraintC
in ashapeS
, afocus nodeF
and avalue nodeV
.
R
is a JavaScriptString
:Create avalidation result?r
. Add a triple?r sh:resultMessage ?s
where?s
is anxsd:string
literal with the JavaScriptString
as its lexical form. Add atriple?r sh:value ?v
where?v
is the currentvalue nodeV
.R
is a JavaScript Array: For each member of the ArrayR
apply the rule forJavaScript Objects.R
is a JavaScriptObject
(not aString
):Create avalidation result?r
. IfR.value
is anRDF term object?v
, add atriple?r sh:value ?v
. IfR.message
is a JavaScriptString
, add atriple?r sh:resultMessage ?s
where?s
is anxsd:string
literal with the givenString
as its lexical form. Otherwise, addtriples?r sh:resultMessage ?m
from theshapeS
following the rules defined by [shacl]. If theshapeS
is anode shape
andR.path
is an RDFNamedNode
object?path
, add atriple?r sh:resultPath ?path
.R
is the JavaScriptBoolean
false
:Create avalidation result?r
. Add atriple?r sh:value ?v
where?v
is the currentvalue nodeV
. Addtriples?r sh:resultMessage ?m
from theshapeS
following the rules defined by [shacl].To create a validation result?r
, create atriple?r rdf:type sh:ValidationResult
using the providedfocus nodeF
as value forsh:focusNode
, derivingsh:resultSeverity
from thesh:severity
of theshapeS
in theshapes graph (usingsh:Violation
as default), and setting thesh:resultPath
,sh:sourceConstraintComponent
andsh:sourceShape
following the rules defined by [shacl]. If the result is produced by aJavaScript-based constraint, then setsh:sourceConstraint
to thevalue ofsh:js
of theconstraintC
in theshapes graph.
SHACL is based onconstraint components, which can be used to expressconstraints in a declarative, high-level vocabulary. For example, the constraint componentsh:MinCountConstraintComponent
defines aparametersh:minCount
. When ashape uses one of these constraint parameters, a SHACL engine finds a suitablevalidator that can produce validation results. SHACL-SPARQL [shacl] defines how SPARQL queries can be used as validators. SHACL-JS defines a classsh:JSValidator
which can be used to declare validators using JavaScript.
This section is non-normative.
The following example demonstrates how JavaScript can be used to specify newconstraint components using SHACL-JS. The example implementssh:maxLength
using a JavaScript-basedvalidator to validate that the string representation of eachvalue node has at most a given number of characters. Note that this is only an example implementation and should not be considered normative.
function hasMaxLength($value, $maxLength) {if($value.isLiteral()) {return $value.lex.length <= $maxLength.lex;}else if($value.isURI()) {return $value.uri.length <= $maxLength.lex;}else { // Blank nodereturn false;}}
sh:MaxLengthConstraintComponenta sh:ConstraintComponent ;sh:parameter [sh:path sh:maxLength ;sh:datatype xsd:integer ;] ;sh:validator ex:hasMaxLength .ex:hasMaxLengtha sh:JSValidator ;sh:message "Value has more than {$maxLength} characters" ;rdfs:comment """Note that $value and $maxLength are RDF nodes expressed in JavaScript Objects.Their string value is accessed via the .lex and .uri attributes.The function returns true if no violation has been found.""" ;sh:jsLibrary [ sh:jsLibraryURL "http://example.org/ns/hasMaxLength.js"^^xsd:anyURI ] ;sh:jsFunctionName "hasMaxLength" .
The declaration ofJavaScript-based Constraint Components in ashapes graph is very similar toSPARQL-based Constraint Components. In particular, components declare theirparameters usingsh:parameter
. In fact, the sameconstraint component may serve as a declaration of both a SPARQL-based and a JavaScript-based constraint component, assuming thatvalidators have been declared for both cases. Where SHACL-SPARQL uses the classessh:SPARQLSelectValidator
andsh:SPARQLAskValidator
, SHACL-JS uses the classsh:JSValidator
, which is a subclass ofsh:JSExecutable
. Each SHACL-JS validator is also aJavaScript executable and therefore has a value forsh:jsFunctionName
.
This section defines thevalidator ofJavaScript-based constraint components.
?E
be theJavaScript executable selected for theconstraint component?C
based on the rules outlined insection 6.2.3 of [shacl]. If theshape is aproperty shape and theshapes graph contains atriple?C sh:propertyValidator ?E
then letpath
be the value ofsh:path
at theshape in theshapes graph, andexecute?E
for eachfocus nodeF
using a mapping{ "this" : F, "path" : path }
. (The validator's JavaScript function can access thepath
structure in theshapes graph$shapes
, assuming the function declares$path
as one of its parameters.) Otherwise, for eachfocus nodeF
and eachvalue nodeV
,execute?E
using a mapping{ "this" : F, "value" : V }
.Construct validation results for each result returned by these function calls. Report afailure if the execution of the JavaScript function results in an exception. The SHACL Advanced Features includes a generic mechanism to declare newSHACL functions. In particular this is used to declare new SPARQL functions, using the classsh:SPARQLFunction
. SHACL-JS includes a very similar mechanism, allowing users to declare new functions in an RDF vocabulary so that certain engines can use them. Functions declared using the SHACL-JS vocabulary can, among others, be used by function calls in SPARQL FILTER or BIND clauses and inSHACL rules.
This section is non-normative.
The following example demonstrates how JavaScript can be used to specify new SHACL function. The function can be used, for example in SPARQL usingBIND (ex:square(4) AS ?s)
.
function square($number) {return $number.lex * $number.lex;}
ex:squarea sh:JSFunction ;sh:parameter [sh:path ex:number ;sh:datatype xsd:integer ;] ;sh:returnType xsd:integer ;sh:jsLibrary [ sh:jsLibraryURL "http://example.org/js/square.js"^^xsd:anyURI ] ;sh:jsFunctionName "square" .
The syntax ofJavaScript-based functions is very similar to SPARQL-based functions. EachSHACL instance ofsh:JSFunction
in ashapes graph, that is anIRI, declares one function. TheIRI identifies the function, for example, in SPARQL queries. The function parameters are declared usingsh:parameter
in the same way as theparameters ofconstraint components are declared. The optional propertysh:returnType
can be used to specify the type of results produced by the function. Finally,sh:JSFunction
is a subclass ofsh:JSExecutable
, and the syntax rules ofJavaScript executables apply to functions, too. In particular, each JavaScript-based function has onevalue ofsh:jsFunctionName
. This is the name of the JavaScript function that is executed whenever the (SHACL) function is called.
The JavaScript resultR
of theexecution of the function is turned into anRDF node using the following rules:
R
is aString
: return anxsd:string
literal with the string as its lexical formR
is anObject
representing anRDF node: returnR
R
is aNumber
and the function declares ash:returnType
T
and the Number can be converted to a well-formedliteral with datatypeT
: return aliteral with datatypeT
and the given value as lexical formR
is aNumber
that can be converted to a well-formedliteral with datatypexsd:decimal
: return anxsd:decimal
literal with the given value as lexical formR
is a Boolean: return anxsd:boolean
literal with the given value as lexical form During the execution of a JavaScript function, the variable$data
can be used to access the current query graph, while the variable$shapes
is undefined.
The SHACL Advanced Features document introduced the concept of SHACL-basedrules which included an extension mechanism that can be used to define newrule types. This section defines arule type calledJavaScript rules.
Rule Type IRI | Key Property | Other Properties |
---|---|---|
sh:JSRule | sh:jsFunctionName | sh:jsLibrary |
This section is non-normative.
The following example illustrates the use of aJavaScript rule to compute the area of a rectangle, by multiplying width and height.
var NS = "http://datashapes.org/js/tests/rules/rectangle.test#";function computeArea($this) {var width = getProperty($this, "width");var height = getProperty($this, "height");var area = TermFactory.literal(width.lex * height.lex, width.datatype);var areaProperty = TermFactory.namedNode(NS + "area");return [ [$this, areaProperty, area] ]; }function getProperty($this, name) {var it = $data.find($this, TermFactory.namedNode(NS + name), null);var result = it.next().object;it.close();return result;}
Note that this code is quite verbose because it uses only the very basic SHACL JavaScript API. In real-world examples, a higher level API with convenience methods is likely used.
ex:RectangleShapea sh:NodeShape ;sh:targetClass ex:Rectangle ;sh:rule [a sh:JSRule ; # This triple is optionalsh:jsFunctionName "computeArea" ;sh:jsLibrary [ sh:jsLibraryURL "http://example.org/js/rectangle.js"^^xsd:anyURI ] ; ] .
For the followingdata graph, thetriples below would be produced.
ex:ExampleRectanglea ex:Rectangle ;ex:width 7 ;ex:height 8 .
Inferred triples:
ex:ExampleRectangle ex:area 56 .
sh:jsLibrary
) have been executed. For eachfocus node,execute the JavaScript function specified as thevalue ofsh:jsFunctionName
at therule in theshapes graph, using thefocus node as the first (and only) argument into the function. If the resultR
of the function call is an Array then for each memberO
of this Array apply the instructions below.O
is an Array: Infer a newtriple withsubjectO[0]
,predicateO[1]
andobjectO[2]
.O
is anotherObject
: Infer a newtriple withsubjectO.subject
,predicateO.predicate
andobjectO.object
. In other words, each member of the Array returned by the JavaScript function must either be another Array with three members (forsubject,predicate andobject), of a JavaScript Object with three fieldssubject
,predicate
andobject
.
As one of the SHACL Advanced Features,custom targets define a mechanism to computetarget nodes by more flexible means than the built-in target types. Similar to SPARQL-based targets, this section introducescustom targets based on JavaScript.
Custom targets that areSHACL instances ofsh:JSTarget
are calledJavaScript-based targets.
JavaScript-based targets have the same syntax rules asJavaScript executables (e.g., requires ash:jsFunctionName
).The function must return a JavaScript Array where each member is an RDF term Object.
T
be aJavaScript-based target. Thetarget nodes ofT
are thenodes in the Array returned by itsexecution against thedata graph. Very similar toSPARQL-basedtarget types, there is a classsh:JSTargetType
declared asrdfs:subClassOf sh:TargetType
forJavaScript-based target types.
JavaScript-based target types have the same syntax rules asJavaScript executables (e.g., requires ash:jsFunctionName
).The function must return a JavaScript Array where each member is an RDF term Object.
T
be aJavaScript-based target of target typeY
. Thetarget nodes ofT
are thenodes in the Array returned by theexecution ofY
against thedata graph. Similar toJavaScript-based constraint components, for the execution of the JavaScript function, allparameter values ofT
are mapped to the JavaScript arguments by thelocal name of theparameter property (for example,ex:country
is passed into the function as values of$country
).This section enumerates all normative syntax rules of SHACL-JS. This section is automatically generated from other parts of this spec and hyperlinks are provided back into the prose if the context of the rule in unclear. Nodes that violate these rules in ashapes graph areill-formed.
Syntax Rule Id | Syntax Rule Text |
---|---|
jsFunctionName-count | EveryJavaScript executable must have exactly onevalue for the propertysh:jsFunctionName . |
jsFunctionName-datatype | The values ofsh:jsFunctionName areliterals withdatatypexsd:string . |
jsLibrary-minCount | EveryJavaScript executable must have at least onevalue for the propertysh:jsLibrary . |
jsLibrary-nodeKind | Thevalues of the propertysh:jsLibrary areIRIs orblank nodes. |
jsLibrary-class | Thevalues of the propertysh:jsLibrary are well-formed SHACL instances of the classsh:JSLibrary . |
jsLibraryURL-datatype | The values of the propertysh:jsLibraryURL areliterals withdatatypexsd:anyURI . |
JSTarget | JavaScript-based targets have the same syntax rules asJavaScript executables (e.g., requires ash:jsFunctionName ). The function must return a JavaScript Array where each member is an RDF term Object. |
JSTargetType | JavaScript-based target types have the same syntax rules asJavaScript executables (e.g., requires ash:jsFunctionName ). The function must return a JavaScript Array where each member is an RDF term Object. |
This section is non-normative.
SHACL-JS shares certain security and privacy considerations with thosementioned in [shacl]. In addition, JavaScript opens a whole new range of topics that are outside of the scope of this document. The general advice is for users to only use trusted and controlled shape graphs.