hyper-readings
Version:
a tool for making and sharing p2p distributed reading lists
1 lines • 35.1 kB
JavaScript
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e(require("fs")):"function"==typeof define&&define.amd?define("HyperReadings",["fs"],e):"object"==typeof exports?exports.HyperReadings=e(require("fs")):t.HyperReadings=e(t.fs)}("undefined"!=typeof self?self:this,function(t){return function(t){var e={};function a(r){if(e[r])return e[r].exports;var n=e[r]={i:r,l:!1,exports:{}};return t[r].call(n.exports,n,n.exports,a),n.l=!0,n.exports}return a.m=t,a.c=e,a.d=function(t,e,r){a.o(t,e)||Object.defineProperty(t,e,{configurable:!1,enumerable:!0,get:r})},a.r=function(t){Object.defineProperty(t,"__esModule",{value:!0})},a.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return a.d(e,"a",e),e},a.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},a.p="",a.w={},a(a.s=10)}([function(t,e){t.exports=require("stream")},function(t,e){t.exports=require("events")},function(t,e){t.exports=require("nanoiterator/to-stream")},function(t,e){t.exports=require("nanoiterator")},function(t,e){t.exports=require("marked")},function(t,e){t.exports=require("parse5")},function(t,e){t.exports=require("uuid/v4")},function(t,e){t.exports=require("inherits")},function(t,e){t.exports=require("hyper-graph-db")},function(e,a){e.exports=t},function(t,e,a){"use strict";a.r(e);var r=a(1),n=a.n(r),i=a(9),o=a.n(i),s=a(8),c=a.n(s),f=a(7),l=a.n(f),u=a(6),h=a.n(u),d=a(5),m=a.n(d);function p(t,e,a){const r=function*t(e){if(e.childNodes&&0!==e.childNodes.length)for(let a of e.childNodes)yield a,yield*t(a)}(t);let n=r.next().value;for(;n;)a=e(a,n),n=r.next().value;return a}const y=t=>t;function b(t){return async(e,a)=>{return{node:await e.createNode(t)}}}function g(t){return async(e,a)=>{return{node:await e.createNode(t,{"c4o:hasContent":(a=a,p(a,(t,e)=>"#text"===e.nodeName?t+e.value:"br"===e.nodeName?t+"\n":t,""))}),terminal:!0}};var e}var w=g("doco:Paragraph"),v=g("doco:Title"),N=b("doco:Section"),P=b("hr:root"),S=b("hr:body");function I(t){return!t.childNodes&&t.value&&/^\s*$/.test(t.value)}var x={html:P,head:b("hr:head"),body:S,section:N,p:w,h1:v,h2:v,h3:v,h4:v,h5:v,h6:v},C=function(t,e){return t.createNode("po:Block")};const j=/^h(\d+)$/,k=t=>{const e=t.nodeName.match(j);return e&&e[1]},T=t=>({nodeName:"section",tagName:"section",childNodes:t,inferred:!0});function A(t){return function(t,e,a){a||(a=y);var r,n=0,i=[],o=[],s=i;return t.forEach(t=>{var c=e(t);if(null===c)s.push(t);else if(c>n)o.push({depth:n,array:s}),n=c,r=[t],s.push(a(r)),s=r;else if(c<=n){for(var f=o.pop();f&&f.depth>=c;)f=o.pop();f?(o.push(f),s=f.array):s=i,n=c,r=[t],s.push(a(r)),s=r}}),i}(t,k,T)}var _=async function(t,e){var a=m.a.parse(e),r=[];for(await i(a.childNodes[0]);r.length;){var n=r.shift();await i(n.node,n.context)}return t;async function i(e,a){if(I(e))return;var n=x[e.nodeName]||C,{node:i,terminal:o}=await n(t,e);if(a&&a.parent&&a.parent.insertNode&&await a.parent.insertNode(i),o)return;if(!e.childNodes&&0===e.childNodes.length)return;e.inferred||(e.childNodes=A(e.childNodes));const s=function(t,e){const a=e.filter(t=>!I(t));return a.length?a.map((e,a)=>({node:e,context:{parent:t}})):[]}(i,e.childNodes);Array.prototype.push.apply(r,s)}},O=a(4),E=a.n(O);const H={rdf:"http://www.w3.org/1999/02/22-rdf-syntax-ns#",rdfs:"http://www.w3.org/2000/01/rdf-schema#",co:"http://purl.org/co/",c4o:"http://purl.org/spar/c4o",po:"http://www.essepuntato.it/2008/12/pattern#",doco:"http://purl.org/spar/doco/",cito:"http://purl.org/spar/cito/",datacite:"http://purl.org/spar/datacite/",oa:"http://www.w3.org/ns/oa#",as:"http://www.w3.org/ns/activitystreams#",dc:"http://purl.org/dc/elements/1.1/",dcterms:"http://purl.org/dc/terms/",dctypes:"http://purl.org/dc/dcmitype/",foaf:"http://xmlns.com/foaf/0.1/",schema:"http://schema.org/",marcrel:"http://id.loc.gov/vocabulary/relators/",bf:"http://id.loc.gov/ontologies/bibframe/"},R={artist:"art",contributor:"ctb",performer:"prf",composer:"cmp",wordsBy:"lyr",sponsor:"spn",cosponsor:"spn",author:"aut",editor:"edt",seriesEditor:"edt",translator:"trl",bookAuthor:"aut",programmer:"prg",recipient:"rcp",director:"drt",producer:"pro",scriptwriter:"aus",interviewee:"ive",interviewer:"ivr",cartographer:"ctg",inventor:"inv",podcaster:"hst",presenter:"pre",castMember:"prf"};async function B(t,e,a){const r=e.split(" ");for(let e=0;e<r.length;e++){const n=r[e].trim();n&&n.length&&("isbn"===a&&await t.addIsbn(n),"issn"===a&&await t.addIssn(n),"doi"===a&&await t.addDoi(n))}}var L={md:function(t,e){const a=E()(e);return _(t,a)},html:_,zoteroApi:async function(t,e){if(!e||!e.itemType)throw new Error("ZoteroApi translator expects data with itemType");const a=await async function(t){const e=await t.collections();if(0===e.length)return(await t.createCollection("default")).addNewPage();const a=await e[0].lastPage();return a?await a.totalItems()<20?a:e[0].addNewPage():e[0]}(t),r=await t.createNode("bf:Instance");if(await a.addItem(r),e.creators&&await async function(t,e,a){for(let n=0;n<a.length;n++){const i=a[n];if(i){const a=(r=i.role,{name:`marcrel:${R[r]||"aut"}`}),n=[i.firstName,i.lastName].join(" "),o=await t.findPeople({name:n});let s;if(0===o.length)s=await t.createNode("bf:Person",{"foaf:name":n,"foaf:firstName":i.firstName,"foaf:lastName":i.lastName});else{s=o[0];const r=await t._query(`\n PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n PREFIX bf: <http://id.loc.gov/ontologies/bibframe/>\n PREFIX hr: <http://hyperreading.com/>\n PREFIX marcrel: <http://id.loc.gov/vocabulary/relators/>\n\n select * where {\n ?contribution rdf:type bf:Contribution .\n ?contribution bf:agent <${s.name}> .\n ?contribution bf:role ${a.name} .\n }\n `);if(r.length)return e.addContributionNode({name:r[0]["?contribution"],type:"bf:Contribution"})}await e.addContribution(s,a)}}var r}(t,r,e.creators),e.title&&await r.setTitle(e.title),e.shortTitle&&await r.setAbbreviatedTitle(e.shortTitle),e.abstractNote&&await r.setSummary(e.abstractNote),e.language&&await r.setLanguage(e.language),e.rights&&await r.setRights(e.rights),e.tags&&await async function(t,e){for(let a=0;a<e.length;a++)e[a]&&e[a].tag&&await t.addSubject(e[a].tag)}(r,e.tags),e.ISBN&&await B(r,e.ISBN,"isbn"),e.ISSN&&await B(r,e.ISSN,"issn"),e.DOI&&await B(r,e.DOI,"doi"),e.extra&&(await async function(t,e){const a=e.split("\n");for(let e=0;e<a.length;e++){const r=a[e];r.startsWith("DOI:")&&await B(t,r.substring(4),"doi")}}(r,e.extra),await r.setNote(e.extra)),e.libraryCatalog&&await r.setSource(e.libraryCatalog),function(t){return!!t.place||!!t.publisher||!!t.date}(e)&&await r.addPublication({place:e.place,date:e.date,publisher:e.publisher}),function(t){return!!(t.url||t.archive||t.archiveLocation||t.callNumber)}(e)){const a=await t.createNode("bf:Item");r.addItem(a),e.callNumber&&await a.setShelfMark(e.callNumber),e.url&&await a.setElectronicLocator(e.url),e.archive&&await a.setHeldBy(e.archive),e.archiveLocation&&await a.setShelfMark(e.archiveLocation)}if(function(t){return!!t.series&&t.series}(e)){const a=await t.findSeriesWithTitle(e.series);let n;0===a.length?(n=await t.createNode("bf:Instance"),await n.setTitle(e.series)):n=a[0],await r.setSeriesOf(n)}return e.seriesNumber&&await r.setSeriesEnumeration(e.seriesNumber),e.edition&&await r.setEditionStatement(e.edition),r}};function M(...t){return function(t,...e){return e.forEach(e=>{let a=Object.keys(e).reduce((t,a)=>(t[a]=Object.getOwnPropertyDescriptor(e,a),t),{});Object.getOwnPropertySymbols(e).forEach(t=>{let r=Object.getOwnPropertyDescriptor(e,t);r.enumerable&&(a[t]=r)}),Object.defineProperties(t,a)}),t}({},...t)}function D(t,e){return function(a){const r=Object.create(t);return e&&Object.assign(r,e),Object.assign(r,a)}}function F(t,e,a){return{subject:t,predicate:e,object:a}}function q(t,e,a){return F(a,e,t)}function $(t){return"string"==typeof t&&'"'===t.charAt(0)}const W=/(".+")(?:\^\^(.+))?$/;function X(t){const e=t.match(W);return e?"xsd:decimal"===e[2]?parseFloat(e[1].slice(1,-1)):JSON.parse(e[1]):t}function G(t){return!!t.name}function z(t){return G(t)?t.name:"number"==typeof t?`"${t}"^^xsd:decimal`:JSON.stringify(t)}const K={};function V(t,e){if("object"==typeof t&&"object"==typeof e){if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return!1;for(let a=0;a<t.length;a++)if(!V(t,e))return!1;return!0}return t.name===e.name}return t===e}function Q(t,e){return!!t.find(t=>V(t,e))}function J(t){return async function(e){const a=await this.properties(),r=Object.keys(a),n=Object.keys(e),i=r.reduce((r,i)=>"rdf:type"===i?r:(t(n,i,e,a)&&r.push(i),r),[]);await Promise.all(i.map(t=>{const r=a[t];if(Array.isArray(r)){const a=Array.isArray(e[t]);return Promise.all(r.map(r=>{if(!a||!Q(e[t],r))return this.remove(t,r)}))}return this.remove(t,r)})),await Promise.all(n.map(t=>{const r=e[t],n=a[t];if(!V(r,n)){if(Array.isArray(r)){const e=Array.isArray(n);return Promise.all(r.map(a=>{if(!e||!Q(n,a))return this.add(t,a)}))}return this.set(t,r)}}))}}function Z(t){return!$(t.object)&&(t.predicate&&"rdf:type"!==t.predicate)}K._castToNodeOrValue=async function(t){return $(t)?X(t):this.hr.node(t)},K.get=async function(t,e){const a=await this.hr._get(F(this.name,t,e),{limit:1});return a&&0!==a.length?this._castToNodeOrValue(a[0].object):null},K.all=async function(t,e){const a=await this.hr._get(F(this.name,t,e));return Promise.all(a.map(t=>this._castToNodeOrValue(t.object)))},K.add=function(t,e){return this.set(t,e,!0)},K.set=async function(t,e,a){if(!t)throw new Error("node.set() requires attribute");if(!a){const e=await this.all(t);for(var r=0;r<e.length;r++){const a=e[r];if(G(a)){1===(await a.parents(null,{limit:2})).length?await a.destroy():await this.hr._del(F(this.name,t,a.name))}else await this.remove(t,a)}}return await this.hr._put(F(this.name,t,z(e))),this},K.update=J(function(t,e,a,r){return!t.includes(e)||!V(a[e],r[e])}),K.merge=J(function(t,e,a,r){return a[e]&&!V(a[e],r[e])}),K.has=async function(t,e){var a=await this.hr._get(F(this.name,t,e&&z(e)),{limit:1});return!!a&&0!==a.length},K.remove=async function(t,e){const a=await this.hr._get(F(this.name,t,e&&z(e)));return a?(await Promise.all(a.map(t=>this.hr._del(t))),this):this},K.parents=async function(t,e){const a=await this.hr._get(q(this.name,t),e);return Promise.all(a.map(t=>this.hr.node(t.subject,{child:this,rel:t.predicate})))},K.properties=async function(){return(await this.hr._get(F(this.name))).reduce((t,e)=>{const a=$(e.object)?X(e.object):{name:e.object};return void 0===t[e.predicate]?t[e.predicate]=a:Array.isArray(t[e.predicate])?t[e.predicate].push(a):t[e.predicate]=[t[e.predicate],a],t},{})},K.children=async function(t){let e=await this.hr._get(F(this.name));if(!t){const t=e.filter(Z).map(t=>this.hr.node(t.object,{parent:this,rel:t.predicate}));return Promise.all(t)}return Promise.all(e.map(async t=>$(t.object)?{attr:t.predicate,value:t.object}:this.hr.node(t.object,{parent:this,rel:t.predicate})))},K.disconnect=async function(){const t=await this.parents();for(var e=0;e<t.length;e++){const a=t[e];await a.remove(a.rel,this)}return this},K.destroy=async function(t){t?t.push(this.name):t=[this.name],await this.disconnect();const e=await this.children(!0);for(var a=0;a<e.length;a++){const r=e[a];if(G(r)){let e=await r.parents();(e=e.filter(e=>!t.includes(e.name))).length?await this.hr._del(F(this.name,r.rel,r.name)):await r.destroy(t)}await this.hr._del(F(this.name,r.attr,r.value))}};var U=K;function Y(t,...e){return function(...a){return t.apply(this,[...e,...a])}}const tt=Y.bind(null,U.get),et=Y.bind(null,U.set),at=Y.bind(null,U.remove),rt=Y.bind(null,U.all),nt=Y.bind(null,U.add);async function it(t,e){const a=this.hr.graph.v,r=await this.hr._search([F(this.name,t,a("id")),F(a("id"),"rdf:type",e)],{limit:1});return r.length?this.hr.node({name:r[0].id,type:e}):null}function ot(t,e,a="many-to-one"){if("many-to-one"===a)return async function(a){await this.add(t,a),await a.set(e,this)};if("one-to-many"===a)return async function(a){await this.set(t,a),await a.add(e,this)};if("many-to-many"===a)return async function(a){await this.add(t,a),await a.add(e,this)};if("one-to-one"===a)return async function(a){await this.set(t,a),await a.set(e,this)};throw new Error("The makeRecipricalBinding function expects a valid relation type")}async function st(t){const e=this.hr.graph.v,a=Object.keys(t).map(a=>"type"===a?F(e("id"),`rdf:${a}`,t[a]):F(e("id"),a,z(t[a])));return(await this.hr._search(a)).map(e=>({name:e.id,type:t.type}))}async function ct(t,e,a){const r=await st.call(this,{[e]:t,type:a});return 0===r.length?this.hr.createNode(a,{[e]:t}):r[0]}const ft=function(t,e,a){return async function(r){if(G(r))return this.set(e,r);let n=await it.call(this,e,a);if(!n)return n=await ct.call(this,r,t,a),this.add(e,n);const i=await n.parents(void 0,{limit:2});if(i&&i.length>1)return n=await ct.call(this,r,t,a),this.set(e,n);const o=await st.call(this,{[t]:r,type:a});return 0===o.length?n.set(t,r):this.set(e,o[0])}}.bind(null,"rdfs:label"),lt=function(t,e,a){return async function(){let r=await this.get(e);return r&&r.name?(r.type!==a&&(r=await it.call(this,e,a)),r?r.get(t):null):r}}.bind(null,"rdfs:label");function ut(t,e){return async function(){let a=await it.call(this,t,e);a&&(await this.remove(t,a),await a.destroy())}}const ht={};ht.content=tt("as:content"),ht.setContent=et("as:content"),ht.removeContent=at("as:content"),ht.context=tt("as:context"),ht.setContext=et("as:context"),ht.removeContext=at("as:context"),ht.getName=tt("as:name"),ht.setName=et("as:name"),ht.removeName=at("as:name"),ht.summary=tt("as:summary"),ht.setSummary=et("as:summary"),ht.removeSummary=at("as:summary"),ht.mediaType=tt("as:mediaType"),ht.setMediaType=et("as:mediaType"),ht.removeMediaType=at("as:mediaType");var dt=ht,mt=a(0);var pt=class extends mt.Readable{constructor(t,e){super({objectMode:!0}),this.collection=t,this.next=null,this.itemStream=null,this.count=0,this.currentPage=e&&void 0!==e.page?e.page:0,this.startPage=this.currentPage,this.endPage=e&&void 0!==e.page?this.currentPage:1/0,this.limit=e&&e.limit?e.limit:1/0,this.proxyStreamData=this._proxyStreamData.bind(this),this.nextStream=this._nextStream.bind(this)}_proxyStreamData(t){if(this.count>=this.limit)return this.push(null),void process.nextTick(()=>this.destroy());const e=this.push(t);this.count++,e||this.itemStream.pause(),this.count,this.limit}_nextStream(){this.next&&this.currentPage<this.endPage?this.next.next().then(t=>{this.next=t,t?this.newItemStream(this.next.itemStream()):this.push(null)}):this.push(null)}newItemStream(t){this.itemStream=t,this.itemStream.on("data",this.proxyStreamData),this.itemStream.on("end",this.nextStream),this.itemStream.on("error",t=>{this.emit("error",t)})}_destroy(){this.itemStream&&(this.itemStream.removeListener("end",this.nextStream),this.itemStream.destroy())}_read(){this.count>=this.limit||(this.next||this.itemStream?this.itemStream&&this.itemStream.isPaused()&&this.itemStream.once("readable",t=>{null!==t&&this.push(t),this.itemStream.resume()}):this.collection.getPageAt(this.startPage).then(t=>{t?(this.next=t,this.newItemStream(t.itemStream())):this.itemStream=this.newItemStream(this.collection.itemStream())}))}};const yt={itemStream:function(){const t=this.hr.graph.getStream(F(this.name,"as:items")),e=this._castToNodeOrValue.bind(this),a=new mt.Transform({objectMode:!0,transform(t,a,r){if(this.destroyed)return r(null,null);e(t.object).then(t=>!this.destroyed&&r(null,t)).catch(r)},destroy(){t.destroy()}});return t.pipe(a)},stream:function(t){return new pt(this,t)},addNewPage:async function(){const t=await this.lastPage(),e=await this.hr.createNode("as:CollectionPage",{"as:partOf":this});return t?(await e.setPrev(t),await t.setNext(e)):await this.setFirstPage(e),await this.setLastPage(e),e},totalItems:async function(){const t=await this.get("as:totalItems");return t||0},incrementItemCount:async function(t=1){const e=await this.totalItems();return this.set("as:totalItems",Number(e)+t)}};yt.currentPage=tt("as:current"),yt.setCurrentPage=et("as:current"),yt.firstPage=tt("as:first"),yt.setFirstPage=et("as:first"),yt.getPageAt=async function(t){if(t<0)return;let e=await this.firstPage();if(!e)return;let a=0;for(;a<t;){if(!(e=await e.next()))return;a++}return e},yt.lastPage=tt("as:last"),yt.setLastPage=et("as:last"),yt.addItem=async function(t){if("as:CollectionPage"===this.type){const t=await this.getParentCollection();await t.incrementItemCount(),await t.setCurrentPage(this)}await this.incrementItemCount(),this.add("as:items",t)},yt.items=rt("as:items");var bt=yt;const gt={};gt.getParentCollection=tt("as:partOf"),gt.next=tt("as:next"),gt.setNext=et("as:next"),gt.prev=tt("as:prev"),gt.setPrev=et("as:prev");var wt=gt;const vt=M(U,dt),Nt=M(vt,bt),Pt=D(vt),St=D(Nt),It=D(M(Nt,wt));var xt={"as:Object":Pt,"as:Collection":St,"as:CollectionPage":It,"as:OrderedCollection":St,"as:OrderedCollectionPage":It};const Ct={};Ct.getName=tt("foaf:name"),Ct.setName=et("foaf:name"),Ct.removeName=at("foaf:name"),Ct.allInterests=rt("foaf:interest"),Ct.addInterest=nt("foaf:interest"),Ct.removeInterest=at("foaf:interest"),Ct.getAge=tt("foaf:age"),Ct.setAge=et("foaf:age"),Ct.removeAge=at("foaf:age"),Ct.getTitle=tt("foaf:title"),Ct.setTitle=et("foaf:title"),Ct.removeTitle=at("foaf:title"),Ct.allMadeRelations=rt("foaf:made"),Ct.addMadeRelation=nt("foaf:made"),Ct.removeMadeRelation=at("foaf:made");var jt=Ct;const kt={};kt.getPlan=tt("foaf:plan"),kt.setPlan=et("foaf:plan"),kt.removePlan=at("foaf:plan"),kt.getFirstName=tt("foaf:firstName"),kt.setFirstName=et("foaf:firstName"),kt.removeFirstName=at("foaf:firstName"),kt.getGivenName=tt("foaf:givenName"),kt.setGivenName=et("foaf:givenName"),kt.removeGivenName=at("foaf:givenName"),kt.getSurname=tt("foaf:surname"),kt.setSurname=et("foaf:surname"),kt.removeSurname=at("foaf:surname"),kt.getLastName=tt("foaf:lastName"),kt.setLastName=et("foaf:lastName"),kt.removeLastName=at("foaf:lastName"),kt.getFamilyName=tt("foaf:familyName"),kt.setFamilyName=et("foaf:familyName"),kt.removeFamilyName=at("foaf:familyName"),kt.getGeekcode=tt("foaf:geekcode"),kt.setGeekcode=et("foaf:geekcode"),kt.removeGeekcode=at("foaf:geekcode"),kt.getCurrentProjects=tt("foaf:currentProject"),kt.allCurrentProjects=rt("foaf:currentProject"),kt.addCurrentProject=nt("foaf:currentProject"),kt.getCurrentProject=at("foaf:currentProject"),kt.allPastProjects=rt("foaf:pastProject"),kt.addPastProject=nt("foaf:pastProject"),kt.removePastProject=at("foaf:pastProject"),kt.allPublications=rt("foaf:publications"),kt.addPublication=nt("foaf:publications"),kt.removePublication=at("foaf:publications"),kt.getWorkplaceHomepage=tt("foaf:workplaceHomepage"),kt.setWorkplaceHomepage=et("foaf:workplaceHomepage"),kt.removeWorkplaceHomepage=at("foaf:workplaceHomepage"),kt.getWorkInfoHomepage=tt("foaf:workInfoHomepage"),kt.setWorkInfoHomepage=et("foaf:workInfoHomepage"),kt.removeWorkInfoHomepage=at("foaf:workInfoHomepage"),kt.getSchoolHomepage=tt("foaf:schoolHomepage"),kt.setSchoolHomepage=et("foaf:schoolHomepage"),kt.removeSchoolHomepage=at("foaf:schoolHomepage"),kt.getMyersBriggs=tt("foaf:myersBriggs"),kt.setMyersBriggs=et("foaf:myersBriggs"),kt.removeMyersBriggs=at("foaf:myersBriggs"),kt.getImage=tt("foaf:img"),kt.setImage=et("foaf:img"),kt.removeImage=at("foaf:img"),kt.allKnowRelations=rt("foaf:knows"),kt.addKnowRelation=nt("foaf:knows"),kt.removeKnowRelation=at("foaf:knows");var Tt=kt;var At={};const _t={};_t.editionStatement=tt("bf:editionStatement"),_t.setEditionStatement=et("bf:editionStatement"),_t.editionEnumeration=tt("bf:editionEnumeration"),_t.setEditionEnumeration=et("bf:editionEnumeration"),_t.seriesStatement=tt("bf:seriesStatement"),_t.setSeriesStatement=et("bf:seriesStatement"),_t.seriesEnumeration=tt("bf:seriesEnumeration"),_t.setSeriesEnumeration=et("bf:seriesEnumeration"),_t.addPublication=async function(t){const e=await this.hr.createNode("bf:Publication",{"bf:date":t.date});if(t.place){let a,r=await this.hr.findPlaces({label:t.place});a=0===r.length?await this.hr.createNode("bf:Place",{"rdfs:label":t.place}):r[0],await e.set("bf:place",a)}if(t.publisher){let a,r=await this.hr.findAgents({label:t.publisher});a=0===r.length?await this.hr.createNode("bf:Agent",{"rdfs:label":t.publisher}):r[0],await e.set("bf:agent",a)}return this.add("bf:provisionActivity",e)},_t.publications=async function(){const t=await async function(t,e){const a=this.hr.graph.v,r=await this.hr._search([F(this.name,t,a("id")),F(a("id"),"rdf:type",e)],{limit:1});return r.length?Promise.all(r.map(t=>this.hr.node({name:t.id,type:e}))):[]}.call(this,"bf:provisionActivity","bf:Publication");return Promise.all(t.map(async t=>({date:await t.get("bf:date"),place:await t.get("bf:place"),agent:await t.get("bf:agent")})))},_t.addItem=ot("bf:hasItem","bf:itemOf","many-to-one"),_t.removeItem=at("bf:hasItem"),_t.items=rt("bf:hasItem"),_t.instanceOf=ot("bf:instanceOf","bf:hasInstance","many-to-many");var Ot=_t;const Et={setHeldBy:async function(t){if(G(t))return this.set("bf:heldBy",t);const e=await this.hr.findAgents({label:t});let a;return a=0===e.length?await this.hr.createNode("bf:Agent",{"rdfs:label":t}):e[0],this.set("bf:heldBy",a)}};Et.heldBy=tt("bf:heldBy"),Et.itemOf=tt("bf:itemOf"),Et.getPhysicalLocation=tt("bf:physicalLocation"),Et.setPhysicalLocation=et("bf:physicalLocation"),Et.removePhysicalLocation=at("bf:physicalLocation"),Et.setShelfMark=ft("bf:shelfMark","bf:ShelfMark"),Et.getShelfMark=lt("bf:shelfMark","bf:ShelfMark"),Et.getElectronicLocator=tt("bf:electronicLocator"),Et.setElectronicLocator=et("bf:electronicLocator"),Et.removeElectronicLocator=at("bf:electronicLocator");var Ht=Et;const Rt={};Rt.getAgent=tt("bf:agent"),Rt.setAgent=et("bf:agent"),Rt.getCode=tt("bf:code"),Rt.setCode=et("bf:code"),Rt.removeCode=at("bf:code"),Rt.getCount=tt("bf:count"),Rt.setCount=et("bf:count"),Rt.removeCount=at("bf:count"),Rt.getDate=tt("bf:date"),Rt.setDate=et("bf:date"),Rt.removeDate=at("bf:date"),Rt.identifiers=async function(){const t=await this.all("bf:identifiedBy");return Promise.all(t.map(async t=>({type:t.type,value:await t.get("rdf:value")})))},Rt.addIdentifier=nt("bf:identifiedBy"),Rt.removeIdentifier=at("bf:identifiedBy"),Rt.addDoi=async function(t){const e=await this.hr.createNode("bf:Doi",{"rdf:value":t});return this.add("bf:identifiedBy",e)},Rt.addIsbn=async function(t){const e=await this.hr.createNode("bf:Isnb",{"rdf:value":t});return this.add("bf:identifiedBy",e)},Rt.addIssn=async function(t){const e=await this.hr.createNode("bf:Issn",{"rdf:value":t});return this.add("bf:identifiedBy",e)},Rt.addIssnL=async function(t){const e=await this.hr.createNode("bf:IssnL",{"rdf:value":t});return this.add("bf:identifiedBy",e)},Rt.language=lt("bf:language","bf:Language"),Rt.setLanguage=ft("bf:language","bf:Language"),Rt.removeLanguage=at("bf:language"),Rt.note=lt("bf:note","bf:Note"),Rt.setNote=ft("bf:note","bf:Note"),Rt.removeNote=at("bf:note"),Rt.getPart=tt("bf:part"),Rt.setPart=et("bf:part"),Rt.removePart=at("bf:part"),Rt.getQualifier=tt("bf:qualifier"),Rt.setQualifier=et("bf:qualifier"),Rt.removeQualifier=at("bf:qualifier"),Rt.setSource=ft("bf:source","bf:Source"),Rt.source=lt("bf:source","bf:Source"),Rt.setStatus=ft("bf:status","bf:Status"),Rt.status=lt("bf:status","bf:Status");var Bt=Rt;const Lt={};Lt.setSeriesOf=ot("bf:hasSeries","bf:seriesOf","one-to-many"),Lt.hasSeries=tt("bf:hasSeries"),Lt.seriesOf=rt("bf:seriesOf"),Lt.setAwards=et("bf:awards"),Lt.removeAwards=at("bf:awards"),Lt.awards=tt("bf:awards"),Lt.setCopyrightDate=et("bf:copyrightDate"),Lt.removeCopyrightDate=at("bf:copyrightDate"),Lt.copyrightDate=tt("bf:copyrightDate"),Lt.setCredits=et("bf:credits"),Lt.removeCredits=at("bf:credits"),Lt.credits=tt("bf:credits"),Lt.setDuration=et("bf:duration"),Lt.removeDuration=at("bf:duration"),Lt.duration=tt("bf:duration"),Lt.setNatureOfContent=et("bf:natureOfContent"),Lt.removePreferredCitation=at("bf:natureOfContent"),Lt.natureOfContent=tt("bf:natureOfContent"),Lt.setPreferredCitation=et("bf:preferredCitation"),Lt.removePreferredCitation=at("bf:preferredCitation"),Lt.preferredCitation=tt("bf:preferredCitation"),Lt.setSummary=ft("bf:summary","bf:Summary"),Lt.getSummary=lt("bf:summary","bf:Summary"),Lt.setRights=ft("bf:copyrightRegistration","bf:CopyrightRegistration"),Lt.rights=lt("bf:copyrightRegistration","bf:CopyrightRegistration");var Mt=Lt;const Dt={};Dt.setTitle=ft("bf:title","bf:Title"),Dt.getTitle=lt("bf:title","bf:Title"),Dt.removeTitle=ut("bf:title","bf:Title"),Dt.setAbbreviatedTitle=ft("bf:title","bf:AbbreviatedTitle"),Dt.getAbbreviatedTitle=lt("bf:title","bf:AbbreviatedTitle"),Dt.removeAbbreviatedTitle=ut("bf:title","bf:AbbreviatedTitle"),Dt.addSubject=nt("bf:subject"),Dt.removeSubject=at("bf:subject"),Dt.subjects=rt("bf:subject"),Dt.addContributionNode=nt("bf:contribution"),Dt.addContribution=async function(t,e){const a=await this.hr.createNode("bf:Contribution",{"bf:agent":t,"bf:role":e});return this.add("bf:contribution",a)},Dt.contributions=async function(t,e){const a=await this.all("bf:contribution");return Promise.all(a.map(async t=>{const e=await t.getAgent(),a=await t.getRole();return{name:await e.getName(),firstName:await e.getFirstName(),lastName:await e.getLastName(),role:a.name}}))},Dt.setCustodialHistory=et("bf:custodialHistory"),Dt.removeCustodialHistory=at("bf:custodialHistory"),Dt.custodialHistory=tt("bf:custodialHistory");var Ft=Dt;const qt={};qt.getRole=tt("bf:role"),qt.setRole=et("bf:role");var $t=qt;const Wt=M(U,Bt),Xt=M(Wt,Ft),Gt=D(M(Xt,Mt,At)),zt=D(M(Xt,Mt,Ot)),Kt=D(M(Xt,Ht)),Vt=D(M(Wt,jt)),Qt=D(M(Wt,jt,Tt));var Jt={"bf:Work":Gt,"bf:Text":Gt,"bf:Cartography":Gt,"bf:Audio":Gt,"bf:NotatedMusic":Gt,"bf:NotatedMovement":Gt,"bf:Dataset":Gt,"bf:StillImage":Gt,"bf:MovingImage":Gt,"bf:Object":Gt,"bf:Multimedia":Gt,"bf:MixedMaterial":Gt,"bf:Instance":zt,"bf:Print":zt,"bf:Manuscript":zt,"bf:Archival":zt,"bf:Tactile":zt,"bf:Electronic":zt,"bf:Item":Kt,"bf:Contribution":D(M(Wt,$t)),"bf:Agent":Vt,"foaf:Agent":Vt,"bf:Person":Qt,"foaf:Person":Qt},Zt=a(3),Ut=a.n(Zt),Yt=a(2),te=a.n(Yt);const ee={firstItem:function(){return this.get("co:firstItem")},itemContent:function(){return this.get("co:itemContent")},contains:function(){return this.all("po:contains")},next:function(){return this.get("co:nextItem")},iterator:function(t){var e=null,a=!(t&&t.listItems);return Ut()({next:t=>{(e?e.next():this.firstItem()).then(t=>(e=t,a?e&&e.itemContent():e)).then(e=>t(null,e)).catch(t)}})},stream:function(t){return te()(this.iterator(t))},iterate:async function(t,e){for(var a=await this.firstItem();a;){if(t)if(e&&e.listItems)await t(a);else{var r=await a.itemContent();await t(r)}a=await a.next()}},lastItem:async function(){var t=await this.get("co:lastItem");return t||(await this.iterate(e=>{t=e},{listItems:!0}),t)},insertNode:async function(t,e){await this.add("po:contains",t);var a=await this.hr.createNode("co:ListItem");if(await a.set("co:itemContent",t),await this.has("co:firstItem")){var r=await this.lastItem();r&&await r.set("co:nextItem",a)}else await this.set("co:firstItem",a);return this},updateList:async function(t){let e=0;for(await this.iterate(async a=>{if(e>t.length)return;if(e===t.length)return await a.parent.destroy([this.name]),void(e+=1);const r=t[e];a.name!==r?(await a.parent.setContent({name:r}),t.includes(a.name)||await this.remove("po:contains",a),await this.add("po:contains",{name:r}),e+=1):e+=1});e<t.length;)await this.insertNode({name:t[e]}),e+=1},at:async function(t,e){let a=0;const r=this.iterator(e);return new Promise((e,n)=>{r.next(function i(o,s){if(o)return r.destroy(),n(o);if(null===s||a>t)return r.destroy(),e(null);a===t&&r.destroy(()=>e(s));a++;r.next(i)})})},removeNodeAt:async function(t){const e=await this.at(t);if(e)return e.destroy()},removeNodesFrom:async function(t){const e=await this.at(t,{listItems:!0});if(e)return e.destroy()},removeNode:async function(t){}};var ae=ee;const re={setContent:function(t){return this.set("co:itemContent",t)},previous:async function(){var t=await this.hr._get(q(this.name,"co:nextItem"),{limit:1});return t.length||(t=await this.hr._get(q(this.name,"co:firstItem"),{limit:1})),t.length?this.hr.node(t[0].subject):void 0},next:function(){return this.get("co:nextItem")},itemContent:async function(){const t=await this.hr._get(F(this.name,"co:itemContent"),{limit:1});return t&&0!==t.length?this.hr.node(t[0].object,{rel:"co:itemContent",parent:this}):null},remove:async function(t,e){if("co:itemContent"===t){const t=await this.previous(),e=await this.next();if(t){const a=t.type===this.type?"co:nextItem":"co:firstItem";e?(await this.hr._del(F(t.name,a,this.name)),await t.set(a,e)):await t.remove(a,this)}}return U.remove.call(this,t,e)}};var ne=re;const ie=D(U),oe=D(M(U,ae)),se=D(M(U,ne)),ce=Object.assign({"hr:root":oe,"hr:head":oe,"hr:body":oe,"doco:List":oe,"doco:Section":oe,"doco:Paragraph":oe,"doco:Title":oe,"po:Block":oe,"po:Inline":oe,"co:ListItem":se},Jt,xt);function fe(t,e){return function(a,r){if(a)return e(a);t(r)}}function le(t,e,a){if(!(this instanceof le))return new le(t,e,a);"string"==typeof e||a||(a=e,e=null),n.a.EventEmitter.call(this),(a=a||{}).prefixes||(a.prefixes=H),a.name||(a.name="hr://"),this.swarm=a.swarm,this.network=null,this._nodeCount=0,this.graph=c()(t,e,a),this.graph.on("ready",t=>{this.emit("ready",t)})}l()(le,n.a.EventEmitter),le.prototype.key=function(){return this.graph.db.key.toString("hex")},le.prototype.joinNetwork=function(t){if(this.swarm)return this.network?(console.warn("Already joined network"),this.network):(this.network=this.swarm(this.graph.db,t),this.network);console.warn("Cannot join network - no swarm set.")},le.prototype.leaveNetwork=async function(){if(this.network)return new Promise((t,e)=>{this.network.leave(this.graph.db.discoveryKey),this.network.destroy(fe(t,e))}).then(()=>{this.network=null})},le.prototype.importZoteroReference=function(t){return this.import(t,{type:"zoteroApi"})},le.prototype.importFile=function(t,e){if(!t||"string"!=typeof t)throw new Error("HyperReadings.importFile requires filename to be a string");let a=e&&e.type;if(a){if(!L[a])throw new Error(`HyperReadings.import does not recognize type ${a}`)}else{const e=t.match(/\.(w+)$/);if(!e||L[e[1]])throw new Error("HyperReadings.import does not recognize file extension");a=e[1]}return new Promise((e,a)=>o.a.readFile(t,fe)).then(t=>this.import(t,a))},le.prototype.import=function(t,e){if(!t)return Promise.resolve();if(!e||!e.type)throw new Error("HyperReadings.import requires opts.type to be set");if(!L[e.type])throw new Error(`HyperReadings.import does not recognize type ${e.type}`);return L[e.type](this,t)},le.prototype.setTitle=function(t){if(!t||"string"!=typeof t)throw new Error("Title must be a string");return new Promise((e,a)=>this.graph.db.put("@title",t,t=>{if(t)return a(t);e()}))},le.prototype.title=function(){return new Promise((t,e)=>this.graph.db.get("@title",(a,r)=>{if(a)return e(a);t(r)})).then(t=>t&&0!==t.length?t[0].value.toString():"untitled")},le.prototype.root=async function(){return this.nodeByType("hr:root")},le.prototype.head=async function(){return this.nodeByType("hr:head")},le.prototype.body=async function(){return this.nodeByType("hr:body")},le.prototype.iterate=async function(...t){return(await this.root()).iterate(...t)},le.prototype.createCollection=async function(t,e){return this.createNode("as:Collection",{"as:name":t,"as:content":e})},le.prototype.collections=async function(){return this.nodesByType("as:Collection")},le.prototype.getCollection=async function(t){const e=this.graph.v,a=[F(e("id"),"rdf:type","as:Collection")];t&&a.push(F(e("id"),"as:name",z(t)));const r=await this._search(a,{limit:1});return 0===r.length?null:this.node({name:r[0].id,type:"as:Collection"})},le.prototype.exists=async function(t,e){const a=await this._get(F(t,e?"rdf:type":void 0,e),{limit:1});return!!(a&&a.length>0)},le.prototype.findPeople=async function(t){const e=this.graph.v,a=[F(e("id"),"rdf:type","bf:Person")];t&&t.name&&a.push(F(e("id"),"foaf:name",z(t.name))),t&&t.firstName&&a.push(F(e("id"),"foaf:firstName",z(t.firstName))),t&&t.lastName&&a.push(F(e("id"),"foaf:lastName",z(t.lastName)));const r=await this._search(a);return Promise.all(r.map(t=>this.node({name:t.id,type:"bf:Person"})))},le.prototype.findAgents=async function(t){const e=this.graph.v,a=[F(e("id"),"rdf:type","bf:Agent")];t&&t.label&&a.push(F(e("id"),"rdfs:label",t.label));const r=await this._search(a);return Promise.all(r.map(t=>this.node({name:t.id,type:"bf:Agent"})))},le.prototype.findPlaces=async function(t){const e=this.graph.v,a=[F(e("id"),"rdf:type","bf:Place")];t&&t.label&&a.push(F(e("id"),"rdfs:label",t.label));const r=await this._search(a);return Promise.all(r.map(t=>this.node({name:t.id,type:"bf:Place"})))},le.prototype.findSeriesWithTitle=async function(t){const e=await this._query(`\n PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n PREFIX bf: <http://id.loc.gov/ontologies/bibframe/>\n select * where {\n {\n ?title rdf:type bf:AbbreviatedTitle .\n } UNION {\n ?title rdf:type bf:Title .\n }\n ?title rdfs:label ${z(t)} .\n ?id rdf:type bf:Instance .\n ?id bf:title ?title .\n }`);return Promise.all(e.map(t=>this.node({name:t["?id"],type:"bf:Instance"})))},le.prototype.nodesByType=async function(t,e){const a=await this._get(q(t,"rdf:type"),e);return Promise.all(a.map(t=>this.node(t)))},le.prototype.nodeByType=async function(t,e){const a=await this.nodesByType(t,{limit:1});return a.length>0?a[0]:null},le.prototype.node=async function(t,e){let a,r;return"string"==typeof t?a=t:t.subject?(a=t.subject,"rdf:type"===t.predicate&&t.object&&(r=t.object)):t.name&&(a=t.name,r=t.type),r||(r=await this._getType(a)),function(t,e,a,r){const n={hr:t,name:e,type:a,rel:r&&r.rel,parent:r&&r.parent,child:r&&r.child};return(ce[a]||ie)(n)}(this,a,r,e)},le.prototype.createNode=async function(t,e){if(!t)throw new Error("Cannot create a node without type");let a=e&&e.id;a||(a=await this.newBlankNodeName());const r=F(a,"rdf:type",t);await this._put(r);const n=await this.node(F(a,"rdf:type",t));return e&&await Promise.all(Object.keys(e).map(t=>{if("id"!==t&&void 0!==e[t])return n.set(t,e[t])})),n},le.prototype.newBlankNodeName=async function(){return await this._name()+"n"+h()()},le.prototype._getType=async function(t){var e=await this._get(F(t,"rdf:type"),{limit:1});return e.length?e[0].object:void 0},le.prototype._name=function(t,e){return new Promise((t,e)=>this.graph.name(fe(t,e)))},le.prototype._get=function(t,e){return new Promise((a,r)=>this.graph.get(t,e,fe(a,r)))},le.prototype._put=function(t){return new Promise((e,a)=>this.graph.put(t,fe(e,a)))},le.prototype._del=function(t){return new Promise((e,a)=>this.graph.del(t,fe(e,a)))},le.prototype._search=function(t,e){return new Promise((a,r)=>this.graph.search(t,e,fe(a,r)))},le.prototype._query=function(t){return new Promise((e,a)=>this.graph.query(t,fe(e,a)))};var ue=le;a.d(e,"HyperReadings",function(){return ue})}])});