UNPKG

lincd-jsonld

Version:

Utilities to parse and write JSON-LD for the LINCD library

169 lines 7.7 kB
"use strict"; 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; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.JSONLDWriter = void 0; /* * 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/. */ const jsonld_1 = __importDefault(require("jsonld")); const { promises: jsonld } = jsonld_1.default; const models_1 = require("lincd/models"); const QuadSet_1 = require("lincd/collections/QuadSet"); const Prefix_1 = require("lincd/utils/Prefix"); const NQuads_1 = require("lincd/utils/NQuads"); const package_js_1 = require("../package.js"); const Shape_1 = require("lincd/shapes/Shape"); const QuadArray_1 = require("lincd/collections/QuadArray"); const NodeSet_1 = require("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_1.QuadSet) { return this.fromQuads(object, true, includeGraphs); } else if (object instanceof models_1.NamedNode || object instanceof Shape_1.Shape) { return this.fromQuads(this.addNodeQuads(object), true, includeGraphs); } else if (object instanceof models_1.Graph) { return this.fromGraph(object, includeGraphs); } else if (object instanceof NodeSet_1.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_1.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_1.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_1.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 ? Object.assign(Object.assign({}, 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 models_1.BlankNode) { this.addNodeQuads(quad.object, quads); } } } return quads; } static getIterableQuads(iterable) { let quads = new QuadArray_1.QuadArray(); iterable.forEach((item) => { if (item instanceof models_1.Graph) { quads = quads.concat([...item.getContents()]); } else if (item instanceof models_1.Quad) { quads.push(item); } else if (item instanceof models_1.Node || item instanceof Shape_1.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_1.QuadArray(); nodeSet.forEach((item) => { quads = quads.concat(this.addNodeQuads(item, quads)); }); return quads; } }; exports.JSONLDWriter = JSONLDWriter; exports.JSONLDWriter = JSONLDWriter = __decorate([ package_js_1.linkedUtil ], JSONLDWriter); //# sourceMappingURL=JSONLDWriter.js.map