lincd-jsonld
Version:
Utilities to parse and write JSON-LD for the LINCD library
163 lines • 7.21 kB
JavaScript
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import pkg from 'jsonld';
const { promises: jsonld } = pkg;
import { BlankNode, Graph, NamedNode, Node, Quad } from 'lincd/models';
import { QuadSet } from 'lincd/collections/QuadSet';
import { Prefix } from 'lincd/utils/Prefix';
import { NQuads } from 'lincd/utils/NQuads';
import { linkedUtil } from '../package.js';
import { Shape } from 'lincd/shapes/Shape';
import { QuadArray } from 'lincd/collections/QuadArray';
import { NodeSet } from 'lincd/collections/NodeSet';
let JSONLDWriter = class JSONLDWriter {
static stringify(object, includeGraphs = true, pretty = false) {
return this.toJSONObject(object, includeGraphs).then((jsonObject) => pretty ? JSON.stringify(jsonObject, null, 2) : JSON.stringify(jsonObject));
}
static toJSONObject(object, includeGraphs = true) {
if (object instanceof QuadSet) {
return this.fromQuads(object, true, includeGraphs);
}
else if (object instanceof NamedNode || object instanceof Shape) {
return this.fromQuads(this.addNodeQuads(object), true, includeGraphs);
}
else if (object instanceof Graph) {
return this.fromGraph(object, includeGraphs);
}
else if (object instanceof NodeSet) {
return this.fromQuads(this.getNodeSetQuads(object), true, includeGraphs);
}
else if (object.forEach) {
//so it must be an ICoreIterable (like an array or a Set) of things
//we'll try to convert each item
return this.fromQuads(this.getIterableQuads(object), true, includeGraphs);
}
else {
throw Error('Invalid argument provided. Not sure how to convert this to JSONLD');
// return this.fromGraphs(object);
}
}
static fromGraph(graph, includeGraphs = true) {
return this.fromGraphs([graph], includeGraphs);
}
static fromGraphs(graphs, includeGraphs = true, compact = true, extraContext) {
var nquads = NQuads.fromGraphs(graphs);
return this.NQuadsToJSONLD(nquads, compact, extraContext);
}
static fromQuads(quads, compact = true, includeGraphs = true, extraContext) {
//NOTE: sometimes we want to send temporary uri's, like when finding the right permanent URI for a temporary URI!
//NOTE: in other cases this may cause issues though. So this can be turned on when needing to debug when temporary URI's get converted to JSONLD
// let quad;
// if (
// (quad = quads.find(
// (q) =>
// q.subject.isTemporaryNode ||
// q.predicate.isTemporaryNode ||
// (q.object instanceof NamedNode && q.object.isTemporaryNode),
// ))
// ) {
// console.warn(
// 'You are converting nodes with a temporary URI to JSONLD. You should probably give these nodes an explicit URI first as their URI will be meaningless outside of the current runtime. Example quad: ' +
// quad.toString(),
// );
// }
var nquads = NQuads.fromQuads(quads, includeGraphs);
return this.NQuadsToJSONLD(nquads, compact, extraContext);
}
static NQuadsToJSONLD(nquads, compact = true, extraContext) {
var context = compact ? this.getContext(nquads, extraContext) : null;
return (jsonld
.fromRDF(nquads, { format: 'application/nquads' })
.then((doc) => {
if (compact) {
return jsonld.compact(doc, context);
}
return doc;
})
// .then(JSON.stringify)
.catch((e) => {
console.log(e.message);
if (e.message.indexOf('parse error on line') !== -1) {
let line = parseInt(e.message.split('parse error on line ')[1].split('.')[0]);
nquads = nquads
.split('\n')
.slice(line - 1, line)
.join('\n');
}
throw new Error('Could not convert quads to JSONLD. ' +
e.message +
`\n\nQuads in question:\n${nquads}`);
// console.warn('Error converting triples to JSONLD.');
// console.log(nquads);
// throw e;
}));
}
static getContext(nquads, extraContext) {
if (!nquads)
return {};
var context = {};
var prefixes = Prefix.getPrefixToUriMap();
//for each mapping from a fullURI to a prefix
prefixes.forEach((fullURI, prefix) => {
//if this fullURI occurs in the n-quads string
if (nquads.indexOf(fullURI) !== -1) {
//then we can use its prefix
context[prefix] = fullURI;
}
});
return extraContext ? { ...context, ...extraContext } : context;
}
static addNodeQuads(node, quads = []) {
//let quads: QuadArray | Quad[] = node.getAllQuads();
let nodeQuads = node.getAllQuads();
for (let quad of nodeQuads) {
//TODO: we had to introduce this check, but it's slow. So switch to using QuadSets. Remove QuadArray from library. that would speed this up a lot
if (quads.indexOf(quad) === -1) {
quads.push(quad);
if (quad.object instanceof BlankNode) {
this.addNodeQuads(quad.object, quads);
}
}
}
return quads;
}
static getIterableQuads(iterable) {
let quads = new QuadArray();
iterable.forEach((item) => {
if (item instanceof Graph) {
quads = quads.concat([...item.getContents()]);
}
else if (item instanceof Quad) {
quads.push(item);
}
else if (item instanceof Node || item instanceof Shape) {
quads = this.addNodeQuads(item, quads);
}
else if (item['forEach']) {
quads = quads.concat(this.getIterableQuads(item));
}
});
return quads;
}
static getNodeSetQuads(nodeSet) {
let quads = new QuadArray();
nodeSet.forEach((item) => {
quads = quads.concat(this.addNodeQuads(item, quads));
});
return quads;
}
};
JSONLDWriter = __decorate([
linkedUtil
], JSONLDWriter);
export { JSONLDWriter };
//# sourceMappingURL=JSONLDWriter.js.map