Movatterモバイル変換


[0]ホーム

URL:


W3C

SHACL JavaScript Extensions

W3C Working Group Note

This version:
https://www.w3.org/TR/2017/NOTE-shacl-js-20170608/
Latest published version:
https://www.w3.org/TR/shacl-js/
Latest editor's draft:
https://w3c.github.io/data-shapes/shacl-js/
Editors:
Holger Knublauch,TopQuadrant, Inc.
Pano Maria,Taxonic

Copyright © 2017W3C® (MIT,ERCIM,Keio,Beihang).W3Cliability,trademark anddocument use rules apply.


Abstract

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.

Status of This Document

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.

Document Conventions

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:

PrefixNamespace
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:

TEXTUAL DEFINITIONS
# 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.

Terminology

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.

1.Introduction

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.

2.Conformance

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].

3.JavaScript API for RDF

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.

3.1RDF Terms

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 KindFactory FunctionTest FunctionAttributes
IRIsTermFactory.namedNode(uri).isURI()uri
Blank NodesTermFactory.blankNode(id) orTermFactory.blankNode().isBlankNode()id
LiteralsTermFactory.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.

3.1.1IRIs / Named Nodes

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.

3.1.2Blank Nodes

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.

3.1.3Literals

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.

3.1.4The TermFactory

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.

3.2Triples

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.

3.3Graphs

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:

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;}}}

3.3.1Accessing the Data Graph via $data

During avalidation process, the variable$data points at the JavaScriptGraph Object representing the SHACLdata graph.

3.3.2Accessing the Shapes Graph via $shapes

During a validation process, the variable$shapes points at the JavaScriptGraph Object representing the SHACLshapes graph. This may be identical to thedata graph.

3.3.3Synchronous versus Asynchronous Queries

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.

3.4Validating Nodes via JavaScript

SHACL-JS processors must provide a JavaScript function with the following signature:

SHACL.nodeConformsToShape(node, shape)
  1. node: TheRDF term Object of thenode to validate
  2. shape: TheRDF term Object of theshape to validate thenode against

The result of this function istrue if and only ifnodeconforms 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.

4.Representing JavaScript in RDF

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.

4.1sh:jsFunctionName

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.

4.2sh:jsLibrary

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.

4.3sh: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.

5.Executing JavaScript

This section defines general rules for the execution of JavaScript declared in RDF, by a SHACL engine.

Execution of a JavaScript function
Letargs 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.

Execution of a JavaScript executable
Theexecution of aJavaScript executable consists ofexecuting anyJavaScript libraries that arevalues ofsh: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.
Execution of a JavaScript library
Within the same JavaScript engine, the sameJavaScript libraryMUST NOT be executed more than once. When aJavaScript library is executed, all its values forsh: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.

6.JavaScript-based Constraints

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:jsconstraint, it will execute the provided JavaScript function and use the returned result to createvalidation results.

Constraint Component IRI:sh:JSConstraintComponent

Parameters:
PropertySummary
sh:jsAJavaScript-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.

6.1An Example JavaScript-based Constraint

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 ;]] .

6.2Validation with JavaScript-based Constraints

This section defines the validator ofsh:JSConstraintComponent.

TEXTUAL DEFINITION
There are no validation results if theJavaScript-based constraint hastrue 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.

6.3Mapping of JavaScript Results to Result Properties

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.

  1. IfR 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.
  2. IfR is a JavaScript Array: For each member of the ArrayR apply the rule forJavaScript Objects.
  3. IfR 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:stringliteral 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.
  4. IfR is the JavaScriptBooleanfalse: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.

7.JavaScript-based Constraint Components

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.

7.1An Example JavaScript-based Constraint Component

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" .

7.2Syntax of JavaScript-based Constraint Components

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.

7.3Validation of JavaScript-based Constraint Components

This section defines thevalidator ofJavaScript-based constraint components.

TEXTUAL DEFINITION
Let?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.

8.JavaScript-based Functions

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.

8.1An Example JavaScript-based Function

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" .

8.2Syntax and Semantics of JavaScript-based Functions

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:

  1. IfR is aString: return anxsd:stringliteral with the string as its lexical form
  2. IfR is anObject representing anRDF node: returnR
  3. IfR is aNumber and the function declares ash:returnTypeTand the Number can be converted to a well-formedliteral with datatypeT: return aliteral with datatypeT and the given value as lexical form
  4. IfR is aNumber that can be converted to a well-formedliteral with datatypexsd:decimal: return anxsd:decimalliteral with the given value as lexical form
  5. IfR is a Boolean: return anxsd:booleanliteral with the given value as lexical form
  6. Otherwise: return no result

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.

9.JavaScript Rules

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 IRIKey PropertyOther Properties
sh:JSRulesh:jsFunctionNamesh:jsLibrary

9.1An Example JavaScript Rule

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 .

9.2Execution Instructions for JavaScript Rules

TEXTUAL DEFINITION
Prior to execution, ensure that all JavaScript libraries for therule (specified viash: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.
  1. IfO is an Array: Infer a newtriple withsubjectO[0],predicateO[1] andobjectO[2].
  2. IfO 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.

10.JavaScript-based Custom Targets

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.

10.1JavaScript-based Targets (sh:JSTarget)

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.

TEXTUAL DEFINITION
LetT be aJavaScript-based target. Thetarget nodes ofT are thenodes in the Array returned by itsexecution against thedata graph.

10.2JavaScript-based Target Types (sh:JSTargetType)

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.

TEXTUAL DEFINITION
LetT 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).

Appendix

A.Summary of SHACL-JS Syntax Rules

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 IdSyntax Rule Text
jsFunctionName-countEveryJavaScript executable must have exactly onevalue for the propertysh:jsFunctionName.
jsFunctionName-datatypeThe values ofsh:jsFunctionName areliterals withdatatypexsd:string.
jsLibrary-minCountEveryJavaScript executable must have at least onevalue for the propertysh:jsLibrary.
jsLibrary-nodeKindThevalues of the propertysh:jsLibrary areIRIs orblank nodes.
jsLibrary-classThevalues of the propertysh:jsLibrary are well-formed SHACL instances of the classsh:JSLibrary.
jsLibraryURL-datatypeThe values of the propertysh:jsLibraryURL areliterals withdatatypexsd:anyURI.
JSTargetJavaScript-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.
JSTargetTypeJavaScript-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.

B.Security and Privacy Considerations

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.

C.References

C.1Normative references

[BCP47]
Tags for Identifying Languages. A. Phillips; M. Davis. IETF. September 2009. IETF Best Current Practice. URL:https://tools.ietf.org/html/bcp47
[RFC2119]
Key words for use in RFCs to Indicate Requirement Levels. S. Bradner. IETF. March 1997. Best Current Practice. URL:https://tools.ietf.org/html/rfc2119
[rdf11-concepts]
RDF 1.1 Concepts and Abstract Syntax. Richard Cyganiak; David Wood; Markus Lanthaler. W3C. 25 February 2014. W3C Recommendation. URL:https://www.w3.org/TR/rdf11-concepts/
[shacl]
Shapes Constraint Language (SHACL). Holger Knublauch; Dimitris Kontokostas. W3C. 11 April 2017. W3C Candidate Recommendation. URL:https://www.w3.org/TR/shacl/
[shacl-af]
SHACL Advanced Features. Holger Knublauch; Dean Allemang; Simon Steyskal. W3C. W3C Working Group Note. URL:https://www.w3.org/TR/shacl-af/
[turtle]
RDF 1.1 Turtle. Eric Prud'hommeaux; Gavin Carothers. W3C. 25 February 2014. W3C Recommendation. URL:https://www.w3.org/TR/turtle/

C.2Informative references

[sparql11-query]
SPARQL 1.1 Query Language. Steven Harris; Andy Seaborne. W3C. 21 March 2013. W3C Recommendation. URL:https://www.w3.org/TR/sparql11-query/


[8]ページ先頭

©2009-2025 Movatter.jp