rdflib.js Documentation

repository·main·Indexed 20 days ago

https://github.com/linkeddata/rdflib.js

A JavaScript RDF library for Node.js and browsers compatible with the RDF/JS data model specification. Version 2.4.0 supports reading and writing multiple formats (RDF/XML, Turtle, N3, RDFa, JSON-LD), SPARQL querying, and real-time collaborative editing. It includes features for owl:sameAs smushing, custom authenticated fetchers for private data like Solid pods, and an UpdateManager for handling server-side updates via PATCH and PUT.

Tokens
13.5K
Snippets
39
Records
54
Agent score
70%

What's inside rdflib.js

  1. Enable owl:sameAs smushing in a store

    main

    "Smushing" is the process of merging identifiers that are stated to denote the same thing. By default, rdflib stores perform no smushing. You must opt-in when creating the graph.

    To enable smushing for owl:sameAs, owl:InverseFunctionalProperty, and owl:FunctionalProperty, pass the feature names to the $rdf.graph() constructor:

    const kb = $rdf.graph(['sameAs', 'InverseFunctionalProperty', 'FunctionalProperty'])

    How Smushing Works

    • Equivalence: When A owl:sameAs B is added, the store chooses one node as canonical and re-indexes all statements under it. Queries for either identifier will return the merged data.
    • Internal Book-keeping: The store records the equivalence using the http://www.w3.org/2007/ont/link#uri namespace. It adds a statement: <canonical> <http://www.w3.org/2007/ont/link#uri> <obsoleted> .
    • Discovery: You can use store.uris(term) and store.allAliases(node) to list identifiers. If a Fetcher is attached, equating nodes triggers a look-up of the newly-learned alias.
    • Metadata: The Fetcher also uses the http://www.w3.org/2007/ont/link# namespace to record HTTP metadata (requests, responses, status codes) in a separate metadata graph. This can be cleared using store.removeMetadata(doc).
    const kb = $rdf.graph(['sameAs', 'InverseFunctionalProperty', 'FunctionalProperty'])
  2. How the UpdateManager determines editability

    main

    The UpdateManager determines if a URI is editable based on its protocol (Non-http(s) vs Http(s)) and specific server headers.

    Non-http(s) URI

    A URI is editable if:

    • The document contains a triple declaring itself as a ont:MachineEditableDocument.
    • OR the wac-allow header supports write access for the current user.

    Http(s) URI

    A URI is editable if both conditions are met:

    • The wac-allow header supports write access for the current user.
    • The response includes either an accept-patch or ms-author-via header (as defined in the update methods below).
  3. Update methods used by UpdateManager

    main

    The UpdateManager selects an update method based on the server's response headers.

    For Non-http(s) URIs

    • N3PATCH: Used if the accept-patch header's mime-essence is text/n3.
    • SPARQL PATCH: Used if the response contains accept-patch or ms-author-via headers.
    • PUT: Used as the fallback method.

    For Http(s) URIs

    • N3PATCH: Used if the accept-patch header's mime-essence is text/n3.
    • SPARQL PATCH: Used if:
      • accept-patch is application/sparql-update
      • accept-patch is application/sparql-update-single-match
      • ms-author-via contains the word SPARQL
    • PUT: Used if the ms-author-via header contains the word DAV.

    Important Implementation Notes

    • N3-PATCH Support: Currently, rdflib does not support N3-PATCH updates, even though it is mentioned in specifications.
    • PATCH vs PUT: When submitting a form, PATCH is used by default. However, PUT is used specifically when re-ordering elements in an ordered list.
  4. Use authenticated or alternate fetches via global variables

    main

    By default, rdflib uses cross-fetch.fetch(), which does not carry authentication information. To access private data (e.g., Solid pods) or use custom fetch implementations (e.g., Dropbox, databases), you can override the global fetch method used by rdflib.

    Steps to implement:

    1. Load your authentication library.
    2. Log in to your identity provider using that library.
    3. Assign the library's fetch method to the global fetch variable:
      • In a Browser: Set window.solidFetch.
      • In Node.js/CLI: Set global.solidFetch.

    Note on version compatibility:

    • For rdflib version 2.2.9 and later: Use solidFetch.
    • For rdflib prior to 2.2.9: Use solidFetcher.
    // Node.js Example
    const auth = new (require("solid-node-client").SolidNodeClient)();
    await auth.login( credentials );
    global.solidFetch = auth.fetch; 
    
    const $rdf = global.$rdf = require('rdflib');
    const kb = $rdf.graph();
    const fetcher = $rdf.fetcher(kb);
    await fetcher.load( 'https://some-private-url' );
  5. Install rdflib

    main

    You can install rdflib for use in a browser (via a bundler like Webpack) or in a Node.js environment.

    Browser (using a bundler)

    npm install rdflib

    Browser (manual build for <script> tag)

    If you need to generate a standalone <script> file, clone the repository and build the dist directory:

    git clone git@github.com:linkeddata/rdflib.js.git;
    cd rdflib.js;
    npm install;
    npm run build:browser

    Node.js

    npm install --save rdflib
    npm install rdflib
  6. Understand the DataFactory interface and supported features

    main

    The DataFactory is the primary interface for creating RDF terms and statements in rdflib.js. It extends the standard RdfJsDataFactory but includes additional extensions for managing graphs, variables, and unique identifiers.

    To understand the capabilities of a specific factory instance, you can inspect its supports property, which is a SupportTable (a mapping of Feature enums to booleans).

  7. Understand RDF/JS Term types

    main

    The library implements the RDF/JS specification for data modeling. All RDF data is composed of Terms, which are the building blocks of Quads.

    There are several types of terms:

    • NamedNode: An IRI (e.g., http://example.org/resource).
    • BlankNode: An identifier for a node without a URI.
    • Literal: A text value that may have a language (BCP-47 string) or a datatype (a NamedNode).
    • Variable: A placeholder used in queries (e.g., ?a).
    • DefaultGraph: A special term representing the default graph, where the value is always an empty string.

    Every term has a termType and a value. You can use the .equals(other) method to check for structural equality between two terms.

  8. Understand the difference between RDF/JS and RDFlib types

    main

    The project maintains two distinct type systems:

    1. RDF/JS spec types: Standardized, generic types used for interoperability.
    2. RDFlib types: Internal, specific implementations used by the library.

    Best Practice: When designing functions or consuming the API, it is preferable to accept generic RDF/JS inputs whenever possible and provide strict RDFlib outputs. Note that RDFlib types (like SubjectType, PredicateType, and ObjectType) are more specific; for example, a PredicateType must be a NamedNode or a Variable, whereas a generic Term could be a Literal.

  9. Understand the Quad and Triple structure

    main

    A Quad represents a single statement in RDF, consisting of a subject, predicate, object, and graph.

    • Subject: Must be a NamedNode, BlankNode, or Variable.
    • Predicate: Must be a NamedNode or Variable.
    • Object: Can be a NamedNode, BlankNode, Literal, Variable, or any other Term.
    • Graph: Can be a NamedNode, DefaultGraph, BlankNode, or Variable.

    If a graph is not provided when creating a statement, it is automatically assigned to the DefaultGraph.

    A Triple is conceptually the same as a Quad but is often used as a shorthand when the graph is implicit.

  10. Implement authenticated fetching in a Browser

    main

    To use authenticated Solid data in a browser environment, use a library like @inrupt/solid-client-authn-browser. You must handle the OIDC login redirect and then set window.solidFetcher (or window.solidFetch for newer versions) to the library's fetch method before performing rdflib operations.

    <!-- Simplified Browser Implementation Pattern -->
    <script src="https://cdn.jsdelivr.net/npm/@inrupt/solid-client-authn-browser@1.11.2/dist/solid-client-authn.bundle.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/rdflib@2.2.6/dist/rdflib.min.js"></script>
    
    <script>
        const idp = "https://solidcommunity.net";
        const privateResource = "https://jeff-zucker.solidcommunity.net/private/";
        
        // Set the fetcher for rdflib
        window.solidFetcher = solidClientAuthentication.fetch;
        
        async function main() {
            const kb = $rdf.graph();
            const fetcher = $rdf.fetcher(kb);
            try {
              await fetcher.load(privateResource);
              alert("Private resource successfully loaded");
            } catch(e) { alert(e); }
        }
    
        // Handle login and redirect logic
        document.getElementById('login').onclick = () => {
            solidClientAuthentication.login({
                oidcIssuer: idp,
                redirectUrl: window.location.href,
                clientName: "rdflib test"
            });
        };
    
        async function handleRedirectAfterLogin() {
            const session = await solidClientAuthentication.handleIncomingRedirect();
            if (session.info.isLoggedIn) main();
        }
        handleRedirectAfterLogin();
    </script>