npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@nanopub/nanopub-js

v0.3.2

Published

[![Coverage Status](https://coveralls.io/repos/github/Nanopublication/nanopub-js/badge.svg?branch=main)](https://coveralls.io/github/Nanopublication/nanopub-js?branch=main)

Readme

nanopub-js

Coverage Status

A TypeScript library for creating, signing, publishing, and querying nanopublications.

Installation

# Using npm
npm install @nanopub/nanopub-js

# Using yarn
yarn add @nanopub/nanopub-js

Usage

See examples/ for demo apps for browser and node usage.

Using NanopubClass

import { NanopubClass, serialize } from '@nanopub/nanopub-js';
import { NamedNode, Quad, Literal } from 'n3';

// Create a nanopub from an RDF string
const npFromRdf = NanopubClass.fromRdf(rdfString, 'trig', {
  privateKey,
  name: 'Hello from nanopub-js',
  orcid: 'https://orcid.org/0000-0000-0000-0000',
});

// Or create a nanopub from an assertion
const assertion = [
  new Quad(
    new NamedNode('https://example.org/subject'),
    new NamedNode('https://example.org/predicate'),
    new Literal('Example object')
  )
];

const np = new NanopubClass({
  assertion,
  options: {
    privateKey: process.env.MY_PRIVATE_KEY!,
    name: 'Hello from nanopub-js',
    orcid: 'https://orcid.org/0000-0000-0000-0000',
  }
});

// Serialize (default: trig)
console.log(np.rdf());

// Or use the serialize helper
console.log(await serialize(np, 'turtle'));
console.log(await serialize(np, 'json-ld'));

Signing and publishing

Nanopublications must be signed before publishing.

Calling publish() will automatically sign the nanopublication if it has not been signed yet.

// Sign the nanopublication
await np.sign();

// Check signature validity
const valid = await np.hasValidSignature();
console.log('Signature valid:', valid);

// Publish to a nanopub server (in this example, we use the test server)
const { uri, server } = await np.publish('https://test.registry.knowledgepixels.com/np/');
console.log(`Published at ${uri} on ${server}`);

Private key formats

The privateKey given to a nanopub is accepted in any of the usual RSA serializations, so a key can be passed straight from wherever it was generated:

  • PEM armor around a PKCS#8 key (-----BEGIN PRIVATE KEY-----), what openssl genpkey, Node's export({format: 'pem', type: 'pkcs8'}) and pycryptodome's export_key('PEM', pkcs=8) produce;
  • PEM armor around a PKCS#1 key (-----BEGIN RSA PRIVATE KEY-----), what openssl genrsa produces, converted to PKCS#8 on the way in;
  • the bare base64 of the DER with no armor, with or without line breaks — the form nanopub itself stores in ~/.nanopub/id_rsa and records in a signature.

Public keys are accepted the same way (-----BEGIN PUBLIC KEY-----, -----BEGIN RSA PUBLIC KEY-----, or bare base64). A key that cannot be used is reported by its format rather than as an opaque crypto error: a passphrase-protected key, for instance, names openssl pkcs8 -topk8 -nocrypt as the fix. The normalization is available on its own:

import { normalizePrivateKey, normalizePublicKey } from '@nanopub/nanopub-js';

normalizePrivateKey(pem); // base64 of the PKCS#8 DER, single line
normalizePublicKey(pem); // base64 of the SubjectPublicKeyInfo DER, single line

Reading JSON-LD

parse() and Nanopub.fromRdf() handle TriG, Turtle and the N-Triples family through n3, which does not parse JSON-LD. To read that syntax, pass a parser:

import jsonld from 'jsonld';

const parser = (input: string) => jsonld.toRDF(JSON.parse(input)) as Quad[];

const np = Nanopub.fromRdf(json, 'jsonld', { parser });

Asking for 'jsonld' without a parser throws, rather than parsing to nothing.

Introducing a key

Before the network trusts what you publish, the key you sign with has to be declared in an introduction nanopublication. createIntroNanopub builds one:

import { createIntroNanopub } from '@nanopub/nanopub-js';

const intro = await createIntroNanopub({
  agent: 'https://orcid.org/0000-0002-1267-0234',
  privateKey,
  name: 'Tobias Kuhn',
});

await intro.sign();
const { uri } = await intro.publish();

The agent IRI is usually an ORCID iD, but any foaf:Agent IRI works, a WebID included. The public key is derived from the private key unless you pass publicKey, and the introduction is self-signed by the key it declares.

Trust is granted per key rather than per agent, so an agent that already has an approved key adds another by publishing a further introduction under the same agent IRI. To restate existing keys alongside a new one, pass them together:

const intro = await createIntroNanopub({
  agent: 'https://orcid.org/0000-0002-1267-0234',
  privateKey,
  keys: [
    { publicKey: existingPublicKey, keyLocation: 'https://nanodash.net/' },
    { publicKey: newPublicKey },
  ],
});

Publishing an introduction does not by itself make the key trusted: an already trusted agent still has to endorse it.

grlc queries

A nanopublication cannot be edited after the fact, so a grlc query whose SPARQL doesn't parse is broken permanently: it can never run, and the only remedy is publishing a corrected version. The SPARQL carried by https://w3id.org/kpxl/grlc/sparql is therefore checked before the nanopublication is signed, and again before it is published — before any server is contacted. Nanopublications published before this check existed still load and read as before.

Where the query is broken by a character that reads as an ordinary one, which is the usual way it happens, the error names that character:

Nanopub has invalid SPARQL and cannot be signed: Invalid SPARQL as object of
https://w3id.org/kpxl/grlc/sparql: This is not valid SPARQL. The character at
line 2, column 8 is U+00A0 (NO-BREAK SPACE), which SPARQL doesn't allow there.
Characters like this one tend to slip in when a query is copied from a word
processor or a web page, and replacing them with their plain equivalents makes
the query valid again.

The same check is available on its own:

import { getSparqlSyntaxError, isValidSparql, getInvalidSparql } from '@nanopub/nanopub-js';

await isValidSparql('select ?np where { ?np ?p ?o }'); // true
await getSparqlSyntaxError(query); // the description above, or null
await getInvalidSparql(np); // one entry per broken query the nanopub carries

The check has to accept what grlc's own endpoint accepts, so it uses Traqula's SPARQL 1.1 parser configured to match RDF4J: the prefixes RDF4J declares for every query are pre-declared, and the restrictions Traqula enforces that RDF4J does not are left to the endpoint that runs the query. Measured against the 1364 grlc queries published so far, it agrees with RDF4J on all but two, and rejects none that RDF4J accepts.

The parser is loaded only when a nanopublication actually carries a grlc query, so it stays out of the bundle everything else pays for.

Using NanopubClient

import { NanopubClient } from '@nanopub/nanopub-js';

const client = new NanopubClient({
  endpoints: ['https://query.knowledgepixels.com/'],
});

// Fetch a nanopublication in Trig format
const trig = await client.fetchNanopub(
  'https://w3id.org/np/RAO0soO0mUWTqqMaz1QcGbdIt90MJ55RXJck8w8wGGc0U'
);
console.log(trig);

// Fetch a nanopublication in JSON-LD
const jsonld = await client.fetchNanopub(
  'https://w3id.org/np/RAO0soO0mUWTqqMaz1QcGbdIt90MJ55RXJck8w8wGGc0U',
  'jsonld'
);
console.log(jsonld);

// Run a text search
for await (const np of client.findNanopubsWithText('example search')) {
  console.log(np);
}

// Run a pattern search
for await (const np of client.findNanopubsWithPattern(
  'http://www.w3.org/2002/07/owl#Thing',
  undefined,
  undefined
)) {
  console.log(np);
}

// Find "things" (concepts)
for await (const thing of client.findThings(
  'http://www.w3.org/2002/07/owl#Class'
)) {
  console.log(thing);
}

// Run a query template
for await (const row of client.runQueryTemplate(
  'RAOGCU2nQzZ0aE2iXwJ20jJtnZsjVR0pfFg0qlSxYtBIA/get-news-content',
  { resource: 'https://w3id.org/spaces/knowledgepixels' }
)) {
  console.log(row);
}

License

This project is licensed under the MIT License.