All files / rdf shape-repository.ts

75.67% Statements 84/111
67.64% Branches 46/68
71.42% Functions 10/14
75.67% Lines 84/111

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354              5x           5x                 6x   6x 3x 48x 44x   44x       3x   3x 1x 1x   1x       3x 1x 1x   1x       3x 2x 1x   1x                         2x 2x 2x 2x       2x 2x 2x 2x                         2x 1x     2x 2x     2x 2x     2x                                                                                                                 4x   4x 1x 1x       3x 1x 1x       2x 2x 1x       1x                                       3x                                                               1x 1x 1x                         2x 2x   2x 3x 2x 2x     3x 1x 1x       2x                       5x                   5x 24x       24x   24x   10x     14x   14x   10x   10x   10x   5x     5x         5x 1x   4x       5x     4x 4x               1x     1x     2x                       5x    
import { rdf, rdfs, sh, SH } from "../ontologies";
import { Store } from "./store";
import { DefinitionQueryOptions, TypedInstanceQueryOptions } from "./resource-repository";
import { IndividualRepository } from "./individual-repository";
import { Quad_Subject } from "@rdfjs/types";
import { dataFactory } from "./data-factory";
 
const { namedNode } = dataFactory;
 
/**
 * A repository for retrieving SHACL shapes from graphs.
 */
export class ShapeRepository extends IndividualRepository {
    constructor(store: Store) { super(store); }
 
    /**
     * Get all shapes in the repository.
     * @param graphUris URIs of the graphs to search, `undefined` for the default graph.
     * @param options Optional query parameters.
     * @returns An iterable of all shapes in the repository.
     */
    *getShapes(graphUris: string | string[] | undefined, subjectUri?: string, options?: DefinitionQueryOptions): IterableIterator<string> {
        const yielded = new Set<string>();
 
        if (!subjectUri) {
            for (let q of this.store.matchAll(graphUris, null, rdf.type, sh.Shape, options?.includeInferred)) {
                if (!yielded.has(q.subject.value) && !this.skip(graphUris, q.subject, options)) {
                    yielded.add(q.subject.value);
 
                    yield q.subject.value;
                }
            }
        } else {
            const s = namedNode(subjectUri);
 
            for (let q of this.store.matchAll(graphUris, s, rdf.type, sh.Shape, options?.includeInferred)) {
                Eif (!yielded.has(q.subject.value) && !this.skip(graphUris, q.subject, options)) {
                    yielded.add(q.subject.value);
 
                    yield q.subject.value;
                }
            }
 
            for (let q of this.store.matchAll(graphUris, null, sh.targetClass, s, options?.includeInferred)) {
                Eif (!yielded.has(q.subject.value) && !this.skip(graphUris, q.subject, options)) {
                    yielded.add(q.subject.value);
 
                    yield q.subject.value;
                }
            }
 
            for (let q of this.store.matchAll(graphUris, null, sh.path, s, options?.includeInferred)) {
                if (!yielded.has(q.subject.value) && !this.skip(graphUris, q.subject, options)) {
                    yielded.add(q.subject.value);
 
                    yield q.subject.value;
                }
            }
        }
    }
 
    /**
     * Get all shape types in the repository.
     * @param graphUris URIs of the graphs to search, `undefined` for the default graph.
     * @param options Optional query parameters.
     * @returns A list of all shape types in the repository.
     */
    *getShapeTypes(graphUris: string | string[] | undefined, options?: DefinitionQueryOptions): IterableIterator<string> {
        for (let q of this.store.matchAll(graphUris, null, rdf.type, sh.NodeShape)) {
            Eif (!this.skip(graphUris, q.subject, options, { includeBlankNodes: true })) {
                yield SH.NodeShape;
                break;
            }
        }
 
        for (let q of this.store.matchAll(graphUris, null, rdf.type, sh.PropertyShape)) {
            Eif (!this.skip(graphUris, q.subject, options, { includeBlankNodes: true })) {
                yield SH.PropertyShape;
                break;
            }
        }
    }
 
    /**
     * Get all validator types in the repository.
     * @param graphUris URIs of the graphs to search, `undefined` for the default graph.
     * @param options Optional query parameters.
     * @returns An iterable of all shape types in the repository.
     */
    *getValidatorTypes(graphUris: string | string[] | undefined, options?: DefinitionQueryOptions): IterableIterator<string> {
        // Get all validators in the repository, including the inferred ones.
        if (this.store.any(graphUris, null, rdf.type, sh.Validator, options?.includeInferred)) {
            yield SH.Validator;
        }
 
        Eif (this.store.any(graphUris, null, rdf.type, sh.JSValidator, false)) {
            yield SH.JSValidator;
        }
 
        Eif (this.store.any(graphUris, null, rdf.type, sh.SPARQLAskValidator, false)) {
            yield SH.SPARQLAskValidator;
        }
 
        Iif (this.store.any(graphUris, null, rdf.type, sh.SPARQLSelectValidator, false)) {
            yield SH.SPARQLSelectValidator;
        }
    }
 
