Skip to content

Instantly share code, notes, and snippets.

@nkavian
Last active August 29, 2015 14:16
Show Gist options
  • Select an option

  • Save nkavian/dbb5c5e0acfc9a0295fb to your computer and use it in GitHub Desktop.

Select an option

Save nkavian/dbb5c5e0acfc9a0295fb to your computer and use it in GitHub Desktop.
function (doc, meta) {
var jsonld={};jsonld.compact=function(input,ctx){var options={};var callbackArg=2;if(arguments.length>3){options=arguments[2]||{};callbackArg+=1}var callback=arguments[callbackArg];if(input===null){return callback(null,null)}if(!('base'in options)){options.base=''}if(!('strict'in options)){options.strict=true}if(!('optimize'in options)){options.optimize=false}if(!('graph'in options)){options.graph=false}if(!('resolver'in options)){options.resolver=jsonld.urlResolver}jsonld.expand(input,options,function(err,expanded){if(err){return callback(new JsonLdError('Could not expand input before compaction.','jsonld.CompactError',{cause:err}))}var activeCtx=_getInitialContext();jsonld.processContext(activeCtx,ctx,options,function(err,activeCtx){if(err){return callback(new JsonLdError('Could not process context before compaction.','jsonld.CompactError',{cause:err}))}try{if(options.optimize){options.optimizeCtx={}}input=expanded;var compacted=new Processor().compact(activeCtx,null,input,options);cleanup(null,compacted,activeCtx,options)}catch(ex){callback(ex)}})});function cleanup(err,compacted,activeCtx,options){if(err){return callback(err)}if(!options.graph&&_isArray(compacted)&&compacted.length===1){compacted=compacted[0]}else if(options.graph&&_isObject(compacted)){compacted=[compacted]}if(_isObject(ctx)&&'@context'in ctx){ctx=ctx['@context']}ctx=_clone(ctx);if(!_isArray(ctx)){ctx=[ctx]}if(options.optimizeCtx){ctx.push(options.optimizeCtx)}var tmp=ctx;ctx=[];for(var i in tmp){if(!_isObject(tmp[i])||Object.keys(tmp[i]).length>0){ctx.push(tmp[i])}}var hasContext=(ctx.length>0);if(ctx.length===1){ctx=ctx[0]}if(hasContext||options.graph){if(_isArray(compacted)){var kwgraph=_compactIri(activeCtx,'@graph');var graph=compacted;compacted={};if(hasContext){compacted['@context']=ctx}compacted[kwgraph]=graph}else if(_isObject(compacted)){var graph=compacted;compacted={'@context':ctx};for(var key in graph){compacted[key]=graph[key]}}}callback(null,compacted,activeCtx)}};jsonld.expand=function(input){var options={};var callback;var callbackArg=1;if(arguments.length>2){options=arguments[1]||{};callbackArg+=1}callback=arguments[callbackArg];if(!('base'in options)){options.base=''}if(!('resolver'in options)){options.resolver=jsonld.urlResolver}input=_clone(input);_resolveContextUrls(input,options.resolver,function(err,input){if(err){return callback(err)}try{var ctx=_getInitialContext();var expanded=new Processor().expand(ctx,null,input,options,false);if(_isObject(expanded)&&('@graph'in expanded)&&Object.keys(expanded).length===1){expanded=expanded['@graph']}if(!_isArray(expanded)){expanded=[expanded]}callback(null,expanded)}catch(ex){callback(ex)}})};jsonld.frame=function(input,frame){var options={};var callbackArg=2;if(arguments.length>3){options=arguments[2]||{};callbackArg+=1}var callback=arguments[callbackArg];if(!('base'in options)){options.base=''}if(!('resolver'in options)){options.resolver=jsonld.urlResolver}if(!('embed'in options)){options.embed=true}options.explicit=options.explicit||false;options.omitDefault=options.omitDefault||false;options.optimize=options.optimize||false;var ctx=frame['@context']||{};jsonld.expand(input,options,function(err,_input){if(err){return callback(new JsonLdError('Could not expand input before framing.','jsonld.FrameError',{cause:err}))}jsonld.expand(frame,options,function(err,_frame){if(err){return callback(new JsonLdError('Could not expand frame before framing.','jsonld.FrameError',{cause:err}))}try{var framed=new Processor().frame(_input,_frame,options)}catch(ex){return callback(ex)}options.graph=true;jsonld.compact(framed,ctx,options,function(err,compacted,ctx){if(err){return callback(new JsonLdError('Could not compact framed output.','jsonld.FrameError',{cause:err}))}var graph=_compactIri(ctx,'@graph');compacted[graph]=_removePreserve(ctx,compacted[graph]);callback(null,compacted)})})})};jsonld.normalize=function(input,callback){var options={};var callback;var callbackArg=1;if(arguments.length>2){options=arguments[1]||{};callbackArg+=1}callback=arguments[callbackArg];if(!('base'in options)){options.base=''}if(!('resolver'in options)){options.resolver=jsonld.urlResolver}jsonld.expand(input,options,function(err,expanded){if(err){return callback(new JsonLdError('Could not expand input before normalization.','jsonld.NormalizeError',{cause:err}))}new Processor().normalize(expanded,options,callback)})};jsonld.fromRDF=function(statements){var options={};var callback;var callbackArg=1;if(arguments.length>2){options=arguments[1]||{};callbackArg+=1}callback=arguments[callbackArg];if(!('notType'in options)){options.notType=false}if(!('format'in options)&&!_isArray(statements)){if(!('format'in options)){options.format='application/nquads'}}if('format'in options){if(options.format in _rdfParsers){statements=_rdfParsers[options.format](statements)}else{throw new JsonLdError('Unknown input format.','jsonld.UnknownFormat',{format:options.format})}}new Processor().fromRDF(statements,options,callback)};jsonld.toRDF=function(input){var options={};var callback;var callbackArg=1;if(arguments.length>2){options=arguments[1]||{};callbackArg+=1}callback=arguments[callbackArg];if(!('base'in options)){options.base=''}if(!('resolver'in options)){options.resolver=jsonld.urlResolver}if(!('collate'in options)){options.collate=false}if(options.collate){var statements=[];var collateCallback=callback;callback=function(err,statement){if(err){return collateCallback(err)}if(statement!==null){for(var i in statements){if(_compareRdfStatements(statements[i],statement)){return}}statements.push(statement)}else{if('format'in options){statements=statements.sort().join('')}collateCallback(null,statements)}}}if('format'in options){if(options.format==='application/nquads'){var statementCallback=callback;callback=function(err,statement){if(err){return statementCallback(err)}if(statement!==null){statement=_toNQuad(statement)}statementCallback(null,statement)}}else{throw new JsonLdError('Unknown output format.','jsonld.UnknownFormat',{format:options.format})}}jsonld.expand(input,options,function(err,expanded){if(err){return callback(new JsonLdError('Could not expand input before conversion to RDF.','jsonld.RdfError',{cause:err}))}try{var namer=new UniqueNamer('_:t');new Processor().toRDF(expanded,namer,null,null,null,callback)}catch(ex){callback(ex)}})};jsonld.urlResolver=function(url,callback){return callback(new JsonLdError('Could not resolve @context URL. URL resolution not implemented.','jsonld.ContextUrlError'))};jsonld.ContextCache=function(size){this.order=[];this.cache={};this.size=size||50;this.expires=30*60*1000};jsonld.ContextCache.prototype.get=function(url){if(url in this.cache){var entry=this.cache[url];if(entry.expires>=+new Date()){return entry.ctx}delete this.cache[url];this.order.splice(this.order.indexOf(url),1)}return null};jsonld.ContextCache.prototype.set=function(url,ctx){if(this.order.length===this.size){delete this.cache[this.order.shift()]}this.order.push(url);this.cache[url]={ctx:ctx,expires:(+new Date()+this.expires)}};jsonld.urlResolvers={};jsonld.urlResolvers['jquery']=function($){var cache=new jsonld.ContextCache();return function(url,callback){var ctx=cache.get(url);if(ctx!==null){return callback(null,ctx)}$.ajax({url:url,dataType:'json',crossDomain:true,success:function(data,textStatus,jqXHR){cache.set(url,data);callback(null,data)},error:function(jqXHR,textStatus,errorThrown){callback(errorThrown)}})}};jsonld.urlResolvers['node']=function(){var request=require('request');var cache=new jsonld.ContextCache();return function(url,callback){var ctx=cache.get(url);if(ctx!==null){return callback(null,ctx)}request(url,function(err,res,body){if(!err){cache.set(url,body)}callback(err,body)})}};jsonld.useUrlResolver=function(type){if(!(type in jsonld.urlResolvers)){throw new JsonLdError('Unknown @context URL resolver type: "'+type+'"','jsonld.UnknownUrlResolver',{type:type})}jsonld.urlResolver=jsonld.urlResolvers[type].apply(jsonld,Array.prototype.slice.call(arguments,1))};jsonld.processContext=function(activeCtx,localCtx){if(localCtx===null){return callback(null,_getInitialContext())}var options={};var callbackArg=2;if(arguments.length>3){options=arguments[2]||{};callbackArg+=1}var callback=arguments[callbackArg];if(!('base'in options)){options.base=''}if(!('resolver'in options)){options.resolver=jsonld.urlResolver}localCtx=_clone(localCtx);if(_isObject(localCtx)&&!('@context'in localCtx)){localCtx={'@context':localCtx}}_resolveContextUrls(localCtx,options.resolver,function(err,ctx){if(err){return callback(err)}try{ctx=new Processor().processContext(activeCtx,ctx,options);callback(null,ctx)}catch(ex){callback(ex)}})};jsonld.hasProperty=function(subject,property){var rval=false;if(property in subject){var value=subject[property];rval=(!_isArray(value)||value.length>0)}return rval};jsonld.hasValue=function(subject,property,value){var rval=false;if(jsonld.hasProperty(subject,property)){var val=subject[property];var isList=_isList(val);if(_isArray(val)||isList){if(isList){val=val['@list']}for(var i in val){if(jsonld.compareValues(value,val[i])){rval=true;break}}}else if(!_isArray(value)){rval=jsonld.compareValues(value,val)}}return rval};jsonld.addValue=function(subject,property,value,options){options=options||{};if(!('propertyIsArray'in options)){options.propertyIsArray=false}if(!('allowDuplicate'in options)){options.allowDuplicate=true}if(_isArray(value)){if(value.length===0&&options.propertyIsArray&&!(property in subject)){subject[property]=[]}for(var i in value){jsonld.addValue(subject,property,value[i],options)}}else if(property in subject){var hasValue=(!options.allowDuplicate&&jsonld.hasValue(subject,property,value));if(!_isArray(subject[property])&&(!hasValue||options.propertyIsArray)){subject[property]=[subject[property]]}if(!hasValue){subject[property].push(value)}}else{subject[property]=options.propertyIsArray?[value]:value}};jsonld.getValues=function(subject,property){var rval=subject[property]||[];if(!_isArray(rval)){rval=[rval]}return rval};jsonld.removeProperty=function(subject,property){delete subject[property]};jsonld.removeValue=function(subject,property,value,options){options=options||{};if(!('propertyIsArray'in options)){options.propertyIsArray=false}var values=jsonld.getValues(subject,property).filter(function(e){return!jsonld.compareValues(e,value)});if(values.length===0){jsonld.removeProperty(subject,property)}else if(values.length===1&&!options.propertyIsArray){subject[property]=values[0]}else{subject[property]=values}};jsonld.compareValues=function(v1,v2){if(v1===v2){return true}if(_isValue(v1)&&_isValue(v2)&&v1['@value']===v2['@value']&&v1['@type']===v2['@type']&&v2['@language']===v2['@language']){return true}if(_isObject(v1)&&('@id'in v1)&&_isObject(v2)&&('@id'in v2)){return v1['@id']===v2['@id']}return false};jsonld.getContextValue=function(ctx,key,type){var rval=null;if(key===null){return rval}if(type==='@language'&&(type in ctx)){rval=ctx[type]}if(key in ctx.mappings){var entry=ctx.mappings[key];if(_isUndefined(type)){rval=entry}else if(type in entry){rval=entry[type]}}return rval};var _rdfParsers={};jsonld.registerRDFParser=function(contentType,parser){_rdfParsers[contentType]=parser};jsonld.unregisterRDFParser=function(contentType){delete _rdfParsers[contentType]};var _nodejs=(typeof module!=='undefined');var _browser=!_nodejs;if(_nodejs){module.exports=jsonld;jsonld.useUrlResolver('node');if(typeof XMLSerializer==='undefined'){var XMLSerializer=null}if(typeof Node==='undefined'){var Node={ELEMENT_NODE:1,ATTRIBUTE_NODE:2,TEXT_NODE:3,CDATA_SECTION_NODE:4,ENTITY_REFERENCE_NODE:5,ENTITY_NODE:6,PROCESSING_INSTRUCTION_NODE:7,COMMENT_NODE:8,DOCUMENT_NODE:9,DOCUMENT_TYPE_NODE:10,DOCUMENT_FRAGMENT_NODE:11,NOTATION_NODE:12}}}var XSD_BOOLEAN='http://www.w3.org/2001/XMLSchema#boolean';var XSD_DOUBLE='http://www.w3.org/2001/XMLSchema#double';var XSD_INTEGER='http://www.w3.org/2001/XMLSchema#integer';var RDF='http://www.w3.org/1999/02/22-rdf-syntax-ns#';var RDF_FIRST=RDF+'first';var RDF_REST=RDF+'rest';var RDF_NIL=RDF+'nil';var RDF_TYPE=RDF+'type';var RDF_PLAIN_LITERAL=RDF+'PlainLiteral';var RDF_XML_LITERAL=RDF+'XMLLiteral';var RDF_OBJECT=RDF+'object';var MAX_CONTEXT_URLS=10;var JsonLdError=function(msg,type,details){if(_nodejs){Error.call(this);Error.captureStackTrace(this,this.constructor)}this.name=type||'jsonld.Error';this.message=msg||'An unspecified JSON-LD error occurred.';this.details=details||{}};if(_nodejs){require('util').inherits(JsonLdError,Error)}var Processor=function(){};Processor.prototype.compact=function(ctx,property,element,options){if(_isArray(element)){var rval=[];for(var i in element){var e=this.compact(ctx,property,element[i],options);if(e!==null){rval.push(e)}}if(rval.length===1){var container=jsonld.getContextValue(ctx,property,'@container');if(container!=='@list'&&container!=='@set'){rval=rval[0]}}return rval}if(_isObject(element)){if(_isValue(element)){if(Object.keys(element).length===1){if(!('@language'in ctx)||!_isString(element['@value'])){return element['@value']}var rval={};rval[_compactIri(ctx,'@value')]=element['@value'];return rval}var type=jsonld.getContextValue(ctx,property,'@type');var language=jsonld.getContextValue(ctx,property,'@language');if(type!==null&&('@type'in element)&&element['@type']===type){return element['@value']}else if(language!==null&&('@language'in element)&&element['@language']===language){return element['@value']}else{var rval={};if('@type'in element){rval[_compactIri(ctx,'@type')]=_compactIri(ctx,element['@type'])}else if('@language'in element){rval[_compactIri(ctx,'@language')]=element['@language']}rval[_compactIri(ctx,'@value')]=element['@value'];return rval}}if(_isSubjectReference(element)){var type=jsonld.getContextValue(ctx,property,'@type');if(type==='@id'||property==='@graph'){return _compactIri(ctx,element['@id'])}}var rval={};for(var key in element){var value=element[key];if(key==='@id'||key==='@type'){if(_isString(value)){value=_compactIri(ctx,value)}else{var types=[];for(var i in value){types.push(_compactIri(ctx,value[i]))}value=types}var prop=_compactIri(ctx,key);var isArray=(_isArray(value)&&value.length===0);jsonld.addValue(rval,prop,value,{propertyIsArray:isArray});continue}if(value.length===0){var prop=_compactIri(ctx,key);jsonld.addValue(rval,prop,[],{propertyIsArray:true})}for(var i in value){var v=value[i];var isList=_isList(v);var prop=_compactIri(ctx,key,v);if(isList){v=v['@list']}v=this.compact(ctx,prop,v,options);var container=jsonld.getContextValue(ctx,prop,'@container');if(isList&&container!=='@list'){if(prop in rval&&options.strict){throw new JsonLdError('JSON-LD compact error; property has a "@list" @container '+'rule but there is more than a single @list that matches '+'the compacted term in the document. Compaction might mix '+'unwanted items into the list.','jsonld.SyntaxError')}var kwlist=_compactIri(ctx,'@list');var val={};val[kwlist]=v;v=val}var isArray=(container==='@set'||container==='@list'||(_isArray(v)&&v.length===0));jsonld.addValue(rval,prop,v,{propertyIsArray:isArray})}}return rval}return element};Processor.prototype.expand=function(ctx,property,element,options,propertyIsList){if(typeof element==='undefined'){throw new JsonLdError('Invalid JSON-LD syntax; undefined element.','jsonld.SyntaxError')}if(_isArray(element)){var rval=[];for(var i in element){var e=this.expand(ctx,property,element[i],options,propertyIsList);if(_isArray(e)&&propertyIsList){throw new JsonLdError('Invalid JSON-LD syntax; lists of lists are not permitted.','jsonld.SyntaxError')}else if(e!==null){rval.push(e)}}return rval}if(_isObject(element)){if('@context'in element){ctx=this.processContext(ctx,element['@context'],options);delete element['@context']}var rval={};for(var key in element){var prop=_expandTerm(ctx,key);if(!_isAbsoluteIri(prop)&&!_isKeyword(prop,ctx)){continue}var value=element[key];if(value===null&&prop!=='@value'){continue}if(prop==='@id'&&!_isString(value)){throw new JsonLdError('Invalid JSON-LD syntax; "@id" value must a string.','jsonld.SyntaxError',{value:value})}if(prop==='@type'){_validateTypeValue(value)}if(prop==='@graph'&&!(_isObject(value)||_isArray(value))){throw new JsonLdError('Invalid JSON-LD syntax; "@value" value must not be an '+'object or an array.','jsonld.SyntaxError',{value:value})}if(prop==='@value'&&(_isObject(value)||_isArray(value))){throw new JsonLdError('Invalid JSON-LD syntax; "@value" value must not be an '+'object or an array.','jsonld.SyntaxError',{value:value})}if(prop==='@language'&&!_isString(value)){throw new JsonLdError('Invalid JSON-LD syntax; "@language" value must not be a string.','jsonld.SyntaxError',{value:value})}var isList=(prop==='@list');if(isList||prop==='@set'){value=this.expand(ctx,property,value,options,isList);if(isList&&_isList(value)){throw new JsonLdError('Invalid JSON-LD syntax; lists of lists are not permitted.','jsonld.SyntaxError')}}else{property=key;value=this.expand(ctx,property,value,options,false)}if(value!==null||prop==='@value'){if(prop!=='@list'&&!_isList(value)){var container=jsonld.getContextValue(ctx,property,'@container');if(container==='@list'){value=_isArray(value)?value:[value];value={'@list':value}}}if(prop==='@type'){if(_isSubjectReference(value)){value=value['@id']}else if(_isArray(value)){var val=[];for(var i in value){var v=value[i];if(_isSubjectReference(v)){val.push(v['@id'])}else{val.push(v)}}value=val}}var useArray=!(prop==='@id'||prop==='@type'||prop==='@value'||prop==='@language');jsonld.addValue(rval,prop,value,{propertyIsArray:useArray})}}var count=Object.keys(rval).length;if('@value'in rval){if((count===2&&!('@type'in rval)&&!('@language'in rval))||count>2){throw new JsonLdError('Invalid JSON-LD syntax; an element containing "@value" must have '+'at most one other property which can be "@type" or "@language".','jsonld.SyntaxError',{element:rval})}if('@type'in rval&&!_isString(rval['@type'])){throw new JsonLdError('Invalid JSON-LD syntax; the "@type" value of an element '+'containing "@value" must be a string.','jsonld.SyntaxError',{element:rval})}else if(rval['@value']===null){rval=null}}else if('@type'in rval&&!_isArray(rval['@type'])){rval['@type']=[rval['@type']]}else if('@set'in rval||'@list'in rval){if(count!==1){throw new JsonLdError('Invalid JSON-LD syntax; if an element has the property "@set" '+'or "@list", then it must be its only property.','jsonld.SyntaxError',{element:rval})}if('@set'in rval){rval=rval['@set']}}else if('@language'in rval&&count===1){rval=null}return rval}return _expandValue(ctx,property,element,options.base)};Processor.prototype.frame=function(input,frame,options){var state={options:options,graphs:{'@default':{},'@merged':{}}};var namer=new UniqueNamer('_:t');_flatten(input,state.graphs,'@default',namer);namer=new UniqueNamer('_:t');_flatten(input,state.graphs,'@merged',namer);state.subjects=state.graphs['@merged'];var framed=[];_frame(state,Object.keys(state.subjects),frame,framed,null);return framed};Processor.prototype.normalize=function(input,options,callback){var statements=[];var bnodes={};var namer=new UniqueNamer('_:t');new Processor().toRDF(input,namer,null,null,null,mapStatements);function mapStatements(err,statement){if(err){return callback(err)}if(statement===null){namer=new UniqueNamer('_:c14n');return hashBlankNodes(Object.keys(bnodes))}for(var i in statements){if(_compareRdfStatements(statements[i],statement)){return}}statements.push(statement);var nodes=['subject','object'];for(var n in nodes){var node=nodes[n];var id=statement[node].nominalValue;if(statement[node].interfaceName==='BlankNode'){if(id in bnodes){bnodes[id].statements.push(statement)}else{bnodes[id]={statements:[statement]}}}}}function hashBlankNodes(unnamed){var nextUnnamed=[];var duplicates={};var unique={};setTimeout(function(){hashUnnamed(0)},0);function hashUnnamed(i){if(i===unnamed.length){return nameBlankNodes(unique,duplicates,nextUnnamed)}var bnode=unnamed[i];var hash=_hashStatements(bnode,bnodes,namer);if(hash in duplicates){duplicates[hash].push(bnode);nextUnnamed.push(bnode)}else if(hash in unique){duplicates[hash]=[unique[hash],bnode];nextUnnamed.push(unique[hash]);nextUnnamed.push(bnode);delete unique[hash]}else{unique[hash]=bnode}setTimeout(function(){hashUnnamed(i+1)},0)}}function nameBlankNodes(unique,duplicates,unnamed){var named=false;var hashes=Object.keys(unique).sort();for(var i in hashes){var bnode=unique[hashes[i]];namer.getName(bnode);named=true}if(named){hashBlankNodes(unnamed)}else{nameDuplicates(duplicates)}}function nameDuplicates(duplicates){var hashes=Object.keys(duplicates).sort();processGroup(0);function processGroup(i){if(i===hashes.length){return createArray()}var group=duplicates[hashes[i]];var results=[];nameGroupMember(group,0);function nameGroupMember(group,n){if(n===group.length){results.sort(function(a,b){a=a.hash;b=b.hash;return(a<b)?-1:((a>b)?1:0)});for(var r in results){for(var key in results[r].pathNamer.existing){namer.getName(key)}}return processGroup(i+1)}var bnode=group[n];if(namer.isNamed(bnode)){return nameGroupMember(group,n+1)}var pathNamer=new UniqueNamer('_:t');pathNamer.getName(bnode);_hashPaths(bnode,bnodes,namer,pathNamer,function(err,result){if(err){return callback(err)}results.push(result);nameGroupMember(group,n+1)})}}}function createArray(){var normalized=[];for(var i in statements){var statement=statements[i];var nodes=['subject','object'];for(var n in nodes){var node=nodes[n];if(statement[node].interfaceName==='BlankNode'){statement[node].nominalValue=namer.getName(statement[node].nominalValue)}}normalized.push(_toNQuad(statement))}normalized.sort();if('format'in options){if(options.format==='application/nquads'){return callback(null,normalized.join(''))}else{return callback(new JsonLdError('Unknown output format.','jsonld.UnknownFormat',{format:options.format}))}}callback(null,_parseNQuads(normalized.join('')))}};Processor.prototype.fromRDF=function(statements,options,callback){var defaultGraph={subjects:{},listMap:{}};var graphs={'':defaultGraph};for(var i in statements){var statement=statements[i];var s=statement.subject.nominalValue;var p=statement.property.nominalValue;var o=statement.object;var name=('name'in statement)?statement.name.nominalValue:'';var graph;if(!(name in graphs)){graph=graphs[name]={subjects:{},listMap:{}}}else{graph=graphs[name]}if(p===RDF_FIRST){var listMap=graph.listMap;var entry;if(!(s in listMap)){entry=listMap[s]={}}else{entry=listMap[s]}entry.first=_rdfToObject(o);continue}if(p===RDF_REST){if(o.interfaceName==='BlankNode'){var listMap=graph.listMap;var entry;if(!(s in listMap)){entry=listMap[s]={}}else{entry=listMap[s]}entry.rest=o.nominalValue}continue}if(name!==''&&!(name in defaultGraph.subjects)){defaultGraph.subjects[name]={'@id':name}}var subjects=graph.subjects;var value;if(!(s in subjects)){value=subjects[s]={'@id':s}}else{value=subjects[s]}if(p===RDF_TYPE&&!options.notType){jsonld.addValue(value,'@type',o.nominalValue,{propertyIsArray:true})}else{var object=_rdfToObject(o);jsonld.addValue(value,p,object,{propertyIsArray:true});if(o.interfaceName==='BlankNode'){var id=object['@id'];var listMap=graph.listMap;var entry;if(!(id in listMap)){entry=listMap[id]={}}else{entry=listMap[id]}entry.head=object}}}for(var name in graphs){var graph=graphs[name];var listMap=graph.listMap;for(var subject in listMap){var entry=listMap[subject];if('head'in entry&&'first'in entry){delete entry.head['@id'];var list=entry.head['@list']=[entry.first];while('rest'in entry){var rest=entry.rest;entry=listMap[rest];if(!('first'in entry)){throw new JsonLdError('Invalid RDF list entry.','jsonld.RdfError',{bnode:rest})}list.push(entry.first)}}}}var output=[];var subjects=defaultGraph.subjects;var ids=Object.keys(subjects).sort();for(var i in ids){var id=ids[i];var subject=subjects[id];output.push(subject);if(id in graphs){var graph=subject['@graph']=[];var _subjects=graphs[id].subjects;var _ids=Object.keys(_subjects).sort();for(var _i in _ids){graph.push(_subjects[_ids[_i]])}}}callback(null,output)};Processor.prototype.toRDF=function(element,namer,subject,property,graph,callback){_toRDF(element,namer,subject,property,graph,callback);callback(null,null)};Processor.prototype.processContext=function(activeCtx,localCtx,options){var rval=_clone(activeCtx);if(_isObject(localCtx)&&'@context'in localCtx&&_isArray(localCtx['@context'])){localCtx=localCtx['@context']}var ctxs=_isArray(localCtx)?localCtx:[localCtx];for(var i in ctxs){var ctx=ctxs[i];if(ctx===null){rval=_getInitialContext();continue}if(_isObject(ctx)&&'@context'in ctx){ctx=ctx['@context']}if(!_isObject(ctx)){throw new JsonLdError('Invalid JSON-LD syntax; @context must be an object.','jsonld.SyntaxError',{context:ctx})}var defined={};for(var key in ctx){_defineContextMapping(rval,ctx,key,options.base,defined)}}return rval};function _expandValue(ctx,property,value,base){if(value===null){return null}var rval=value;var prop=_expandTerm(ctx,property);if(prop==='@id'){rval=_expandTerm(ctx,value,base)}else if(prop==='@type'){rval=_expandTerm(ctx,value)}else{var type=jsonld.getContextValue(ctx,property,'@type');if(type==='@id'||prop==='@graph'){rval={'@id':_expandTerm(ctx,value,base)}}else if(!_isKeyword(prop)){rval={'@value':value};if(type!==null){rval['@type']=type}else{var language=jsonld.getContextValue(ctx,property,'@language');if(language!==null){rval['@language']=language}}}}return rval}function _toRDF(element,namer,subject,property,graph,callback){if(_isObject(element)){if(_isValue(element)){var value=element['@value'];var datatype=element['@type']||null;if(_isBoolean(value)||_isNumber(value)){if(_isBoolean(value)){value=String(value);datatype=datatype||XSD_BOOLEAN}else if(_isDouble(value)){value=value.toExponential(15).replace(/(e(?:\+|-))([0-9])$/,'$10$2');datatype=datatype||XSD_DOUBLE}else{value=String(value);datatype=datatype||XSD_INTEGER}}var object={nominalValue:value,interfaceName:'LiteralNode'};if(datatype!==null){object.datatype={nominalValue:datatype,interfaceName:'IRI'}}else if('@language'in element){object.language=element['@language']}var statement={subject:_clone(subject),property:_clone(property),object:object};if(graph!==null){statement.name=graph}return callback(null,statement)}if(_isList(element)){var list=_makeLinkedList(element);return _toRDF(list,namer,subject,property,graph,callback)}var isBnode=_isBlankNode(element);var id=isBnode?namer.getName(element['@id']):element['@id'];var object={nominalValue:id,interfaceName:isBnode?'BlankNode':'IRI'};if(subject!==null){var statement={subject:_clone(subject),property:_clone(property),object:_clone(object)};if(graph!==null){statement.name=graph}callback(null,statement)}subject=object;var props=Object.keys(element).sort();for(var pi in props){var prop=props[pi];var e=element[prop];if(prop==='@type'){prop=RDF_TYPE}if(prop==='@graph'){_toRDF(e,namer,null,null,subject,callback);continue}if(_isKeyword(prop)){continue}property={nominalValue:prop,interfaceName:'IRI'};_toRDF(e,namer,subject,property,graph,callback)}return}if(_isArray(element)){for(var i in element){_toRDF(element[i],namer,subject,property,graph,callback)}return}if(_isString(element)){var statement={subject:_clone(subject),property:_clone(property),object:{nominalValue:element,interfaceName:'IRI'}};if(graph!==null){statement.name=graph}return callback(null,statement)}}function _rdfToObject(o){if(o.interfaceName==='IRI'&&o.nominalValue===RDF_NIL){return{'@list':[]}}if(o.interfaceName==='IRI'||o.interfaceName==='BlankNode'){return{'@id':o.nominalValue}}var rval={'@value':o.nominalValue};if('datatype'in o){rval['@type']=o.datatype.nominalValue}else if('language'in o){rval['@language']=o.language}return rval}function _compareRdfStatements(s1,s2){if(_isString(s1)||_isString(s2)){return s1===s2}var attrs=['subject','property','object'];for(var i in attrs){var attr=attrs[i];if(s1[attr].interfaceName!==s2[attr].interfaceName||s1[attr].nominalValue!==s2[attr].nominalValue){return false}}if(s1.object.language!==s2.object.language){return false}if(('datatype'in s1.object)!==('datatype'in s2.object)){return false}if('datatype'in s1.object){if(s1.object.datatype.interfaceName!==s2.object.datatype.interfaceName||s1.object.datatype.nominalValue!==s2.object.datatype.nominalValue){return false}}if(s1.name!==s2.name){return false}return true}function _makeLinkedList(value){var list=value['@list'];var len=list.length;var tail={'@id':RDF_NIL};for(var i=len-1;i>=0;--i){var e={};e[RDF_FIRST]=[list[i]];e[RDF_REST]=[tail];tail=e}return tail}function _hashStatements(id,bnodes,namer){if('hash'in bnodes[id]){return bnodes[id].hash}var statements=bnodes[id].statements;var nquads=[];for(var i in statements){nquads.push(_toNQuad(statements[i],id))}nquads.sort();var hash=bnodes[id].hash=sha1.hash(nquads);return hash}function _hashPaths(id,bnodes,namer,pathNamer,callback){var md=sha1.create();var groups={};var groupHashes;var statements=bnodes[id].statements;setTimeout(function(){groupNodes(0)},0);function groupNodes(i){if(i===statements.length){groupHashes=Object.keys(groups).sort();return hashGroup(0)}var statement=statements[i];var bnode=_getAdjacentBlankNodeName(statement.subject,id);var direction=null;if(bnode!==null){direction='p'}else{bnode=_getAdjacentBlankNodeName(statement.object,id);if(bnode!==null){direction='r'}}if(bnode!==null){var name;if(namer.isNamed(bnode)){name=namer.getName(bnode)}else if(pathNamer.isNamed(bnode)){name=pathNamer.getName(bnode)}else{name=_hashStatements(bnode,bnodes,namer)}var md=sha1.create();md.update(direction);md.update(statement.property.nominalValue);md.update(name);var groupHash=md.digest();if(groupHash in groups){groups[groupHash].push(bnode)}else{groups[groupHash]=[bnode]}}setTimeout(function(){groupNodes(i+1)},0)}function hashGroup(i){if(i===groupHashes.length){return callback(null,{hash:md.digest(),pathNamer:pathNamer})}var groupHash=groupHashes[i];md.update(groupHash);var chosenPath=null;var chosenNamer=null;var permutator=new Permutator(groups[groupHash]);setTimeout(function(){permutate()},0);function permutate(){var permutation=permutator.next();var pathNamerCopy=pathNamer.clone();var path='';var recurse=[];for(var n in permutation){var bnode=permutation[n];if(namer.isNamed(bnode)){path+=namer.getName(bnode)}else{if(!pathNamerCopy.isNamed(bnode)){recurse.push(bnode)}path+=pathNamerCopy.getName(bnode)}if(chosenPath!==null&&path.length>=chosenPath.length&&path>chosenPath){return nextPermutation(true)}}nextRecursion(0);function nextRecursion(n){if(n===recurse.length){return nextPermutation(false)}var bnode=recurse[n];_hashPaths(bnode,bnodes,namer,pathNamerCopy,function(err,result){if(err){return callback(err)}path+=pathNamerCopy.getName(bnode)+'<'+result.hash+'>';pathNamerCopy=result.pathNamer;if(chosenPath!==null&&path.length>=chosenPath.length&&path>chosenPath){return nextPermutation(true)}nextRecursion(n+1)})}function nextPermutation(skipped){if(!skipped&&(chosenPath===null||path<chosenPath)){chosenPath=path;chosenNamer=pathNamerCopy}if(permutator.hasNext()){setTimeout(function(){permutate()},0)}else{md.update(chosenPath);pathNamer=chosenNamer;hashGroup(i+1)}}}}}function _getAdjacentBlankNodeName(node,id){return(node.interfaceName==='BlankNode'&&node.nominalValue!==id?node.nominalValue:null)}function _flatten(input,graphs,graph,namer,name,list){if(_isArray(input)){for(var i in input){_flatten(input[i],graphs,graph,namer,undefined,list)}return}if(!_isObject(input)||_isValue(input)){if(list){list.push(input)}return}if(_isUndefined(name)){name=_isBlankNode(input)?namer.getName(input['@id']):input['@id']}if(list){list.push({'@id':name})}var subjects=graphs[graph];var subject=subjects[name]=subjects[name]||{};subject['@id']=name;var props=Object.keys(input).sort();for(var p in props){var prop=props[p];if(prop==='@id'){continue}if(prop==='@graph'){if(!(name in graphs)){graphs[name]={}}var g=(graph==='@merged')?graph:name;_flatten(input[prop],graphs,g,namer);continue}if(prop!=='@type'&&_isKeyword(prop)){subject[prop]=input[prop];continue}var objects=input[prop];for(var i in objects){var o=objects[i];if(_isSubject(o)||_isSubjectReference(o)){var id=_isBlankNode(o)?namer.getName(o['@id']):o['@id'];jsonld.addValue(subject,prop,{'@id':id},{propertyIsArray:true});_flatten(o,graphs,graph,namer,id)}else{if(_isList(o)){var _list=[];_flatten(o['@list'],graphs,graph,namer,name,_list);o={'@list':_list}}else if(prop==='@type'&&o.indexOf('_:')===0){o=namer.getName(o)}jsonld.addValue(subject,prop,o,{propertyIsArray:true})}}}}function _frame(state,subjects,frame,parent,property){_validateFrame(state,frame);frame=frame[0];var matches=_filterSubjects(state,subjects,frame);var options=state.options;var embedOn=_getFrameFlag(frame,options,'embed');var explicitOn=_getFrameFlag(frame,options,'explicit');var ids=Object.keys(matches).sort();for(var idx in ids){var id=ids[idx];if(property===null){state.embeds={}}var output={};output['@id']=id;var embed={parent:parent,property:property};if(embedOn&&(id in state.embeds)){embedOn=false;var existing=state.embeds[id];if(_isArray(existing.parent)){for(var i in existing.parent){if(jsonld.compareValues(output,existing.parent[i])){embedOn=true;break}}}else if(jsonld.hasValue(existing.parent,existing.property,output)){embedOn=true}if(embedOn){_removeEmbed(state,id)}}if(!embedOn){_addFrameOutput(state,parent,property,output)}else{state.embeds[id]=embed;var subject=matches[id];var props=Object.keys(subject).sort();for(var i in props){var prop=props[i];if(_isKeyword(prop)){output[prop]=_clone(subject[prop]);continue}if(!(prop in frame)){if(!explicitOn){_embedValues(state,subject,prop,output)}continue}var objects=subject[prop];for(var i in objects){var o=objects[i];if(_isList(o)){var list={'@list':[]};_addFrameOutput(state,output,prop,list);var src=o['@list'];for(var n in src){o=src[n];if(_isSubjectReference(o)){_frame(state,[o['@id']],frame[prop],list,'@list')}else{_addFrameOutput(state,list,'@list',_clone(o))}}continue}if(_isSubjectReference(o)){_frame(state,[o['@id']],frame[prop],output,prop)}else{_addFrameOutput(state,output,prop,_clone(o))}}}var props=Object.keys(frame).sort();for(var i in props){var prop=props[i];if(_isKeyword(prop)){continue}var next=frame[prop][0];var omitDefaultOn=_getFrameFlag(next,options,'omitDefault');if(!omitDefaultOn&&!(prop in output)){var preserve='@null';if('@default'in next){preserve=_clone(next['@default'])}output[prop]={'@preserve':preserve}}}_addFrameOutput(state,parent,property,output)}}}function _getFrameFlag(frame,options,name){var flag='@'+name;return(flag in frame)?frame[flag][0]:options[name]}function _validateFrame(state,frame){if(!_isArray(frame)||frame.length!==1||!_isObject(frame[0])){throw new JsonLdError('Invalid JSON-LD syntax; a JSON-LD frame must be a single object.','jsonld.SyntaxError',{frame:frame})}}function _filterSubjects(state,subjects,frame){var rval={};for(var i in subjects){var id=subjects[i];var subject=state.subjects[id];if(_filterSubject(subject,frame)){rval[id]=subject}}return rval}function _filterSubject(subject,frame){if('@type'in frame&&!(frame['@type'].length===1&&_isObject(frame['@type'][0]))){var types=frame['@type'];for(var i in types){if(jsonld.hasValue(subject,'@type',types[i])){return true}}return false}for(var key in frame){if((key==='@id'||!_isKeyword(key))&&!(key in subject)){return false}}return true}function _embedValues(state,subject,property,output){var objects=subject[property];for(var i in objects){var o=objects[i];if(_isList(o)){var list={'@list':[]};_addFrameOutput(state,output,property,list);return _embedValues(state,o,'@list',list['@list'])}if(_isSubjectReference(o)){var id=o['@id'];if(!(id in state.embeds)){var embed={parent:output,property:property};state.embeds[id]=embed;o={};var s=state.subjects[id];for(var prop in s){if(_isKeyword(prop)){o[prop]=_clone(s[prop]);continue}_embedValues(state,s,prop,o)}}_addFrameOutput(state,output,property,o)}else{_addFrameOutput(state,output,property,_clone(o))}}}function _removeEmbed(state,id){var embeds=state.embeds;var embed=embeds[id];var parent=embed.parent;var property=embed.property;var subject={'@id':id};if(_isArray(parent)){for(var i in parent){if(jsonld.compareValues(parent[i],subject)){parent[i]=subject;break}}}else{var useArray=_isArray(parent[property]);jsonld.removeValue(parent,property,subject,{propertyIsArray:useArray});jsonld.addValue(parent,property,subject,{propertyIsArray:useArray})}var removeDependents=function(id){var ids=Object.keys(embeds);for(var i in ids){var next=ids[i];if(next in embeds&&_isObject(embeds[next].parent)&&embeds[next].parent['@id']===id){delete embeds[next];removeDependents(next)}}};removeDependents(id)}function _addFrameOutput(state,parent,property,output){if(_isObject(parent)){jsonld.addValue(parent,property,output,{propertyIsArray:true})}else{parent.push(output)}}function _removePreserve(ctx,input){if(_isArray(input)){var output=[];for(var i in input){var result=_removePreserve(ctx,input[i]);if(result!==null){output.push(result)}}input=output}else if(_isObject(input)){if('@preserve'in input){if(input['@preserve']==='@null'){return null}return input['@preserve']}if(_isValue(input)){return input}if(_isList(input)){input['@list']=_removePreserve(ctx,input['@list']);return input}for(var prop in input){var result=_removePreserve(ctx,input[prop]);var container=jsonld.getContextValue(ctx,prop,'@container');if(_isArray(result)&&result.length===1&&container!=='@set'&&container!=='@list'){result=result[0]}input[prop]=result}}return input}function _compareShortestLeast(a,b){if(a.length<b.length){return-1}else if(b.length<a.length){return 1}return(a<b)?-1:((a>b)?1:0)}function _rankTerm(ctx,term,value){if(value===null){return 3}var entry=ctx.mappings[term];var hasType=('@type'in entry);var hasLanguage=('@language'in entry);var hasDefaultLanguage=('@language'in ctx);if(_isList(value)){var list=value['@list'];if(list.length===0){return(entry['@container']==='@list')?1:0}var sum=0;for(var i in list){sum+=_rankTerm(ctx,term,list[i])}return sum}if(_isValue(value)){if('@type'in value){if(value['@type']===entry['@type']){return 3}return(!hasType&&!hasLanguage)?1:0}if(!_isString(value['@value'])){return(!hasType&&!hasLanguage)?2:1}if(!('@language'in value)){if(entry['@language']===null||(!hasType&&!hasLanguage&&!hasDefaultLanguage)){return 3}return 0}if((value['@language']===entry['@language'])||(!hasType&&!hasLanguage&&value['@language']===ctx['@language'])){return 3}return(!hasType&&!hasLanguage)?1:0}if(entry['@type']==='@id'){return 3}return(!hasType&&!hasLanguage)?1:0}function _compactIri(ctx,iri,value){if(iri===null){return iri}if(_isKeyword(iri)){var aliases=ctx.keywords[iri];if(aliases.length>0){return aliases[0]}else{return iri}}if(_isUndefined(value)){value=null}var terms=[];var highest=0;var listContainer=false;var isList=_isList(value);for(var term in ctx.mappings){var entry=ctx.mappings[term];if(entry['@id']!==iri){continue}if(isList&&entry['@container']==='@set'){continue}if(!isList&&entry['@container']==='@list'&&value!==null){continue}if(isList&&listContainer&&entry['@container']!=='@list'){continue}var rank=_rankTerm(ctx,term,value);if(rank>0){if(entry['@container']==='@set'){rank+=1}if(isList&&!listContainer&&entry['@container']==='@list'){listContainer=true;terms.length=0;highest=rank;terms.push(term)}else if(rank>=highest){if(rank>highest){terms.length=0;highest=rank}terms.push(term)}}}if(terms.length===0){for(var term in ctx.mappings){if(term.indexOf(':')!==-1){continue}var entry=ctx.mappings[term];if(entry['@id']===iri||iri.indexOf(entry['@id'])!==0){continue}var curie=term+':'+iri.substr(entry['@id'].length);if(!(curie in ctx.mappings)){terms.push(curie)}}}if(terms.length===0){return iri}terms.sort(_compareShortestLeast);return terms[0]}function _defineContextMapping(activeCtx,ctx,key,base,defined){if(key in defined){if(defined[key]){return}throw new JsonLdError('Cyclical context definition detected.','jsonld.CyclicalContext',{context:ctx,key:key})}defined[key]=false;var colon=key.indexOf(':');var prefix=null;if(colon!==-1){prefix=key.substr(0,colon);if(prefix in ctx){_defineContextMapping(activeCtx,ctx,prefix,base,defined)}}var value=ctx[key];if(_isKeyword(key)){if(key!=='@language'){throw new JsonLdError('Invalid JSON-LD syntax; keywords cannot be overridden.','jsonld.SyntaxError',{context:ctx})}if(value!==null&&!_isString(value)){throw new JsonLdError('Invalid JSON-LD syntax; the value of "@language" in a '+'@context must be a string or null.','jsonld.SyntaxError',{context:ctx})}if(value===null){delete activeCtx['@language']}else{activeCtx['@language']=value}defined[key]=true;return}if(value===null||(_isObject(value)&&value['@id']===null)){if(key in activeCtx.mappings){var kw=activeCtx.mappings[key]['@id'];if(_isKeyword(kw)){var aliases=activeCtx.keywords[kw];aliases.splice(aliases.indexOf(key),1)}delete activeCtx.mappings[key]}defined[key]=true;return}if(_isString(value)){if(_isKeyword(value)){if(value==='@context'||value==='@preserve'){throw new JsonLdError('Invalid JSON-LD syntax; @context and @preserve cannot be aliased.','jsonld.SyntaxError')}var aliases=activeCtx.keywords[value];if(aliases.indexOf(key)===-1){aliases.push(key);aliases.sort(_compareShortestLeast)}}else{value=_expandContextIri(activeCtx,ctx,value,base,defined)}activeCtx.mappings[key]={'@id':value};defined[key]=true;return}if(!_isObject(value)){throw new JsonLdError('Invalid JSON-LD syntax; @context property values must be '+'strings or objects.','jsonld.SyntaxError',{context:ctx})}var mapping={};if('@id'in value){var id=value['@id'];if(!_isString(id)){throw new JsonLdError('Invalid JSON-LD syntax; @context @id values must be strings.','jsonld.SyntaxError',{context:ctx})}if(id!=='@type'){id=_expandContextIri(activeCtx,ctx,id,base,defined)}mapping['@id']=id}else{if(prefix===null){throw new JsonLdError('Invalid JSON-LD syntax; @context terms must define an @id.','jsonld.SyntaxError',{context:ctx,key:key})}if(prefix in activeCtx.mappings){var suffix=key.substr(colon+1);mapping['@id']=activeCtx.mappings[prefix]['@id']+suffix}else{mapping['@id']=key}}if('@type'in value){var type=value['@type'];if(!_isString(type)){throw new JsonLdError('Invalid JSON-LD syntax; @context @type values must be strings.','jsonld.SyntaxError',{context:ctx})}if(type!=='@id'){type=_expandContextIri(activeCtx,ctx,type,'',defined)}mapping['@type']=type}if('@container'in value){var container=value['@container'];if(container!=='@list'&&container!=='@set'){throw new JsonLdError('Invalid JSON-LD syntax; @context @container value must be '+'"@list" or "@set".','jsonld.SyntaxError',{context:ctx})}mapping['@container']=container}if('@language'in value&&!('@type'in value)){var language=value['@language'];if(language!==null&&!_isString(language)){throw new JsonLdError('Invalid JSON-LD syntax; @context @language value must be '+'a string or null.','jsonld.SyntaxError',{context:ctx})}mapping['@language']=language}if(prefix!==null&&prefix in activeCtx.mappings){var child=mapping;mapping=_clone(activeCtx.mappings[prefix]);for(var k in child){mapping[k]=child[k]}}activeCtx.mappings[key]=mapping;defined[key]=true}function _expandContextIri(activeCtx,ctx,value,base,defined){if(value in ctx&&defined[value]!==true){_defineContextMapping(activeCtx,ctx,value,base,defined)}if(value in activeCtx.mappings){var id=activeCtx.mappings[value]['@id'];if(value===id){return value}return _expandContextIri(activeCtx,ctx,id,base,defined)}var colon=value.indexOf(':');if(colon!==-1){var prefix=value.substr(0,colon);var suffix=value.substr(colon+1);if(prefix==='_'){return value}if(suffix.indexOf('//')===0){return value}if(prefix in ctx&&defined[prefix]!==true){_defineContextMapping(activeCtx,ctx,prefix,base,defined)}if(prefix in activeCtx.mappings){var id=activeCtx.mappings[prefix]['@id'];return _expandContextIri(activeCtx,ctx,id,base,defined)+suffix}return value}value=_prependBase(base,value);if(!_isAbsoluteIri(value)){throw new JsonLdError('Invalid JSON-LD syntax; a @context value does not expand to '+'an absolute IRI.','jsonld.SyntaxError',{context:ctx,value:value})}return value}function _expandTerm(ctx,term,base){if(term===null){return null}if(term in ctx.mappings){var id=ctx.mappings[term]['@id'];if(term===id){return term}return _expandTerm(ctx,id,base)}var colon=term.indexOf(':');if(colon!==-1){var prefix=term.substr(0,colon);var suffix=term.substr(colon+1);if(prefix==='_'){return term}if(suffix.indexOf('//')===0){return term}if(prefix in ctx.mappings){return _expandTerm(ctx,ctx.mappings[prefix]['@id'],base)+suffix}return term}if(!_isUndefined(base)){term=_prependBase(base,term)}return term}function _prependBase(base,iri){if(iri===''||iri.indexOf('#')===0){return base+iri}else{return base.substr(0,base.lastIndexOf('/')+1)+iri}}function _getInitialContext(){return{mappings:{},keywords:{'@context':[],'@container':[],'@default':[],'@embed':[],'@explicit':[],'@graph':[],'@id':[],'@language':[],'@list':[],'@omitDefault':[],'@preserve':[],'@set':[],'@type':[],'@value':[]}}}function _isKeyword(v,ctx){if(ctx){if(v in ctx.keywords){return true}for(var key in ctx.keywords){var aliases=ctx.keywords[key];if(aliases.indexOf(v)!==-1){return true}}}else{switch(v){case'@context':case'@container':case'@default':case'@embed':case'@explicit':case'@graph':case'@id':case'@language':case'@list':case'@omitDefault':case'@preserve':case'@set':case'@type':case'@value':return true}}return false}function _isObject(v){return(Object.prototype.toString.call(v)==='[object Object]')}function _isEmptyObject(v){return _isObject(v)&&Object.keys(v).length===0}function _isArray(v){return Array.isArray(v)}function _validateTypeValue(v){if(_isString(v)||_isSubjectReference(v)||_isEmptyObject(v)){return}var isValid=false;if(_isArray(v)){isValid=true;for(var i in v){if(!(_isString(v[i])||_isSubjectReference(v[i]))){isValid=false;break}}}if(!isValid){throw new JsonLdError('Invalid JSON-LD syntax; "@type" value must a string, a subject '+'reference, an array of strings or subject references, or an '+'empty object.','jsonld.SyntaxError',{value:v})}}function _isString(v){return(typeof v==='string'||Object.prototype.toString.call(v)==='[object String]')}function _isNumber(v){return(typeof v==='number'||Object.prototype.toString.call(v)==='[object Number]')}function _isDouble(v){return _isNumber(v)&&String(v).indexOf('.')!==-1}function _isBoolean(v){return(typeof v==='boolean'||Object.prototype.toString.call(v)==='[object Boolean]')}function _isUndefined(v){return(typeof v==='undefined')}function _isSubject(v){var rval=false;if(_isObject(v)&&!(('@value'in v)||('@set'in v)||('@list'in v))){var keyCount=Object.keys(v).length;rval=(keyCount>1||!('@id'in v))}return rval}function _isSubjectReference(v){return(_isObject(v)&&Object.keys(v).length===1&&('@id'in v))}function _isValue(v){return _isObject(v)&&('@value'in v)}function _isList(v){return _isObject(v)&&('@list'in v)}function _isBlankNode(v){var rval=false;if(_isObject(v)){if('@id'in v){rval=(v['@id'].indexOf('_:')===0)}else{rval=(Object.keys(v).length===0||!(('@value'in v)||('@set'in v)||('@list'in v)))}}return rval}function _isAbsoluteIri(v){return v.indexOf(':')!==-1}function _clone(value){var rval;if(_isObject(value)){rval={};for(var key in value){rval[key]=_clone(value[key])}}else if(_isArray(value)){rval=[];for(var i in value){rval[i]=_clone(value[i])}}else{rval=value}return rval}function _findContextUrls(input,urls,replace){var count=Object.keys(urls).length;if(_isArray(input)){for(var i in input){_findContextUrls(input[i],urls,replace)}return(count<Object.keys(urls).length)}else if(_isObject(input)){for(var key in input){if(key!=='@context'){_findContextUrls(input[key],urls,replace);continue}var ctx=input[key];if(_isArray(ctx)){var length=ctx.length;for(var i=0;i<length;++i){var _ctx=ctx[i];if(_isString(_ctx)){if(replace){_ctx=urls[_ctx];if(_isArray(_ctx)){Array.prototype.splice.apply(ctx,[i,1].concat(_ctx));i+=_ctx.length;length+=_ctx.length}else{ctx[i]=_ctx}}else if(!(_ctx in urls)){urls[_ctx]=false}}}}else if(_isString(ctx)){if(replace){input[key]=urls[ctx]}else if(!(ctx in urls)){urls[ctx]=false}}}return(count<Object.keys(urls).length)}return false}function _resolveContextUrls(input,resolver,callback){var error=null;var regex=/(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;var resolve=function(input,cycles,resolver,callback){if(Object.keys(cycles).length>MAX_CONTEXT_URLS){error=new JsonLdError('Maximum number of @context URLs exceeded.','jsonld.ContextUrlError',{max:MAX_CONTEXT_URLS});return callback(error)}var urls={};var finished=function(){_findContextUrls(input,urls,true);callback(null,input)};if(!_findContextUrls(input,urls,false)){finished()}var queue=[];for(var url in urls){if(urls[url]===false){if(!regex.test(url)){error=new JsonLdError('Malformed URL.','jsonld.InvalidUrl',{url:url});return callback(error)}queue.push(url)}}var count=queue.length;for(var i in queue){(function(url){if(url in cycles){error=new JsonLdError('Cyclical @context URLs detected.','jsonld.ContextUrlError',{url:url});return callback(error)}var _cycles=_clone(cycles);_cycles[url]=true;resolver(url,function(err,ctx){if(error){return}if(!err&&_isString(ctx)){try{ctx=JSON.parse(ctx)}catch(ex){err=ex}}if(err||!_isObject(ctx)){err=new JsonLdError('URL does not resolve to a valid JSON-LD object.','jsonld.InvalidUrl',{url:url})}if(err){error=err;return callback(error)}if(!('@context'in ctx)){ctx={'@context':{}}}resolve(ctx,_cycles,resolver,function(err,ctx){if(err){return callback(err)}urls[url]=ctx['@context'];count-=1;if(count===0){finished()}})})}(queue[i]))}};resolve(input,{},resolver,callback)}if(!Object.keys){Object.keys=function(o){if(o!==Object(o)){throw new TypeError('Object.keys called on non-object')}var rval=[];for(var p in o){if(Object.prototype.hasOwnProperty.call(o,p)){rval.push(p)}}return rval}}function _parseNQuads(input){var iri='(?:<([^:]+:[^>]*)>)';var bnode='(_:(?:[A-Za-z][A-Za-z0-9]*))';var plain='"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"';var datatype='(?:\\^\\^'+iri+')';var language='(?:@([a-z]+(?:-[a-z0-9]+)*))';var literal='(?:'+plain+'(?:'+datatype+'|'+language+')?)';var ws='[ \\t]+';var wso='[ \\t]*';var eoln=/(?:\r\n)|(?:\n)|(?:\r)/g;var empty=new RegExp('^'+wso+'$');var subject='(?:'+iri+'|'+bnode+')'+ws;var property=iri+ws;var object='(?:'+iri+'|'+bnode+'|'+literal+')'+wso;var graph='(?:\\.|(?:(?:'+iri+'|'+bnode+')'+wso+'\\.))';var quad=new RegExp('^'+wso+subject+property+object+graph+wso+'$');var statements=[];var lines=input.split(eoln);var lineNumber=0;for(var i in lines){var line=lines[i];lineNumber++;if(empty.test(line)){continue}var match=line.match(quad);if(match===null){throw new JsonLdError('Error while parsing N-Quads; invalid quad.','jsonld.ParseError',{line:lineNumber})}var s={};if(!_isUndefined(match[1])){s.subject={nominalValue:match[1],interfaceName:'IRI'}}else{s.subject={nominalValue:match[2],interfaceName:'BlankNode'}}s.property={nominalValue:match[3],interfaceName:'IRI'};if(!_isUndefined(match[4])){s.object={nominalValue:match[4],interfaceName:'IRI'}}else if(!_isUndefined(match[5])){s.object={nominalValue:match[5],interfaceName:'BlankNode'}}else{var unescaped=match[6].replace(/\\"/g,'"').replace(/\\t/g,'\t').replace(/\\n/g,'\n').replace(/\\r/g,'\r').replace(/\\\\/g,'\\');s.object={nominalValue:unescaped,interfaceName:'LiteralNode'};if(!_isUndefined(match[7])){s.object.datatype={nominalValue:match[7],interfaceName:'IRI'}}else if(!_isUndefined(match[8])){s.object.language=match[8]}}if(!_isUndefined(match[9])){s.name={nominalValue:match[9],interfaceName:'IRI'}}else if(!_isUndefined(match[10])){s.name={nominalValue:match[10],interfaceName:'BlankNode'}}for(var si in statements){if(_compareRdfStatements(statements[si],s)){continue}}statements.push(s)}return statements}jsonld.registerRDFParser('application/nquads',_parseNQuads);function _toNQuad(statement,bnode){var s=statement.subject;var p=statement.property;var o=statement.object;var g=statement.name||null;var quad='';if(s.interfaceName==='IRI'){quad+='<'+s.nominalValue+'>'}else if(bnode){quad+=(s.nominalValue===bnode)?'_:a':'_:z'}else{quad+=s.nominalValue}quad+=' <'+p.nominalValue+'> ';if(o.interfaceName==='IRI'){quad+='<'+o.nominalValue+'>'}else if(o.interfaceName==='BlankNode'){if(bnode){quad+=(o.nominalValue===bnode)?'_:a':'_:z'}else{quad+=o.nominalValue}}else{var escaped=o.nominalValue.replace(/\\/g,'\\\\').replace(/\t/g,'\\t').replace(/\n/g,'\\n').replace(/\r/g,'\\r').replace(/\"/g,'\\"');quad+='"'+escaped+'"';if('datatype'in o){quad+='^^<'+o.datatype.nominalValue+'>'}else if('language'in o){quad+='@'+o.language}}if(g!==null){if(g.interfaceName==='IRI'){quad+=' <'+g.nominalValue+'>'}else if(bnode){quad+=' _:g'}else{quad+=' '+g.nominalValue}}quad+=' .\n';return quad}function _parseRdfaApiData(data){var statements=[];var subjects=data.getSubjects();for(var si in subjects){var subject=subjects[si];if(subject===null){continue}var triples=data.getSubjectTriples(subject);if(triples===null){continue}var predicates=triples.predicates;for(var p in predicates){var objects=predicates[p].objects;for(var oi in objects){var object=objects[oi];var s={};if(subject.indexOf('_:')===0){s.subject={nominalValue:subject,interfaceName:'BlankNode'}}else{s.subject={nominalValue:subject,interfaceName:'IRI'}}s.property={nominalValue:p,interfaceName:'IRI'};var value=object.value;if(object.type===RDF_XML_LITERAL){if(!XMLSerializer){_defineXMLSerializer()}var serializer=new XMLSerializer();value='';for(var x=0;x<object.value.length;x++){if(object.value[x].nodeType===Node.ELEMENT_NODE){value+=serializer.serializeToString(object.value[x])}else if(object.value[x].nodeType===Node.TEXT_NODE){value+=object.value[x].nodeValue}}}s.object={nominalValue:value};if(object.type===RDF_OBJECT){if(object.value.indexOf('_:')===0){s.object.interfaceName='BlankNode'}else{s.object.interfaceName='IRI'}}else{s.object.interfaceName='LiteralNode';if(object.type===RDF_PLAIN_LITERAL){if(object.language){s.object.language=object.language}}else{s.object.datatype={nominalValue:object.type,interfaceName:'IRI'}}}statements.push(s)}}}return statements}jsonld.registerRDFParser('rdfa-api',_parseRdfaApiData);var UniqueNamer=function(prefix){this.prefix=prefix;this.counter=0;this.existing={}};UniqueNamer.prototype.clone=function(){var copy=new UniqueNamer(this.prefix);copy.counter=this.counter;copy.existing=_clone(this.existing);return copy};UniqueNamer.prototype.getName=function(oldName){if(oldName&&oldName in this.existing){return this.existing[oldName]}var name=this.prefix+this.counter;this.counter+=1;if(oldName){this.existing[oldName]=name}return name};UniqueNamer.prototype.isNamed=function(oldName){return(oldName in this.existing)};Permutator=function(list){this.list=list.sort();this.done=false;this.left={};for(var i in list){this.left[list[i]]=true}};Permutator.prototype.hasNext=function(){return!this.done};Permutator.prototype.next=function(){var rval=this.list.slice();var k=null;var pos=0;var length=this.list.length;for(var i=0;i<length;++i){var element=this.list[i];var left=this.left[element];if((k===null||element>k)&&((left&&i>0&&element>this.list[i-1])||(!left&&i<(length-1)&&element>this.list[i+1]))){k=element;pos=i}}if(k===null){this.done=true}else{var swap=this.left[k]?pos-1:pos+1;this.list[pos]=this.list[swap];this.list[swap]=k;for(var i=0;i<length;++i){if(this.list[i]>k){this.left[this.list[i]]=!this.left[this.list[i]]}}}return rval};var sha1=jsonld.sha1={};if(_nodejs){var crypto=require('crypto');sha1.create=function(){var md=crypto.createHash('sha1');return{update:function(data){md.update(data,'utf8')},digest:function(){return md.digest('hex')}}}}else{sha1.create=function(){return new sha1.MessageDigest()}}sha1.hash=function(nquads){var md=sha1.create();for(var i in nquads){md.update(nquads[i])}return md.digest()};if(!_nodejs){sha1.Buffer=function(){this.data='';this.read=0};sha1.Buffer.prototype.putInt32=function(i){this.data+=(String.fromCharCode(i>>24&0xFF)+String.fromCharCode(i>>16&0xFF)+String.fromCharCode(i>>8&0xFF)+String.fromCharCode(i&0xFF))};sha1.Buffer.prototype.getInt32=function(){var rval=(this.data.charCodeAt(this.read)<<24^this.data.charCodeAt(this.read+1)<<16^this.data.charCodeAt(this.read+2)<<8^this.data.charCodeAt(this.read+3));this.read+=4;return rval};sha1.Buffer.prototype.bytes=function(){return this.data.slice(this.read)};sha1.Buffer.prototype.length=function(){return this.data.length-this.read};sha1.Buffer.prototype.compact=function(){this.data=this.data.slice(this.read);this.read=0};sha1.Buffer.prototype.toHex=function(){var rval='';for(var i=this.read;i<this.data.length;++i){var b=this.data.charCodeAt(i);if(b<16){rval+='0'}rval+=b.toString(16)}return rval};sha1.MessageDigest=function(){if(!_sha1.initialized){_sha1.init()}this.blockLength=64;this.digestLength=20;this.messageLength=0;this.input=new sha1.Buffer();this.words=new Array(80);this.state={h0:0x67452301,h1:0xEFCDAB89,h2:0x98BADCFE,h3:0x10325476,h4:0xC3D2E1F0}};sha1.MessageDigest.prototype.update=function(msg){msg=unescape(encodeURIComponent(msg));this.messageLength+=msg.length;this.input.data+=msg;_sha1.update(this.state,this.words,this.input);if(this.input.read>2048||this.input.length()===0){this.input.compact()}};sha1.MessageDigest.prototype.digest=function(){var len=this.messageLength;var padBytes=new sha1.Buffer();padBytes.data+=this.input.bytes();padBytes.data+=_sha1.padding.substr(0,64-((len+8)%64));padBytes.putInt32((len>>>29)&0xFF);padBytes.putInt32((len<<3)&0xFFFFFFFF);_sha1.update(this.state,this.words,padBytes);var rval=new sha1.Buffer();rval.putInt32(this.state.h0);rval.putInt32(this.state.h1);rval.putInt32(this.state.h2);rval.putInt32(this.state.h3);rval.putInt32(this.state.h4);return rval.toHex()};var _sha1={padding:null,initialized:false};_sha1.init=function(){_sha1.padding=String.fromCharCode(128);var c=String.fromCharCode(0x00);var n=64;while(n>0){if(n&1){_sha1.padding+=c}n>>>=1;if(n>0){c+=c}}_sha1.initialized=true};_sha1.update=function(s,w,input){var t,a,b,c,d,e,f,i;var len=input.length();while(len>=64){a=s.h0;b=s.h1;c=s.h2;d=s.h3;e=s.h4;for(i=0;i<16;++i){t=input.getInt32();w[i]=t;f=d^(b&(c^d));t=((a<<5)|(a>>>27))+f+e+0x5A827999+t;e=d;d=c;c=(b<<30)|(b>>>2);b=a;a=t}for(;i<20;++i){t=(w[i-3]^w[i-8]^w[i-14]^w[i-16]);t=(t<<1)|(t>>>31);w[i]=t;f=d^(b&(c^d));t=((a<<5)|(a>>>27))+f+e+0x5A827999+t;e=d;d=c;c=(b<<30)|(b>>>2);b=a;a=t}for(;i<32;++i){t=(w[i-3]^w[i-8]^w[i-14]^w[i-16]);t=(t<<1)|(t>>>31);w[i]=t;f=b^c^d;t=((a<<5)|(a>>>27))+f+e+0x6ED9EBA1+t;e=d;d=c;c=(b<<30)|(b>>>2);b=a;a=t}for(;i<40;++i){t=(w[i-6]^w[i-16]^w[i-28]^w[i-32]);t=(t<<2)|(t>>>30);w[i]=t;f=b^c^d;t=((a<<5)|(a>>>27))+f+e+0x6ED9EBA1+t;e=d;d=c;c=(b<<30)|(b>>>2);b=a;a=t}for(;i<60;++i){t=(w[i-6]^w[i-16]^w[i-28]^w[i-32]);t=(t<<2)|(t>>>30);w[i]=t;f=(b&c)|(d&(b^c));t=((a<<5)|(a>>>27))+f+e+0x8F1BBCDC+t;e=d;d=c;c=(b<<30)|(b>>>2);b=a;a=t}for(;i<80;++i){t=(w[i-6]^w[i-16]^w[i-28]^w[i-32]);t=(t<<2)|(t>>>30);w[i]=t;f=b^c^d;t=((a<<5)|(a>>>27))+f+e+0xCA62C1D6+t;e=d;d=c;c=(b<<30)|(b>>>2);b=a;a=t}s.h0+=a;s.h1+=b;s.h2+=c;s.h3+=d;s.h4+=e;len-=64}}}if(!XMLSerializer){function _defineXMLSerializer(){XMLSerializer=require('xmldom').XMLSerializer}}
var callback = function(err, statement) {
if(err) {
}
if(statement !== null) {
emit([statement.subject,statement.property,statement.object], null);
}
};
var rdf = jsonld.toRDF(doc,callback);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment