Skip to content

Commit

Permalink
update to latest jsdom
Browse files Browse the repository at this point in the history
  • Loading branch information
sballesteros committed Feb 25, 2019
1 parent 58143ea commit 1fbf3a2
Show file tree
Hide file tree
Showing 4 changed files with 106 additions and 91 deletions.
7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
"module": "src/index.js",
"scripts": {
"test": "mocha --compilers js:babel-register",
"prepublish": "rm -rf dist && babel src --out-dir dist"
"prepublish": "rm -rf dist && babel src --out-dir dist",
"postversion": "git push && git push --tags"
},
"repository": {
"type": "git",
Expand All @@ -25,15 +26,15 @@
"dependencies": {
"graph-rdfa-processor": "^1.3.0",
"is-url": "^1.2.2",
"jsdom": "^9.11.0",
"jsdom": "^13.2.0",
"xmldom": "^0.1.27"
},
"devDependencies": {
"babel-cli": "^6.23.0",
"babel-plugin-add-module-exports": "0.2.1",
"babel-preset-es2015": "^6.22.0",
"babel-register": "^6.23.0",
"eslint-config-scienceai": "^2.6.0",
"eslint-config-scienceai": "^4.4.0",
"jsonld": "0.4.11",
"mocha": "^3.2.0"
},
Expand Down
20 changes: 13 additions & 7 deletions src/browser/jsdom.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
let jsdom = {
env: (config) => {
if (config.done) {
config.done(new Error('Only DOM elements are supported in a browser environment'));
}
},
export function JSDOM() {
throw new Error('Only DOM elements are supported in a browser environment');
}

JSDOM.fromFile = function() {
return Promise.reject(
new Error('Only DOM elements are supported in a browser environment')
);
};

export default jsdom;
JSDOM.fromURL = function() {
return Promise.reject(
new Error('Only DOM elements are supported in a browser environment')
);
};
97 changes: 51 additions & 46 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@

import getRDFaGraph from 'graph-rdfa-processor';
import jsdom from 'jsdom'; // see ./browser/jsdom.js for browser version
import { JSDOM } from 'jsdom'; // see ./browser/jsdom.js for browser version
import { XMLSerializer } from 'xmldom'; // see ./browser/xmldom.js for browser version
import isUrl from 'is-url';

Expand All @@ -15,35 +14,15 @@ const XSD_STRING = 'http://www.w3.org/2001/XMLSchema#string';
/**
* @param data - a filePath, HTML string or URL
*/
export default function jsonldRdfaParser (data, callback) {
if (typeof data === 'object' && 'nodeType' in data) {
process(data);
}
else if (typeof data === 'string') {
let config = {
done: (err, window) => {
if (err) return callback(err);
process(window.document);
},
};
if (isUrl(data)) config.url = data;
else if (/<[a-z][\s\S]*>/i.test(data)) config.html = data;
else config.file = data;
jsdom.env(config);
}
else {
return callback(new Error('data must be a file path, HTML string, URL or a DOM element'));
}

export default function jsonldRdfaParser(data, callback) {
function process(node) {
let opts;
if (!node.baseURI || node.baseURI === 'about:blank') {
opts = { baseURI: 'http://localhost/' };
}

let dataset
, processingError
;
let dataset, processingError;
try {
let graph = getRDFaGraph(node, opts);
dataset = processGraph(graph);
Expand All @@ -52,24 +31,48 @@ export default function jsonldRdfaParser (data, callback) {
}
callback(processingError, dataset);
}

if (typeof data === 'object' && 'nodeType' in data) {
process(data);
} else if (typeof data === 'string') {
if (isUrl(data)) {
JSDOM.fromURL(data)
.then(dom => {
process(dom.window.document);
})
.catch(callback);
} else if (/<[a-z][\s\S]*>/i.test(data)) {
process(new JSDOM(data).window.document);
} else {
JSDOM.fromFile(data)
.then(dom => {
process(dom.window.document);
})
.catch(callback);
}
} else {
return callback(
new Error('data must be a file path, HTML string, URL or a DOM element')
);
}
}

/**
* This function is mostly taken from the jsonld.js lib but updated to
* the latest green-turtle API, and for support for HTML
*/
function processGraph (data) {
function processGraph(data) {
let dataset = {
'@default': [],
'@default': []
};

let subjects = data.subjects
, htmlMapper = (n) => {
let div = n.ownerDocument.createElement('div');
div.appendChild(n.cloneNode(true));
return div.innerHTML;
}
;
let subjects = data.subjects,
htmlMapper = n => {
let div = n.ownerDocument.createElement('div');
div.appendChild(n.cloneNode(true));
return div.innerHTML;
};

Object.keys(subjects).forEach(subject => {
let predicates = subjects[subject].predicates;
Object.keys(predicates).forEach(predicate => {
Expand All @@ -83,12 +86,12 @@ function processGraph (data) {

// add subject & predicate
triple.subject = {
type: subject.indexOf('_:') === 0 ? 'blank node' : 'IRI',
value: subject,
type: subject.indexOf('_:') === 0 ? 'blank node' : 'IRI',
value: subject
};
triple.predicate = {
type: predicate.indexOf('_:') === 0 ? 'blank node' : 'IRI',
value: predicate,
type: predicate.indexOf('_:') === 0 ? 'blank node' : 'IRI',
value: predicate
};
triple.object = {};

Expand All @@ -102,32 +105,34 @@ function processGraph (data) {
if (object.type === RDF_XML_LITERAL) {
// initialize XMLSerializer
let serializer = new XMLSerializer();
value = Array.from(object.value).map(n => serializer.serializeToString(n)).join('');
value = Array.from(object.value)
.map(n => serializer.serializeToString(n))
.join('');
triple.object.datatype = RDF_XML_LITERAL;
}
// serialise HTML literal
else if (object.type === RDF_HTML_LITERAL) {
value = Array.from(object.value).map(htmlMapper).join('');
value = Array.from(object.value)
.map(htmlMapper)
.join('');
triple.object.datatype = RDF_HTML_LITERAL;
}
// object is an IRI
else if (object.type === RDF_OBJECT) {
if (object.value.indexOf('_:') === 0) triple.object.type = 'blank node';
if (object.value.indexOf('_:') === 0)
triple.object.type = 'blank node';
else triple.object.type = 'IRI';
}
else {
} else {
// object is a literal
triple.object.type = 'literal';
if (object.type === RDF_PLAIN_LITERAL) {
if (object.language) {
triple.object.datatype = RDF_LANGSTRING;
triple.object.language = object.language;
}
else {
} else {
triple.object.datatype = XSD_STRING;
}
}
else {
} else {
triple.object.datatype = object.type;
}
}
Expand Down
73 changes: 38 additions & 35 deletions test/test.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@

import assert from 'assert';
import fs from 'fs';
import path from 'path';
import jsonld from 'jsonld';
import jsonldRdfaParser from '../src';
import jsdom from 'jsdom';
import { JSDOM } from 'jsdom';
import http from 'http';

const htmlPath = path.join(path.dirname(__filename), 'fixtures', 'test.html');
Expand All @@ -14,44 +13,43 @@ const expected = {
'@type': 'ScholarlyArticle',
name: {
'@type': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#HTML',
'@value': 'De la <em>bombe</em> bébé!',
'@value': 'De la <em>bombe</em> bébé!'
},
author: {
'@id': '_:b0',
'@type': 'sa:ContributorRole',
roleAffiliation: {
'@id': 'https://science.ai/',
'@type': 'Corporation',
name: 'science.ai',
name: 'science.ai'
},
roleContactPoint: {
'@id': '_:b1',
'@type': 'ContactPoint',
email: { '@id': 'mailto:[email protected]' },
email: { '@id': 'mailto:[email protected]' }
},
author:
{
author: {
'@id': 'http://berjon.com/',
'@type': 'Person',
familyName: 'Berjon',
givenName: 'Robin',
},
givenName: 'Robin'
}
},
contributor: {
'@id': '_:b2',
'@type': 'sa:ContributorRole',
roleAffiliation: {
roleAffiliation: {
'@id': 'https://science.ai/',
'@type': 'Corporation',
name: 'science.ai',
name: 'science.ai'
},
contributor: {
'@id': 'https://github.com/sballesteros',
'@type': 'Person',
familyName: 'Ballesteros',
givenName: 'Sebastien',
},
},
givenName: 'Sebastien'
}
}
};

const frame = {
Expand All @@ -60,28 +58,27 @@ const frame = {
sa: 'http://ns.science.ai#',
roleAffiliation: {
'@id': 'sa:roleAffiliation',
'@type': '@id',
'@type': '@id'
},
roleContactPoint: {
'@id': 'sa:roleContactPoint',
'@type': '@id',
'@type': '@id'
},
author: {
'@type': '@id',
'@type': '@id'
},
contributor: {
'@type': '@id',
},
'@type': '@id'
}
},
'@embed': '@always',
'@type': 'ScholarlyArticle',
'@type': 'ScholarlyArticle'
};


describe('jsonld-rdfa-parser', () => {
let server;

before((done) => {
before(done => {
jsonld.registerRDFParser('text/html', jsonldRdfaParser);
server = http.createServer((req, res) => {
fs.readFile(htmlPath, (error, data) => {
Expand All @@ -92,18 +89,20 @@ describe('jsonld-rdfa-parser', () => {
server.listen(3000, '127.0.0.1', done);
});

it('should parse RDFa from a file path ', (done) => {
it('should parse RDFa from a file path ', done => {
jsonld.fromRDF(htmlPath, { format: 'text/html' }, (err, data) => {
if (err) return done(err);
jsonld.frame(data, frame, (err, framed) => {
assert.deepEqual(framed['@graph'][0], expected);
done();
});
});
});

it('should parse RDFa from a string of HTML ', (done) => {
it('should parse RDFa from a string of HTML ', done => {
fs.readFile(htmlPath, { encoding: 'utf8' }, (err, html) => {
jsonld.fromRDF(html, { format: 'text/html' }, (err, data) => {
if (err) return done(err);
jsonld.frame(data, frame, (err, framed) => {
assert.deepEqual(framed['@graph'][0], expected);
done();
Expand All @@ -112,11 +111,11 @@ describe('jsonld-rdfa-parser', () => {
});
});

it('should parse RDFa from a DOM node', (done) => {
it('should parse RDFa from a DOM node', done => {
fs.readFile(htmlPath, { encoding: 'utf8' }, (err, html) => {
let { body } = jsdom.jsdom(html).defaultView.window.document;
let { body } = new JSDOM(html).window.document;
jsonld.fromRDF(body, { format: 'text/html' }, (err, data) => {
if (err) throw err;
if (err) return done(err);
jsonld.frame(data, frame, (err, framed) => {
assert.deepEqual(framed['@graph'][0], expected);
done();
Expand All @@ -125,14 +124,18 @@ describe('jsonld-rdfa-parser', () => {
});
});

it('should parse RDFa from a URL', (done) => {
jsonld.fromRDF('http://127.0.0.1:3000', { format: 'text/html' }, (err, data) => {
if (err) throw err;
jsonld.frame(data, frame, (err, framed) => {
assert.deepEqual(framed['@graph'][0], expected);
done();
});
});
it('should parse RDFa from a URL', done => {
jsonld.fromRDF(
'http://127.0.0.1:3000',
{ format: 'text/html' },
(err, data) => {
if (err) return done(err);
jsonld.frame(data, frame, (err, framed) => {
assert.deepEqual(framed['@graph'][0], expected);
done();
});
}
);
});

after(() => {
Expand Down

0 comments on commit 1fbf3a2

Please sign in to comment.