    /**
     * Get all target classes, nodes or properties of a given shape in the repository.
     * @param graphUris URIs of the graphs to search, `undefined` for the default graph.
     * @param shape The URI or blank id of the shape.
     * @param options Optional query parameters.
     * @returns An iterable of all targeted resources in the repository.
     */
    *getShapeTargets(graphUris: string | string[] | undefined, shape: Quad_Subject, options?: DefinitionQueryOptions): IterableIterator<string> {
        const yielded = new Set<string>();
 
        // Add the shape definition itself if it is a class.
        for (let q of this.store.matchAll(graphUris, shape, rdf.type, rdfs.Class, true)) {
            if (!yielded.has(q.subject.value)) {
                yielded.add(q.subject.value);
 
                yield q.subject.value;
            }
        }
 
        for (let q of this.store.matchAll(graphUris, shape, sh.targetClass, null, options?.includeInferred)) {
            if (!yielded.has(q.object.value)) {
                yielded.add(q.object.value);
 
                yield q.object.value;
            }
        }
 
        for (let q of this.store.matchAll(graphUris, shape, sh.targetNode, null, options?.includeInferred)) {
            if (!yielded.has(q.object.value)) {
                yielded.add(q.object.value);
 
                yield q.object.value;
            }
        }
 
        for (let q of this.store.matchAll(graphUris, shape, sh.path, null, options?.includeInferred)) {
            if (!yielded.has(q.object.value)) {
                yielded.add(q.object.value);
 
                yield q.object.value;
            }
        }
    }
 
    /**
     * Indicate if there are shapes for a subject in the repository.
     * @param graphUris URIs of the graphs to search, `undefined` for the default graph.
     * @param subjectUri The URI of the subject.
     * @param options Optional query parameters.
     * @returns `true` if there are shapes for the subject, `false` otherwise.
     */
    hasShapes(graphUris: string | string[] | undefined, subjectUri: string, options?: DefinitionQueryOptions): boolean {
        const s = namedNode(subjectUri);
 
        for (let q of this.store.matchAll(graphUris, s, rdf.type, sh.Shape)) {
            Eif (!this.skip(graphUris, q.subject, options, { includeBlankNodes: true })) {
                return true;
            }
        }
 
        for (let q of this.store.matchAll(graphUris, null, sh.targetClass, s)) {
            Eif (!this.skip(graphUris, q.subject, options, { includeBlankNodes: true })) {
                return true;
            }
        }
 
        for (let q of this.store.matchAll(graphUris, null, sh.path, s)) {
            if (!this.skip(graphUris, q.subject, options, { includeBlankNodes: true })) {
                return true;
            }
        }
 
        return false;
    }
 
    /**
     * Indicate if there validators defined in the vocabulary.
     * @param graphUris URIs of the graphs to search, `undefined` for the default graph.
     * @param options Optional query parameters.
     * @returns A list of all validators in the repository.
     */
    hasValidators(graphUris: string | string[] | undefined, options?: DefinitionQueryOptions & TypedInstanceQueryOptions): boolean {
        return this.hasSubjectsOfType(graphUris, SH.Validator, options);
    }
 
    /**
     * Get all validators in the repository.
     * @param graphUris URIs of the graphs to search, `undefined` for the default graph.
     * @param options Optional query parameters.
     * @returns A list of all validators in the repository.
     */
    *getValidators(graphUris: string | string[] | undefined, options?: DefinitionQueryOptions & TypedInstanceQueryOptions): IterableIterator<string> {
        yield* this.getSubjectsOfType(graphUris, SH.Validator, options);
    }
 
    /**
     * Indicate if there are rules in the repository.
     * @param graphUris URIs of the graphs to search, `undefined` for the default graph.
     * @param subjectUri The URI of the subject.
     * @param options Optional query parameters.
     * @returns `true` if there are rules for the subject, `false` otherwise.
     */
    hasRules(graphUris: string | string[] | undefined, options?: DefinitionQueryOptions & TypedInstanceQueryOptions): boolean {
        return this.hasSubjectsOfType(graphUris, SH.Rule, options);
    }
 
    /**
     * Get all rules in the repository.
     * @param graphUris URIs of the graphs to search, `undefined` for the default graph.
     * @param options Optional query parameters.
     * @returns A list of all rules in the repository.
     */
    *getRules(graphUris: string | string[] | undefined, options?: DefinitionQueryOptions & TypedInstanceQueryOptions): IterableIterator<string> {
        yield* this.getSubjectsOfType(graphUris, SH.Rule, options);
    }
 
    /**
     * Get the SHACL datatype of a given property.
     * @param graphUris URIs of the graphs to search, `undefined` for the default graph.
     * @param subjectUri The URI of the subject.
     * @param options Optional query parameters.
     * @returns A datatype URI on success, `xsd:anyURI` otherwise.
     */
    getDatatype(graphUris: string | string[] | undefined, subjectUri: string, options?: DefinitionQueryOptions): string | undefined {
        for (let q of this.store.matchAll(graphUris, null, sh.path, namedNode(subjectUri), options?.includeInferred)) {
            for (let x of this.store.matchAll(graphUris, q.subject, sh.datatype, null, options?.includeInferred)) {
                return x.object.value;
            }
        }
    }
 
    /**
     * Get the SHACL cardinality constraints of a given property.
     * @param graphUris URIs of the graphs to search, `undefined` for the default graph.
     * @param subjectUri The URI of the subject.
     * @param options Optional query parameters.
     * @returns An object with the minimum and maximum cardinalities; values are `-1` if not found.
     */
    getCardinalites(graphUris: string | string[] | undefined, subjectUri: string, options?: DefinitionQueryOptions): { minCount: number, maxCount: number } {
        let minCount = -1;
        let maxCount = -1;
 
        for (let q of this.store.matchAll(graphUris, null, sh.path, namedNode(subjectUri), options?.includeInferred)) {
            for (let x of this.store.matchAll(graphUris, q.subject, sh.minCount, null, options?.includeInferred)) {
                minCount = parseInt(x.object.value);
                break;
            }
 
            for (let x of this.store.matchAll(graphUris, q.subject, sh.maxCount, null, options?.includeInferred)) {
                maxCount = parseInt(x.object.value);
                break;
            }
        }
 
        return { minCount, maxCount };
    }
 
    /**
     * Get the RDF property path representation of the given SHACL property path. This method parses the SHACL property path and 
     * returns the RDF property path as a combination of nodes and strings.
     * @param graphUris URIs of the graphs to search, `undefined` for the default graph.
     * @param subject The URI or blank id of the node referred to by sh:path.
     * @param options Optional query parameters.
     * @returns A flattened list of all path components, either as URIs or as strings.
     */
    getPropertyPathTokens(graphUris: string | string[] | undefined, subject: Quad_Subject) {
        const visitedNodes = new Set<string>();
 
        /**
         * Parse the given subject node and return the path components.
         * @param subject The currently parsed focus node.
         * @param level The nesting level of the current path.
         * @param separator The separator to use to separate path components.
         * @param i The index of the current node in a list.
         * @returns The sub path of the current node.
         */
        const parse = (subject: Quad_Subject, level: number, separator: string = '/', i: number = 0): Array<Quad_Subject | string> => {
            Iif (visitedNodes.has(subject.value)) {
                return [];
            }
 
            visitedNodes.add(subject.value);
 
            if (subject.termType === 'NamedNode') {
                // If we have a terminal node, we add it to the path.
                return [subject];
            } else {
                // Determine if we are looking at an item in a collection.
                const first = this.store.matchAll(graphUris, subject, rdf.first, null, false).next().value;
 
                if (first) {
                    // Note: We increase the nesting level as nested nodes in paths need to be wrapped in parentheses.
                    const path = parse(first.object as Quad_Subject, level + 1);
 
                    const rest = this.store.matchAll(graphUris, subject, rdf.rest, null, false).next().value;
 
                    if (rest && rest.object.value !== rdf.nil.value) {
                        // The first item of the list sees the complete recursively parsed sub path.
                        const tail = parse(rest.object as Quad_Subject, level, separator, i + 1);
 
                        // If there is no tail we return the current item's path.
                        Iif (tail.length === 0) {
                            return path;
                        }
 
                        // For nested paths, we wrap the path in parentheses if it contains more than one item.
                        if (i === 0 && level > 0) {
                            return ['(', ...path, separator, ...tail, ')']
                        } else {
                            return [...path, separator, ...tail];
                        }
                    }
 
                    return path;
                } else {
                    // Blank nodes that are not lists contain SHACL path predicates.
                    for (let q of this.store.matchAll(graphUris, subject, null, null, false)) {
                        switch (q.predicate.value) {
                            case sh.inversePath.value: {
                                return ['^', ...parse(q.object as Quad_Subject, level)];
                            }
                            case sh.zeroOrOnePath.value: {
                                return [...parse(q.object as Quad_Subject, level), '?'];
                            }
                            case sh.zeroOrMorePath.value: {
                                return [...parse(q.object as Quad_Subject, level), '*'];
                            }
                            case sh.oneOrMorePath.value: {
                                return [...parse(q.object as Quad_Subject, level), '+'];
                            }
                            case sh.alternativePath.value: {
                                return parse(q.object as Quad_Subject, level, '|');
                            }
                            default:
                                throw new Error(`Unsupported path predicate: ${q.predicate.value}`);
                        }
                    }
 
                    throw new Error(`Unsupported path subject: ${subject}`);
                }
            }
        }
 
        return parse(subject, 0);
    }
}