diff --git a/.nvmrc b/.nvmrc index bf79505b..eb800ed4 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ -v16.14.0 +v18.19.0 diff --git a/dist/670.mashlib.min.js b/dist/670.mashlib.min.js deleted file mode 100644 index aecde3b2..00000000 --- a/dist/670.mashlib.min.js +++ /dev/null @@ -1 +0,0 @@ -(self.webpackChunkMashlib=self.webpackChunkMashlib||[]).push([[670],{3421:()=>{}}]); \ No newline at end of file diff --git a/dist/789.mashlib.min.js b/dist/789.mashlib.min.js new file mode 100644 index 00000000..da3a2ab0 --- /dev/null +++ b/dist/789.mashlib.min.js @@ -0,0 +1 @@ +(self.webpackChunkMashlib=self.webpackChunkMashlib||[]).push([[789],{7789:()=>{}}]); \ No newline at end of file diff --git a/dist/805.mashlib.min.js b/dist/805.mashlib.min.js deleted file mode 100644 index c6ac3284..00000000 --- a/dist/805.mashlib.min.js +++ /dev/null @@ -1,3 +0,0 @@ -/*! For license information please see 805.mashlib.min.js.LICENSE.txt */ -(self.webpackChunkMashlib=self.webpackChunkMashlib||[]).push([[805],{5456:e=>{"use strict";e.exports=function e(t){return null===t||"object"!=typeof t||null!=t.toJSON?JSON.stringify(t):Array.isArray(t)?"["+t.reduce(((t,n,o)=>t+(0===o?"":",")+e(void 0===n||"symbol"==typeof n?null:n)),"")+"]":"{"+Object.keys(t).sort().reduce(((n,o,r)=>void 0===t[o]||"symbol"==typeof t[o]?n:n+(0===n.length?"":",")+e(o)+":"+e(t[o])),"")+"}"}},8058:(e,t,n)=>{"use strict";const{isArray:o,isObject:r,isString:a}=n(832),{asArray:i}=n(1055),{prependBase:s}=n(6938),l=n(4093),c=n(6767);function d(e){throw new l("Invalid JSON-LD syntax; @context must be an object.","jsonld.SyntaxError",{code:"invalid local context",context:e})}function u({context:e,base:t}){if(!e)return;const n=e["@context"];if(a(n))e["@context"]=s(t,n);else if(o(n))for(let e=0;e10)throw new l("Maximum number of @context URLs exceeded.","jsonld.ContextUrlError",{code:"json-ld-1.0"===e.processingMode?"loading remote context failed":"context overflow",max:10});if(i.has(t))throw new l("Cyclical @context URLs detected.","jsonld.ContextUrlError",{code:"json-ld-1.0"===e.processingMode?"recursive context inclusion":"context overflow",url:t});let s,c;i.add(t);try{c=await n(t),s=c.document||null,a(s)&&(s=JSON.parse(s))}catch(e){throw new l("Dereferencing a URL did not result in a valid JSON-LD object. Possible causes are an inaccessible URL perhaps due to a same-origin policy (ensure the server uses CORS if you are using client-side JavaScript), too many redirects, a non-JSON response, or more than one HTTP Link Header was provided for a remote context.","jsonld.InvalidUrl",{code:"loading remote context failed",url:t,cause:e})}if(!r(s))throw new l("Dereferencing a URL did not result in a JSON object. The response was valid JSON, but it was not a JSON object.","jsonld.InvalidUrl",{code:"invalid remote context",url:t});return s="@context"in s?{"@context":s["@context"]}:{"@context":{}},c.contextUrl&&(o(s["@context"])||(s["@context"]=[s["@context"]]),s["@context"].push(c.contextUrl)),{context:s,remoteDoc:c}}}},4093:e=>{"use strict";e.exports=class extends Error{constructor(e="An unspecified JSON-LD error occurred.",t="jsonld.Error",n={}){super(e),this.name=t,this.message=e,this.details=n}}},731:e=>{"use strict";e.exports=e=>{class t{toString(){return"[object JsonLdProcessor]"}}return Object.defineProperty(t,"prototype",{writable:!1,enumerable:!1}),Object.defineProperty(t.prototype,"constructor",{writable:!0,enumerable:!1,configurable:!0,value:t}),t.compact=function(t,n){return arguments.length<2?Promise.reject(new TypeError("Could not compact, too few arguments.")):e.compact(t,n)},t.expand=function(t){return arguments.length<1?Promise.reject(new TypeError("Could not expand, too few arguments.")):e.expand(t)},t.flatten=function(t){return arguments.length<1?Promise.reject(new TypeError("Could not flatten, too few arguments.")):e.flatten(t)},t}},9048:(e,t,n)=>{"use strict";e.exports=n(7055).NQuads},533:e=>{"use strict";e.exports=class{constructor(){this._requests={}}wrapLoader(e){const t=this;return t._loader=e,function(){return t.add.apply(t,arguments)}}async add(e){let t=this._requests[e];if(t)return Promise.resolve(t);t=this._requests[e]=this._loader(e);try{return await t}finally{delete this._requests[e]}}}},6767:(e,t,n)=>{"use strict";const o=n(9593);e.exports=class{constructor({document:e}){this.document=e,this.cache=new o({max:10})}getProcessed(e){return this.cache.get(e)}setProcessed(e,t){this.cache.set(e,t)}}},3251:(e,t,n)=>{"use strict";const o=n(4093),{isArray:r,isObject:a,isString:i,isUndefined:s}=n(832),{isList:l,isValue:c,isGraph:d,isSimpleGraph:u,isSubjectReference:p}=n(8463),{expandIri:h,getContextValue:f,isKeyword:v,process:g,processingMode:y}=n(4131),{removeBase:m,prependBase:x}=n(6938),{REGEX_KEYWORD:b,addValue:w,asArray:j,compareShortestLeast:I}=n(1055),N={};function S(e,t,n){if("@nest"!==h(e,t,{vocab:!0},n))throw new o("JSON-LD compact error; nested property must have an @nest value resolving to @nest.","jsonld.SyntaxError",{code:"invalid @nest value"})}e.exports=N,N.compact=async({activeCtx:e,activeProperty:t=null,element:n,options:h={}})=>{if(r(n)){let o=[];for(let r=0;r1&&(O=Array.from(O).sort());const E=e;for(const t of O){const n=N.compactIri({activeCtx:E,iri:t,relativeTo:{vocab:!0}}),o=f(b,n,"@context");s(o)||(e=await g({activeCtx:e,localCtx:o,options:h,propagate:!1}))}const D=Object.keys(n).sort();for(const s of D){const p=n[s];if("@id"!==s)if("@type"!==s)if("@reverse"!==s)if("@preserve"!==s)if("@index"!==s)if("@graph"!==s&&"@list"!==s&&"@included"!==s&&v(s)){const t=N.compactIri({activeCtx:e,iri:s,relativeTo:{vocab:!0}});w(x,t,p)}else{if(!r(p))throw new o("JSON-LD expansion error; expanded value must be an array.","jsonld.SyntaxError");if(0===p.length){const t=N.compactIri({activeCtx:e,iri:s,value:p,relativeTo:{vocab:!0},reverse:m}),n=e.mappings.has(t)?e.mappings.get(t)["@nest"]:null;let o=x;n&&(S(e,n,h),a(x[n])||(x[n]={}),o=x[n]),w(o,t,p,{propertyIsArray:!0})}for(const t of p){const n=N.compactIri({activeCtx:e,iri:s,value:t,relativeTo:{vocab:!0},reverse:m}),o=e.mappings.has(n)?e.mappings.get(n)["@nest"]:null;let p=x;o&&(S(e,o,h),a(x[o])||(x[o]={}),p=x[o]);const v=f(e,n,"@container")||[],g=d(t),y=l(t);let b;y?b=t["@list"]:g&&(b=t["@graph"]);let I=await N.compact({activeCtx:e,activeProperty:n,element:y||g?b:t,options:h});if(y){if(r(I)||(I=[I]),v.includes("@list")){w(p,n,I,{valueIsArray:!0,allowDuplicate:!0});continue}I={[N.compactIri({activeCtx:e,iri:"@list",relativeTo:{vocab:!0}})]:I},"@index"in t&&(I[N.compactIri({activeCtx:e,iri:"@index",relativeTo:{vocab:!0}})]=t["@index"])}if(g)if(v.includes("@graph")&&(v.includes("@id")||v.includes("@index")&&u(t))){let o;p.hasOwnProperty(n)?o=p[n]:p[n]=o={};const r=(v.includes("@id")?t["@id"]:t["@index"])||N.compactIri({activeCtx:e,iri:"@none",relativeTo:{vocab:!0}});w(o,r,I,{propertyIsArray:!h.compactArrays||v.includes("@set")})}else v.includes("@graph")&&u(t)?(r(I)&&I.length>1&&(I={"@included":I}),w(p,n,I,{propertyIsArray:!h.compactArrays||v.includes("@set")})):(r(I)&&1===I.length&&h.compactArrays&&(I=I[0]),I={[N.compactIri({activeCtx:e,iri:"@graph",relativeTo:{vocab:!0}})]:I},"@id"in t&&(I[N.compactIri({activeCtx:e,iri:"@id",relativeTo:{vocab:!0}})]=t["@id"]),"@index"in t&&(I[N.compactIri({activeCtx:e,iri:"@index",relativeTo:{vocab:!0}})]=t["@index"]),w(p,n,I,{propertyIsArray:!h.compactArrays||v.includes("@set")}));else if(v.includes("@language")||v.includes("@index")||v.includes("@id")||v.includes("@type")){let o,r;if(p.hasOwnProperty(n)?o=p[n]:p[n]=o={},v.includes("@language"))c(I)&&(I=I["@value"]),r=t["@language"];else if(v.includes("@index")){const o=f(e,n,"@index")||"@index",a=N.compactIri({activeCtx:e,iri:o,relativeTo:{vocab:!0}});if("@index"===o)r=t["@index"],delete I[a];else{let e;if([r,...e]=j(I[o]||[]),i(r))switch(e.length){case 0:delete I[o];break;case 1:I[o]=e[0];break;default:I[o]=e}else r=null}}else if(v.includes("@id")){const t=N.compactIri({activeCtx:e,iri:"@id",relativeTo:{vocab:!0}});r=I[t],delete I[t]}else if(v.includes("@type")){const o=N.compactIri({activeCtx:e,iri:"@type",relativeTo:{vocab:!0}});let a;switch([r,...a]=j(I[o]||[]),a.length){case 0:delete I[o];break;case 1:I[o]=a[0];break;default:I[o]=a}1===Object.keys(I).length&&"@id"in t&&(I=await N.compact({activeCtx:e,activeProperty:n,element:{"@id":t["@id"]},options:h}))}r||(r=N.compactIri({activeCtx:e,iri:"@none",relativeTo:{vocab:!0}})),w(o,r,I,{propertyIsArray:v.includes("@set")})}else{const e=!h.compactArrays||v.includes("@set")||v.includes("@list")||r(I)&&0===I.length||"@list"===s||"@graph"===s;w(p,n,I,{propertyIsArray:e})}}}else{if((f(e,t,"@container")||[]).includes("@index"))continue;const n=N.compactIri({activeCtx:e,iri:s,relativeTo:{vocab:!0}});w(x,n,p)}else{const n=await N.compact({activeCtx:e,activeProperty:t,element:p,options:h});r(n)&&0===n.length||w(x,s,n)}else{const t=await N.compact({activeCtx:e,activeProperty:"@reverse",element:p,options:h});for(const n in t)if(e.mappings.has(n)&&e.mappings.get(n).reverse){const o=t[n],r=(f(e,n,"@container")||[]).includes("@set")||!h.compactArrays;w(x,n,o,{propertyIsArray:r}),delete t[n]}if(Object.keys(t).length>0){const n=N.compactIri({activeCtx:e,iri:s,relativeTo:{vocab:!0}});w(x,n,t)}}else{let t=j(p).map((e=>N.compactIri({activeCtx:b,iri:e,relativeTo:{vocab:!0}})));1===t.length&&(t=t[0]);const n=N.compactIri({activeCtx:e,iri:"@type",relativeTo:{vocab:!0}}),o=(f(e,n,"@container")||[]).includes("@set")&&y(e,1.1)||r(t)&&0===p.length;w(x,n,t,{propertyIsArray:o})}else{let t=j(p).map((t=>N.compactIri({activeCtx:e,iri:t,relativeTo:{vocab:!1},base:h.base})));1===t.length&&(t=t[0]),x[N.compactIri({activeCtx:e,iri:"@id",relativeTo:{vocab:!0}})]=t}}return x}return n},N.compactIri=({activeCtx:e,iri:t,value:n=null,relativeTo:r={vocab:!1},reverse:i=!1,base:s=null})=>{if(null===t)return t;e.isPropertyTermScoped&&e.previousContext&&(e=e.previousContext);const u=e.getInverse();if(v(t)&&t in u&&"@none"in u[t]&&"@type"in u[t]["@none"]&&"@none"in u[t]["@none"]["@type"])return u[t]["@none"]["@type"]["@none"];if(r.vocab&&t in u){const o=e["@language"]||"@none",r=[];a(n)&&"@index"in n&&!("@graph"in n)&&r.push("@index","@index@set"),a(n)&&"@preserve"in n&&(n=n["@preserve"][0]),d(n)?("@index"in n&&r.push("@graph@index","@graph@index@set","@index","@index@set"),"@id"in n&&r.push("@graph@id","@graph@id@set"),r.push("@graph","@graph@set","@set"),"@index"in n||r.push("@graph@index","@graph@index@set","@index","@index@set"),"@id"in n||r.push("@graph@id","@graph@id@set")):a(n)&&!c(n)&&r.push("@id","@id@set","@type","@set@type");let s="@language",u="@null";if(i)s="@type",u="@reverse",r.push("@set");else if(l(n)){"@index"in n||r.push("@list");const e=n["@list"];if(0===e.length)s="@any",u="@none";else{let t=0===e.length?o:null,n=null;for(let o=0;oe.includes("_")));e&&s.push(e.replace(/^[^_]+_/,"_"))}s.push("@none");const l=e.inverse[t];for(const e of o){if(!(e in l))continue;const t=l[e][r];for(const e of s)if(e in t)return t[e]}return null}(e,t,n,r,s,u);if(null!==p)return p}if(r.vocab&&"@vocab"in e){const n=e["@vocab"];if(0===t.indexOf(n)&&t!==n){const o=t.substr(n.length);if(!e.mappings.has(o))return o}}let p=null;const h=[];let f=e.fastCurieMap;const g=t.length-1;for(let e=0;e=0;--o){const r=h[o],a=r.terms;for(const o of a){const a=o+":"+t.substr(r.iri.length);e.mappings.get(o)._prefix&&(!e.mappings.has(a)||null===n&&e.mappings.get(a)["@id"]===t)&&(null===p||I(a,p)<0)&&(p=a)}}if(null!==p)return p;for(const[n,r]of e.mappings)if(r&&r._prefix&&t.startsWith(n+":"))throw new o(`Absolute IRI "${t}" confused with prefix "${n}".`,"jsonld.SyntaxError",{code:"IRI confused with prefix",context:e});if(!r.vocab){if("@base"in e){if(e["@base"]){const n=m(x(s,e["@base"]),t);return b.test(n)?`./${n}`:n}return t}return m(s,t)}return t},N.compactValue=({activeCtx:e,activeProperty:t,value:n,options:o})=>{if(c(n)){const o=f(e,t,"@type"),r=f(e,t,"@language"),a=f(e,t,"@direction"),s=f(e,t,"@container")||[],l="@index"in n&&!s.includes("@index");if(!l&&"@none"!==o){if(n["@type"]===o)return n["@value"];if("@language"in n&&n["@language"]===r&&"@direction"in n&&n["@direction"]===a)return n["@value"];if("@language"in n&&n["@language"]===r)return n["@value"];if("@direction"in n&&n["@direction"]===a)return n["@value"]}const c=Object.keys(n).length,d=1===c||2===c&&"@index"in n&&!l,u="@language"in e,p=i(n["@value"]),h=e.mappings.has(t)&&null===e.mappings.get(t)["@language"];if(d&&"@none"!==o&&(!u||!p||h))return n["@value"];const v={};return l&&(v[N.compactIri({activeCtx:e,iri:"@index",relativeTo:{vocab:!0}})]=n["@index"]),"@type"in n?v[N.compactIri({activeCtx:e,iri:"@type",relativeTo:{vocab:!0}})]=N.compactIri({activeCtx:e,iri:n["@type"],relativeTo:{vocab:!0}}):"@language"in n&&(v[N.compactIri({activeCtx:e,iri:"@language",relativeTo:{vocab:!0}})]=n["@language"]),"@direction"in n&&(v[N.compactIri({activeCtx:e,iri:"@direction",relativeTo:{vocab:!0}})]=n["@direction"]),v[N.compactIri({activeCtx:e,iri:"@value",relativeTo:{vocab:!0}})]=n["@value"],v}const r=h(e,t,{vocab:!0},o),a=f(e,t,"@type"),s=N.compactIri({activeCtx:e,iri:n["@id"],relativeTo:{vocab:"@vocab"===a},base:o.base});return"@id"===a||"@vocab"===a||"@graph"===r?s:{[N.compactIri({activeCtx:e,iri:"@id",relativeTo:{vocab:!0}})]:s}}},3770:e=>{"use strict";const t="http://www.w3.org/1999/02/22-rdf-syntax-ns#",n="http://www.w3.org/2001/XMLSchema#";e.exports={LINK_HEADER_REL:"http://www.w3.org/ns/json-ld#context",LINK_HEADER_CONTEXT:"http://www.w3.org/ns/json-ld#context",RDF:t,RDF_LIST:t+"List",RDF_FIRST:t+"first",RDF_REST:t+"rest",RDF_NIL:t+"nil",RDF_TYPE:t+"type",RDF_PLAIN_LITERAL:t+"PlainLiteral",RDF_XML_LITERAL:t+"XMLLiteral",RDF_JSON_LITERAL:t+"JSON",RDF_OBJECT:t+"object",RDF_LANGSTRING:t+"langString",XSD:n,XSD_BOOLEAN:n+"boolean",XSD_DOUBLE:n+"double",XSD_INTEGER:n+"integer",XSD_STRING:n+"string"}},4131:(e,t,n)=>{"use strict";const o=n(1055),r=n(4093),{isArray:a,isObject:i,isString:s,isUndefined:l}=n(832),{isAbsolute:c,isRelative:d,prependBase:u}=n(6938),{handleEvent:p}=n(1696),{REGEX_BCP47:h,REGEX_KEYWORD:f,asArray:v,compareShortestLeast:g}=n(1055),y=new Map,m={};function x(e,t,n,o,r,a){if(null===t||!s(t)||m.isKeyword(t))return t;if(t.match(f))return null;if(o&&o.hasOwnProperty(t)&&!0!==r.get(t)&&m.createTermDefinition({activeCtx:e,localCtx:o,term:t,defined:r,options:a}),(n=n||{}).vocab){const n=e.mappings.get(t);if(null===n)return null;if(i(n)&&"@id"in n)return n["@id"]}const l=t.indexOf(":");if(l>0){const n=t.substr(0,l),i=t.substr(l+1);if("_"===n||0===i.indexOf("//"))return t;o&&o.hasOwnProperty(n)&&m.createTermDefinition({activeCtx:e,localCtx:o,term:n,defined:r,options:a});const s=e.mappings.get(n);if(s&&s._prefix)return s["@id"]+i;if(c(t))return t}if(n.vocab&&"@vocab"in e)t=e["@vocab"]+t;else if(n.base){let n,o;"@base"in e?e["@base"]?(o=u(a.base,e["@base"]),n=u(o,t)):(o=e["@base"],n=t):(o=a.base,n=u(a.base,t)),t=n}return t}function b(e,t){if(!e||"object"!=typeof e||!t||"object"!=typeof t)return e===t;const n=Array.isArray(e);if(n!==Array.isArray(t))return!1;if(n){if(e.length!==t.length)return!1;for(let n=0;n{if(i(t)&&"@context"in t&&a(t["@context"])&&(t=t["@context"]),0===v(t).length)return e;const g=[],y=[({event:e,next:t})=>{g.push(e),t()}];n.eventHandler&&y.push(n.eventHandler);const b=n;n={...n,eventHandler:y};const w=await n.contextResolver.resolve({activeCtx:e,context:t,documentLoader:n.documentLoader,base:n.base});i(w[0].document)&&"boolean"==typeof w[0].document["@propagate"]&&(o=w[0].document["@propagate"]);let j=e;o||j.previousContext||(j=j.clone(),j.previousContext=e);for(const o of w){let{document:a}=o;if(e=j,null===a){if(!l&&0!==Object.keys(e.protected).length)throw new r("Tried to nullify a context with protected terms outside of a term definition.","jsonld.SyntaxError",{code:"invalid context nullification"});j=e=m.getInitialContext(n).clone();continue}const v=o.getProcessed(e);if(v){if(b.eventHandler)for(const e of v.events)p({event:e,options:b});j=e=v.context;continue}if(i(a)&&"@context"in a&&(a=a["@context"]),!i(a))throw new r("Invalid JSON-LD syntax; @context must be an object.","jsonld.SyntaxError",{code:"invalid local context",context:a});j=j.clone();const y=new Map;if("@version"in a){if(1.1!==a["@version"])throw new r("Unsupported JSON-LD version: "+a["@version"],"jsonld.UnsupportedVersion",{code:"invalid @version value",context:a});if(e.processingMode&&"json-ld-1.0"===e.processingMode)throw new r("@version: "+a["@version"]+" not compatible with "+e.processingMode,"jsonld.ProcessingModeConflict",{code:"processing mode conflict",context:a});j.processingMode="json-ld-1.1",j["@version"]=a["@version"],y.set("@version",!0)}if(j.processingMode=j.processingMode||e.processingMode,"@base"in a){let e=a["@base"];if(null===e||c(e));else{if(!d(e))throw new r('Invalid JSON-LD syntax; the value of "@base" in a @context must be an absolute IRI, a relative IRI, or null.',"jsonld.SyntaxError",{code:"invalid base IRI",context:a});e=u(j["@base"],e)}j["@base"]=e,y.set("@base",!0)}if("@vocab"in a){const e=a["@vocab"];if(null===e)delete j["@vocab"];else{if(!s(e))throw new r('Invalid JSON-LD syntax; the value of "@vocab" in a @context must be a string or null.',"jsonld.SyntaxError",{code:"invalid vocab mapping",context:a});if(!c(e)&&m.processingMode(j,1))throw new r('Invalid JSON-LD syntax; the value of "@vocab" in a @context must be an absolute IRI.',"jsonld.SyntaxError",{code:"invalid vocab mapping",context:a});{const t=x(j,e,{vocab:!0,base:!0},void 0,void 0,n);c(t)||n.eventHandler&&p({event:{type:["JsonLdEvent"],code:"relative @vocab reference",level:"warning",message:"Relative @vocab reference found.",details:{vocab:t}},options:n}),j["@vocab"]=t}}y.set("@vocab",!0)}if("@language"in a){const e=a["@language"];if(null===e)delete j["@language"];else{if(!s(e))throw new r('Invalid JSON-LD syntax; the value of "@language" in a @context must be a string or null.',"jsonld.SyntaxError",{code:"invalid default language",context:a});e.match(h)||n.eventHandler&&p({event:{type:["JsonLdEvent"],code:"invalid @language value",level:"warning",message:"@language value must be valid BCP47.",details:{language:e}},options:n}),j["@language"]=e.toLowerCase()}y.set("@language",!0)}if("@direction"in a){const t=a["@direction"];if("json-ld-1.0"===e.processingMode)throw new r("Invalid JSON-LD syntax; @direction not compatible with "+e.processingMode,"jsonld.SyntaxError",{code:"invalid context member",context:a});if(null===t)delete j["@direction"];else{if("ltr"!==t&&"rtl"!==t)throw new r('Invalid JSON-LD syntax; the value of "@direction" in a @context must be null, "ltr", or "rtl".',"jsonld.SyntaxError",{code:"invalid base direction",context:a});j["@direction"]=t}y.set("@direction",!0)}if("@propagate"in a){const n=a["@propagate"];if("json-ld-1.0"===e.processingMode)throw new r("Invalid JSON-LD syntax; @propagate not compatible with "+e.processingMode,"jsonld.SyntaxError",{code:"invalid context entry",context:a});if("boolean"!=typeof n)throw new r("Invalid JSON-LD syntax; @propagate value must be a boolean.","jsonld.SyntaxError",{code:"invalid @propagate value",context:t});y.set("@propagate",!0)}if("@import"in a){const o=a["@import"];if("json-ld-1.0"===e.processingMode)throw new r("Invalid JSON-LD syntax; @import not compatible with "+e.processingMode,"jsonld.SyntaxError",{code:"invalid context entry",context:a});if(!s(o))throw new r("Invalid JSON-LD syntax; @import must be a string.","jsonld.SyntaxError",{code:"invalid @import value",context:t});const i=await n.contextResolver.resolve({activeCtx:e,context:o,documentLoader:n.documentLoader,base:n.base});if(1!==i.length)throw new r("Invalid JSON-LD syntax; @import must reference a single context.","jsonld.SyntaxError",{code:"invalid remote context",context:t});const l=i[0].getProcessed(e);if(l)a=l;else{const n=i[0].document;if("@import"in n)throw new r("Invalid JSON-LD syntax: imported context must not include @import.","jsonld.SyntaxError",{code:"invalid context entry",context:t});for(const e in n)a.hasOwnProperty(e)||(a[e]=n[e]);i[0].setProcessed(e,a)}y.set("@import",!0)}y.set("@protected",a["@protected"]||!1);for(const e in a)if(m.createTermDefinition({activeCtx:j,localCtx:a,term:e,defined:y,options:n,overrideProtected:l}),i(a[e])&&"@context"in a[e]){const t=a[e]["@context"];let o=!0;if(s(t)){const e=u(n.base,t);f.has(e)?o=!1:f.add(e)}if(o)try{await m.process({activeCtx:j.clone(),localCtx:a[e]["@context"],overrideProtected:!0,options:n,cycles:f})}catch(t){throw new r("Invalid JSON-LD syntax; invalid scoped context.","jsonld.SyntaxError",{code:"invalid scoped context",context:a[e]["@context"],term:e})}}o.setProcessed(e,{context:j,events:g})}return j},m.createTermDefinition=({activeCtx:e,localCtx:t,term:n,defined:o,options:l,overrideProtected:d=!1})=>{if(o.has(n)){if(o.get(n))return;throw new r("Cyclical context definition detected.","jsonld.CyclicalContext",{code:"cyclic IRI mapping",context:t,term:n})}let u;if(o.set(n,!1),t.hasOwnProperty(n)&&(u=t[n]),"@type"===n&&i(u)&&"@set"===(u["@container"]||"@set")&&m.processingMode(e,1.1)){const e=["@container","@id","@protected"],o=Object.keys(u);if(0===o.length||o.some((t=>!e.includes(t))))throw new r("Invalid JSON-LD syntax; keywords cannot be overridden.","jsonld.SyntaxError",{code:"keyword redefinition",context:t,term:n})}else{if(m.isKeyword(n))throw new r("Invalid JSON-LD syntax; keywords cannot be overridden.","jsonld.SyntaxError",{code:"keyword redefinition",context:t,term:n});if(n.match(f))return void(l.eventHandler&&p({event:{type:["JsonLdEvent"],code:"reserved term",level:"warning",message:'Terms beginning with "@" are reserved for future use and dropped.',details:{term:n}},options:l}));if(""===n)throw new r("Invalid JSON-LD syntax; a term cannot be an empty string.","jsonld.SyntaxError",{code:"invalid term definition",context:t})}const h=e.mappings.get(n);e.mappings.has(n)&&e.mappings.delete(n);let v=!1;if((s(u)||null===u)&&(v=!0,u={"@id":u}),!i(u))throw new r("Invalid JSON-LD syntax; @context term values must be strings or objects.","jsonld.SyntaxError",{code:"invalid term definition",context:t});const g={};e.mappings.set(n,g),g.reverse=!1;const y=["@container","@id","@language","@reverse","@type"];m.processingMode(e,1.1)&&y.push("@context","@direction","@index","@nest","@prefix","@protected");for(const e in u)if(!y.includes(e))throw new r("Invalid JSON-LD syntax; a term definition must not contain "+e,"jsonld.SyntaxError",{code:"invalid term definition",context:t});const w=n.indexOf(":");if(g._termHasColon=w>0,"@reverse"in u){if("@id"in u)throw new r("Invalid JSON-LD syntax; a @reverse term definition must not contain @id.","jsonld.SyntaxError",{code:"invalid reverse property",context:t});if("@nest"in u)throw new r("Invalid JSON-LD syntax; a @reverse term definition must not contain @nest.","jsonld.SyntaxError",{code:"invalid reverse property",context:t});const a=u["@reverse"];if(!s(a))throw new r("Invalid JSON-LD syntax; a @context @reverse value must be a string.","jsonld.SyntaxError",{code:"invalid IRI mapping",context:t});if(a.match(f))return l.eventHandler&&p({event:{type:["JsonLdEvent"],code:"reserved @reverse value",level:"warning",message:'@reverse values beginning with "@" are reserved for future use and dropped.',details:{reverse:a}},options:l}),void(h?e.mappings.set(n,h):e.mappings.delete(n));const i=x(e,a,{vocab:!0,base:!1},t,o,l);if(!c(i))throw new r("Invalid JSON-LD syntax; a @context @reverse value must be an absolute IRI or a blank node identifier.","jsonld.SyntaxError",{code:"invalid IRI mapping",context:t});g["@id"]=i,g.reverse=!0}else if("@id"in u){let a=u["@id"];if(a&&!s(a))throw new r("Invalid JSON-LD syntax; a @context @id value must be an array of strings or a string.","jsonld.SyntaxError",{code:"invalid IRI mapping",context:t});if(null===a)g["@id"]=null;else{if(!m.isKeyword(a)&&a.match(f))return l.eventHandler&&p({event:{type:["JsonLdEvent"],code:"reserved @id value",level:"warning",message:'@id values beginning with "@" are reserved for future use and dropped.',details:{id:a}},options:l}),void(h?e.mappings.set(n,h):e.mappings.delete(n));if(a!==n){if(a=x(e,a,{vocab:!0,base:!1},t,o,l),!c(a)&&!m.isKeyword(a))throw new r("Invalid JSON-LD syntax; a @context @id value must be an absolute IRI, a blank node identifier, or a keyword.","jsonld.SyntaxError",{code:"invalid IRI mapping",context:t});if(n.match(/(?::[^:])|\//)&&x(e,n,{vocab:!0,base:!1},t,new Map(o).set(n,!0),l)!==a)throw new r("Invalid JSON-LD syntax; term in form of IRI must expand to definition.","jsonld.SyntaxError",{code:"invalid IRI mapping",context:t});g["@id"]=a,g._prefix=v&&!g._termHasColon&&null!==a.match(/[:\/\?#\[\]@]$/)}}}if(!("@id"in g))if(g._termHasColon){const r=n.substr(0,w);if(t.hasOwnProperty(r)&&m.createTermDefinition({activeCtx:e,localCtx:t,term:r,defined:o,options:l}),e.mappings.has(r)){const t=n.substr(w+1);g["@id"]=e.mappings.get(r)["@id"]+t}else g["@id"]=n}else if("@type"===n)g["@id"]=n;else{if(!("@vocab"in e))throw new r("Invalid JSON-LD syntax; @context terms must define an @id.","jsonld.SyntaxError",{code:"invalid IRI mapping",context:t,term:n});g["@id"]=e["@vocab"]+n}if((!0===u["@protected"]||!0===o.get("@protected")&&!1!==u["@protected"])&&(e.protected[n]=!0,g.protected=!0),o.set(n,!0),"@type"in u){let n=u["@type"];if(!s(n))throw new r("Invalid JSON-LD syntax; an @context @type value must be a string.","jsonld.SyntaxError",{code:"invalid type mapping",context:t});if("@json"===n||"@none"===n){if(m.processingMode(e,1))throw new r(`Invalid JSON-LD syntax; an @context @type value must not be "${n}" in JSON-LD 1.0 mode.`,"jsonld.SyntaxError",{code:"invalid type mapping",context:t})}else if("@id"!==n&&"@vocab"!==n){if(n=x(e,n,{vocab:!0,base:!1},t,o,l),!c(n))throw new r("Invalid JSON-LD syntax; an @context @type value must be an absolute IRI.","jsonld.SyntaxError",{code:"invalid type mapping",context:t});if(0===n.indexOf("_:"))throw new r("Invalid JSON-LD syntax; an @context @type value must be an IRI, not a blank node identifier.","jsonld.SyntaxError",{code:"invalid type mapping",context:t})}g["@type"]=n}if("@container"in u){const n=s(u["@container"])?[u["@container"]]:u["@container"]||[],o=["@list","@set","@index","@language"];let i=!0;const l=n.includes("@set");if(m.processingMode(e,1.1)){if(o.push("@graph","@id","@type"),n.includes("@list")){if(1!==n.length)throw new r("Invalid JSON-LD syntax; @context @container with @list must have no other values","jsonld.SyntaxError",{code:"invalid container mapping",context:t})}else if(n.includes("@graph")){if(n.some((e=>"@graph"!==e&&"@id"!==e&&"@index"!==e&&"@set"!==e)))throw new r("Invalid JSON-LD syntax; @context @container with @graph must have no other values other than @id, @index, and @set","jsonld.SyntaxError",{code:"invalid container mapping",context:t})}else i&=n.length<=(l?2:1);if(n.includes("@type")&&(g["@type"]=g["@type"]||"@id",!["@id","@vocab"].includes(g["@type"])))throw new r("Invalid JSON-LD syntax; container: @type requires @type to be @id or @vocab.","jsonld.SyntaxError",{code:"invalid type mapping",context:t})}else i&=!a(u["@container"]),i&=n.length<=1;if(i&=n.every((e=>o.includes(e))),i&=!(l&&n.includes("@list")),!i)throw new r("Invalid JSON-LD syntax; @context @container value must be one of the following: "+o.join(", "),"jsonld.SyntaxError",{code:"invalid container mapping",context:t});if(g.reverse&&!n.every((e=>["@index","@set"].includes(e))))throw new r("Invalid JSON-LD syntax; @context @container value for a @reverse type definition must be @index or @set.","jsonld.SyntaxError",{code:"invalid reverse property",context:t});g["@container"]=n}if("@index"in u){if(!("@container"in u)||!g["@container"].includes("@index"))throw new r(`Invalid JSON-LD syntax; @index without @index in @container: "${u["@index"]}" on term "${n}".`,"jsonld.SyntaxError",{code:"invalid term definition",context:t});if(!s(u["@index"])||0===u["@index"].indexOf("@"))throw new r(`Invalid JSON-LD syntax; @index must expand to an IRI: "${u["@index"]}" on term "${n}".`,"jsonld.SyntaxError",{code:"invalid term definition",context:t});g["@index"]=u["@index"]}if("@context"in u&&(g["@context"]=u["@context"]),"@language"in u&&!("@type"in u)){let e=u["@language"];if(null!==e&&!s(e))throw new r("Invalid JSON-LD syntax; @context @language value must be a string or null.","jsonld.SyntaxError",{code:"invalid language mapping",context:t});null!==e&&(e=e.toLowerCase()),g["@language"]=e}if("@prefix"in u){if(n.match(/:|\//))throw new r("Invalid JSON-LD syntax; @context @prefix used on a compact IRI term","jsonld.SyntaxError",{code:"invalid term definition",context:t});if(m.isKeyword(g["@id"]))throw new r("Invalid JSON-LD syntax; keywords may not be used as prefixes","jsonld.SyntaxError",{code:"invalid term definition",context:t});if("boolean"!=typeof u["@prefix"])throw new r("Invalid JSON-LD syntax; @context value for @prefix must be boolean","jsonld.SyntaxError",{code:"invalid @prefix value",context:t});g._prefix=!0===u["@prefix"]}if("@direction"in u){const e=u["@direction"];if(null!==e&&"ltr"!==e&&"rtl"!==e)throw new r('Invalid JSON-LD syntax; @direction value must be null, "ltr", or "rtl".',"jsonld.SyntaxError",{code:"invalid base direction",context:t});g["@direction"]=e}if("@nest"in u){const e=u["@nest"];if(!s(e)||"@nest"!==e&&0===e.indexOf("@"))throw new r("Invalid JSON-LD syntax; @context @nest value must be a string which is not a keyword other than @nest.","jsonld.SyntaxError",{code:"invalid @nest value",context:t});g["@nest"]=e}const j=g["@id"];if("@context"===j||"@preserve"===j)throw new r("Invalid JSON-LD syntax; @context and @preserve cannot be aliased.","jsonld.SyntaxError",{code:"invalid keyword alias",context:t});if(h&&h.protected&&!d&&(e.protected[n]=!0,g.protected=!0,!b(h,g)))throw new r("Invalid JSON-LD syntax; tried to redefine a protected term.","jsonld.SyntaxError",{code:"protected term redefinition",context:t,term:n})},m.expandIri=(e,t,n,o)=>x(e,t,n,void 0,void 0,o),m.getInitialContext=e=>{const t=JSON.stringify({processingMode:e.processingMode}),n=y.get(t);if(n)return n;const r={processingMode:e.processingMode,mappings:new Map,inverse:null,getInverse:function(){const e=this;if(e.inverse)return e.inverse;const t=e.inverse={},n=e.fastCurieMap={},o={},r=(e["@language"]||"@none").toLowerCase(),s=e["@direction"],l=e.mappings,c=[...l.keys()].sort(g);for(const e of c){const a=l.get(e);if(null===a)continue;let c=a["@container"]||"@none";if(c=[].concat(c).sort().join(""),null===a["@id"])continue;const d=v(a["@id"]);for(const l of d){let d=t[l];const u=m.isKeyword(l);if(d)u||a._termHasColon||o[l].push(e);else if(t[l]=d={},!u&&!a._termHasColon){o[l]=[e];const t={iri:l,terms:o[l]};l[0]in n?n[l[0]].push(t):n[l[0]]=[t]}if(d[c]||(d[c]={"@language":{},"@type":{},"@any":{}}),d=d[c],i(e,d["@any"],"@none"),a.reverse)i(e,d["@type"],"@reverse");else if("@none"===a["@type"])i(e,d["@any"],"@none"),i(e,d["@language"],"@none"),i(e,d["@type"],"@none");else if("@type"in a)i(e,d["@type"],a["@type"]);else if("@language"in a&&"@direction"in a){const t=a["@language"],n=a["@direction"];i(e,d["@language"],t&&n?`${t}_${n}`.toLowerCase():t?t.toLowerCase():n?`_${n}`:"@null")}else"@language"in a?i(e,d["@language"],(a["@language"]||"@null").toLowerCase()):"@direction"in a?a["@direction"]?i(e,d["@language"],`_${a["@direction"]}`):i(e,d["@language"],"@none"):s?(i(e,d["@language"],`_${s}`),i(e,d["@language"],"@none"),i(e,d["@type"],"@none")):(i(e,d["@language"],r),i(e,d["@language"],"@none"),i(e,d["@type"],"@none"))}}for(const e in n)a(n,e,1);return t},clone:function(){const e={};return e.mappings=o.clone(this.mappings),e.clone=this.clone,e.inverse=null,e.getInverse=this.getInverse,e.protected=o.clone(this.protected),this.previousContext&&(e.previousContext=this.previousContext.clone()),e.revertToPreviousContext=this.revertToPreviousContext,"@base"in this&&(e["@base"]=this["@base"]),"@language"in this&&(e["@language"]=this["@language"]),"@vocab"in this&&(e["@vocab"]=this["@vocab"]),e},revertToPreviousContext:function(){return this.previousContext?this.previousContext.clone():this},protected:{}};return 1e4===y.size&&y.clear(),y.set(t,r),r;function a(e,t,n){const o=e[t],r=e[t]={};let i,s;for(const e of o)i=e.iri,s=n>=i.length?"":i[n],s in r?r[s].push(e):r[s]=[e];for(const e in r)""!==e&&a(r,e,n+1)}function i(e,t,n){t.hasOwnProperty(n)||(t[n]=e)}},m.getContextValue=(e,t,n)=>{if(null===t){if("@context"===n)return;return null}if(e.mappings.has(t)){const o=e.mappings.get(t);if(l(n))return o;if(o.hasOwnProperty(n))return o[n]}return"@language"===n&&n in e||"@direction"===n&&n in e?e[n]:"@context"!==n?null:void 0},m.processingMode=(e,t)=>t.toString()>="1.1"?!e.processingMode||e.processingMode>="json-ld-"+t.toString():"json-ld-1.0"===e.processingMode,m.isKeyword=e=>{if(!s(e)||"@"!==e[0])return!1;switch(e){case"@base":case"@container":case"@context":case"@default":case"@direction":case"@embed":case"@explicit":case"@graph":case"@id":case"@included":case"@index":case"@json":case"@language":case"@list":case"@nest":case"@none":case"@omitDefault":case"@prefix":case"@preserve":case"@protected":case"@requireAll":case"@reverse":case"@set":case"@type":case"@value":case"@version":case"@vocab":return!0}return!1}},8831:(e,t,n)=>{"use strict";const{parseLinkHeader:o,buildHeaders:r}=n(1055),{LINK_HEADER_CONTEXT:a}=n(3770),i=n(4093),s=n(533),{prependBase:l}=n(6938),c=/(^|(\r\n))link:/i;e.exports=({secure:e,headers:t={},xhr:n}={headers:{}})=>(t=r(t),(new s).wrapLoader((async function r(s){if(0!==s.indexOf("http:")&&0!==s.indexOf("https:"))throw new i('URL could not be dereferenced; only "http" and "https" URLs are supported.',"jsonld.InvalidUrl",{code:"loading document failed",url:s});if(e&&0!==s.indexOf("https"))throw new i('URL could not be dereferenced; secure mode is enabled and the URL\'s scheme is not "https".',"jsonld.InvalidUrl",{code:"loading document failed",url:s});let d;try{d=await function(e,t,n){const o=new(e=e||XMLHttpRequest);return new Promise(((e,r)=>{o.onload=()=>e(o),o.onerror=e=>r(e),o.open("GET",t,!0);for(const e in n)o.setRequestHeader(e,n[e]);o.send()}))}(n,s,t)}catch(e){throw new i("URL could not be dereferenced, an error occurred.","jsonld.LoadDocumentError",{code:"loading document failed",url:s,cause:e})}if(d.status>=400)throw new i("URL could not be dereferenced: "+d.statusText,"jsonld.LoadDocumentError",{code:"loading document failed",url:s,httpStatusCode:d.status});let u={contextUrl:null,documentUrl:s,document:d.response},p=null;const h=d.getResponseHeader("Content-Type");let f;if(c.test(d.getAllResponseHeaders())&&(f=d.getResponseHeader("Link")),f&&"application/ld+json"!==h){const e=o(f),t=e[a];if(Array.isArray(t))throw new i("URL could not be dereferenced, it has more than one associated HTTP Link Header.","jsonld.InvalidUrl",{code:"multiple context link headers",url:s});t&&(u.contextUrl=t.target),p=e.alternate,p&&"application/ld+json"==p.type&&!(h||"").match(/^application\/(\w*\+)?json$/)&&(u=await r(l(s,p.target)))}return u})))},1696:(e,t,n)=>{"use strict";var o=n(5108);const r=n(4093),{isArray:a}=n(832),{asArray:i}=n(1055),s={};function l({event:e,handlers:t}){let n=!0;for(let o=0;n&&o{n=!0}});else{if("object"!=typeof i)throw new r("Invalid event handler.","jsonld.InvalidEventHandler",{event:e});e.code in i?i[e.code]({event:e,next:()=>{n=!0}}):n=!0}}return n}e.exports=s,s.defaultEventHandler=null,s.setupEventHandler=({options:e={}})=>{const t=[].concat(e.safe?s.safeEventHandler:[],e.eventHandler?i(e.eventHandler):[],s.defaultEventHandler?s.defaultEventHandler:[]);return 0===t.length?null:t},s.handleEvent=({event:e,options:t})=>{l({event:e,handlers:t.eventHandler})};const c=new Set(["empty object","free-floating scalar","invalid @language value","invalid property","null @id value","null @value value","object with only @id","object with only @language","object with only @list","object with only @value","relative @id reference","relative @type reference","relative @vocab reference","reserved @id value","reserved @reverse value","reserved term","blank node predicate","relative graph reference","relative object reference","relative predicate reference","relative subject reference","rdfDirection not set"]);s.safeEventHandler=function({event:e,next:t}){if("warning"===e.level&&c.has(e.code))throw new r("Safe mode validation error.","jsonld.ValidationError",{event:e});t()},s.logEventHandler=function({event:e,next:t}){o.log(`EVENT: ${e.message}`,{event:e}),t()},s.logWarningEventHandler=function({event:e,next:t}){"warning"===e.level&&o.warn(`WARNING: ${e.message}`,{event:e}),t()},s.unhandledEventHandler=function({event:e}){throw new r("No handler for event.","jsonld.UnhandledEvent",{event:e})},s.setDefaultEventHandler=function({eventHandler:e}={}){s.defaultEventHandler=e?i(e):null}},2759:(e,t,n)=>{"use strict";const o=n(4093),{isArray:r,isObject:a,isEmptyObject:i,isString:s,isUndefined:l}=n(832),{isList:c,isValue:d,isGraph:u,isSubject:p}=n(8463),{expandIri:h,getContextValue:f,isKeyword:v,process:g,processingMode:y}=n(4131),{isAbsolute:m}=n(6938),{REGEX_BCP47:x,REGEX_KEYWORD:b,addValue:w,asArray:j,getValues:I,validateTypeValue:N}=n(1055),{handleEvent:S}=n(1696),O={};function E({value:e,count:t,options:n}){if(0===t||"@value"in e||"@list"in e||1===t&&"@id"in e){if(n.eventHandler){let o,r;0===t?(o="empty object",r="Dropping empty object."):"@value"in e?(o="object with only @value",r="Dropping object with only @value."):"@list"in e?(o="object with only @list",r="Dropping object with only @list."):1===t&&"@id"in e&&(o="object with only @id",r="Dropping object with only @id."),S({event:{type:["JsonLdEvent"],code:o,level:"warning",message:r,details:{value:e}},options:n})}return null}return e}async function D({activeCtx:e,activeProperty:t,expandedActiveProperty:n,element:u,expandedParent:b,options:I={},insideList:k,typeKey:R,typeScopedContext:T}){const A=Object.keys(u).sort(),_=[];let M;const J=u[R]&&"@json"===h(e,r(u[R])?u[R][0]:u[R],{vocab:!0},{...I,typeExpansion:!0});for(const D of A){let k,R=u[D];if("@context"===D)continue;const A=h(e,D,{vocab:!0},I);if(null===A||!m(A)&&!v(A)){I.eventHandler&&S({event:{type:["JsonLdEvent"],code:"invalid property",level:"warning",message:"Dropping property that did not expand into an absolute IRI or keyword.",details:{property:D,expandedProperty:A}},options:I});continue}if(v(A)){if("@reverse"===n)throw new o("Invalid JSON-LD syntax; a keyword cannot be used as a @reverse property.","jsonld.SyntaxError",{code:"invalid reverse property map",value:R});if(A in b&&"@included"!==A&&"@type"!==A)throw new o("Invalid JSON-LD syntax; colliding keywords detected.","jsonld.SyntaxError",{code:"colliding keywords",keyword:A})}if("@id"===A){if(!s(R)){if(!I.isFrame)throw new o('Invalid JSON-LD syntax; "@id" value must a string.',"jsonld.SyntaxError",{code:"invalid @id value",value:R});if(a(R)){if(!i(R))throw new o('Invalid JSON-LD syntax; "@id" value an empty object or array of strings, if framing',"jsonld.SyntaxError",{code:"invalid @id value",value:R})}else{if(!r(R))throw new o('Invalid JSON-LD syntax; "@id" value an empty object or array of strings, if framing',"jsonld.SyntaxError",{code:"invalid @id value",value:R});if(!R.every((e=>s(e))))throw new o('Invalid JSON-LD syntax; "@id" value an empty object or array of strings, if framing',"jsonld.SyntaxError",{code:"invalid @id value",value:R})}}w(b,"@id",j(R).map((t=>{if(s(t)){const n=h(e,t,{base:!0},I);return I.eventHandler&&(null===n?S(null===t?{event:{type:["JsonLdEvent"],code:"null @id value",level:"warning",message:"Null @id found.",details:{id:t}},options:I}:{event:{type:["JsonLdEvent"],code:"reserved @id value",level:"warning",message:"Reserved @id found.",details:{id:t}},options:I}):m(n)||S({event:{type:["JsonLdEvent"],code:"relative @id reference",level:"warning",message:"Relative @id reference found.",details:{id:t,expandedId:n}},options:I})),n}return t})),{propertyIsArray:I.isFrame});continue}if("@type"===A){a(R)&&(R=Object.fromEntries(Object.entries(R).map((([e,t])=>[h(T,e,{vocab:!0}),j(t).map((e=>h(T,e,{base:!0,vocab:!0},{...I,typeExpansion:!0})))])))),N(R,I.isFrame),w(b,"@type",j(R).map((e=>{if(s(e)){const t=h(T,e,{base:!0,vocab:!0},{...I,typeExpansion:!0});return"@json"===t||m(t)||I.eventHandler&&S({event:{type:["JsonLdEvent"],code:"relative @type reference",level:"warning",message:"Relative @type reference found.",details:{type:e}},options:I}),t}return e})),{propertyIsArray:!!I.isFrame});continue}if("@included"===A&&y(e,1.1)){const n=j(await O.expand({activeCtx:e,activeProperty:t,element:R,options:I}));if(!n.every((e=>p(e))))throw new o("Invalid JSON-LD syntax; values of @included must expand to node objects.","jsonld.SyntaxError",{code:"invalid @included value",value:R});w(b,"@included",n,{propertyIsArray:!0});continue}if("@graph"===A&&!a(R)&&!r(R))throw new o('Invalid JSON-LD syntax; "@graph" value must not be an object or an array.',"jsonld.SyntaxError",{code:"invalid @graph value",value:R});if("@value"===A){M=R,J&&y(e,1.1)?b["@value"]=R:w(b,"@value",R,{propertyIsArray:I.isFrame});continue}if("@language"===A){if(null===R)continue;if(!s(R)&&!I.isFrame)throw new o('Invalid JSON-LD syntax; "@language" value must be a string.',"jsonld.SyntaxError",{code:"invalid language-tagged string",value:R});R=j(R).map((e=>s(e)?e.toLowerCase():e));for(const e of R)s(e)&&!e.match(x)&&I.eventHandler&&S({event:{type:["JsonLdEvent"],code:"invalid @language value",level:"warning",message:"@language value must be valid BCP47.",details:{language:e}},options:I});w(b,"@language",R,{propertyIsArray:I.isFrame});continue}if("@direction"===A){if(!s(R)&&!I.isFrame)throw new o('Invalid JSON-LD syntax; "@direction" value must be a string.',"jsonld.SyntaxError",{code:"invalid base direction",value:R});R=j(R);for(const e of R)if(s(e)&&"ltr"!==e&&"rtl"!==e)throw new o('Invalid JSON-LD syntax; "@direction" must be "ltr" or "rtl".',"jsonld.SyntaxError",{code:"invalid base direction",value:R});w(b,"@direction",R,{propertyIsArray:I.isFrame});continue}if("@index"===A){if(!s(R))throw new o('Invalid JSON-LD syntax; "@index" value must be a string.',"jsonld.SyntaxError",{code:"invalid @index value",value:R});w(b,"@index",R);continue}if("@reverse"===A){if(!a(R))throw new o('Invalid JSON-LD syntax; "@reverse" value must be an object.',"jsonld.SyntaxError",{code:"invalid @reverse value",value:R});if(k=await O.expand({activeCtx:e,activeProperty:"@reverse",element:R,options:I}),"@reverse"in k)for(const e in k["@reverse"])w(b,e,k["@reverse"][e],{propertyIsArray:!0});let t=b["@reverse"]||null;for(const e in k){if("@reverse"===e)continue;null===t&&(t=b["@reverse"]={}),w(t,e,[],{propertyIsArray:!0});const n=k[e];for(let r=0;r"@id"===e||"@index"===e))){if(k=j(k),I.isFrame||(k=k.filter((e=>null!==E({value:e,count:Object.keys(e).length,options:I})))),0===k.length)continue;k=k.map((e=>({"@graph":j(e)})))}if(P.mappings.has(D)&&P.mappings.get(D).reverse){const e=b["@reverse"]=b["@reverse"]||{};k=j(k);for(let t=0;t"@value"===h(e,t,{vocab:!0},I))))throw new o("Invalid JSON-LD syntax; nested value must be a node object.","jsonld.SyntaxError",{code:"invalid @nest value",value:r});await D({activeCtx:e,activeProperty:t,expandedActiveProperty:n,element:r,expandedParent:b,options:I,insideList:k,typeScopedContext:T,typeKey:R})}}}function k({activeCtx:e,activeProperty:t,value:n,options:o}){if(null==n)return null;const r=h(e,t,{vocab:!0},o);if("@id"===r)return h(e,n,{base:!0},o);if("@type"===r)return h(e,n,{vocab:!0,base:!0},{...o,typeExpansion:!0});const a=f(e,t,"@type");if(("@id"===a||"@graph"===r)&&s(n)){const r=h(e,n,{base:!0},o);return null===r&&n.match(b)&&o.eventHandler&&S({event:{type:["JsonLdEvent"],code:"reserved @id value",level:"warning",message:"Reserved @id found.",details:{id:t}},options:o}),{"@id":r}}if("@vocab"===a&&s(n))return{"@id":h(e,n,{vocab:!0,base:!0},o)};if(v(r))return n;const i={};if(a&&!["@id","@vocab","@none"].includes(a))i["@type"]=a;else if(s(n)){const n=f(e,t,"@language");null!==n&&(i["@language"]=n);const o=f(e,t,"@direction");null!==o&&(i["@direction"]=o)}return["boolean","number","string"].includes(typeof n)||(n=n.toString()),i["@value"]=n,i}function C(e,t,n,a){const i=[],l=Object.keys(t).sort();for(const c of l){const l=h(e,c,{vocab:!0},a);let d=t[c];r(d)||(d=[d]);for(const e of d){if(null===e)continue;if(!s(e))throw new o("Invalid JSON-LD syntax; language map values must be strings.","jsonld.SyntaxError",{code:"invalid language map value",languageMap:t});const r={"@value":e};"@none"!==l&&(c.match(x)||a.eventHandler&&S({event:{type:["JsonLdEvent"],code:"invalid @language value",level:"warning",message:"@language value must be valid BCP47.",details:{language:c}},options:a}),r["@language"]=c.toLowerCase()),n&&(r["@direction"]=n),i.push(r)}}return i}async function L({activeCtx:e,options:t,activeProperty:n,value:a,asGraph:i,indexKey:s,propertyIndex:c}){const p=[],v=Object.keys(a).sort(),y="@type"===s;for(let m of v){if(y){const n=f(e,m,"@context");l(n)||(e=await g({activeCtx:e,localCtx:n,propagate:!1,options:t}))}let v,x=a[m];r(x)||(x=[x]),x=await O.expand({activeCtx:e,activeProperty:n,element:x,options:t,insideList:!1,insideIndex:!0}),v=c?"@none"===m?"@none":k({activeCtx:e,activeProperty:s,value:m,options:t}):h(e,m,{vocab:!0},t),"@id"===s?m=h(e,m,{base:!0},t):y&&(m=v);for(let e of x){if(i&&!u(e)&&(e={"@graph":[e]}),"@type"===s)"@none"===v||(e["@type"]?e["@type"]=[m].concat(e["@type"]):e["@type"]=[m]);else{if(d(e)&&!["@language","@type","@index"].includes(s))throw new o(`Invalid JSON-LD syntax; Attempt to add illegal key to value object: "${s}".`,"jsonld.SyntaxError",{code:"invalid value object",value:e});c?"@none"!==v&&w(e,c,v,{propertyIsArray:!0,prependValue:!0}):"@none"===v||s in e||(e[s]=m)}p.push(e)}}return p}e.exports=O,O.expand=async({activeCtx:e,activeProperty:t=null,element:n,options:c={},insideList:d=!1,insideIndex:u=!1,typeScopedContext:p=null})=>{if(null==n)return null;if("@default"===t&&(c=Object.assign({},c,{isFrame:!1})),!r(n)&&!a(n))return d||null!==t&&"@graph"!==h(e,t,{vocab:!0},c)?k({activeCtx:e,activeProperty:t,value:n,options:c}):(c.eventHandler&&S({event:{type:["JsonLdEvent"],code:"free-floating scalar",level:"warning",message:"Dropping free-floating scalar not in a list.",details:{value:n}},options:c}),null);if(r(n)){let o=[];const a=f(e,t,"@container")||[];d=d||a.includes("@list");for(let a=0;a1?o.slice().sort():o:[o];for(const t of r){const n=f(p,t,"@context");l(n)||(e=await g({activeCtx:e,localCtx:n,options:c,propagate:!1}))}}let C={};await D({activeCtx:e,activeProperty:t,expandedActiveProperty:v,element:n,expandedParent:C,options:c,insideList:d,typeKey:N,typeScopedContext:p}),b=Object.keys(C);let L=b.length;if("@value"in C){if("@type"in C&&("@language"in C||"@direction"in C))throw new o('Invalid JSON-LD syntax; an element containing "@value" may not contain both "@type" and either "@language" or "@direction".',"jsonld.SyntaxError",{code:"invalid value object",element:C});let t=L-1;if("@type"in C&&(t-=1),"@index"in C&&(t-=1),"@language"in C&&(t-=1),"@direction"in C&&(t-=1),0!==t)throw new o('Invalid JSON-LD syntax; an element containing "@value" may only have an "@index" property and either "@type" or either or both "@language" or "@direction".',"jsonld.SyntaxError",{code:"invalid value object",element:C});const n=null===C["@value"]?[]:j(C["@value"]),r=I(C,"@type");if(y(e,1.1)&&r.includes("@json")&&1===r.length);else if(0===n.length)c.eventHandler&&S({event:{type:["JsonLdEvent"],code:"null @value value",level:"warning",message:"Dropping null @value value.",details:{value:C}},options:c}),C=null;else{if(!n.every((e=>s(e)||i(e)))&&"@language"in C)throw new o("Invalid JSON-LD syntax; only strings may be language-tagged.","jsonld.SyntaxError",{code:"invalid language-tagged value",element:C});if(!r.every((e=>m(e)&&!(s(e)&&0===e.indexOf("_:"))||i(e))))throw new o('Invalid JSON-LD syntax; an element containing "@value" and "@type" must have an absolute IRI for the value of "@type".',"jsonld.SyntaxError",{code:"invalid typed value",element:C})}}else if("@type"in C&&!r(C["@type"]))C["@type"]=[C["@type"]];else if("@set"in C||"@list"in C){if(L>1&&(2!==L||!("@index"in C)))throw new o('Invalid JSON-LD syntax; if an element has the property "@set" or "@list", then it can have at most one other property that is "@index".',"jsonld.SyntaxError",{code:"invalid set or list object",element:C});"@set"in C&&(C=C["@set"],b=Object.keys(C),L=b.length)}else 1===L&&"@language"in C&&(c.eventHandler&&S({event:{type:["JsonLdEvent"],code:"object with only @language",level:"warning",message:"Dropping object with only @language.",details:{value:C}},options:c}),C=null);return!a(C)||c.keepFreeFloatingNodes||d||null!==t&&"@graph"!==v&&!(f(e,t,"@container")||[]).includes("@graph")||(C=E({value:C,count:L,options:c})),C}},1565:(e,t,n)=>{"use strict";const{isSubjectReference:o}=n(8463),{createMergedNodeMap:r}=n(2664),a={};e.exports=a,a.flatten=e=>{const t=r(e),n=[],a=Object.keys(t).sort();for(let e=0;e{"use strict";const{isKeyword:o}=n(4131),r=n(8463),a=n(832),i=n(1055),s=n(6938),l=n(4093),{createNodeMap:c,mergeNodeMapGraphs:d}=n(2664),u={};function p(e){const t={};for(const n in e)void 0!==e[n]&&(t["@"+n]=[e[n]]);return[t]}function h(e,t,n){for(let o=n.length-1;o>=0;--o){const r=n[o];if(r.graph===t&&r.subject["@id"]===e["@id"])return!0}return!1}function f(e,t,n){const o="@"+n;let r=o in e?e[o][0]:t[n];if("embed"===n)if(!0===r)r="@once";else if(!1===r)r="@never";else if("@always"!==r&&"@never"!==r&&"@link"!==r&&"@first"!==r&&"@last"!==r&&"@once"!==r)throw new l("Invalid JSON-LD syntax; invalid value of @embed.","jsonld.SyntaxError",{code:"invalid @embed value",frame:e});return r}function v(e){if(!a.isArray(e)||1!==e.length||!a.isObject(e[0]))throw new l("Invalid JSON-LD syntax; a JSON-LD frame must be a single object.","jsonld.SyntaxError",{frame:e});if("@id"in e[0])for(const t of i.asArray(e[0]["@id"]))if(!a.isObject(t)&&!s.isAbsolute(t)||a.isString(t)&&0===t.indexOf("_:"))throw new l("Invalid JSON-LD syntax; invalid @id in frame.","jsonld.SyntaxError",{code:"invalid frame",frame:e});if("@type"in e[0])for(const t of i.asArray(e[0]["@type"]))if(!a.isObject(t)&&!s.isAbsolute(t)&&"@json"!==t||a.isString(t)&&0===t.indexOf("_:"))throw new l("Invalid JSON-LD syntax; invalid @type in frame.","jsonld.SyntaxError",{code:"invalid frame",frame:e})}function g(e,t,n,s){let l=!0,c=!1;for(const d in n){let u=!1;const p=i.getValues(t,d),h=0===i.getValues(n,d).length;if("@id"===d){if(a.isEmptyObject(n["@id"][0]||{})?u=!0:n["@id"].length>=0&&(u=n["@id"].includes(p[0])),!s.requireAll)return u}else if("@type"===d){if(l=!1,h){if(p.length>0)return!1;u=!0}else if(1===n["@type"].length&&a.isEmptyObject(n["@type"][0]))u=p.length>0;else for(const e of n["@type"])u=!(!a.isObject(e)||!("@default"in e))||u||p.some((t=>t===e));if(!s.requireAll)return u}else{if(o(d))continue;{const t=i.getValues(n,d)[0];let o=!1;if(t&&(v([t]),o="@default"in t),l=!1,0===p.length&&o)continue;if(p.length>0&&h)return!1;if(void 0===t){if(p.length>0)return!1;u=!0}else if(r.isList(t)){const n=t["@list"][0];if(r.isList(p[0])){const t=p[0]["@list"];r.isValue(n)?u=t.some((e=>w(n,e))):(r.isSubject(n)||r.isSubjectReference(n))&&(u=t.some((t=>b(e,n,t,s))))}}else u=r.isValue(t)?p.some((e=>w(t,e))):r.isSubjectReference(t)?p.some((n=>b(e,t,n,s))):!!a.isObject(t)&&p.length>0}}if(!u&&s.requireAll)return!1;c=c||u}return l||c}function y(e,t){const n=e.uniqueEmbeds[e.graph],o=n[t],r=o.parent,s=o.property,l={"@id":t};if(a.isArray(r)){for(let e=0;e{const t=Object.keys(n);for(const o of t)o in n&&a.isObject(n[o].parent)&&n[o].parent["@id"]===e&&(delete n[o],c(o))};c(t)}function m(e,t){if(a.isArray(e))return e.map((e=>m(e,t)));if(a.isObject(e)){if("@preserve"in e)return e["@preserve"][0];if(r.isValue(e))return e;if(r.isList(e))return e["@list"]=m(e["@list"],t),e;if("@id"in e){const n=e["@id"];if(t.link.hasOwnProperty(n)){const o=t.link[n].indexOf(e);if(-1!==o)return t.link[n][o];t.link[n].push(e)}else t.link[n]=[e]}for(const n in e)"@id"===n&&t.bnodesToClear.includes(e[n])?delete e["@id"]:e[n]=m(e[n],t)}return e}function x(e,t,n){a.isObject(e)?i.addValue(e,t,n,{propertyIsArray:!0}):e.push(n)}function b(e,t,n,o){if(!("@id"in n))return!1;const r=e.subjects[n["@id"]];return r&&g(e,r,t,o)}function w(e,t){const n=t["@value"],o=t["@type"],r=t["@language"],i=e["@value"]?a.isArray(e["@value"])?e["@value"]:[e["@value"]]:[],s=e["@type"]?a.isArray(e["@type"])?e["@type"]:[e["@type"]]:[],l=e["@language"]?a.isArray(e["@language"])?e["@language"]:[e["@language"]]:[];return 0===i.length&&0===s.length&&0===l.length||!(!i.includes(n)&&!a.isEmptyObject(i[0]))&&!!(!o&&0===s.length||s.includes(o)||o&&a.isEmptyObject(s[0]))&&!!(!r&&0===l.length||l.includes(r)||r&&a.isEmptyObject(l[0]))}e.exports=u,u.frameMergedOrDefault=(e,t,n)=>{const o={options:n,embedded:!1,graph:"@default",graphMap:{"@default":{}},subjectStack:[],link:{},bnodeMap:{}},r=new i.IdentifierIssuer("_:b");c(e,o.graphMap,"@default",r),n.merged&&(o.graphMap["@merged"]=d(o.graphMap),o.graph="@merged"),o.subjects=o.graphMap[o.graph];const a=[];return u.frame(o,Object.keys(o.subjects).sort(),t,a),n.pruneBlankNodeIdentifiers&&(n.bnodesToClear=Object.keys(o.bnodeMap).filter((e=>1===o.bnodeMap[e].length))),n.link={},m(a,n)},u.frame=(e,t,n,s,c=null)=>{v(n),n=n[0];const d=e.options,m={embed:f(n,d,"embed"),explicit:f(n,d,"explicit"),requireAll:f(n,d,"requireAll")};e.link.hasOwnProperty(e.graph)||(e.link[e.graph]={});const b=e.link[e.graph],j=function(e,t,n,o){const r={};for(const a of t){const t=e.graphMap[e.graph][a];g(e,t,n,o)&&(r[a]=t)}return r}(e,t,n,m),I=Object.keys(j).sort();for(const v of I){const g=j[v];if(null===c?e.uniqueEmbeds={[e.graph]:{}}:e.uniqueEmbeds[e.graph]=e.uniqueEmbeds[e.graph]||{},"@link"===m.embed&&v in b){x(s,c,b[v]);continue}const I={"@id":v};if(0===v.indexOf("_:")&&i.addValue(e.bnodeMap,v,I,{propertyIsArray:!0}),b[v]=I,("@first"===m.embed||"@last"===m.embed)&&e.is11)throw new l("Invalid JSON-LD syntax; invalid value of @embed.","jsonld.SyntaxError",{code:"invalid @embed value",frame:n});if(e.embedded||!e.uniqueEmbeds[e.graph].hasOwnProperty(v))if(!e.embedded||"@never"!==m.embed&&!h(g,e.graph,e.subjectStack))if(!e.embedded||"@first"!=m.embed&&"@once"!=m.embed||!e.uniqueEmbeds[e.graph].hasOwnProperty(v)){if("@last"===m.embed&&v in e.uniqueEmbeds[e.graph]&&y(e,v),e.uniqueEmbeds[e.graph][v]={parent:s,property:c},e.subjectStack.push({subject:g,graph:e.graph}),v in e.graphMap){let t=!1,o=null;"@graph"in n?(o=n["@graph"][0],t=!("@merged"===v||"@default"===v),a.isObject(o)||(o={})):(t="@merged"!==e.graph,o={}),t&&u.frame({...e,graph:v,embedded:!1},Object.keys(e.graphMap[v]).sort(),[o],I,"@graph")}"@included"in n&&u.frame({...e,embedded:!1},t,n["@included"],I,"@included");for(const t of Object.keys(g).sort())if(o(t)){if(I[t]=i.clone(g[t]),"@type"===t)for(const t of g["@type"])0===t.indexOf("_:")&&i.addValue(e.bnodeMap,t,I,{propertyIsArray:!0})}else if(!m.explicit||t in n)for(const o of g[t]){const a=t in n?n[t]:p(m);if(r.isList(o)){const a=n[t]&&n[t][0]&&n[t][0]["@list"]?n[t][0]["@list"]:p(m),s={"@list":[]};x(I,t,s);const l=o["@list"];for(const t of l)r.isSubjectReference(t)?u.frame({...e,embedded:!0},[t["@id"]],a,s,"@list"):x(s,"@list",i.clone(t))}else r.isSubjectReference(o)?u.frame({...e,embedded:!0},[o["@id"]],a,I,t):w(a[0],o)&&x(I,t,i.clone(o))}for(const e of Object.keys(n).sort()){if("@type"===e){if(!a.isObject(n[e][0])||!("@default"in n[e][0]))continue}else if(o(e))continue;const t=n[e][0]||{};if(!f(t,d,"omitDefault")&&!(e in I)){let n="@null";"@default"in t&&(n=i.clone(t["@default"])),a.isArray(n)||(n=[n]),I[e]=[{"@preserve":n}]}}for(const t of Object.keys(n["@reverse"]||{}).sort()){const o=n["@reverse"][t];for(const n of Object.keys(e.subjects))i.getValues(e.subjects[n],t).some((e=>e["@id"]===v))&&(I["@reverse"]=I["@reverse"]||{},i.addValue(I["@reverse"],t,[],{propertyIsArray:!0}),u.frame({...e,embedded:!0},[n],o,I["@reverse"][t],c))}x(s,c,I),e.subjectStack.pop()}else x(s,c,I);else x(s,c,I)}},u.cleanupNull=(e,t)=>{if(a.isArray(e))return e.map((e=>u.cleanupNull(e,t))).filter((e=>e));if("@null"===e)return null;if(a.isObject(e)){if("@id"in e){const n=e["@id"];if(t.link.hasOwnProperty(n)){const o=t.link[n].indexOf(e);if(-1!==o)return t.link[n][o];t.link[n].push(e)}else t.link[n]=[e]}for(const n in e)e[n]=u.cleanupNull(e[n],t)}return e}},5076:(e,t,n)=>{"use strict";const o=n(4093),r=n(8463),a=n(832),{REGEX_BCP47:i,addValue:s}=n(1055),{handleEvent:l}=n(1696),{RDF_LIST:c,RDF_FIRST:d,RDF_REST:u,RDF_NIL:p,RDF_TYPE:h,RDF_JSON_LITERAL:f,XSD_BOOLEAN:v,XSD_DOUBLE:g,XSD_INTEGER:y,XSD_STRING:m}=n(3770),x={};function b(e,t,n,r){if(e.termType.endsWith("Node"))return{"@id":e.value};const s={"@value":e.value};if(e.language)e.language.match(i)||r.eventHandler&&l({event:{type:["JsonLdEvent"],code:"invalid @language value",level:"warning",message:"@language value must be valid BCP47.",details:{language:e.language}},options:r}),s["@language"]=e.language;else{let c=e.datatype.value;if(c||(c=m),c===f){c="@json";try{s["@value"]=JSON.parse(s["@value"])}catch(e){throw new o("JSON literal could not be parsed.","jsonld.InvalidJsonLiteral",{code:"invalid JSON literal",value:s["@value"],cause:e})}}if(t){if(c===v)"true"===s["@value"]?s["@value"]=!0:"false"===s["@value"]&&(s["@value"]=!1);else if(a.isNumeric(s["@value"]))if(c===y){const e=parseInt(s["@value"],10);e.toFixed(0)===s["@value"]&&(s["@value"]=e)}else c===g&&(s["@value"]=parseFloat(s["@value"]));[v,y,g,m].includes(c)||(s["@type"]=c)}else if("i18n-datatype"===n&&c.startsWith("https://www.w3.org/ns/i18n#")){const[,e,t]=c.split(/[#_]/);e.length>0&&(s["@language"]=e,e.match(i)||r.eventHandler&&l({event:{type:["JsonLdEvent"],code:"invalid @language value",level:"warning",message:"@language value must be valid BCP47.",details:{language:e}},options:r})),s["@direction"]=t}else c!==m&&(s["@type"]=c)}return s}e.exports=x,x.fromRDF=async(e,t)=>{const{useRdfType:n=!1,useNativeTypes:i=!1,rdfDirection:l=null}=t,f={},v={"@default":f},g={};if(l){if("compound-literal"===l)throw new o("Unsupported rdfDirection value.","jsonld.InvalidRdfDirection",{value:l});if("i18n-datatype"!==l)throw new o("Unknown rdfDirection value.","jsonld.InvalidRdfDirection",{value:l})}for(const o of e){const e="DefaultGraph"===o.graph.termType?"@default":o.graph.value;e in v||(v[e]={}),"@default"===e||e in f||(f[e]={"@id":e});const r=v[e],a=o.subject.value,c=o.predicate.value,d=o.object;a in r||(r[a]={"@id":a});const u=r[a],y=d.termType.endsWith("Node");if(y&&!(d.value in r)&&(r[d.value]={"@id":d.value}),c===h&&!n&&y){s(u,"@type",d.value,{propertyIsArray:!0});continue}const m=b(d,i,l,t);if(s(u,c,m,{propertyIsArray:!0}),y)if(d.value===p){const e=r[d.value];"usages"in e||(e.usages=[]),e.usages.push({node:u,property:c,value:m})}else d.value in g?g[d.value]=!1:g[d.value]={node:u,property:c,value:m}}for(const e in v){const t=v[e];if(!(p in t))continue;const n=t[p];if(n.usages){for(let e of n.usages){let n=e.node,o=e.property,i=e.value;const s=[],l=[];let p=Object.keys(n).length;for(;o===u&&a.isObject(g[n["@id"]])&&a.isArray(n[d])&&1===n[d].length&&a.isArray(n[u])&&1===n[u].length&&(3===p||4===p&&a.isArray(n["@type"])&&1===n["@type"].length&&n["@type"][0]===c)&&(s.push(n[d][0]),l.push(n["@id"]),e=g[n["@id"]],n=e.node,o=e.property,i=e.value,p=Object.keys(n).length,r.isBlankNode(n)););delete i["@id"],i["@list"]=s.reverse();for(const e of l)delete t[e]}delete n.usages}}const y=[],m=Object.keys(f).sort();for(const e of m){const t=f[e];if(e in v){const n=t["@graph"]=[],o=v[e],a=Object.keys(o).sort();for(const e of a){const t=o[e];r.isSubjectReference(t)||n.push(t)}}r.isSubjectReference(t)||y.push(t)}return y}},8463:(e,t,n)=>{"use strict";const o=n(832),r={};e.exports=r,r.isSubject=e=>!(!o.isObject(e)||"@value"in e||"@set"in e||"@list"in e)&&(Object.keys(e).length>1||!("@id"in e)),r.isSubjectReference=e=>o.isObject(e)&&1===Object.keys(e).length&&"@id"in e,r.isValue=e=>o.isObject(e)&&"@value"in e,r.isList=e=>o.isObject(e)&&"@list"in e,r.isGraph=e=>o.isObject(e)&&"@graph"in e&&1===Object.keys(e).filter((e=>"@id"!==e&&"@index"!==e)).length,r.isSimpleGraph=e=>r.isGraph(e)&&!("@id"in e),r.isBlankNode=e=>{if(o.isObject(e)){if("@id"in e){const t=e["@id"];return!o.isString(t)||0===t.indexOf("_:")}return 0===Object.keys(e).length||!("@value"in e||"@set"in e||"@list"in e)}return!1}},6805:(e,t,n)=>{const o=n(7055),r=n(7222),a=n(1055),i=n(8058),s=a.IdentifierIssuer,l=n(4093),c=n(9593),d=n(9048),{expand:u}=n(2759),{flatten:p}=n(1565),{fromRDF:h}=n(5076),{toRDF:f}=n(9382),{frameMergedOrDefault:v,cleanupNull:g}=n(3859),{isArray:y,isObject:m,isString:x}=n(832),{isSubjectReference:b}=n(8463),{expandIri:w,getInitialContext:j,process:I,processingMode:N}=n(4131),{compact:S,compactIri:O}=n(3251),{createNodeMap:E,createMergedNodeMap:D,mergeNodeMaps:k}=n(2664),{logEventHandler:C,logWarningEventHandler:L,safeEventHandler:R,setDefaultEventHandler:T,setupEventHandler:A,strictEventHandler:_,unhandledEventHandler:M}=n(1696),J=function(e){const t={},J=new c({max:100});function P(t,{documentLoader:n=e.documentLoader,...o}){if(t&&"compactionMap"in t)throw new l('"compactionMap" not supported.',"jsonld.OptionsError");if(t&&"expansionMap"in t)throw new l('"expansionMap" not supported.',"jsonld.OptionsError");return Object.assign({},{documentLoader:n},o,t,{eventHandler:A({options:t})})}return e.compact=async function(t,n,o){if(arguments.length<2)throw new TypeError("Could not compact, too few arguments.");if(null===n)throw new l("The compaction context must not be null.","jsonld.CompactError",{code:"invalid local context"});if(null===t)return null;let r;(o=P(o,{base:x(t)?t:"",compactArrays:!0,compactToRelative:!0,graph:!1,skipExpansion:!1,link:!1,issuer:new s("_:b"),contextResolver:new i({sharedCache:J})})).link&&(o.skipExpansion=!0),o.compactToRelative||delete o.base,r=o.skipExpansion?t:await e.expand(t,o);const c=await e.processContext(j(o),n,o);let d=await S({activeCtx:c,element:r,options:o});o.compactArrays&&!o.graph&&y(d)?1===d.length?d=d[0]:0===d.length&&(d={}):o.graph&&m(d)&&(d=[d]),m(n)&&"@context"in n&&(n=n["@context"]),n=a.clone(n),y(n)||(n=[n]);const u=n;n=[];for(let e=0;e0)&&n.push(u[e]);const p=n.length>0;if(1===n.length&&(n=n[0]),y(d)){const e=O({activeCtx:c,iri:"@graph",relativeTo:{vocab:!0}}),t=d;d={},p&&(d["@context"]=n),d[e]=t}else if(m(d)&&p){const e=d;d={"@context":n};for(const t in e)d[t]=e[t]}return d},e.expand=async function(t,n){if(arguments.length<1)throw new TypeError("Could not expand, too few arguments.");const o={},r=[];if("expandContext"in(n=P(n,{keepFreeFloatingNodes:!1,contextResolver:new i({sharedCache:J})}))){const e=a.clone(n.expandContext);m(e)&&"@context"in e?o.expandContext=e:o.expandContext={"@context":e},r.push(o.expandContext)}let s;if(x(t)){const a=await e.get(t,n);s=a.documentUrl,o.input=a.document,a.contextUrl&&(o.remoteContext={"@context":a.contextUrl},r.push(o.remoteContext))}else o.input=a.clone(t);"base"in n||(n.base=s||"");let l=j(n);for(const e of r)l=await I({activeCtx:l,localCtx:e,options:n});let c=await u({activeCtx:l,element:o.input,options:n});return m(c)&&"@graph"in c&&1===Object.keys(c).length?c=c["@graph"]:null===c&&(c=[]),y(c)||(c=[c]),c},e.flatten=async function(t,n,o){if(arguments.length<1)return new TypeError("Could not flatten, too few arguments.");n="function"==typeof n?null:n||null,o=P(o,{base:x(t)?t:"",contextResolver:new i({sharedCache:J})});const r=await e.expand(t,o),a=p(r);return null===n?a:(o.graph=!0,o.skipExpansion=!0,await e.compact(a,n,o))},e.frame=async function(t,n,o){if(arguments.length<2)throw new TypeError("Could not frame, too few arguments.");if(o=P(o,{base:x(t)?t:"",embed:"@once",explicit:!1,requireAll:!1,omitDefault:!1,bnodesToClear:[],contextResolver:new i({sharedCache:J})}),x(n)){const t=await e.get(n,o);if(n=t.document,t.contextUrl){let e=n["@context"];e?y(e)?e.push(t.contextUrl):e=[e,t.contextUrl]:e=t.contextUrl,n["@context"]=e}}const r=n&&n["@context"]||{},a=await e.processContext(j(o),r,o);o.hasOwnProperty("omitGraph")||(o.omitGraph=N(a,1.1)),o.hasOwnProperty("pruneBlankNodeIdentifiers")||(o.pruneBlankNodeIdentifiers=N(a,1.1));const s=await e.expand(t,o),l={...o};l.isFrame=!0,l.keepFreeFloatingNodes=!0;const c=await e.expand(n,l),d=Object.keys(n).map((e=>w(a,e,{vocab:!0})));l.merged=!d.includes("@graph"),l.is11=N(a,1.1);const u=v(s,c,l);l.graph=!o.omitGraph,l.skipExpansion=!0,l.link={},l.framing=!0;let p=await e.compact(u,r,l);return l.link={},p=g(p,l),p},e.link=async function(t,n,o){const r={};return n&&(r["@context"]=n),r["@embed"]="@link",e.frame(t,r,o)},e.normalize=e.canonize=async function(t,n){if(arguments.length<1)throw new TypeError("Could not canonize, too few arguments.");if("inputFormat"in(n=P(n,{base:x(t)?t:null,algorithm:"URDNA2015",skipExpansion:!1,safe:!0,contextResolver:new i({sharedCache:J})}))){if("application/n-quads"!==n.inputFormat&&"application/nquads"!==n.inputFormat)throw new l("Unknown canonicalization input format.","jsonld.CanonizeError");const e=d.parse(t);return o.canonize(e,n)}const r={...n};delete r.format,r.produceGeneralizedRdf=!1;const a=await e.toRDF(t,r);return o.canonize(a,n)},e.fromRDF=async function(e,n){if(arguments.length<1)throw new TypeError("Could not convert from RDF, too few arguments.");n=P(n,{format:x(e)?"application/n-quads":void 0});const{format:o}=n;let{rdfParser:r}=n;if(o){if(r=r||t[o],!r)throw new l("Unknown input format.","jsonld.UnknownFormat",{format:o})}else r=()=>e;const a=await r(e);return h(a,n)},e.toRDF=async function(t,n){if(arguments.length<1)throw new TypeError("Could not convert to RDF, too few arguments.");let o;o=(n=P(n,{base:x(t)?t:"",skipExpansion:!1,contextResolver:new i({sharedCache:J})})).skipExpansion?t:await e.expand(t,n);const r=f(o,n);if(n.format){if("application/n-quads"===n.format||"application/nquads"===n.format)return d.serialize(r);throw new l("Unknown output format.","jsonld.UnknownFormat",{format:n.format})}return r},e.createNodeMap=async function(t,n){if(arguments.length<1)throw new TypeError("Could not create node map, too few arguments.");n=P(n,{base:x(t)?t:"",contextResolver:new i({sharedCache:J})});const o=await e.expand(t,n);return D(o,n)},e.merge=async function(t,n,o){if(arguments.length<1)throw new TypeError("Could not merge, too few arguments.");if(!y(t))throw new TypeError('Could not merge, "docs" must be an array.');n="function"==typeof n?null:n||null,o=P(o,{contextResolver:new i({sharedCache:J})});const r=await Promise.all(t.map((t=>{const n={...o};return e.expand(t,n)})));let l=!0;"mergeNodes"in o&&(l=o.mergeNodes);const c=o.issuer||new s("_:b"),d={"@default":{}};for(let e=0;ee._documentLoader,set:t=>e._documentLoader=t}),e.documentLoader=async e=>{throw new l("Could not retrieve a JSON-LD document from the URL. URL dereferencing not implemented.","jsonld.LoadDocumentError",{code:"loading document failed",url:e})},e.get=async function(t,n){let o;o="function"==typeof n.documentLoader?n.documentLoader:e.documentLoader;const r=await o(t);try{if(!r.document)throw new l("No remote document found at the given URL.","jsonld.NullRemoteDocument");x(r.document)&&(r.document=JSON.parse(r.document))}catch(e){throw new l("Could not retrieve a JSON-LD document from the URL.","jsonld.LoadDocumentError",{code:"loading document failed",cause:e,remoteDoc:r})}return r},e.processContext=async function(e,t,n){return n=P(n,{base:"",contextResolver:new i({sharedCache:J})}),null===t?j(n):(t=a.clone(t),m(t)&&"@context"in t||(t={"@context":t}),I({activeCtx:e,localCtx:t,options:n}))},e.getContextValue=n(4131).getContextValue,e.documentLoaders={},e.useDocumentLoader=function(t){if(!(t in e.documentLoaders))throw new l('Unknown document loader type: "'+t+'"',"jsonld.UnknownDocumentLoader",{type:t});e.documentLoader=e.documentLoaders[t].apply(e,Array.prototype.slice.call(arguments,1))},e.registerRDFParser=function(e,n){t[e]=n},e.unregisterRDFParser=function(e){delete t[e]},e.registerRDFParser("application/n-quads",d.parse),e.registerRDFParser("application/nquads",d.parse),e.url=n(6938),e.logEventHandler=C,e.logWarningEventHandler=L,e.safeEventHandler=R,e.setDefaultEventHandler=T,e.strictEventHandler=_,e.unhandledEventHandler=M,e.util=a,Object.assign(e,a),e.promises=e,e.RequestQueue=n(533),e.JsonLdProcessor=n(731)(e),r.setupGlobals(e),r.setupDocumentLoaders(e),e},P=function(){return J((function(){return P()}))};J(P),e.exports=P},2664:(e,t,n)=>{"use strict";const{isKeyword:o}=n(4131),r=n(8463),a=n(832),i=n(1055),s=n(4093),l={};e.exports=l,l.createMergedNodeMap=(e,t)=>{const n=(t=t||{}).issuer||new i.IdentifierIssuer("_:b"),o={"@default":{}};return l.createNodeMap(e,o,"@default",n),l.mergeNodeMaps(o)},l.createNodeMap=(e,t,n,c,d,u)=>{if(a.isArray(e)){for(const o of e)l.createNodeMap(o,t,n,c,void 0,u);return}if(!a.isObject(e))return void(u&&u.push(e));if(r.isValue(e)){if("@type"in e){let t=e["@type"];0===t.indexOf("_:")&&(e["@type"]=t=c.getId(t))}return void(u&&u.push(e))}if(u&&r.isList(e)){const o=[];return l.createNodeMap(e["@list"],t,n,c,d,o),void u.push({"@list":o})}if("@type"in e){const t=e["@type"];for(const e of t)0===e.indexOf("_:")&&c.getId(e)}a.isUndefined(d)&&(d=r.isBlankNode(e)?c.getId(e["@id"]):e["@id"]),u&&u.push({"@id":d});const p=t[n],h=p[d]=p[d]||{};h["@id"]=d;const f=Object.keys(e).sort();for(let a of f){if("@id"===a)continue;if("@reverse"===a){const o={"@id":d},a=e["@reverse"];for(const e in a){const s=a[e];for(const a of s){let s=a["@id"];r.isBlankNode(a)&&(s=c.getId(s)),l.createNodeMap(a,t,n,c,s),i.addValue(p[s],e,o,{propertyIsArray:!0,allowDuplicate:!1})}}continue}if("@graph"===a){d in t||(t[d]={}),l.createNodeMap(e[a],t,d,c);continue}if("@included"===a){l.createNodeMap(e[a],t,n,c);continue}if("@type"!==a&&o(a)){if("@index"===a&&a in h&&(e[a]!==h[a]||e[a]["@id"]!==h[a]["@id"]))throw new s("Invalid JSON-LD syntax; conflicting @index property detected.","jsonld.SyntaxError",{code:"conflicting indexes",subject:h});h[a]=e[a];continue}const u=e[a];if(0===a.indexOf("_:")&&(a=c.getId(a)),0!==u.length)for(let e of u)if("@type"===a&&(e=0===e.indexOf("_:")?c.getId(e):e),r.isSubject(e)||r.isSubjectReference(e)){if("@id"in e&&!e["@id"])continue;const o=r.isBlankNode(e)?c.getId(e["@id"]):e["@id"];i.addValue(h,a,{"@id":o},{propertyIsArray:!0,allowDuplicate:!1}),l.createNodeMap(e,t,n,c,o)}else if(r.isValue(e))i.addValue(h,a,e,{propertyIsArray:!0,allowDuplicate:!1});else if(r.isList(e)){const o=[];l.createNodeMap(e["@list"],t,n,c,d,o),e={"@list":o},i.addValue(h,a,e,{propertyIsArray:!0,allowDuplicate:!1})}else l.createNodeMap(e,t,n,c,d),i.addValue(h,a,e,{propertyIsArray:!0,allowDuplicate:!1});else i.addValue(h,a,[],{propertyIsArray:!0})}},l.mergeNodeMapGraphs=e=>{const t={};for(const n of Object.keys(e).sort())for(const r of Object.keys(e[n]).sort()){const a=e[n][r];r in t||(t[r]={"@id":r});const s=t[r];for(const e of Object.keys(a).sort())if(o(e)&&"@type"!==e)s[e]=i.clone(a[e]);else for(const t of a[e])i.addValue(s,e,i.clone(t),{propertyIsArray:!0,allowDuplicate:!1})}return t},l.mergeNodeMaps=e=>{const t=e["@default"],n=Object.keys(e).sort();for(const o of n){if("@default"===o)continue;const n=e[o];let a=t[o];a?"@graph"in a||(a["@graph"]=[]):t[o]=a={"@id":o,"@graph":[]};const i=a["@graph"];for(const e of Object.keys(n).sort()){const t=n[e];r.isSubjectReference(t)||i.push(t)}}return t}},7222:(e,t,n)=>{"use strict";const o=n(8831),r={};e.exports=r,r.setupDocumentLoaders=function(e){"undefined"!=typeof XMLHttpRequest&&(e.documentLoaders.xhr=o,e.useDocumentLoader("xhr"))},r.setupGlobals=function(e){void 0===globalThis.JsonLdProcessor&&Object.defineProperty(globalThis,"JsonLdProcessor",{writable:!0,enumerable:!1,configurable:!0,value:e.JsonLdProcessor})}},9382:(e,t,n)=>{"use strict";const{createNodeMap:o}=n(2664),{isKeyword:r}=n(4131),a=n(8463),i=n(5456),s=n(4093),l=n(832),c=n(1055),{handleEvent:d}=n(1696),{RDF_FIRST:u,RDF_REST:p,RDF_NIL:h,RDF_TYPE:f,RDF_JSON_LITERAL:v,RDF_LANGSTRING:g,XSD_BOOLEAN:y,XSD_DOUBLE:m,XSD_INTEGER:x,XSD_STRING:b}=n(3770),{isAbsolute:w}=n(6938),j={};function I(e,t,n,o,a){const i=Object.keys(t).sort();for(const s of i){const i=t[s],l=Object.keys(i).sort();for(let t of l){const l=i[t];if("@type"===t)t=f;else if(r(t))continue;for(const r of l){const i={termType:s.startsWith("_:")?"BlankNode":"NamedNode",value:s};if(!w(s)){a.eventHandler&&d({event:{type:["JsonLdEvent"],code:"relative subject reference",level:"warning",message:"Relative subject reference found.",details:{subject:s}},options:a});continue}const l={termType:t.startsWith("_:")?"BlankNode":"NamedNode",value:t};if(!w(t)){a.eventHandler&&d({event:{type:["JsonLdEvent"],code:"relative predicate reference",level:"warning",message:"Relative predicate reference found.",details:{predicate:t}},options:a});continue}if("BlankNode"===l.termType&&!a.produceGeneralizedRdf){a.eventHandler&&d({event:{type:["JsonLdEvent"],code:"blank node predicate",level:"warning",message:"Dropping blank node predicate.",details:{property:o.getOldIds().find((e=>o.getId(e)===t))}},options:a});continue}const c=N(r,o,e,n,a.rdfDirection,a);c&&e.push({subject:i,predicate:l,object:c,graph:n})}}}}function N(e,t,n,o,r,c){const f={};if(a.isValue(e)){f.termType="Literal",f.value=void 0,f.datatype={termType:"NamedNode"};let t=e["@value"];const n=e["@type"]||null;if("@json"===n)f.value=i(t),f.datatype.value=v;else if(l.isBoolean(t))f.value=t.toString(),f.datatype.value=n||y;else if(l.isDouble(t)||n===m)l.isDouble(t)||(t=parseFloat(t)),f.value=t.toExponential(15).replace(/(\d)0*e\+?/,"$1E"),f.datatype.value=n||m;else if(l.isNumber(t))f.value=t.toFixed(0),f.datatype.value=n||x;else if("@direction"in e&&"i18n-datatype"===r){const n=`https://www.w3.org/ns/i18n#${(e["@language"]||"").toLowerCase()}_${e["@direction"]}`;f.datatype.value=n,f.value=t}else{if("@direction"in e&&"compound-literal"===r)throw new s("Unsupported rdfDirection value.","jsonld.InvalidRdfDirection",{value:r});if("@direction"in e&&r)throw new s("Unknown rdfDirection value.","jsonld.InvalidRdfDirection",{value:r});"@language"in e?("@direction"in e&&!r&&c.eventHandler&&d({event:{type:["JsonLdEvent"],code:"rdfDirection not set",level:"warning",message:"rdfDirection not set for @direction.",details:{object:f.value}},options:c}),f.value=t,f.datatype.value=n||g,f.language=e["@language"]):("@direction"in e&&!r&&c.eventHandler&&d({event:{type:["JsonLdEvent"],code:"rdfDirection not set",level:"warning",message:"rdfDirection not set for @direction.",details:{object:f.value}},options:c}),f.value=t,f.datatype.value=n||b)}}else if(a.isList(e)){const a=function(e,t,n,o,r,a){const i={termType:"NamedNode",value:u},s={termType:"NamedNode",value:p},l={termType:"NamedNode",value:h},c=e.pop(),d=c?{termType:"BlankNode",value:t.getId()}:l;let f=d;for(const l of e){const e=N(l,t,n,o,r,a),c={termType:"BlankNode",value:t.getId()};n.push({subject:f,predicate:i,object:e,graph:o}),n.push({subject:f,predicate:s,object:c,graph:o}),f=c}if(c){const e=N(c,t,n,o,r,a);n.push({subject:f,predicate:i,object:e,graph:o}),n.push({subject:f,predicate:s,object:l,graph:o})}return d}(e["@list"],t,n,o,r,c);f.termType=a.termType,f.value=a.value}else{const t=l.isObject(e)?e["@id"]:e;f.termType=t.startsWith("_:")?"BlankNode":"NamedNode",f.value=t}return"NamedNode"!==f.termType||w(f.value)?f:(c.eventHandler&&d({event:{type:["JsonLdEvent"],code:"relative object reference",level:"warning",message:"Relative object reference found.",details:{object:f.value}},options:c}),null)}e.exports=j,j.toRDF=(e,t)=>{const n=new c.IdentifierIssuer("_:b"),r={"@default":{}};o(e,r,"@default",n);const a=[],i=Object.keys(r).sort();for(const e of i){let o;if("@default"===e)o={termType:"DefaultGraph",value:""};else{if(!w(e)){t.eventHandler&&d({event:{type:["JsonLdEvent"],code:"relative graph reference",level:"warning",message:"Relative graph reference found.",details:{graph:e}},options:t});continue}o=e.startsWith("_:")?{termType:"BlankNode"}:{termType:"NamedNode"},o.value=e}I(a,r[e],o,n,t)}return a}},832:e=>{"use strict";const t={};e.exports=t,t.isArray=Array.isArray,t.isBoolean=e=>"boolean"==typeof e||"[object Boolean]"===Object.prototype.toString.call(e),t.isDouble=e=>t.isNumber(e)&&(-1!==String(e).indexOf(".")||Math.abs(e)>=1e21),t.isEmptyObject=e=>t.isObject(e)&&0===Object.keys(e).length,t.isNumber=e=>"number"==typeof e||"[object Number]"===Object.prototype.toString.call(e),t.isNumeric=e=>!isNaN(parseFloat(e))&&isFinite(e),t.isObject=e=>"[object Object]"===Object.prototype.toString.call(e),t.isString=e=>"string"==typeof e||"[object String]"===Object.prototype.toString.call(e),t.isUndefined=e=>void 0===e},6938:(e,t,n)=>{"use strict";const o=n(832),r={};e.exports=r,r.parsers={simple:{keys:["href","scheme","authority","path","query","fragment"],regex:/^(?:([^:\/?#]+):)?(?:\/\/([^\/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?/},full:{keys:["href","protocol","scheme","authority","auth","user","password","hostname","port","path","directory","file","query","fragment"],regex:/^(([a-zA-Z][a-zA-Z0-9+-.]*):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?(?:(((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/}},r.parse=(e,t)=>{const n={},o=r.parsers[t||"full"],a=o.regex.exec(e);let i=o.keys.length;for(;i--;)n[o.keys[i]]=void 0===a[i]?null:a[i];return("https"===n.scheme&&"443"===n.port||"http"===n.scheme&&"80"===n.port)&&(n.href=n.href.replace(":"+n.port,""),n.authority=n.authority.replace(":"+n.port,""),n.port=null),n.normalizedPath=r.removeDotSegments(n.path),n},r.prependBase=(e,t)=>{if(null===e)return t;if(r.isAbsolute(t))return t;e&&!o.isString(e)||(e=r.parse(e||""));const n=r.parse(t),a={protocol:e.protocol||""};if(null!==n.authority)a.authority=n.authority,a.path=n.path,a.query=n.query;else if(a.authority=e.authority,""===n.path)a.path=e.path,null!==n.query?a.query=n.query:a.query=e.query;else{if(0===n.path.indexOf("/"))a.path=n.path;else{let t=e.path;t=t.substr(0,t.lastIndexOf("/")+1),(t.length>0||e.authority)&&"/"!==t.substr(-1)&&(t+="/"),t+=n.path,a.path=t}a.query=n.query}""!==n.path&&(a.path=r.removeDotSegments(a.path));let i=a.protocol;return null!==a.authority&&(i+="//"+a.authority),i+=a.path,null!==a.query&&(i+="?"+a.query),null!==n.fragment&&(i+="#"+n.fragment),""===i&&(i="./"),i},r.removeBase=(e,t)=>{if(null===e)return t;e&&!o.isString(e)||(e=r.parse(e||""));let n="";if(""!==e.href?n+=(e.protocol||"")+"//"+(e.authority||""):t.indexOf("//")&&(n+="//"),0!==t.indexOf(n))return t;const a=r.parse(t.substr(n.length)),i=e.normalizedPath.split("/"),s=a.normalizedPath.split("/"),l=a.fragment||a.query?0:1;for(;i.length>0&&s.length>l&&i[0]===s[0];)i.shift(),s.shift();let c="";if(i.length>0){i.pop();for(let e=0;e{if(0===e.length)return"";const t=e.split("/"),n=[];for(;t.length>0;){const e=t.shift(),o=0===t.length;"."!==e?".."!==e?n.push(e):(n.pop(),o&&n.push("")):o&&n.push("")}return"/"===e[0]&&n.length>0&&""!==n[0]&&n.unshift(""),1===n.length&&""===n[0]?"/":n.join("/")};const a=/^([A-Za-z][A-Za-z0-9+-.]*|_):[^\s]*$/;r.isAbsolute=e=>o.isString(e)&&a.test(e),r.isRelative=e=>o.isString(e)},1055:(e,t,n)=>{"use strict";const o=n(8463),r=n(832),a=n(7055).IdentifierIssuer,i=n(4093),s=/(?:<[^>]*?>|"[^"]*?"|[^,])+/g,l=/\s*<([^>]*?)>\s*(?:;\s*(.*))?/,c=/(.*?)=(?:(?:"([^"]*?)")|([^"]*?))\s*(?:(?:;\s*)|$)/g,d="application/ld+json, application/json",u={};function p(e,t){if(r.isArray(t))for(let n=0;n{if(Object.keys(e).some((e=>"accept"===e.toLowerCase())))throw new RangeError('Accept header may not be specified; only "'+d+'" is supported.');return Object.assign({Accept:d},e)},u.parseLinkHeader=e=>{const t={},n=e.match(s);for(let e=0;e{if(!(r.isString(e)||r.isArray(e)&&e.every((e=>r.isString(e))))){if(t&&r.isObject(e))switch(Object.keys(e).length){case 0:return;case 1:if("@default"in e&&u.asArray(e["@default"]).every((e=>r.isString(e))))return}throw new i('Invalid JSON-LD syntax; "@type" value must a string, an array of strings, an empty object, or a default object.',"jsonld.SyntaxError",{code:"invalid type value",value:e})}},u.hasProperty=(e,t)=>{if(e.hasOwnProperty(t)){const n=e[t];return!r.isArray(n)||n.length>0}return!1},u.hasValue=(e,t,n)=>{if(u.hasProperty(e,t)){let a=e[t];const i=o.isList(a);if(r.isArray(a)||i){i&&(a=a["@list"]);for(let e=0;e{if("propertyIsArray"in(o=o||{})||(o.propertyIsArray=!1),"valueIsArray"in o||(o.valueIsArray=!1),"allowDuplicate"in o||(o.allowDuplicate=!0),"prependValue"in o||(o.prependValue=!1),o.valueIsArray)e[t]=n;else if(r.isArray(n)){0===n.length&&o.propertyIsArray&&!e.hasOwnProperty(t)&&(e[t]=[]),o.prependValue&&(n=n.concat(e[t]),e[t]=[]);for(let r=0;r[].concat(e[t]||[]),u.removeProperty=(e,t)=>{delete e[t]},u.removeValue=(e,t,n,o)=>{"propertyIsArray"in(o=o||{})||(o.propertyIsArray=!1);const r=u.getValues(e,t).filter((e=>!u.compareValues(e,n)));0===r.length?u.removeProperty(e,t):1!==r.length||o.propertyIsArray?e[t]=r:e[t]=r[0]},u.relabelBlankNodes=(e,t)=>p((t=t||{}).issuer||new a("_:b"),e),u.compareValues=(e,t)=>e===t||!(!o.isValue(e)||!o.isValue(t)||e["@value"]!==t["@value"]||e["@type"]!==t["@type"]||e["@language"]!==t["@language"]||e["@index"]!==t["@index"])||!!(r.isObject(e)&&"@id"in e&&r.isObject(t)&&"@id"in t)&&e["@id"]===t["@id"],u.compareShortestLeast=(e,t)=>e.length{"use strict";const o=n(4411),r=Symbol("max"),a=Symbol("length"),i=Symbol("lengthCalculator"),s=Symbol("allowStale"),l=Symbol("maxAge"),c=Symbol("dispose"),d=Symbol("noDisposeOnSet"),u=Symbol("lruList"),p=Symbol("cache"),h=Symbol("updateAgeOnGet"),f=()=>1,v=(e,t,n)=>{const o=e[p].get(t);if(o){const t=o.value;if(g(e,t)){if(m(e,o),!e[s])return}else n&&(e[h]&&(o.value.now=Date.now()),e[u].unshiftNode(o));return t.value}},g=(e,t)=>{if(!t||!t.maxAge&&!e[l])return!1;const n=Date.now()-t.now;return t.maxAge?n>t.maxAge:e[l]&&n>e[l]},y=e=>{if(e[a]>e[r])for(let t=e[u].tail;e[a]>e[r]&&null!==t;){const n=t.prev;m(e,t),t=n}},m=(e,t)=>{if(t){const n=t.value;e[c]&&e[c](n.key,n.value),e[a]-=n.length,e[p].delete(n.key),e[u].removeNode(t)}};class x{constructor(e,t,n,o,r){this.key=e,this.value=t,this.length=n,this.now=o,this.maxAge=r||0}}const b=(e,t,n,o)=>{let r=n.value;g(e,r)&&(m(e,n),e[s]||(r=void 0)),r&&t.call(o,r.value,r.key,e)};e.exports=class{constructor(e){if("number"==typeof e&&(e={max:e}),e||(e={}),e.max&&("number"!=typeof e.max||e.max<0))throw new TypeError("max must be a non-negative number");this[r]=e.max||1/0;const t=e.length||f;if(this[i]="function"!=typeof t?f:t,this[s]=e.stale||!1,e.maxAge&&"number"!=typeof e.maxAge)throw new TypeError("maxAge must be a number");this[l]=e.maxAge||0,this[c]=e.dispose,this[d]=e.noDisposeOnSet||!1,this[h]=e.updateAgeOnGet||!1,this.reset()}set max(e){if("number"!=typeof e||e<0)throw new TypeError("max must be a non-negative number");this[r]=e||1/0,y(this)}get max(){return this[r]}set allowStale(e){this[s]=!!e}get allowStale(){return this[s]}set maxAge(e){if("number"!=typeof e)throw new TypeError("maxAge must be a non-negative number");this[l]=e,y(this)}get maxAge(){return this[l]}set lengthCalculator(e){"function"!=typeof e&&(e=f),e!==this[i]&&(this[i]=e,this[a]=0,this[u].forEach((e=>{e.length=this[i](e.value,e.key),this[a]+=e.length}))),y(this)}get lengthCalculator(){return this[i]}get length(){return this[a]}get itemCount(){return this[u].length}rforEach(e,t){t=t||this;for(let n=this[u].tail;null!==n;){const o=n.prev;b(this,e,n,t),n=o}}forEach(e,t){t=t||this;for(let n=this[u].head;null!==n;){const o=n.next;b(this,e,n,t),n=o}}keys(){return this[u].toArray().map((e=>e.key))}values(){return this[u].toArray().map((e=>e.value))}reset(){this[c]&&this[u]&&this[u].length&&this[u].forEach((e=>this[c](e.key,e.value))),this[p]=new Map,this[u]=new o,this[a]=0}dump(){return this[u].map((e=>!g(this,e)&&{k:e.key,v:e.value,e:e.now+(e.maxAge||0)})).toArray().filter((e=>e))}dumpLru(){return this[u]}set(e,t,n){if((n=n||this[l])&&"number"!=typeof n)throw new TypeError("maxAge must be a number");const o=n?Date.now():0,s=this[i](t,e);if(this[p].has(e)){if(s>this[r])return m(this,this[p].get(e)),!1;const i=this[p].get(e).value;return this[c]&&(this[d]||this[c](e,i.value)),i.now=o,i.maxAge=n,i.value=t,this[a]+=s-i.length,i.length=s,this.get(e),y(this),!0}const h=new x(e,t,s,o,n);return h.length>this[r]?(this[c]&&this[c](e,t),!1):(this[a]+=h.length,this[u].unshift(h),this[p].set(e,this[u].head),y(this),!0)}has(e){if(!this[p].has(e))return!1;const t=this[p].get(e).value;return!g(this,t)}get(e){return v(this,e,!0)}peek(e){return v(this,e,!1)}pop(){const e=this[u].tail;return e?(m(this,e),e.value):null}del(e){m(this,this[p].get(e))}load(e){this.reset();const t=Date.now();for(let n=e.length-1;n>=0;n--){const o=e[n],r=o.e||0;if(0===r)this.set(o.k,o.v);else{const e=r-t;e>0&&this.set(o.k,o.v,e)}}}prune(){this[p].forEach(((e,t)=>v(this,t,!1)))}}},7055:(e,t,n)=>{e.exports=n(9344)},2401:e=>{"use strict";e.exports=class e{constructor(e,t=new Map,n=0){this.prefix=e,this._existing=t,this.counter=n}clone(){const{prefix:t,_existing:n,counter:o}=this;return new e(t,new Map(n),o)}getId(e){const t=e&&this._existing.get(e);if(t)return t;const n=this.prefix+this.counter;return this.counter++,e&&this._existing.set(e,n),n}hasId(e){return this._existing.has(e)}getOldIds(){return[...this._existing.keys()]}}},5947:(e,t,n)=>{"use strict";n(4889);const o=self.crypto||self.msCrypto;e.exports=class{constructor(e){if(!o||!o.subtle)throw new Error("crypto.subtle not found.");if("sha256"===e)this.algorithm={name:"SHA-256"};else{if("sha1"!==e)throw new Error(`Unsupported algorithm "${e}".`);this.algorithm={name:"SHA-1"}}this._content=""}update(e){this._content+=e}async digest(){const e=(new TextEncoder).encode(this._content),t=new Uint8Array(await o.subtle.digest(this.algorithm,e));let n="";for(let e=0;e{"use strict";const t="http://www.w3.org/1999/02/22-rdf-syntax-ns#langString",n="http://www.w3.org/2001/XMLSchema#string",o="NamedNode",r="BlankNode",a="Literal",i="DefaultGraph",s={};(()=>{const e="(?:<([^:]+:[^>]*)>)",t="A-Za-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�_",n=t+"0-9-·̀-ͯ‿-⁀",o="(_:(?:["+t+"0-9])(?:(?:["+n+".])*(?:["+n+"]))?)",r="[ \\t]+",a="[ \\t]*",i="(?:"+e+"|"+o+")"+r,l=e+r,c="(?:"+e+"|"+o+'|(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"(?:(?:\\^\\^'+e+")|(?:@([a-zA-Z]+(?:-[a-zA-Z0-9]+)*)))?))"+a,d="(?:\\.|(?:(?:"+e+"|"+o+")"+a+"\\.))";s.eoln=/(?:\r\n)|(?:\n)|(?:\r)/g,s.empty=new RegExp("^"+a+"$"),s.quad=new RegExp("^"+a+i+l+c+d+a+"$")})(),e.exports=class e{static parse(e){const l=[],d={},u=e.split(s.eoln);let p=0;for(const e of u){if(p++,s.empty.test(e))continue;const u=e.match(s.quad);if(null===u)throw new Error("N-Quads parse error on line "+p+".");const v={subject:null,predicate:null,object:null,graph:null};if(void 0!==u[1]?v.subject={termType:o,value:u[1]}:v.subject={termType:r,value:u[2]},v.predicate={termType:o,value:u[3]},void 0!==u[4]?v.object={termType:o,value:u[4]}:void 0!==u[5]?v.object={termType:r,value:u[5]}:(v.object={termType:a,value:void 0,datatype:{termType:o}},void 0!==u[7]?v.object.datatype.value=u[7]:void 0!==u[8]?(v.object.datatype.value=t,v.object.language=u[8]):v.object.datatype.value=n,v.object.value=u[6].replace(c,(function(e,t,n,o){if(t)switch(t){case"t":return"\t";case"b":return"\b";case"n":return"\n";case"r":return"\r";case"f":return"\f";case'"':return'"';case"'":return"'";case"\\":return"\\"}if(n)return String.fromCharCode(parseInt(n,16));if(o)throw new Error("Unsupported U escape")}))),void 0!==u[9]?v.graph={termType:o,value:u[9]}:void 0!==u[10]?v.graph={termType:r,value:u[10]}:v.graph={termType:i,value:""},v.graph.value in d){let e=!0;const t=d[v.graph.value];for(const n of t)if(f=v,(h=n).subject.termType===f.subject.termType&&h.object.termType===f.object.termType&&h.subject.value===f.subject.value&&h.predicate.value===f.predicate.value&&h.object.value===f.object.value&&(h.object.termType!==a||h.object.datatype.termType===f.object.datatype.termType&&h.object.language===f.object.language&&h.object.datatype.value===f.object.datatype.value)){e=!1;break}e&&(t.push(v),l.push(v))}else d[v.graph.value]=[v],l.push(v)}var h,f;return l}static serialize(t){Array.isArray(t)||(t=e.legacyDatasetToQuads(t));const n=[];for(const o of t)n.push(e.serializeQuad(o));return n.sort().join("")}static serializeQuadComponents(e,a,i,s){let c="";return e.termType===o?c+=`<${e.value}>`:c+=`${e.value}`,c+=` <${a.value}> `,i.termType===o?c+=`<${i.value}>`:i.termType===r?c+=i.value:(c+=`"${function(e){return e.replace(l,(function(e){switch(e){case'"':return'\\"';case"\\":return"\\\\";case"\n":return"\\n";case"\r":return"\\r"}}))}(i.value)}"`,i.datatype.value===t?i.language&&(c+=`@${i.language}`):i.datatype.value!==n&&(c+=`^^<${i.datatype.value}>`)),s.termType===o?c+=` <${s.value}>`:s.termType===r&&(c+=` ${s.value}`),c+=" .\n",c}static serializeQuad(t){return e.serializeQuadComponents(t.subject,t.predicate,t.object,t.graph)}static legacyDatasetToQuads(e){const s=[],l={"blank node":r,IRI:o,literal:a};for(const c in e)e[c].forEach((e=>{const d={};for(const r in e){const i=e[r],s={termType:l[i.type],value:i.value};s.termType===a&&(s.datatype={termType:o},"datatype"in i&&(s.datatype.value=i.datatype),"language"in i?("datatype"in i||(s.datatype.value=t),s.language=i.language):"datatype"in i||(s.datatype.value=n)),d[r]=s}d.graph="@default"===c?{termType:i,value:""}:{termType:c.startsWith("_:")?r:o,value:c},s.push(d)}));return s}};const l=/["\\\n\r]/g,c=/(?:\\([tbnrf"'\\]))|(?:\\u([0-9A-Fa-f]{4}))|(?:\\U([0-9A-Fa-f]{8}))/g},8326:e=>{"use strict";e.exports=class{constructor(e){this.current=e.sort(),this.done=!1,this.dir=new Map;for(let t=0;to)&&(s&&n>0&&i>e[n-1]||!s&&ne[n+1])&&(o=i,r=n)}if(null===o)this.done=!0;else{const n=t.get(o)?r-1:r+1;e[r]=e[n],e[n]=o;for(const n of e)n>o&&t.set(n,!t.get(n))}return n}}},3445:(e,t,n)=>{"use strict";const o=n(2401),r=n(5947),a=n(8326),i=n(9980);function s(e,t){return e.hasht.hash?1:0}e.exports=class{constructor({createMessageDigest:e=(()=>new r("sha256")),canonicalIdMap:t=new Map,maxDeepIterations:n=1/0}={}){this.name="URDNA2015",this.blankNodeInfo=new Map,this.canonicalIssuer=new o("_:c14n",t),this.createMessageDigest=e,this.maxDeepIterations=n,this.quads=null,this.deepIterations=null}async main(e){this.deepIterations=new Map,this.quads=e;for(const t of e)this._addBlankNodeQuadInfo({quad:t,component:t.subject}),this._addBlankNodeQuadInfo({quad:t,component:t.object}),this._addBlankNodeQuadInfo({quad:t,component:t.graph});const t=new Map,n=[...this.blankNodeInfo.keys()];let r=0;for(const e of n)++r%100==0&&await this._yield(),await this._hashAndTrackBlankNode({id:e,hashToBlankNodes:t});const a=[...t.keys()].sort(),l=[];for(const e of a){const n=t.get(e);if(n.length>1){l.push(n);continue}const o=n[0];this.canonicalIssuer.getId(o)}for(const e of l){const t=[];for(const n of e){if(this.canonicalIssuer.hasId(n))continue;const e=new o("_:b");e.getId(n);const r=await this.hashNDegreeQuads(n,e);t.push(r)}t.sort(s);for(const e of t){const t=e.issuer.getOldIds();for(const e of t)this.canonicalIssuer.getId(e)}}const c=[];for(const e of this.quads){const t=i.serializeQuadComponents(this._componentWithCanonicalId(e.subject),e.predicate,this._componentWithCanonicalId(e.object),this._componentWithCanonicalId(e.graph));c.push(t)}return c.sort(),c.join("")}async hashFirstDegreeQuads(e){const t=[],n=this.blankNodeInfo.get(e),o=n.quads;for(const n of o){const o={subject:null,predicate:n.predicate,object:null,graph:null};o.subject=this.modifyFirstDegreeComponent(e,n.subject,"subject"),o.object=this.modifyFirstDegreeComponent(e,n.object,"object"),o.graph=this.modifyFirstDegreeComponent(e,n.graph,"graph"),t.push(i.serializeQuad(o))}t.sort();const r=this.createMessageDigest();for(const e of t)r.update(e);return n.hash=await r.digest(),n.hash}async hashRelatedBlankNode(e,t,n,o){let r;r=this.canonicalIssuer.hasId(e)?this.canonicalIssuer.getId(e):n.hasId(e)?n.getId(e):this.blankNodeInfo.get(e).hash;const a=this.createMessageDigest();return a.update(o),"g"!==o&&a.update(this.getRelatedPredicate(t)),a.update(r),a.digest()}async hashNDegreeQuads(e,t){const n=this.deepIterations.get(e)||0;if(n>this.maxDeepIterations)throw new Error(`Maximum deep iterations (${this.maxDeepIterations}) exceeded.`);this.deepIterations.set(e,n+1);const o=this.createMessageDigest(),r=await this.createHashToRelated(e,t),i=[...r.keys()].sort();for(const e of i){o.update(e);let n,i="";const s=new a(r.get(e));let l=0;for(;s.hasNext();){const e=s.next();++l%3==0&&await this._yield();let o=t.clone(),r="";const a=[];let c=!1;for(const t of e)if(this.canonicalIssuer.hasId(t)?r+=this.canonicalIssuer.getId(t):(o.hasId(t)||a.push(t),r+=o.getId(t)),0!==i.length&&r>i){c=!0;break}if(!c){for(const e of a){const t=await this.hashNDegreeQuads(e,o);if(r+=o.getId(e),r+=`<${t.hash}>`,o=t.issuer,0!==i.length&&r>i){c=!0;break}}c||(0===i.length||r`}async createHashToRelated(e,t){const n=new Map,o=this.blankNodeInfo.get(e).quads;let r=0;for(const a of o)++r%100==0&&await this._yield(),await Promise.all([this._addRelatedBlankNodeHash({quad:a,component:a.subject,position:"s",id:e,issuer:t,hashToRelated:n}),this._addRelatedBlankNodeHash({quad:a,component:a.object,position:"o",id:e,issuer:t,hashToRelated:n}),this._addRelatedBlankNodeHash({quad:a,component:a.graph,position:"g",id:e,issuer:t,hashToRelated:n})]);return n}async _hashAndTrackBlankNode({id:e,hashToBlankNodes:t}){const n=await this.hashFirstDegreeQuads(e),o=t.get(n);o?o.push(e):t.set(n,[e])}_addBlankNodeQuadInfo({quad:e,component:t}){if("BlankNode"!==t.termType)return;const n=t.value,o=this.blankNodeInfo.get(n);o?o.quads.add(e):this.blankNodeInfo.set(n,{quads:new Set([e]),hash:null})}async _addRelatedBlankNodeHash({quad:e,component:t,position:n,id:o,issuer:r,hashToRelated:a}){if("BlankNode"!==t.termType||t.value===o)return;const i=t.value,s=await this.hashRelatedBlankNode(i,e,r,n),l=a.get(s);l?l.push(i):a.set(s,[i])}_componentWithCanonicalId(e){return"BlankNode"!==e.termType||e.value.startsWith(this.canonicalIssuer.prefix)?e:{termType:"BlankNode",value:this.canonicalIssuer.getId(e.value)}}async _yield(){return new Promise((e=>setImmediate(e)))}}},5643:(e,t,n)=>{"use strict";const o=n(2401),r=n(5947),a=n(8326),i=n(9980);function s(e,t){return e.hasht.hash?1:0}e.exports=class{constructor({createMessageDigest:e=(()=>new r("sha256")),canonicalIdMap:t=new Map,maxDeepIterations:n=1/0}={}){this.name="URDNA2015",this.blankNodeInfo=new Map,this.canonicalIssuer=new o("_:c14n",t),this.createMessageDigest=e,this.maxDeepIterations=n,this.quads=null,this.deepIterations=null}main(e){this.deepIterations=new Map,this.quads=e;for(const t of e)this._addBlankNodeQuadInfo({quad:t,component:t.subject}),this._addBlankNodeQuadInfo({quad:t,component:t.object}),this._addBlankNodeQuadInfo({quad:t,component:t.graph});const t=new Map,n=[...this.blankNodeInfo.keys()];for(const e of n)this._hashAndTrackBlankNode({id:e,hashToBlankNodes:t});const r=[...t.keys()].sort(),a=[];for(const e of r){const n=t.get(e);if(n.length>1){a.push(n);continue}const o=n[0];this.canonicalIssuer.getId(o)}for(const e of a){const t=[];for(const n of e){if(this.canonicalIssuer.hasId(n))continue;const e=new o("_:b");e.getId(n);const r=this.hashNDegreeQuads(n,e);t.push(r)}t.sort(s);for(const e of t){const t=e.issuer.getOldIds();for(const e of t)this.canonicalIssuer.getId(e)}}const l=[];for(const e of this.quads){const t=i.serializeQuadComponents(this._componentWithCanonicalId({component:e.subject}),e.predicate,this._componentWithCanonicalId({component:e.object}),this._componentWithCanonicalId({component:e.graph}));l.push(t)}return l.sort(),l.join("")}hashFirstDegreeQuads(e){const t=[],n=this.blankNodeInfo.get(e),o=n.quads;for(const n of o){const o={subject:null,predicate:n.predicate,object:null,graph:null};o.subject=this.modifyFirstDegreeComponent(e,n.subject,"subject"),o.object=this.modifyFirstDegreeComponent(e,n.object,"object"),o.graph=this.modifyFirstDegreeComponent(e,n.graph,"graph"),t.push(i.serializeQuad(o))}t.sort();const r=this.createMessageDigest();for(const e of t)r.update(e);return n.hash=r.digest(),n.hash}hashRelatedBlankNode(e,t,n,o){let r;r=this.canonicalIssuer.hasId(e)?this.canonicalIssuer.getId(e):n.hasId(e)?n.getId(e):this.blankNodeInfo.get(e).hash;const a=this.createMessageDigest();return a.update(o),"g"!==o&&a.update(this.getRelatedPredicate(t)),a.update(r),a.digest()}hashNDegreeQuads(e,t){const n=this.deepIterations.get(e)||0;if(n>this.maxDeepIterations)throw new Error(`Maximum deep iterations (${this.maxDeepIterations}) exceeded.`);this.deepIterations.set(e,n+1);const o=this.createMessageDigest(),r=this.createHashToRelated(e,t),i=[...r.keys()].sort();for(const e of i){o.update(e);let n,i="";const s=new a(r.get(e));for(;s.hasNext();){const e=s.next();let o=t.clone(),r="";const a=[];let l=!1;for(const t of e)if(this.canonicalIssuer.hasId(t)?r+=this.canonicalIssuer.getId(t):(o.hasId(t)||a.push(t),r+=o.getId(t)),0!==i.length&&r>i){l=!0;break}if(!l){for(const e of a){const t=this.hashNDegreeQuads(e,o);if(r+=o.getId(e),r+=`<${t.hash}>`,o=t.issuer,0!==i.length&&r>i){l=!0;break}}l||(0===i.length||r`}createHashToRelated(e,t){const n=new Map,o=this.blankNodeInfo.get(e).quads;for(const r of o)this._addRelatedBlankNodeHash({quad:r,component:r.subject,position:"s",id:e,issuer:t,hashToRelated:n}),this._addRelatedBlankNodeHash({quad:r,component:r.object,position:"o",id:e,issuer:t,hashToRelated:n}),this._addRelatedBlankNodeHash({quad:r,component:r.graph,position:"g",id:e,issuer:t,hashToRelated:n});return n}_hashAndTrackBlankNode({id:e,hashToBlankNodes:t}){const n=this.hashFirstDegreeQuads(e),o=t.get(n);o?o.push(e):t.set(n,[e])}_addBlankNodeQuadInfo({quad:e,component:t}){if("BlankNode"!==t.termType)return;const n=t.value,o=this.blankNodeInfo.get(n);o?o.quads.add(e):this.blankNodeInfo.set(n,{quads:new Set([e]),hash:null})}_addRelatedBlankNodeHash({quad:e,component:t,position:n,id:o,issuer:r,hashToRelated:a}){if("BlankNode"!==t.termType||t.value===o)return;const i=t.value,s=this.hashRelatedBlankNode(i,e,r,n),l=a.get(s);l?l.push(i):a.set(s,[i])}_componentWithCanonicalId({component:e}){return"BlankNode"!==e.termType||e.value.startsWith(this.canonicalIssuer.prefix)?e:{termType:"BlankNode",value:this.canonicalIssuer.getId(e.value)}}}},9201:(e,t,n)=>{"use strict";const o=n(5947),r=n(3445);e.exports=class extends r{constructor(){super(),this.name="URGNA2012",this.createMessageDigest=()=>new o("sha1")}modifyFirstDegreeComponent(e,t,n){return"BlankNode"!==t.termType?t:"graph"===n?{termType:"BlankNode",value:"_:g"}:{termType:"BlankNode",value:t.value===e?"_:a":"_:z"}}getRelatedPredicate(e){return e.predicate.value}async createHashToRelated(e,t){const n=new Map,o=this.blankNodeInfo.get(e).quads;let r=0;for(const a of o){let o,i;if("BlankNode"===a.subject.termType&&a.subject.value!==e)i=a.subject.value,o="p";else{if("BlankNode"!==a.object.termType||a.object.value===e)continue;i=a.object.value,o="r"}++r%100==0&&await this._yield();const s=await this.hashRelatedBlankNode(i,a,t,o),l=n.get(s);l?l.push(i):n.set(s,[i])}return n}}},7702:(e,t,n)=>{"use strict";const o=n(5947),r=n(5643);e.exports=class extends r{constructor(){super(),this.name="URGNA2012",this.createMessageDigest=()=>new o("sha1")}modifyFirstDegreeComponent(e,t,n){return"BlankNode"!==t.termType?t:"graph"===n?{termType:"BlankNode",value:"_:g"}:{termType:"BlankNode",value:t.value===e?"_:a":"_:z"}}getRelatedPredicate(e){return e.predicate.value}createHashToRelated(e,t){const n=new Map,o=this.blankNodeInfo.get(e).quads;for(const r of o){let o,a;if("BlankNode"===r.subject.termType&&r.subject.value!==e)a=r.subject.value,o="p";else{if("BlankNode"!==r.object.termType||r.object.value===e)continue;a=r.object.value,o="r"}const i=this.hashRelatedBlankNode(a,r,t,o),s=n.get(i);s?s.push(a):n.set(i,[a])}return n}}},9344:(e,t,n)=>{"use strict";const o=n(3445),r=n(9201),a=n(5643),i=n(7702);let s;try{s=n(3421)}catch(e){}function l(e){return Array.isArray(e)?e:t.NQuads.legacyDatasetToQuads(e)}t.NQuads=n(9980),t.IdentifierIssuer=n(2401),t._rdfCanonizeNative=function(e){return e&&(s=e),s},t.canonize=async function(e,t){const n=l(e);if(t.useNative){if(!s)throw new Error("rdf-canonize-native not available");if(t.createMessageDigest)throw new Error('"createMessageDigest" cannot be used with "useNative".');return new Promise(((e,o)=>s.canonize(n,t,((t,n)=>t?o(t):e(n)))))}if("URDNA2015"===t.algorithm)return new o(t).main(n);if("URGNA2012"===t.algorithm){if(t.createMessageDigest)throw new Error('"createMessageDigest" cannot be used with "URGNA2012".');return new r(t).main(n)}if(!("algorithm"in t))throw new Error("No RDF Dataset Canonicalization algorithm specified.");throw new Error("Invalid RDF Dataset Canonicalization algorithm: "+t.algorithm)},t._canonizeSync=function(e,t){const n=l(e);if(t.useNative){if(!s)throw new Error("rdf-canonize-native not available");if(t.createMessageDigest)throw new Error('"createMessageDigest" cannot be used with "useNative".');return s.canonizeSync(n,t)}if("URDNA2015"===t.algorithm)return new a(t).main(n);if("URGNA2012"===t.algorithm){if(t.createMessageDigest)throw new Error('"createMessageDigest" cannot be used with "URGNA2012".');return new i(t).main(n)}if(!("algorithm"in t))throw new Error("No RDF Dataset Canonicalization algorithm specified.");throw new Error("Invalid RDF Dataset Canonicalization algorithm: "+t.algorithm)}},4889:function(e,t,n){var o=n(4155);!function(e,t){"use strict";if(!e.setImmediate){var n,r,a,i,s,l=1,c={},d=!1,u=e.document,p=Object.getPrototypeOf&&Object.getPrototypeOf(e);p=p&&p.setTimeout?p:e,"[object process]"==={}.toString.call(e.process)?n=function(e){o.nextTick((function(){f(e)}))}:function(){if(e.postMessage&&!e.importScripts){var t=!0,n=e.onmessage;return e.onmessage=function(){t=!1},e.postMessage("","*"),e.onmessage=n,t}}()?(i="setImmediate$"+Math.random()+"$",s=function(t){t.source===e&&"string"==typeof t.data&&0===t.data.indexOf(i)&&f(+t.data.slice(i.length))},e.addEventListener?e.addEventListener("message",s,!1):e.attachEvent("onmessage",s),n=function(t){e.postMessage(i+t,"*")}):e.MessageChannel?((a=new MessageChannel).port1.onmessage=function(e){f(e.data)},n=function(e){a.port2.postMessage(e)}):u&&"onreadystatechange"in u.createElement("script")?(r=u.documentElement,n=function(e){var t=u.createElement("script");t.onreadystatechange=function(){f(e),t.onreadystatechange=null,r.removeChild(t),t=null},r.appendChild(t)}):n=function(e){setTimeout(f,0,e)},p.setImmediate=function(e){"function"!=typeof e&&(e=new Function(""+e));for(var t=new Array(arguments.length-1),o=0;o{"use strict";e.exports=function(e){e.prototype[Symbol.iterator]=function*(){for(let e=this.head;e;e=e.next)yield e.value}}},4411:(e,t,n)=>{"use strict";function o(e){var t=this;if(t instanceof o||(t=new o),t.tail=null,t.head=null,t.length=0,e&&"function"==typeof e.forEach)e.forEach((function(e){t.push(e)}));else if(arguments.length>0)for(var n=0,r=arguments.length;n1)n=t;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");o=this.head.next,n=this.head.value}for(var r=0;null!==o;r++)n=e(n,o.value,r),o=o.next;return n},o.prototype.reduceReverse=function(e,t){var n,o=this.tail;if(arguments.length>1)n=t;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");o=this.tail.prev,n=this.tail.value}for(var r=this.length-1;null!==o;r--)n=e(n,o.value,r),o=o.prev;return n},o.prototype.toArray=function(){for(var e=new Array(this.length),t=0,n=this.head;null!==n;t++)e[t]=n.value,n=n.next;return e},o.prototype.toArrayReverse=function(){for(var e=new Array(this.length),t=0,n=this.tail;null!==n;t++)e[t]=n.value,n=n.prev;return e},o.prototype.slice=function(e,t){(t=t||this.length)<0&&(t+=this.length),(e=e||0)<0&&(e+=this.length);var n=new o;if(tthis.length&&(t=this.length);for(var r=0,a=this.head;null!==a&&rthis.length&&(t=this.length);for(var r=this.length,a=this.tail;null!==a&&r>t;r--)a=a.prev;for(;null!==a&&r>e;r--,a=a.prev)n.push(a.value);return n},o.prototype.splice=function(e,t,...n){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);for(var o=0,a=this.head;null!==a&&o{"use strict";e.exports=function e(t){return null===t||"object"!=typeof t||null!=t.toJSON?JSON.stringify(t):Array.isArray(t)?"["+t.reduce(((t,n,o)=>t+(0===o?"":",")+e(void 0===n||"symbol"==typeof n?null:n)),"")+"]":"{"+Object.keys(t).sort().reduce(((n,o,r)=>void 0===t[o]||"symbol"==typeof t[o]?n:n+(0===n.length?"":",")+e(o)+":"+e(t[o])),"")+"}"}},7034:(e,t,n)=>{"use strict";const{isArray:o,isObject:r,isString:a}=n(7382),{asArray:i}=n(9263),{prependBase:s}=n(470),l=n(2207),c=n(5151);function d(e){throw new l("Invalid JSON-LD syntax; @context must be an object.","jsonld.SyntaxError",{code:"invalid local context",context:e})}function u({context:e,base:t}){if(!e)return;const n=e["@context"];if(a(n))e["@context"]=s(t,n);else if(o(n))for(let e=0;e10)throw new l("Maximum number of @context URLs exceeded.","jsonld.ContextUrlError",{code:"json-ld-1.0"===e.processingMode?"loading remote context failed":"context overflow",max:10});if(i.has(t))throw new l("Cyclical @context URLs detected.","jsonld.ContextUrlError",{code:"json-ld-1.0"===e.processingMode?"recursive context inclusion":"context overflow",url:t});let s,c;i.add(t);try{c=await n(t),s=c.document||null,a(s)&&(s=JSON.parse(s))}catch(e){throw new l("Dereferencing a URL did not result in a valid JSON-LD object. Possible causes are an inaccessible URL perhaps due to a same-origin policy (ensure the server uses CORS if you are using client-side JavaScript), too many redirects, a non-JSON response, or more than one HTTP Link Header was provided for a remote context.","jsonld.InvalidUrl",{code:"loading remote context failed",url:t,cause:e})}if(!r(s))throw new l("Dereferencing a URL did not result in a JSON object. The response was valid JSON, but it was not a JSON object.","jsonld.InvalidUrl",{code:"invalid remote context",url:t});return s="@context"in s?{"@context":s["@context"]}:{"@context":{}},c.contextUrl&&(o(s["@context"])||(s["@context"]=[s["@context"]]),s["@context"].push(c.contextUrl)),{context:s,remoteDoc:c}}}},2207:e=>{"use strict";e.exports=class extends Error{constructor(e="An unspecified JSON-LD error occurred.",t="jsonld.Error",n={}){super(e),this.name=t,this.message=e,this.details=n}}},5445:e=>{"use strict";e.exports=e=>{class t{toString(){return"[object JsonLdProcessor]"}}return Object.defineProperty(t,"prototype",{writable:!1,enumerable:!1}),Object.defineProperty(t.prototype,"constructor",{writable:!0,enumerable:!1,configurable:!0,value:t}),t.compact=function(t,n){return arguments.length<2?Promise.reject(new TypeError("Could not compact, too few arguments.")):e.compact(t,n)},t.expand=function(t){return arguments.length<1?Promise.reject(new TypeError("Could not expand, too few arguments.")):e.expand(t)},t.flatten=function(t){return arguments.length<1?Promise.reject(new TypeError("Could not flatten, too few arguments.")):e.flatten(t)},t}},8229:(e,t,n)=>{"use strict";e.exports=n(989).NQuads},3743:e=>{"use strict";e.exports=class{constructor(){this._requests={}}wrapLoader(e){const t=this;return t._loader=e,function(){return t.add.apply(t,arguments)}}async add(e){let t=this._requests[e];if(t)return Promise.resolve(t);t=this._requests[e]=this._loader(e);try{return await t}finally{delete this._requests[e]}}}},5151:(e,t,n)=>{"use strict";const o=n(9749);e.exports=class{constructor({document:e}){this.document=e,this.cache=new o({max:10})}getProcessed(e){return this.cache.get(e)}setProcessed(e,t){this.cache.set(e,t)}}},1058:(e,t,n)=>{"use strict";const o=n(2207),{isArray:r,isObject:a,isString:i,isUndefined:s}=n(7382),{isList:l,isValue:c,isGraph:d,isSimpleGraph:u,isSubjectReference:p}=n(3978),{expandIri:h,getContextValue:f,isKeyword:v,process:g,processingMode:y}=n(1972),{removeBase:m,prependBase:x}=n(470),{REGEX_KEYWORD:b,addValue:w,asArray:j,compareShortestLeast:I}=n(9263),N={};function S(e,t,n){if("@nest"!==h(e,t,{vocab:!0},n))throw new o("JSON-LD compact error; nested property must have an @nest value resolving to @nest.","jsonld.SyntaxError",{code:"invalid @nest value"})}e.exports=N,N.compact=async({activeCtx:e,activeProperty:t=null,element:n,options:h={}})=>{if(r(n)){let o=[];for(let r=0;r1&&(O=Array.from(O).sort());const E=e;for(const t of O){const n=N.compactIri({activeCtx:E,iri:t,relativeTo:{vocab:!0}}),o=f(b,n,"@context");s(o)||(e=await g({activeCtx:e,localCtx:o,options:h,propagate:!1}))}const D=Object.keys(n).sort();for(const s of D){const p=n[s];if("@id"!==s)if("@type"!==s)if("@reverse"!==s)if("@preserve"!==s)if("@index"!==s)if("@graph"!==s&&"@list"!==s&&"@included"!==s&&v(s)){const t=N.compactIri({activeCtx:e,iri:s,relativeTo:{vocab:!0}});w(x,t,p)}else{if(!r(p))throw new o("JSON-LD expansion error; expanded value must be an array.","jsonld.SyntaxError");if(0===p.length){const t=N.compactIri({activeCtx:e,iri:s,value:p,relativeTo:{vocab:!0},reverse:m}),n=e.mappings.has(t)?e.mappings.get(t)["@nest"]:null;let o=x;n&&(S(e,n,h),a(x[n])||(x[n]={}),o=x[n]),w(o,t,p,{propertyIsArray:!0})}for(const t of p){const n=N.compactIri({activeCtx:e,iri:s,value:t,relativeTo:{vocab:!0},reverse:m}),o=e.mappings.has(n)?e.mappings.get(n)["@nest"]:null;let p=x;o&&(S(e,o,h),a(x[o])||(x[o]={}),p=x[o]);const v=f(e,n,"@container")||[],g=d(t),y=l(t);let b;y?b=t["@list"]:g&&(b=t["@graph"]);let I=await N.compact({activeCtx:e,activeProperty:n,element:y||g?b:t,options:h});if(y){if(r(I)||(I=[I]),v.includes("@list")){w(p,n,I,{valueIsArray:!0,allowDuplicate:!0});continue}I={[N.compactIri({activeCtx:e,iri:"@list",relativeTo:{vocab:!0}})]:I},"@index"in t&&(I[N.compactIri({activeCtx:e,iri:"@index",relativeTo:{vocab:!0}})]=t["@index"])}if(g)if(v.includes("@graph")&&(v.includes("@id")||v.includes("@index")&&u(t))){let o;p.hasOwnProperty(n)?o=p[n]:p[n]=o={};const r=(v.includes("@id")?t["@id"]:t["@index"])||N.compactIri({activeCtx:e,iri:"@none",relativeTo:{vocab:!0}});w(o,r,I,{propertyIsArray:!h.compactArrays||v.includes("@set")})}else v.includes("@graph")&&u(t)?(r(I)&&I.length>1&&(I={"@included":I}),w(p,n,I,{propertyIsArray:!h.compactArrays||v.includes("@set")})):(r(I)&&1===I.length&&h.compactArrays&&(I=I[0]),I={[N.compactIri({activeCtx:e,iri:"@graph",relativeTo:{vocab:!0}})]:I},"@id"in t&&(I[N.compactIri({activeCtx:e,iri:"@id",relativeTo:{vocab:!0}})]=t["@id"]),"@index"in t&&(I[N.compactIri({activeCtx:e,iri:"@index",relativeTo:{vocab:!0}})]=t["@index"]),w(p,n,I,{propertyIsArray:!h.compactArrays||v.includes("@set")}));else if(v.includes("@language")||v.includes("@index")||v.includes("@id")||v.includes("@type")){let o,r;if(p.hasOwnProperty(n)?o=p[n]:p[n]=o={},v.includes("@language"))c(I)&&(I=I["@value"]),r=t["@language"];else if(v.includes("@index")){const o=f(e,n,"@index")||"@index",a=N.compactIri({activeCtx:e,iri:o,relativeTo:{vocab:!0}});if("@index"===o)r=t["@index"],delete I[a];else{let e;if([r,...e]=j(I[o]||[]),i(r))switch(e.length){case 0:delete I[o];break;case 1:I[o]=e[0];break;default:I[o]=e}else r=null}}else if(v.includes("@id")){const t=N.compactIri({activeCtx:e,iri:"@id",relativeTo:{vocab:!0}});r=I[t],delete I[t]}else if(v.includes("@type")){const o=N.compactIri({activeCtx:e,iri:"@type",relativeTo:{vocab:!0}});let a;switch([r,...a]=j(I[o]||[]),a.length){case 0:delete I[o];break;case 1:I[o]=a[0];break;default:I[o]=a}1===Object.keys(I).length&&"@id"in t&&(I=await N.compact({activeCtx:e,activeProperty:n,element:{"@id":t["@id"]},options:h}))}r||(r=N.compactIri({activeCtx:e,iri:"@none",relativeTo:{vocab:!0}})),w(o,r,I,{propertyIsArray:v.includes("@set")})}else{const e=!h.compactArrays||v.includes("@set")||v.includes("@list")||r(I)&&0===I.length||"@list"===s||"@graph"===s;w(p,n,I,{propertyIsArray:e})}}}else{if((f(e,t,"@container")||[]).includes("@index"))continue;const n=N.compactIri({activeCtx:e,iri:s,relativeTo:{vocab:!0}});w(x,n,p)}else{const n=await N.compact({activeCtx:e,activeProperty:t,element:p,options:h});r(n)&&0===n.length||w(x,s,n)}else{const t=await N.compact({activeCtx:e,activeProperty:"@reverse",element:p,options:h});for(const n in t)if(e.mappings.has(n)&&e.mappings.get(n).reverse){const o=t[n],r=(f(e,n,"@container")||[]).includes("@set")||!h.compactArrays;w(x,n,o,{propertyIsArray:r}),delete t[n]}if(Object.keys(t).length>0){const n=N.compactIri({activeCtx:e,iri:s,relativeTo:{vocab:!0}});w(x,n,t)}}else{let t=j(p).map((e=>N.compactIri({activeCtx:b,iri:e,relativeTo:{vocab:!0}})));1===t.length&&(t=t[0]);const n=N.compactIri({activeCtx:e,iri:"@type",relativeTo:{vocab:!0}}),o=(f(e,n,"@container")||[]).includes("@set")&&y(e,1.1)||r(t)&&0===p.length;w(x,n,t,{propertyIsArray:o})}else{let t=j(p).map((t=>N.compactIri({activeCtx:e,iri:t,relativeTo:{vocab:!1},base:h.base})));1===t.length&&(t=t[0]),x[N.compactIri({activeCtx:e,iri:"@id",relativeTo:{vocab:!0}})]=t}}return x}return n},N.compactIri=({activeCtx:e,iri:t,value:n=null,relativeTo:r={vocab:!1},reverse:i=!1,base:s=null})=>{if(null===t)return t;e.isPropertyTermScoped&&e.previousContext&&(e=e.previousContext);const u=e.getInverse();if(v(t)&&t in u&&"@none"in u[t]&&"@type"in u[t]["@none"]&&"@none"in u[t]["@none"]["@type"])return u[t]["@none"]["@type"]["@none"];if(r.vocab&&t in u){const o=e["@language"]||"@none",r=[];a(n)&&"@index"in n&&!("@graph"in n)&&r.push("@index","@index@set"),a(n)&&"@preserve"in n&&(n=n["@preserve"][0]),d(n)?("@index"in n&&r.push("@graph@index","@graph@index@set","@index","@index@set"),"@id"in n&&r.push("@graph@id","@graph@id@set"),r.push("@graph","@graph@set","@set"),"@index"in n||r.push("@graph@index","@graph@index@set","@index","@index@set"),"@id"in n||r.push("@graph@id","@graph@id@set")):a(n)&&!c(n)&&r.push("@id","@id@set","@type","@set@type");let s="@language",u="@null";if(i)s="@type",u="@reverse",r.push("@set");else if(l(n)){"@index"in n||r.push("@list");const e=n["@list"];if(0===e.length)s="@any",u="@none";else{let t=0===e.length?o:null,n=null;for(let o=0;oe.includes("_")));e&&s.push(e.replace(/^[^_]+_/,"_"))}s.push("@none");const l=e.inverse[t];for(const e of o){if(!(e in l))continue;const t=l[e][r];for(const e of s)if(e in t)return t[e]}return null}(e,t,n,r,s,u);if(null!==p)return p}if(r.vocab&&"@vocab"in e){const n=e["@vocab"];if(0===t.indexOf(n)&&t!==n){const o=t.substr(n.length);if(!e.mappings.has(o))return o}}let p=null;const h=[];let f=e.fastCurieMap;const g=t.length-1;for(let e=0;e=0;--o){const r=h[o],a=r.terms;for(const o of a){const a=o+":"+t.substr(r.iri.length);e.mappings.get(o)._prefix&&(!e.mappings.has(a)||null===n&&e.mappings.get(a)["@id"]===t)&&(null===p||I(a,p)<0)&&(p=a)}}if(null!==p)return p;for(const[n,r]of e.mappings)if(r&&r._prefix&&t.startsWith(n+":"))throw new o(`Absolute IRI "${t}" confused with prefix "${n}".`,"jsonld.SyntaxError",{code:"IRI confused with prefix",context:e});if(!r.vocab){if("@base"in e){if(e["@base"]){const n=m(x(s,e["@base"]),t);return b.test(n)?`./${n}`:n}return t}return m(s,t)}return t},N.compactValue=({activeCtx:e,activeProperty:t,value:n,options:o})=>{if(c(n)){const o=f(e,t,"@type"),r=f(e,t,"@language"),a=f(e,t,"@direction"),s=f(e,t,"@container")||[],l="@index"in n&&!s.includes("@index");if(!l&&"@none"!==o){if(n["@type"]===o)return n["@value"];if("@language"in n&&n["@language"]===r&&"@direction"in n&&n["@direction"]===a)return n["@value"];if("@language"in n&&n["@language"]===r)return n["@value"];if("@direction"in n&&n["@direction"]===a)return n["@value"]}const c=Object.keys(n).length,d=1===c||2===c&&"@index"in n&&!l,u="@language"in e,p=i(n["@value"]),h=e.mappings.has(t)&&null===e.mappings.get(t)["@language"];if(d&&"@none"!==o&&(!u||!p||h))return n["@value"];const v={};return l&&(v[N.compactIri({activeCtx:e,iri:"@index",relativeTo:{vocab:!0}})]=n["@index"]),"@type"in n?v[N.compactIri({activeCtx:e,iri:"@type",relativeTo:{vocab:!0}})]=N.compactIri({activeCtx:e,iri:n["@type"],relativeTo:{vocab:!0}}):"@language"in n&&(v[N.compactIri({activeCtx:e,iri:"@language",relativeTo:{vocab:!0}})]=n["@language"]),"@direction"in n&&(v[N.compactIri({activeCtx:e,iri:"@direction",relativeTo:{vocab:!0}})]=n["@direction"]),v[N.compactIri({activeCtx:e,iri:"@value",relativeTo:{vocab:!0}})]=n["@value"],v}const r=h(e,t,{vocab:!0},o),a=f(e,t,"@type"),s=N.compactIri({activeCtx:e,iri:n["@id"],relativeTo:{vocab:"@vocab"===a},base:o.base});return"@id"===a||"@vocab"===a||"@graph"===r?s:{[N.compactIri({activeCtx:e,iri:"@id",relativeTo:{vocab:!0}})]:s}}},9378:e=>{"use strict";const t="http://www.w3.org/1999/02/22-rdf-syntax-ns#",n="http://www.w3.org/2001/XMLSchema#";e.exports={LINK_HEADER_REL:"http://www.w3.org/ns/json-ld#context",LINK_HEADER_CONTEXT:"http://www.w3.org/ns/json-ld#context",RDF:t,RDF_LIST:t+"List",RDF_FIRST:t+"first",RDF_REST:t+"rest",RDF_NIL:t+"nil",RDF_TYPE:t+"type",RDF_PLAIN_LITERAL:t+"PlainLiteral",RDF_XML_LITERAL:t+"XMLLiteral",RDF_JSON_LITERAL:t+"JSON",RDF_OBJECT:t+"object",RDF_LANGSTRING:t+"langString",XSD:n,XSD_BOOLEAN:n+"boolean",XSD_DOUBLE:n+"double",XSD_INTEGER:n+"integer",XSD_STRING:n+"string"}},1972:(e,t,n)=>{"use strict";const o=n(9263),r=n(2207),{isArray:a,isObject:i,isString:s,isUndefined:l}=n(7382),{isAbsolute:c,isRelative:d,prependBase:u}=n(470),{handleEvent:p}=n(2246),{REGEX_BCP47:h,REGEX_KEYWORD:f,asArray:v,compareShortestLeast:g}=n(9263),y=new Map,m={};function x(e,t,n,o,r,a){if(null===t||!s(t)||m.isKeyword(t))return t;if(t.match(f))return null;if(o&&o.hasOwnProperty(t)&&!0!==r.get(t)&&m.createTermDefinition({activeCtx:e,localCtx:o,term:t,defined:r,options:a}),(n=n||{}).vocab){const n=e.mappings.get(t);if(null===n)return null;if(i(n)&&"@id"in n)return n["@id"]}const l=t.indexOf(":");if(l>0){const n=t.substr(0,l),i=t.substr(l+1);if("_"===n||0===i.indexOf("//"))return t;o&&o.hasOwnProperty(n)&&m.createTermDefinition({activeCtx:e,localCtx:o,term:n,defined:r,options:a});const s=e.mappings.get(n);if(s&&s._prefix)return s["@id"]+i;if(c(t))return t}if(n.vocab&&"@vocab"in e)t=e["@vocab"]+t;else if(n.base){let n,o;"@base"in e?e["@base"]?(o=u(a.base,e["@base"]),n=u(o,t)):(o=e["@base"],n=t):(o=a.base,n=u(a.base,t)),t=n}return t}function b(e,t){if(!e||"object"!=typeof e||!t||"object"!=typeof t)return e===t;const n=Array.isArray(e);if(n!==Array.isArray(t))return!1;if(n){if(e.length!==t.length)return!1;for(let n=0;n{if(i(t)&&"@context"in t&&a(t["@context"])&&(t=t["@context"]),0===v(t).length)return e;const g=[],y=[({event:e,next:t})=>{g.push(e),t()}];n.eventHandler&&y.push(n.eventHandler);const b=n;n={...n,eventHandler:y};const w=await n.contextResolver.resolve({activeCtx:e,context:t,documentLoader:n.documentLoader,base:n.base});i(w[0].document)&&"boolean"==typeof w[0].document["@propagate"]&&(o=w[0].document["@propagate"]);let j=e;o||j.previousContext||(j=j.clone(),j.previousContext=e);for(const o of w){let{document:a}=o;if(e=j,null===a){if(!l&&0!==Object.keys(e.protected).length)throw new r("Tried to nullify a context with protected terms outside of a term definition.","jsonld.SyntaxError",{code:"invalid context nullification"});j=e=m.getInitialContext(n).clone();continue}const v=o.getProcessed(e);if(v){if(b.eventHandler)for(const e of v.events)p({event:e,options:b});j=e=v.context;continue}if(i(a)&&"@context"in a&&(a=a["@context"]),!i(a))throw new r("Invalid JSON-LD syntax; @context must be an object.","jsonld.SyntaxError",{code:"invalid local context",context:a});j=j.clone();const y=new Map;if("@version"in a){if(1.1!==a["@version"])throw new r("Unsupported JSON-LD version: "+a["@version"],"jsonld.UnsupportedVersion",{code:"invalid @version value",context:a});if(e.processingMode&&"json-ld-1.0"===e.processingMode)throw new r("@version: "+a["@version"]+" not compatible with "+e.processingMode,"jsonld.ProcessingModeConflict",{code:"processing mode conflict",context:a});j.processingMode="json-ld-1.1",j["@version"]=a["@version"],y.set("@version",!0)}if(j.processingMode=j.processingMode||e.processingMode,"@base"in a){let e=a["@base"];if(null===e||c(e));else{if(!d(e))throw new r('Invalid JSON-LD syntax; the value of "@base" in a @context must be an absolute IRI, a relative IRI, or null.',"jsonld.SyntaxError",{code:"invalid base IRI",context:a});e=u(j["@base"],e)}j["@base"]=e,y.set("@base",!0)}if("@vocab"in a){const e=a["@vocab"];if(null===e)delete j["@vocab"];else{if(!s(e))throw new r('Invalid JSON-LD syntax; the value of "@vocab" in a @context must be a string or null.',"jsonld.SyntaxError",{code:"invalid vocab mapping",context:a});if(!c(e)&&m.processingMode(j,1))throw new r('Invalid JSON-LD syntax; the value of "@vocab" in a @context must be an absolute IRI.',"jsonld.SyntaxError",{code:"invalid vocab mapping",context:a});{const t=x(j,e,{vocab:!0,base:!0},void 0,void 0,n);c(t)||n.eventHandler&&p({event:{type:["JsonLdEvent"],code:"relative @vocab reference",level:"warning",message:"Relative @vocab reference found.",details:{vocab:t}},options:n}),j["@vocab"]=t}}y.set("@vocab",!0)}if("@language"in a){const e=a["@language"];if(null===e)delete j["@language"];else{if(!s(e))throw new r('Invalid JSON-LD syntax; the value of "@language" in a @context must be a string or null.',"jsonld.SyntaxError",{code:"invalid default language",context:a});e.match(h)||n.eventHandler&&p({event:{type:["JsonLdEvent"],code:"invalid @language value",level:"warning",message:"@language value must be valid BCP47.",details:{language:e}},options:n}),j["@language"]=e.toLowerCase()}y.set("@language",!0)}if("@direction"in a){const t=a["@direction"];if("json-ld-1.0"===e.processingMode)throw new r("Invalid JSON-LD syntax; @direction not compatible with "+e.processingMode,"jsonld.SyntaxError",{code:"invalid context member",context:a});if(null===t)delete j["@direction"];else{if("ltr"!==t&&"rtl"!==t)throw new r('Invalid JSON-LD syntax; the value of "@direction" in a @context must be null, "ltr", or "rtl".',"jsonld.SyntaxError",{code:"invalid base direction",context:a});j["@direction"]=t}y.set("@direction",!0)}if("@propagate"in a){const n=a["@propagate"];if("json-ld-1.0"===e.processingMode)throw new r("Invalid JSON-LD syntax; @propagate not compatible with "+e.processingMode,"jsonld.SyntaxError",{code:"invalid context entry",context:a});if("boolean"!=typeof n)throw new r("Invalid JSON-LD syntax; @propagate value must be a boolean.","jsonld.SyntaxError",{code:"invalid @propagate value",context:t});y.set("@propagate",!0)}if("@import"in a){const o=a["@import"];if("json-ld-1.0"===e.processingMode)throw new r("Invalid JSON-LD syntax; @import not compatible with "+e.processingMode,"jsonld.SyntaxError",{code:"invalid context entry",context:a});if(!s(o))throw new r("Invalid JSON-LD syntax; @import must be a string.","jsonld.SyntaxError",{code:"invalid @import value",context:t});const i=await n.contextResolver.resolve({activeCtx:e,context:o,documentLoader:n.documentLoader,base:n.base});if(1!==i.length)throw new r("Invalid JSON-LD syntax; @import must reference a single context.","jsonld.SyntaxError",{code:"invalid remote context",context:t});const l=i[0].getProcessed(e);if(l)a=l;else{const n=i[0].document;if("@import"in n)throw new r("Invalid JSON-LD syntax: imported context must not include @import.","jsonld.SyntaxError",{code:"invalid context entry",context:t});for(const e in n)a.hasOwnProperty(e)||(a[e]=n[e]);i[0].setProcessed(e,a)}y.set("@import",!0)}y.set("@protected",a["@protected"]||!1);for(const e in a)if(m.createTermDefinition({activeCtx:j,localCtx:a,term:e,defined:y,options:n,overrideProtected:l}),i(a[e])&&"@context"in a[e]){const t=a[e]["@context"];let o=!0;if(s(t)){const e=u(n.base,t);f.has(e)?o=!1:f.add(e)}if(o)try{await m.process({activeCtx:j.clone(),localCtx:a[e]["@context"],overrideProtected:!0,options:n,cycles:f})}catch(t){throw new r("Invalid JSON-LD syntax; invalid scoped context.","jsonld.SyntaxError",{code:"invalid scoped context",context:a[e]["@context"],term:e})}}o.setProcessed(e,{context:j,events:g})}return j},m.createTermDefinition=({activeCtx:e,localCtx:t,term:n,defined:o,options:l,overrideProtected:d=!1})=>{if(o.has(n)){if(o.get(n))return;throw new r("Cyclical context definition detected.","jsonld.CyclicalContext",{code:"cyclic IRI mapping",context:t,term:n})}let u;if(o.set(n,!1),t.hasOwnProperty(n)&&(u=t[n]),"@type"===n&&i(u)&&"@set"===(u["@container"]||"@set")&&m.processingMode(e,1.1)){const e=["@container","@id","@protected"],o=Object.keys(u);if(0===o.length||o.some((t=>!e.includes(t))))throw new r("Invalid JSON-LD syntax; keywords cannot be overridden.","jsonld.SyntaxError",{code:"keyword redefinition",context:t,term:n})}else{if(m.isKeyword(n))throw new r("Invalid JSON-LD syntax; keywords cannot be overridden.","jsonld.SyntaxError",{code:"keyword redefinition",context:t,term:n});if(n.match(f))return void(l.eventHandler&&p({event:{type:["JsonLdEvent"],code:"reserved term",level:"warning",message:'Terms beginning with "@" are reserved for future use and dropped.',details:{term:n}},options:l}));if(""===n)throw new r("Invalid JSON-LD syntax; a term cannot be an empty string.","jsonld.SyntaxError",{code:"invalid term definition",context:t})}const h=e.mappings.get(n);e.mappings.has(n)&&e.mappings.delete(n);let v=!1;if((s(u)||null===u)&&(v=!0,u={"@id":u}),!i(u))throw new r("Invalid JSON-LD syntax; @context term values must be strings or objects.","jsonld.SyntaxError",{code:"invalid term definition",context:t});const g={};e.mappings.set(n,g),g.reverse=!1;const y=["@container","@id","@language","@reverse","@type"];m.processingMode(e,1.1)&&y.push("@context","@direction","@index","@nest","@prefix","@protected");for(const e in u)if(!y.includes(e))throw new r("Invalid JSON-LD syntax; a term definition must not contain "+e,"jsonld.SyntaxError",{code:"invalid term definition",context:t});const w=n.indexOf(":");if(g._termHasColon=w>0,"@reverse"in u){if("@id"in u)throw new r("Invalid JSON-LD syntax; a @reverse term definition must not contain @id.","jsonld.SyntaxError",{code:"invalid reverse property",context:t});if("@nest"in u)throw new r("Invalid JSON-LD syntax; a @reverse term definition must not contain @nest.","jsonld.SyntaxError",{code:"invalid reverse property",context:t});const a=u["@reverse"];if(!s(a))throw new r("Invalid JSON-LD syntax; a @context @reverse value must be a string.","jsonld.SyntaxError",{code:"invalid IRI mapping",context:t});if(a.match(f))return l.eventHandler&&p({event:{type:["JsonLdEvent"],code:"reserved @reverse value",level:"warning",message:'@reverse values beginning with "@" are reserved for future use and dropped.',details:{reverse:a}},options:l}),void(h?e.mappings.set(n,h):e.mappings.delete(n));const i=x(e,a,{vocab:!0,base:!1},t,o,l);if(!c(i))throw new r("Invalid JSON-LD syntax; a @context @reverse value must be an absolute IRI or a blank node identifier.","jsonld.SyntaxError",{code:"invalid IRI mapping",context:t});g["@id"]=i,g.reverse=!0}else if("@id"in u){let a=u["@id"];if(a&&!s(a))throw new r("Invalid JSON-LD syntax; a @context @id value must be an array of strings or a string.","jsonld.SyntaxError",{code:"invalid IRI mapping",context:t});if(null===a)g["@id"]=null;else{if(!m.isKeyword(a)&&a.match(f))return l.eventHandler&&p({event:{type:["JsonLdEvent"],code:"reserved @id value",level:"warning",message:'@id values beginning with "@" are reserved for future use and dropped.',details:{id:a}},options:l}),void(h?e.mappings.set(n,h):e.mappings.delete(n));if(a!==n){if(a=x(e,a,{vocab:!0,base:!1},t,o,l),!c(a)&&!m.isKeyword(a))throw new r("Invalid JSON-LD syntax; a @context @id value must be an absolute IRI, a blank node identifier, or a keyword.","jsonld.SyntaxError",{code:"invalid IRI mapping",context:t});if(n.match(/(?::[^:])|\//)&&x(e,n,{vocab:!0,base:!1},t,new Map(o).set(n,!0),l)!==a)throw new r("Invalid JSON-LD syntax; term in form of IRI must expand to definition.","jsonld.SyntaxError",{code:"invalid IRI mapping",context:t});g["@id"]=a,g._prefix=v&&!g._termHasColon&&null!==a.match(/[:\/\?#\[\]@]$/)}}}if(!("@id"in g))if(g._termHasColon){const r=n.substr(0,w);if(t.hasOwnProperty(r)&&m.createTermDefinition({activeCtx:e,localCtx:t,term:r,defined:o,options:l}),e.mappings.has(r)){const t=n.substr(w+1);g["@id"]=e.mappings.get(r)["@id"]+t}else g["@id"]=n}else if("@type"===n)g["@id"]=n;else{if(!("@vocab"in e))throw new r("Invalid JSON-LD syntax; @context terms must define an @id.","jsonld.SyntaxError",{code:"invalid IRI mapping",context:t,term:n});g["@id"]=e["@vocab"]+n}if((!0===u["@protected"]||!0===o.get("@protected")&&!1!==u["@protected"])&&(e.protected[n]=!0,g.protected=!0),o.set(n,!0),"@type"in u){let n=u["@type"];if(!s(n))throw new r("Invalid JSON-LD syntax; an @context @type value must be a string.","jsonld.SyntaxError",{code:"invalid type mapping",context:t});if("@json"===n||"@none"===n){if(m.processingMode(e,1))throw new r(`Invalid JSON-LD syntax; an @context @type value must not be "${n}" in JSON-LD 1.0 mode.`,"jsonld.SyntaxError",{code:"invalid type mapping",context:t})}else if("@id"!==n&&"@vocab"!==n){if(n=x(e,n,{vocab:!0,base:!1},t,o,l),!c(n))throw new r("Invalid JSON-LD syntax; an @context @type value must be an absolute IRI.","jsonld.SyntaxError",{code:"invalid type mapping",context:t});if(0===n.indexOf("_:"))throw new r("Invalid JSON-LD syntax; an @context @type value must be an IRI, not a blank node identifier.","jsonld.SyntaxError",{code:"invalid type mapping",context:t})}g["@type"]=n}if("@container"in u){const n=s(u["@container"])?[u["@container"]]:u["@container"]||[],o=["@list","@set","@index","@language"];let i=!0;const l=n.includes("@set");if(m.processingMode(e,1.1)){if(o.push("@graph","@id","@type"),n.includes("@list")){if(1!==n.length)throw new r("Invalid JSON-LD syntax; @context @container with @list must have no other values","jsonld.SyntaxError",{code:"invalid container mapping",context:t})}else if(n.includes("@graph")){if(n.some((e=>"@graph"!==e&&"@id"!==e&&"@index"!==e&&"@set"!==e)))throw new r("Invalid JSON-LD syntax; @context @container with @graph must have no other values other than @id, @index, and @set","jsonld.SyntaxError",{code:"invalid container mapping",context:t})}else i&=n.length<=(l?2:1);if(n.includes("@type")&&(g["@type"]=g["@type"]||"@id",!["@id","@vocab"].includes(g["@type"])))throw new r("Invalid JSON-LD syntax; container: @type requires @type to be @id or @vocab.","jsonld.SyntaxError",{code:"invalid type mapping",context:t})}else i&=!a(u["@container"]),i&=n.length<=1;if(i&=n.every((e=>o.includes(e))),i&=!(l&&n.includes("@list")),!i)throw new r("Invalid JSON-LD syntax; @context @container value must be one of the following: "+o.join(", "),"jsonld.SyntaxError",{code:"invalid container mapping",context:t});if(g.reverse&&!n.every((e=>["@index","@set"].includes(e))))throw new r("Invalid JSON-LD syntax; @context @container value for a @reverse type definition must be @index or @set.","jsonld.SyntaxError",{code:"invalid reverse property",context:t});g["@container"]=n}if("@index"in u){if(!("@container"in u)||!g["@container"].includes("@index"))throw new r(`Invalid JSON-LD syntax; @index without @index in @container: "${u["@index"]}" on term "${n}".`,"jsonld.SyntaxError",{code:"invalid term definition",context:t});if(!s(u["@index"])||0===u["@index"].indexOf("@"))throw new r(`Invalid JSON-LD syntax; @index must expand to an IRI: "${u["@index"]}" on term "${n}".`,"jsonld.SyntaxError",{code:"invalid term definition",context:t});g["@index"]=u["@index"]}if("@context"in u&&(g["@context"]=u["@context"]),"@language"in u&&!("@type"in u)){let e=u["@language"];if(null!==e&&!s(e))throw new r("Invalid JSON-LD syntax; @context @language value must be a string or null.","jsonld.SyntaxError",{code:"invalid language mapping",context:t});null!==e&&(e=e.toLowerCase()),g["@language"]=e}if("@prefix"in u){if(n.match(/:|\//))throw new r("Invalid JSON-LD syntax; @context @prefix used on a compact IRI term","jsonld.SyntaxError",{code:"invalid term definition",context:t});if(m.isKeyword(g["@id"]))throw new r("Invalid JSON-LD syntax; keywords may not be used as prefixes","jsonld.SyntaxError",{code:"invalid term definition",context:t});if("boolean"!=typeof u["@prefix"])throw new r("Invalid JSON-LD syntax; @context value for @prefix must be boolean","jsonld.SyntaxError",{code:"invalid @prefix value",context:t});g._prefix=!0===u["@prefix"]}if("@direction"in u){const e=u["@direction"];if(null!==e&&"ltr"!==e&&"rtl"!==e)throw new r('Invalid JSON-LD syntax; @direction value must be null, "ltr", or "rtl".',"jsonld.SyntaxError",{code:"invalid base direction",context:t});g["@direction"]=e}if("@nest"in u){const e=u["@nest"];if(!s(e)||"@nest"!==e&&0===e.indexOf("@"))throw new r("Invalid JSON-LD syntax; @context @nest value must be a string which is not a keyword other than @nest.","jsonld.SyntaxError",{code:"invalid @nest value",context:t});g["@nest"]=e}const j=g["@id"];if("@context"===j||"@preserve"===j)throw new r("Invalid JSON-LD syntax; @context and @preserve cannot be aliased.","jsonld.SyntaxError",{code:"invalid keyword alias",context:t});if(h&&h.protected&&!d&&(e.protected[n]=!0,g.protected=!0,!b(h,g)))throw new r("Invalid JSON-LD syntax; tried to redefine a protected term.","jsonld.SyntaxError",{code:"protected term redefinition",context:t,term:n})},m.expandIri=(e,t,n,o)=>x(e,t,n,void 0,void 0,o),m.getInitialContext=e=>{const t=JSON.stringify({processingMode:e.processingMode}),n=y.get(t);if(n)return n;const r={processingMode:e.processingMode,mappings:new Map,inverse:null,getInverse:function(){const e=this;if(e.inverse)return e.inverse;const t=e.inverse={},n=e.fastCurieMap={},o={},r=(e["@language"]||"@none").toLowerCase(),s=e["@direction"],l=e.mappings,c=[...l.keys()].sort(g);for(const e of c){const a=l.get(e);if(null===a)continue;let c=a["@container"]||"@none";if(c=[].concat(c).sort().join(""),null===a["@id"])continue;const d=v(a["@id"]);for(const l of d){let d=t[l];const u=m.isKeyword(l);if(d)u||a._termHasColon||o[l].push(e);else if(t[l]=d={},!u&&!a._termHasColon){o[l]=[e];const t={iri:l,terms:o[l]};l[0]in n?n[l[0]].push(t):n[l[0]]=[t]}if(d[c]||(d[c]={"@language":{},"@type":{},"@any":{}}),d=d[c],i(e,d["@any"],"@none"),a.reverse)i(e,d["@type"],"@reverse");else if("@none"===a["@type"])i(e,d["@any"],"@none"),i(e,d["@language"],"@none"),i(e,d["@type"],"@none");else if("@type"in a)i(e,d["@type"],a["@type"]);else if("@language"in a&&"@direction"in a){const t=a["@language"],n=a["@direction"];i(e,d["@language"],t&&n?`${t}_${n}`.toLowerCase():t?t.toLowerCase():n?`_${n}`:"@null")}else"@language"in a?i(e,d["@language"],(a["@language"]||"@null").toLowerCase()):"@direction"in a?a["@direction"]?i(e,d["@language"],`_${a["@direction"]}`):i(e,d["@language"],"@none"):s?(i(e,d["@language"],`_${s}`),i(e,d["@language"],"@none"),i(e,d["@type"],"@none")):(i(e,d["@language"],r),i(e,d["@language"],"@none"),i(e,d["@type"],"@none"))}}for(const e in n)a(n,e,1);return t},clone:function(){const e={};return e.mappings=o.clone(this.mappings),e.clone=this.clone,e.inverse=null,e.getInverse=this.getInverse,e.protected=o.clone(this.protected),this.previousContext&&(e.previousContext=this.previousContext.clone()),e.revertToPreviousContext=this.revertToPreviousContext,"@base"in this&&(e["@base"]=this["@base"]),"@language"in this&&(e["@language"]=this["@language"]),"@vocab"in this&&(e["@vocab"]=this["@vocab"]),e},revertToPreviousContext:function(){return this.previousContext?this.previousContext.clone():this},protected:{}};return 1e4===y.size&&y.clear(),y.set(t,r),r;function a(e,t,n){const o=e[t],r=e[t]={};let i,s;for(const e of o)i=e.iri,s=n>=i.length?"":i[n],s in r?r[s].push(e):r[s]=[e];for(const e in r)""!==e&&a(r,e,n+1)}function i(e,t,n){t.hasOwnProperty(n)||(t[n]=e)}},m.getContextValue=(e,t,n)=>{if(null===t){if("@context"===n)return;return null}if(e.mappings.has(t)){const o=e.mappings.get(t);if(l(n))return o;if(o.hasOwnProperty(n))return o[n]}return"@language"===n&&n in e||"@direction"===n&&n in e?e[n]:"@context"!==n?null:void 0},m.processingMode=(e,t)=>t.toString()>="1.1"?!e.processingMode||e.processingMode>="json-ld-"+t.toString():"json-ld-1.0"===e.processingMode,m.isKeyword=e=>{if(!s(e)||"@"!==e[0])return!1;switch(e){case"@base":case"@container":case"@context":case"@default":case"@direction":case"@embed":case"@explicit":case"@graph":case"@id":case"@included":case"@index":case"@json":case"@language":case"@list":case"@nest":case"@none":case"@omitDefault":case"@prefix":case"@preserve":case"@protected":case"@requireAll":case"@reverse":case"@set":case"@type":case"@value":case"@version":case"@vocab":return!0}return!1}},6957:(e,t,n)=>{"use strict";const{parseLinkHeader:o,buildHeaders:r}=n(9263),{LINK_HEADER_CONTEXT:a}=n(9378),i=n(2207),s=n(3743),{prependBase:l}=n(470),c=/(^|(\r\n))link:/i;e.exports=({secure:e,headers:t={},xhr:n}={headers:{}})=>(t=r(t),(new s).wrapLoader((async function r(s){if(0!==s.indexOf("http:")&&0!==s.indexOf("https:"))throw new i('URL could not be dereferenced; only "http" and "https" URLs are supported.',"jsonld.InvalidUrl",{code:"loading document failed",url:s});if(e&&0!==s.indexOf("https"))throw new i('URL could not be dereferenced; secure mode is enabled and the URL\'s scheme is not "https".',"jsonld.InvalidUrl",{code:"loading document failed",url:s});let d;try{d=await function(e,t,n){const o=new(e=e||XMLHttpRequest);return new Promise(((e,r)=>{o.onload=()=>e(o),o.onerror=e=>r(e),o.open("GET",t,!0);for(const e in n)o.setRequestHeader(e,n[e]);o.send()}))}(n,s,t)}catch(e){throw new i("URL could not be dereferenced, an error occurred.","jsonld.LoadDocumentError",{code:"loading document failed",url:s,cause:e})}if(d.status>=400)throw new i("URL could not be dereferenced: "+d.statusText,"jsonld.LoadDocumentError",{code:"loading document failed",url:s,httpStatusCode:d.status});let u={contextUrl:null,documentUrl:s,document:d.response},p=null;const h=d.getResponseHeader("Content-Type");let f;if(c.test(d.getAllResponseHeaders())&&(f=d.getResponseHeader("Link")),f&&"application/ld+json"!==h){const e=o(f),t=e[a];if(Array.isArray(t))throw new i("URL could not be dereferenced, it has more than one associated HTTP Link Header.","jsonld.InvalidUrl",{code:"multiple context link headers",url:s});t&&(u.contextUrl=t.target),p=e.alternate,p&&"application/ld+json"==p.type&&!(h||"").match(/^application\/(\w*\+)?json$/)&&(u=await r(l(s,p.target)))}return u})))},2246:(e,t,n)=>{"use strict";var o=n(6763);const r=n(2207),{isArray:a}=n(7382),{asArray:i}=n(9263),s={};function l({event:e,handlers:t}){let n=!0;for(let o=0;n&&o{n=!0}});else{if("object"!=typeof i)throw new r("Invalid event handler.","jsonld.InvalidEventHandler",{event:e});e.code in i?i[e.code]({event:e,next:()=>{n=!0}}):n=!0}}return n}e.exports=s,s.defaultEventHandler=null,s.setupEventHandler=({options:e={}})=>{const t=[].concat(e.safe?s.safeEventHandler:[],e.eventHandler?i(e.eventHandler):[],s.defaultEventHandler?s.defaultEventHandler:[]);return 0===t.length?null:t},s.handleEvent=({event:e,options:t})=>{l({event:e,handlers:t.eventHandler})};const c=new Set(["empty object","free-floating scalar","invalid @language value","invalid property","null @id value","null @value value","object with only @id","object with only @language","object with only @list","object with only @value","relative @id reference","relative @type reference","relative @vocab reference","reserved @id value","reserved @reverse value","reserved term","blank node predicate","relative graph reference","relative object reference","relative predicate reference","relative subject reference","rdfDirection not set"]);s.safeEventHandler=function({event:e,next:t}){if("warning"===e.level&&c.has(e.code))throw new r("Safe mode validation error.","jsonld.ValidationError",{event:e});t()},s.logEventHandler=function({event:e,next:t}){o.log(`EVENT: ${e.message}`,{event:e}),t()},s.logWarningEventHandler=function({event:e,next:t}){"warning"===e.level&&o.warn(`WARNING: ${e.message}`,{event:e}),t()},s.unhandledEventHandler=function({event:e}){throw new r("No handler for event.","jsonld.UnhandledEvent",{event:e})},s.setDefaultEventHandler=function({eventHandler:e}={}){s.defaultEventHandler=e?i(e):null}},4019:(e,t,n)=>{"use strict";const o=n(2207),{isArray:r,isObject:a,isEmptyObject:i,isString:s,isUndefined:l}=n(7382),{isList:c,isValue:d,isGraph:u,isSubject:p}=n(3978),{expandIri:h,getContextValue:f,isKeyword:v,process:g,processingMode:y}=n(1972),{isAbsolute:m}=n(470),{REGEX_BCP47:x,REGEX_KEYWORD:b,addValue:w,asArray:j,getValues:I,validateTypeValue:N}=n(9263),{handleEvent:S}=n(2246),O={};function E({value:e,count:t,options:n}){if(0===t||"@value"in e||"@list"in e||1===t&&"@id"in e){if(n.eventHandler){let o,r;0===t?(o="empty object",r="Dropping empty object."):"@value"in e?(o="object with only @value",r="Dropping object with only @value."):"@list"in e?(o="object with only @list",r="Dropping object with only @list."):1===t&&"@id"in e&&(o="object with only @id",r="Dropping object with only @id."),S({event:{type:["JsonLdEvent"],code:o,level:"warning",message:r,details:{value:e}},options:n})}return null}return e}async function D({activeCtx:e,activeProperty:t,expandedActiveProperty:n,element:u,expandedParent:b,options:I={},insideList:k,typeKey:R,typeScopedContext:T}){const A=Object.keys(u).sort(),_=[];let M;const J=u[R]&&"@json"===h(e,r(u[R])?u[R][0]:u[R],{vocab:!0},{...I,typeExpansion:!0});for(const D of A){let k,R=u[D];if("@context"===D)continue;const A=h(e,D,{vocab:!0},I);if(null===A||!m(A)&&!v(A)){I.eventHandler&&S({event:{type:["JsonLdEvent"],code:"invalid property",level:"warning",message:"Dropping property that did not expand into an absolute IRI or keyword.",details:{property:D,expandedProperty:A}},options:I});continue}if(v(A)){if("@reverse"===n)throw new o("Invalid JSON-LD syntax; a keyword cannot be used as a @reverse property.","jsonld.SyntaxError",{code:"invalid reverse property map",value:R});if(A in b&&"@included"!==A&&"@type"!==A)throw new o("Invalid JSON-LD syntax; colliding keywords detected.","jsonld.SyntaxError",{code:"colliding keywords",keyword:A})}if("@id"===A){if(!s(R)){if(!I.isFrame)throw new o('Invalid JSON-LD syntax; "@id" value must a string.',"jsonld.SyntaxError",{code:"invalid @id value",value:R});if(a(R)){if(!i(R))throw new o('Invalid JSON-LD syntax; "@id" value an empty object or array of strings, if framing',"jsonld.SyntaxError",{code:"invalid @id value",value:R})}else{if(!r(R))throw new o('Invalid JSON-LD syntax; "@id" value an empty object or array of strings, if framing',"jsonld.SyntaxError",{code:"invalid @id value",value:R});if(!R.every((e=>s(e))))throw new o('Invalid JSON-LD syntax; "@id" value an empty object or array of strings, if framing',"jsonld.SyntaxError",{code:"invalid @id value",value:R})}}w(b,"@id",j(R).map((t=>{if(s(t)){const n=h(e,t,{base:!0},I);return I.eventHandler&&(null===n?S(null===t?{event:{type:["JsonLdEvent"],code:"null @id value",level:"warning",message:"Null @id found.",details:{id:t}},options:I}:{event:{type:["JsonLdEvent"],code:"reserved @id value",level:"warning",message:"Reserved @id found.",details:{id:t}},options:I}):m(n)||S({event:{type:["JsonLdEvent"],code:"relative @id reference",level:"warning",message:"Relative @id reference found.",details:{id:t,expandedId:n}},options:I})),n}return t})),{propertyIsArray:I.isFrame});continue}if("@type"===A){a(R)&&(R=Object.fromEntries(Object.entries(R).map((([e,t])=>[h(T,e,{vocab:!0}),j(t).map((e=>h(T,e,{base:!0,vocab:!0},{...I,typeExpansion:!0})))])))),N(R,I.isFrame),w(b,"@type",j(R).map((e=>{if(s(e)){const t=h(T,e,{base:!0,vocab:!0},{...I,typeExpansion:!0});return"@json"===t||m(t)||I.eventHandler&&S({event:{type:["JsonLdEvent"],code:"relative @type reference",level:"warning",message:"Relative @type reference found.",details:{type:e}},options:I}),t}return e})),{propertyIsArray:!!I.isFrame});continue}if("@included"===A&&y(e,1.1)){const n=j(await O.expand({activeCtx:e,activeProperty:t,element:R,options:I}));if(!n.every((e=>p(e))))throw new o("Invalid JSON-LD syntax; values of @included must expand to node objects.","jsonld.SyntaxError",{code:"invalid @included value",value:R});w(b,"@included",n,{propertyIsArray:!0});continue}if("@graph"===A&&!a(R)&&!r(R))throw new o('Invalid JSON-LD syntax; "@graph" value must not be an object or an array.',"jsonld.SyntaxError",{code:"invalid @graph value",value:R});if("@value"===A){M=R,J&&y(e,1.1)?b["@value"]=R:w(b,"@value",R,{propertyIsArray:I.isFrame});continue}if("@language"===A){if(null===R)continue;if(!s(R)&&!I.isFrame)throw new o('Invalid JSON-LD syntax; "@language" value must be a string.',"jsonld.SyntaxError",{code:"invalid language-tagged string",value:R});R=j(R).map((e=>s(e)?e.toLowerCase():e));for(const e of R)s(e)&&!e.match(x)&&I.eventHandler&&S({event:{type:["JsonLdEvent"],code:"invalid @language value",level:"warning",message:"@language value must be valid BCP47.",details:{language:e}},options:I});w(b,"@language",R,{propertyIsArray:I.isFrame});continue}if("@direction"===A){if(!s(R)&&!I.isFrame)throw new o('Invalid JSON-LD syntax; "@direction" value must be a string.',"jsonld.SyntaxError",{code:"invalid base direction",value:R});R=j(R);for(const e of R)if(s(e)&&"ltr"!==e&&"rtl"!==e)throw new o('Invalid JSON-LD syntax; "@direction" must be "ltr" or "rtl".',"jsonld.SyntaxError",{code:"invalid base direction",value:R});w(b,"@direction",R,{propertyIsArray:I.isFrame});continue}if("@index"===A){if(!s(R))throw new o('Invalid JSON-LD syntax; "@index" value must be a string.',"jsonld.SyntaxError",{code:"invalid @index value",value:R});w(b,"@index",R);continue}if("@reverse"===A){if(!a(R))throw new o('Invalid JSON-LD syntax; "@reverse" value must be an object.',"jsonld.SyntaxError",{code:"invalid @reverse value",value:R});if(k=await O.expand({activeCtx:e,activeProperty:"@reverse",element:R,options:I}),"@reverse"in k)for(const e in k["@reverse"])w(b,e,k["@reverse"][e],{propertyIsArray:!0});let t=b["@reverse"]||null;for(const e in k){if("@reverse"===e)continue;null===t&&(t=b["@reverse"]={}),w(t,e,[],{propertyIsArray:!0});const n=k[e];for(let r=0;r"@id"===e||"@index"===e))){if(k=j(k),I.isFrame||(k=k.filter((e=>null!==E({value:e,count:Object.keys(e).length,options:I})))),0===k.length)continue;k=k.map((e=>({"@graph":j(e)})))}if(P.mappings.has(D)&&P.mappings.get(D).reverse){const e=b["@reverse"]=b["@reverse"]||{};k=j(k);for(let t=0;t"@value"===h(e,t,{vocab:!0},I))))throw new o("Invalid JSON-LD syntax; nested value must be a node object.","jsonld.SyntaxError",{code:"invalid @nest value",value:r});await D({activeCtx:e,activeProperty:t,expandedActiveProperty:n,element:r,expandedParent:b,options:I,insideList:k,typeScopedContext:T,typeKey:R})}}}function k({activeCtx:e,activeProperty:t,value:n,options:o}){if(null==n)return null;const r=h(e,t,{vocab:!0},o);if("@id"===r)return h(e,n,{base:!0},o);if("@type"===r)return h(e,n,{vocab:!0,base:!0},{...o,typeExpansion:!0});const a=f(e,t,"@type");if(("@id"===a||"@graph"===r)&&s(n)){const r=h(e,n,{base:!0},o);return null===r&&n.match(b)&&o.eventHandler&&S({event:{type:["JsonLdEvent"],code:"reserved @id value",level:"warning",message:"Reserved @id found.",details:{id:t}},options:o}),{"@id":r}}if("@vocab"===a&&s(n))return{"@id":h(e,n,{vocab:!0,base:!0},o)};if(v(r))return n;const i={};if(a&&!["@id","@vocab","@none"].includes(a))i["@type"]=a;else if(s(n)){const n=f(e,t,"@language");null!==n&&(i["@language"]=n);const o=f(e,t,"@direction");null!==o&&(i["@direction"]=o)}return["boolean","number","string"].includes(typeof n)||(n=n.toString()),i["@value"]=n,i}function C(e,t,n,a){const i=[],l=Object.keys(t).sort();for(const c of l){const l=h(e,c,{vocab:!0},a);let d=t[c];r(d)||(d=[d]);for(const e of d){if(null===e)continue;if(!s(e))throw new o("Invalid JSON-LD syntax; language map values must be strings.","jsonld.SyntaxError",{code:"invalid language map value",languageMap:t});const r={"@value":e};"@none"!==l&&(c.match(x)||a.eventHandler&&S({event:{type:["JsonLdEvent"],code:"invalid @language value",level:"warning",message:"@language value must be valid BCP47.",details:{language:c}},options:a}),r["@language"]=c.toLowerCase()),n&&(r["@direction"]=n),i.push(r)}}return i}async function L({activeCtx:e,options:t,activeProperty:n,value:a,asGraph:i,indexKey:s,propertyIndex:c}){const p=[],v=Object.keys(a).sort(),y="@type"===s;for(let m of v){if(y){const n=f(e,m,"@context");l(n)||(e=await g({activeCtx:e,localCtx:n,propagate:!1,options:t}))}let v,x=a[m];r(x)||(x=[x]),x=await O.expand({activeCtx:e,activeProperty:n,element:x,options:t,insideList:!1,insideIndex:!0}),v=c?"@none"===m?"@none":k({activeCtx:e,activeProperty:s,value:m,options:t}):h(e,m,{vocab:!0},t),"@id"===s?m=h(e,m,{base:!0},t):y&&(m=v);for(let e of x){if(i&&!u(e)&&(e={"@graph":[e]}),"@type"===s)"@none"===v||(e["@type"]?e["@type"]=[m].concat(e["@type"]):e["@type"]=[m]);else{if(d(e)&&!["@language","@type","@index"].includes(s))throw new o(`Invalid JSON-LD syntax; Attempt to add illegal key to value object: "${s}".`,"jsonld.SyntaxError",{code:"invalid value object",value:e});c?"@none"!==v&&w(e,c,v,{propertyIsArray:!0,prependValue:!0}):"@none"===v||s in e||(e[s]=m)}p.push(e)}}return p}e.exports=O,O.expand=async({activeCtx:e,activeProperty:t=null,element:n,options:c={},insideList:d=!1,insideIndex:u=!1,typeScopedContext:p=null})=>{if(null==n)return null;if("@default"===t&&(c=Object.assign({},c,{isFrame:!1})),!r(n)&&!a(n))return d||null!==t&&"@graph"!==h(e,t,{vocab:!0},c)?k({activeCtx:e,activeProperty:t,value:n,options:c}):(c.eventHandler&&S({event:{type:["JsonLdEvent"],code:"free-floating scalar",level:"warning",message:"Dropping free-floating scalar not in a list.",details:{value:n}},options:c}),null);if(r(n)){let o=[];const a=f(e,t,"@container")||[];d=d||a.includes("@list");for(let a=0;a1?o.slice().sort():o:[o];for(const t of r){const n=f(p,t,"@context");l(n)||(e=await g({activeCtx:e,localCtx:n,options:c,propagate:!1}))}}let C={};await D({activeCtx:e,activeProperty:t,expandedActiveProperty:v,element:n,expandedParent:C,options:c,insideList:d,typeKey:N,typeScopedContext:p}),b=Object.keys(C);let L=b.length;if("@value"in C){if("@type"in C&&("@language"in C||"@direction"in C))throw new o('Invalid JSON-LD syntax; an element containing "@value" may not contain both "@type" and either "@language" or "@direction".',"jsonld.SyntaxError",{code:"invalid value object",element:C});let t=L-1;if("@type"in C&&(t-=1),"@index"in C&&(t-=1),"@language"in C&&(t-=1),"@direction"in C&&(t-=1),0!==t)throw new o('Invalid JSON-LD syntax; an element containing "@value" may only have an "@index" property and either "@type" or either or both "@language" or "@direction".',"jsonld.SyntaxError",{code:"invalid value object",element:C});const n=null===C["@value"]?[]:j(C["@value"]),r=I(C,"@type");if(y(e,1.1)&&r.includes("@json")&&1===r.length);else if(0===n.length)c.eventHandler&&S({event:{type:["JsonLdEvent"],code:"null @value value",level:"warning",message:"Dropping null @value value.",details:{value:C}},options:c}),C=null;else{if(!n.every((e=>s(e)||i(e)))&&"@language"in C)throw new o("Invalid JSON-LD syntax; only strings may be language-tagged.","jsonld.SyntaxError",{code:"invalid language-tagged value",element:C});if(!r.every((e=>m(e)&&!(s(e)&&0===e.indexOf("_:"))||i(e))))throw new o('Invalid JSON-LD syntax; an element containing "@value" and "@type" must have an absolute IRI for the value of "@type".',"jsonld.SyntaxError",{code:"invalid typed value",element:C})}}else if("@type"in C&&!r(C["@type"]))C["@type"]=[C["@type"]];else if("@set"in C||"@list"in C){if(L>1&&(2!==L||!("@index"in C)))throw new o('Invalid JSON-LD syntax; if an element has the property "@set" or "@list", then it can have at most one other property that is "@index".',"jsonld.SyntaxError",{code:"invalid set or list object",element:C});"@set"in C&&(C=C["@set"],b=Object.keys(C),L=b.length)}else 1===L&&"@language"in C&&(c.eventHandler&&S({event:{type:["JsonLdEvent"],code:"object with only @language",level:"warning",message:"Dropping object with only @language.",details:{value:C}},options:c}),C=null);return!a(C)||c.keepFreeFloatingNodes||d||null!==t&&"@graph"!==v&&!(f(e,t,"@container")||[]).includes("@graph")||(C=E({value:C,count:L,options:c})),C}},5229:(e,t,n)=>{"use strict";const{isSubjectReference:o}=n(3978),{createMergedNodeMap:r}=n(9233),a={};e.exports=a,a.flatten=e=>{const t=r(e),n=[],a=Object.keys(t).sort();for(let e=0;e{"use strict";const{isKeyword:o}=n(1972),r=n(3978),a=n(7382),i=n(9263),s=n(470),l=n(2207),{createNodeMap:c,mergeNodeMapGraphs:d}=n(9233),u={};function p(e){const t={};for(const n in e)void 0!==e[n]&&(t["@"+n]=[e[n]]);return[t]}function h(e,t,n){for(let o=n.length-1;o>=0;--o){const r=n[o];if(r.graph===t&&r.subject["@id"]===e["@id"])return!0}return!1}function f(e,t,n){const o="@"+n;let r=o in e?e[o][0]:t[n];if("embed"===n)if(!0===r)r="@once";else if(!1===r)r="@never";else if("@always"!==r&&"@never"!==r&&"@link"!==r&&"@first"!==r&&"@last"!==r&&"@once"!==r)throw new l("Invalid JSON-LD syntax; invalid value of @embed.","jsonld.SyntaxError",{code:"invalid @embed value",frame:e});return r}function v(e){if(!a.isArray(e)||1!==e.length||!a.isObject(e[0]))throw new l("Invalid JSON-LD syntax; a JSON-LD frame must be a single object.","jsonld.SyntaxError",{frame:e});if("@id"in e[0])for(const t of i.asArray(e[0]["@id"]))if(!a.isObject(t)&&!s.isAbsolute(t)||a.isString(t)&&0===t.indexOf("_:"))throw new l("Invalid JSON-LD syntax; invalid @id in frame.","jsonld.SyntaxError",{code:"invalid frame",frame:e});if("@type"in e[0])for(const t of i.asArray(e[0]["@type"]))if(!a.isObject(t)&&!s.isAbsolute(t)&&"@json"!==t||a.isString(t)&&0===t.indexOf("_:"))throw new l("Invalid JSON-LD syntax; invalid @type in frame.","jsonld.SyntaxError",{code:"invalid frame",frame:e})}function g(e,t,n,s){let l=!0,c=!1;for(const d in n){let u=!1;const p=i.getValues(t,d),h=0===i.getValues(n,d).length;if("@id"===d){if(a.isEmptyObject(n["@id"][0]||{})?u=!0:n["@id"].length>=0&&(u=n["@id"].includes(p[0])),!s.requireAll)return u}else if("@type"===d){if(l=!1,h){if(p.length>0)return!1;u=!0}else if(1===n["@type"].length&&a.isEmptyObject(n["@type"][0]))u=p.length>0;else for(const e of n["@type"])u=!(!a.isObject(e)||!("@default"in e))||u||p.some((t=>t===e));if(!s.requireAll)return u}else{if(o(d))continue;{const t=i.getValues(n,d)[0];let o=!1;if(t&&(v([t]),o="@default"in t),l=!1,0===p.length&&o)continue;if(p.length>0&&h)return!1;if(void 0===t){if(p.length>0)return!1;u=!0}else if(r.isList(t)){const n=t["@list"][0];if(r.isList(p[0])){const t=p[0]["@list"];r.isValue(n)?u=t.some((e=>w(n,e))):(r.isSubject(n)||r.isSubjectReference(n))&&(u=t.some((t=>b(e,n,t,s))))}}else u=r.isValue(t)?p.some((e=>w(t,e))):r.isSubjectReference(t)?p.some((n=>b(e,t,n,s))):!!a.isObject(t)&&p.length>0}}if(!u&&s.requireAll)return!1;c=c||u}return l||c}function y(e,t){const n=e.uniqueEmbeds[e.graph],o=n[t],r=o.parent,s=o.property,l={"@id":t};if(a.isArray(r)){for(let e=0;e{const t=Object.keys(n);for(const o of t)o in n&&a.isObject(n[o].parent)&&n[o].parent["@id"]===e&&(delete n[o],c(o))};c(t)}function m(e,t){if(a.isArray(e))return e.map((e=>m(e,t)));if(a.isObject(e)){if("@preserve"in e)return e["@preserve"][0];if(r.isValue(e))return e;if(r.isList(e))return e["@list"]=m(e["@list"],t),e;if("@id"in e){const n=e["@id"];if(t.link.hasOwnProperty(n)){const o=t.link[n].indexOf(e);if(-1!==o)return t.link[n][o];t.link[n].push(e)}else t.link[n]=[e]}for(const n in e)"@id"===n&&t.bnodesToClear.includes(e[n])?delete e["@id"]:e[n]=m(e[n],t)}return e}function x(e,t,n){a.isObject(e)?i.addValue(e,t,n,{propertyIsArray:!0}):e.push(n)}function b(e,t,n,o){if(!("@id"in n))return!1;const r=e.subjects[n["@id"]];return r&&g(e,r,t,o)}function w(e,t){const n=t["@value"],o=t["@type"],r=t["@language"],i=e["@value"]?a.isArray(e["@value"])?e["@value"]:[e["@value"]]:[],s=e["@type"]?a.isArray(e["@type"])?e["@type"]:[e["@type"]]:[],l=e["@language"]?a.isArray(e["@language"])?e["@language"]:[e["@language"]]:[];return 0===i.length&&0===s.length&&0===l.length||!(!i.includes(n)&&!a.isEmptyObject(i[0]))&&!!(!o&&0===s.length||s.includes(o)||o&&a.isEmptyObject(s[0]))&&!!(!r&&0===l.length||l.includes(r)||r&&a.isEmptyObject(l[0]))}e.exports=u,u.frameMergedOrDefault=(e,t,n)=>{const o={options:n,embedded:!1,graph:"@default",graphMap:{"@default":{}},subjectStack:[],link:{},bnodeMap:{}},r=new i.IdentifierIssuer("_:b");c(e,o.graphMap,"@default",r),n.merged&&(o.graphMap["@merged"]=d(o.graphMap),o.graph="@merged"),o.subjects=o.graphMap[o.graph];const a=[];return u.frame(o,Object.keys(o.subjects).sort(),t,a),n.pruneBlankNodeIdentifiers&&(n.bnodesToClear=Object.keys(o.bnodeMap).filter((e=>1===o.bnodeMap[e].length))),n.link={},m(a,n)},u.frame=(e,t,n,s,c=null)=>{v(n),n=n[0];const d=e.options,m={embed:f(n,d,"embed"),explicit:f(n,d,"explicit"),requireAll:f(n,d,"requireAll")};e.link.hasOwnProperty(e.graph)||(e.link[e.graph]={});const b=e.link[e.graph],j=function(e,t,n,o){const r={};for(const a of t){const t=e.graphMap[e.graph][a];g(e,t,n,o)&&(r[a]=t)}return r}(e,t,n,m),I=Object.keys(j).sort();for(const v of I){const g=j[v];if(null===c?e.uniqueEmbeds={[e.graph]:{}}:e.uniqueEmbeds[e.graph]=e.uniqueEmbeds[e.graph]||{},"@link"===m.embed&&v in b){x(s,c,b[v]);continue}const I={"@id":v};if(0===v.indexOf("_:")&&i.addValue(e.bnodeMap,v,I,{propertyIsArray:!0}),b[v]=I,("@first"===m.embed||"@last"===m.embed)&&e.is11)throw new l("Invalid JSON-LD syntax; invalid value of @embed.","jsonld.SyntaxError",{code:"invalid @embed value",frame:n});if(e.embedded||!e.uniqueEmbeds[e.graph].hasOwnProperty(v))if(!e.embedded||"@never"!==m.embed&&!h(g,e.graph,e.subjectStack))if(!e.embedded||"@first"!=m.embed&&"@once"!=m.embed||!e.uniqueEmbeds[e.graph].hasOwnProperty(v)){if("@last"===m.embed&&v in e.uniqueEmbeds[e.graph]&&y(e,v),e.uniqueEmbeds[e.graph][v]={parent:s,property:c},e.subjectStack.push({subject:g,graph:e.graph}),v in e.graphMap){let t=!1,o=null;"@graph"in n?(o=n["@graph"][0],t=!("@merged"===v||"@default"===v),a.isObject(o)||(o={})):(t="@merged"!==e.graph,o={}),t&&u.frame({...e,graph:v,embedded:!1},Object.keys(e.graphMap[v]).sort(),[o],I,"@graph")}"@included"in n&&u.frame({...e,embedded:!1},t,n["@included"],I,"@included");for(const t of Object.keys(g).sort())if(o(t)){if(I[t]=i.clone(g[t]),"@type"===t)for(const t of g["@type"])0===t.indexOf("_:")&&i.addValue(e.bnodeMap,t,I,{propertyIsArray:!0})}else if(!m.explicit||t in n)for(const o of g[t]){const a=t in n?n[t]:p(m);if(r.isList(o)){const a=n[t]&&n[t][0]&&n[t][0]["@list"]?n[t][0]["@list"]:p(m),s={"@list":[]};x(I,t,s);const l=o["@list"];for(const t of l)r.isSubjectReference(t)?u.frame({...e,embedded:!0},[t["@id"]],a,s,"@list"):x(s,"@list",i.clone(t))}else r.isSubjectReference(o)?u.frame({...e,embedded:!0},[o["@id"]],a,I,t):w(a[0],o)&&x(I,t,i.clone(o))}for(const e of Object.keys(n).sort()){if("@type"===e){if(!a.isObject(n[e][0])||!("@default"in n[e][0]))continue}else if(o(e))continue;const t=n[e][0]||{};if(!f(t,d,"omitDefault")&&!(e in I)){let n="@null";"@default"in t&&(n=i.clone(t["@default"])),a.isArray(n)||(n=[n]),I[e]=[{"@preserve":n}]}}for(const t of Object.keys(n["@reverse"]||{}).sort()){const o=n["@reverse"][t];for(const n of Object.keys(e.subjects))i.getValues(e.subjects[n],t).some((e=>e["@id"]===v))&&(I["@reverse"]=I["@reverse"]||{},i.addValue(I["@reverse"],t,[],{propertyIsArray:!0}),u.frame({...e,embedded:!0},[n],o,I["@reverse"][t],c))}x(s,c,I),e.subjectStack.pop()}else x(s,c,I);else x(s,c,I)}},u.cleanupNull=(e,t)=>{if(a.isArray(e))return e.map((e=>u.cleanupNull(e,t))).filter((e=>e));if("@null"===e)return null;if(a.isObject(e)){if("@id"in e){const n=e["@id"];if(t.link.hasOwnProperty(n)){const o=t.link[n].indexOf(e);if(-1!==o)return t.link[n][o];t.link[n].push(e)}else t.link[n]=[e]}for(const n in e)e[n]=u.cleanupNull(e[n],t)}return e}},3947:(e,t,n)=>{"use strict";const o=n(2207),r=n(3978),a=n(7382),{REGEX_BCP47:i,addValue:s}=n(9263),{handleEvent:l}=n(2246),{RDF_LIST:c,RDF_FIRST:d,RDF_REST:u,RDF_NIL:p,RDF_TYPE:h,RDF_JSON_LITERAL:f,XSD_BOOLEAN:v,XSD_DOUBLE:g,XSD_INTEGER:y,XSD_STRING:m}=n(9378),x={};function b(e,t,n,r){if(e.termType.endsWith("Node"))return{"@id":e.value};const s={"@value":e.value};if(e.language)e.language.match(i)||r.eventHandler&&l({event:{type:["JsonLdEvent"],code:"invalid @language value",level:"warning",message:"@language value must be valid BCP47.",details:{language:e.language}},options:r}),s["@language"]=e.language;else{let c=e.datatype.value;if(c||(c=m),c===f){c="@json";try{s["@value"]=JSON.parse(s["@value"])}catch(e){throw new o("JSON literal could not be parsed.","jsonld.InvalidJsonLiteral",{code:"invalid JSON literal",value:s["@value"],cause:e})}}if(t){if(c===v)"true"===s["@value"]?s["@value"]=!0:"false"===s["@value"]&&(s["@value"]=!1);else if(a.isNumeric(s["@value"]))if(c===y){const e=parseInt(s["@value"],10);e.toFixed(0)===s["@value"]&&(s["@value"]=e)}else c===g&&(s["@value"]=parseFloat(s["@value"]));[v,y,g,m].includes(c)||(s["@type"]=c)}else if("i18n-datatype"===n&&c.startsWith("https://www.w3.org/ns/i18n#")){const[,e,t]=c.split(/[#_]/);e.length>0&&(s["@language"]=e,e.match(i)||r.eventHandler&&l({event:{type:["JsonLdEvent"],code:"invalid @language value",level:"warning",message:"@language value must be valid BCP47.",details:{language:e}},options:r})),s["@direction"]=t}else c!==m&&(s["@type"]=c)}return s}e.exports=x,x.fromRDF=async(e,t)=>{const{useRdfType:n=!1,useNativeTypes:i=!1,rdfDirection:l=null}=t,f={},v={"@default":f},g={};if(l){if("compound-literal"===l)throw new o("Unsupported rdfDirection value.","jsonld.InvalidRdfDirection",{value:l});if("i18n-datatype"!==l)throw new o("Unknown rdfDirection value.","jsonld.InvalidRdfDirection",{value:l})}for(const o of e){const e="DefaultGraph"===o.graph.termType?"@default":o.graph.value;e in v||(v[e]={}),"@default"===e||e in f||(f[e]={"@id":e});const r=v[e],a=o.subject.value,c=o.predicate.value,d=o.object;a in r||(r[a]={"@id":a});const u=r[a],y=d.termType.endsWith("Node");if(y&&!(d.value in r)&&(r[d.value]={"@id":d.value}),c===h&&!n&&y){s(u,"@type",d.value,{propertyIsArray:!0});continue}const m=b(d,i,l,t);if(s(u,c,m,{propertyIsArray:!0}),y)if(d.value===p){const e=r[d.value];"usages"in e||(e.usages=[]),e.usages.push({node:u,property:c,value:m})}else d.value in g?g[d.value]=!1:g[d.value]={node:u,property:c,value:m}}for(const e in v){const t=v[e];if(!(p in t))continue;const n=t[p];if(n.usages){for(let e of n.usages){let n=e.node,o=e.property,i=e.value;const s=[],l=[];let p=Object.keys(n).length;for(;o===u&&a.isObject(g[n["@id"]])&&a.isArray(n[d])&&1===n[d].length&&a.isArray(n[u])&&1===n[u].length&&(3===p||4===p&&a.isArray(n["@type"])&&1===n["@type"].length&&n["@type"][0]===c)&&(s.push(n[d][0]),l.push(n["@id"]),e=g[n["@id"]],n=e.node,o=e.property,i=e.value,p=Object.keys(n).length,r.isBlankNode(n)););delete i["@id"],i["@list"]=s.reverse();for(const e of l)delete t[e]}delete n.usages}}const y=[],m=Object.keys(f).sort();for(const e of m){const t=f[e];if(e in v){const n=t["@graph"]=[],o=v[e],a=Object.keys(o).sort();for(const e of a){const t=o[e];r.isSubjectReference(t)||n.push(t)}}r.isSubjectReference(t)||y.push(t)}return y}},3978:(e,t,n)=>{"use strict";const o=n(7382),r={};e.exports=r,r.isSubject=e=>!(!o.isObject(e)||"@value"in e||"@set"in e||"@list"in e)&&(Object.keys(e).length>1||!("@id"in e)),r.isSubjectReference=e=>o.isObject(e)&&1===Object.keys(e).length&&"@id"in e,r.isValue=e=>o.isObject(e)&&"@value"in e,r.isList=e=>o.isObject(e)&&"@list"in e,r.isGraph=e=>o.isObject(e)&&"@graph"in e&&1===Object.keys(e).filter((e=>"@id"!==e&&"@index"!==e)).length,r.isSimpleGraph=e=>r.isGraph(e)&&!("@id"in e),r.isBlankNode=e=>{if(o.isObject(e)){if("@id"in e){const t=e["@id"];return!o.isString(t)||0===t.indexOf("_:")}return 0===Object.keys(e).length||!("@value"in e||"@set"in e||"@list"in e)}return!1}},4841:(e,t,n)=>{const o=n(989),r=n(701),a=n(9263),i=n(7034),s=a.IdentifierIssuer,l=n(2207),c=n(9749),d=n(8229),{expand:u}=n(4019),{flatten:p}=n(5229),{fromRDF:h}=n(3947),{toRDF:f}=n(9180),{frameMergedOrDefault:v,cleanupNull:g}=n(7946),{isArray:y,isObject:m,isString:x}=n(7382),{isSubjectReference:b}=n(3978),{expandIri:w,getInitialContext:j,process:I,processingMode:N}=n(1972),{compact:S,compactIri:O}=n(1058),{createNodeMap:E,createMergedNodeMap:D,mergeNodeMaps:k}=n(9233),{logEventHandler:C,logWarningEventHandler:L,safeEventHandler:R,setDefaultEventHandler:T,setupEventHandler:A,strictEventHandler:_,unhandledEventHandler:M}=n(2246),J=function(e){const t={},J=new c({max:100});function P(t,{documentLoader:n=e.documentLoader,...o}){if(t&&"compactionMap"in t)throw new l('"compactionMap" not supported.',"jsonld.OptionsError");if(t&&"expansionMap"in t)throw new l('"expansionMap" not supported.',"jsonld.OptionsError");return Object.assign({},{documentLoader:n},o,t,{eventHandler:A({options:t})})}return e.compact=async function(t,n,o){if(arguments.length<2)throw new TypeError("Could not compact, too few arguments.");if(null===n)throw new l("The compaction context must not be null.","jsonld.CompactError",{code:"invalid local context"});if(null===t)return null;let r;(o=P(o,{base:x(t)?t:"",compactArrays:!0,compactToRelative:!0,graph:!1,skipExpansion:!1,link:!1,issuer:new s("_:b"),contextResolver:new i({sharedCache:J})})).link&&(o.skipExpansion=!0),o.compactToRelative||delete o.base,r=o.skipExpansion?t:await e.expand(t,o);const c=await e.processContext(j(o),n,o);let d=await S({activeCtx:c,element:r,options:o});o.compactArrays&&!o.graph&&y(d)?1===d.length?d=d[0]:0===d.length&&(d={}):o.graph&&m(d)&&(d=[d]),m(n)&&"@context"in n&&(n=n["@context"]),n=a.clone(n),y(n)||(n=[n]);const u=n;n=[];for(let e=0;e0)&&n.push(u[e]);const p=n.length>0;if(1===n.length&&(n=n[0]),y(d)){const e=O({activeCtx:c,iri:"@graph",relativeTo:{vocab:!0}}),t=d;d={},p&&(d["@context"]=n),d[e]=t}else if(m(d)&&p){const e=d;d={"@context":n};for(const t in e)d[t]=e[t]}return d},e.expand=async function(t,n){if(arguments.length<1)throw new TypeError("Could not expand, too few arguments.");const o={},r=[];if("expandContext"in(n=P(n,{keepFreeFloatingNodes:!1,contextResolver:new i({sharedCache:J})}))){const e=a.clone(n.expandContext);m(e)&&"@context"in e?o.expandContext=e:o.expandContext={"@context":e},r.push(o.expandContext)}let s;if(x(t)){const a=await e.get(t,n);s=a.documentUrl,o.input=a.document,a.contextUrl&&(o.remoteContext={"@context":a.contextUrl},r.push(o.remoteContext))}else o.input=a.clone(t);"base"in n||(n.base=s||"");let l=j(n);for(const e of r)l=await I({activeCtx:l,localCtx:e,options:n});let c=await u({activeCtx:l,element:o.input,options:n});return m(c)&&"@graph"in c&&1===Object.keys(c).length?c=c["@graph"]:null===c&&(c=[]),y(c)||(c=[c]),c},e.flatten=async function(t,n,o){if(arguments.length<1)return new TypeError("Could not flatten, too few arguments.");n="function"==typeof n?null:n||null,o=P(o,{base:x(t)?t:"",contextResolver:new i({sharedCache:J})});const r=await e.expand(t,o),a=p(r);return null===n?a:(o.graph=!0,o.skipExpansion=!0,await e.compact(a,n,o))},e.frame=async function(t,n,o){if(arguments.length<2)throw new TypeError("Could not frame, too few arguments.");if(o=P(o,{base:x(t)?t:"",embed:"@once",explicit:!1,requireAll:!1,omitDefault:!1,bnodesToClear:[],contextResolver:new i({sharedCache:J})}),x(n)){const t=await e.get(n,o);if(n=t.document,t.contextUrl){let e=n["@context"];e?y(e)?e.push(t.contextUrl):e=[e,t.contextUrl]:e=t.contextUrl,n["@context"]=e}}const r=n&&n["@context"]||{},a=await e.processContext(j(o),r,o);o.hasOwnProperty("omitGraph")||(o.omitGraph=N(a,1.1)),o.hasOwnProperty("pruneBlankNodeIdentifiers")||(o.pruneBlankNodeIdentifiers=N(a,1.1));const s=await e.expand(t,o),l={...o};l.isFrame=!0,l.keepFreeFloatingNodes=!0;const c=await e.expand(n,l),d=Object.keys(n).map((e=>w(a,e,{vocab:!0})));l.merged=!d.includes("@graph"),l.is11=N(a,1.1);const u=v(s,c,l);l.graph=!o.omitGraph,l.skipExpansion=!0,l.link={},l.framing=!0;let p=await e.compact(u,r,l);return l.link={},p=g(p,l),p},e.link=async function(t,n,o){const r={};return n&&(r["@context"]=n),r["@embed"]="@link",e.frame(t,r,o)},e.normalize=e.canonize=async function(t,n){if(arguments.length<1)throw new TypeError("Could not canonize, too few arguments.");if("inputFormat"in(n=P(n,{base:x(t)?t:null,algorithm:"URDNA2015",skipExpansion:!1,safe:!0,contextResolver:new i({sharedCache:J})}))){if("application/n-quads"!==n.inputFormat&&"application/nquads"!==n.inputFormat)throw new l("Unknown canonicalization input format.","jsonld.CanonizeError");const e=d.parse(t);return o.canonize(e,n)}const r={...n};delete r.format,r.produceGeneralizedRdf=!1;const a=await e.toRDF(t,r);return o.canonize(a,n)},e.fromRDF=async function(e,n){if(arguments.length<1)throw new TypeError("Could not convert from RDF, too few arguments.");n=P(n,{format:x(e)?"application/n-quads":void 0});const{format:o}=n;let{rdfParser:r}=n;if(o){if(r=r||t[o],!r)throw new l("Unknown input format.","jsonld.UnknownFormat",{format:o})}else r=()=>e;const a=await r(e);return h(a,n)},e.toRDF=async function(t,n){if(arguments.length<1)throw new TypeError("Could not convert to RDF, too few arguments.");let o;o=(n=P(n,{base:x(t)?t:"",skipExpansion:!1,contextResolver:new i({sharedCache:J})})).skipExpansion?t:await e.expand(t,n);const r=f(o,n);if(n.format){if("application/n-quads"===n.format||"application/nquads"===n.format)return d.serialize(r);throw new l("Unknown output format.","jsonld.UnknownFormat",{format:n.format})}return r},e.createNodeMap=async function(t,n){if(arguments.length<1)throw new TypeError("Could not create node map, too few arguments.");n=P(n,{base:x(t)?t:"",contextResolver:new i({sharedCache:J})});const o=await e.expand(t,n);return D(o,n)},e.merge=async function(t,n,o){if(arguments.length<1)throw new TypeError("Could not merge, too few arguments.");if(!y(t))throw new TypeError('Could not merge, "docs" must be an array.');n="function"==typeof n?null:n||null,o=P(o,{contextResolver:new i({sharedCache:J})});const r=await Promise.all(t.map((t=>{const n={...o};return e.expand(t,n)})));let l=!0;"mergeNodes"in o&&(l=o.mergeNodes);const c=o.issuer||new s("_:b"),d={"@default":{}};for(let e=0;ee._documentLoader,set:t=>e._documentLoader=t}),e.documentLoader=async e=>{throw new l("Could not retrieve a JSON-LD document from the URL. URL dereferencing not implemented.","jsonld.LoadDocumentError",{code:"loading document failed",url:e})},e.get=async function(t,n){let o;o="function"==typeof n.documentLoader?n.documentLoader:e.documentLoader;const r=await o(t);try{if(!r.document)throw new l("No remote document found at the given URL.","jsonld.NullRemoteDocument");x(r.document)&&(r.document=JSON.parse(r.document))}catch(e){throw new l("Could not retrieve a JSON-LD document from the URL.","jsonld.LoadDocumentError",{code:"loading document failed",cause:e,remoteDoc:r})}return r},e.processContext=async function(e,t,n){return n=P(n,{base:"",contextResolver:new i({sharedCache:J})}),null===t?j(n):(t=a.clone(t),m(t)&&"@context"in t||(t={"@context":t}),I({activeCtx:e,localCtx:t,options:n}))},e.getContextValue=n(1972).getContextValue,e.documentLoaders={},e.useDocumentLoader=function(t){if(!(t in e.documentLoaders))throw new l('Unknown document loader type: "'+t+'"',"jsonld.UnknownDocumentLoader",{type:t});e.documentLoader=e.documentLoaders[t].apply(e,Array.prototype.slice.call(arguments,1))},e.registerRDFParser=function(e,n){t[e]=n},e.unregisterRDFParser=function(e){delete t[e]},e.registerRDFParser("application/n-quads",d.parse),e.registerRDFParser("application/nquads",d.parse),e.url=n(470),e.logEventHandler=C,e.logWarningEventHandler=L,e.safeEventHandler=R,e.setDefaultEventHandler=T,e.strictEventHandler=_,e.unhandledEventHandler=M,e.util=a,Object.assign(e,a),e.promises=e,e.RequestQueue=n(3743),e.JsonLdProcessor=n(5445)(e),r.setupGlobals(e),r.setupDocumentLoaders(e),e},P=function(){return J((function(){return P()}))};J(P),e.exports=P},9233:(e,t,n)=>{"use strict";const{isKeyword:o}=n(1972),r=n(3978),a=n(7382),i=n(9263),s=n(2207),l={};e.exports=l,l.createMergedNodeMap=(e,t)=>{const n=(t=t||{}).issuer||new i.IdentifierIssuer("_:b"),o={"@default":{}};return l.createNodeMap(e,o,"@default",n),l.mergeNodeMaps(o)},l.createNodeMap=(e,t,n,c,d,u)=>{if(a.isArray(e)){for(const o of e)l.createNodeMap(o,t,n,c,void 0,u);return}if(!a.isObject(e))return void(u&&u.push(e));if(r.isValue(e)){if("@type"in e){let t=e["@type"];0===t.indexOf("_:")&&(e["@type"]=t=c.getId(t))}return void(u&&u.push(e))}if(u&&r.isList(e)){const o=[];return l.createNodeMap(e["@list"],t,n,c,d,o),void u.push({"@list":o})}if("@type"in e){const t=e["@type"];for(const e of t)0===e.indexOf("_:")&&c.getId(e)}a.isUndefined(d)&&(d=r.isBlankNode(e)?c.getId(e["@id"]):e["@id"]),u&&u.push({"@id":d});const p=t[n],h=p[d]=p[d]||{};h["@id"]=d;const f=Object.keys(e).sort();for(let a of f){if("@id"===a)continue;if("@reverse"===a){const o={"@id":d},a=e["@reverse"];for(const e in a){const s=a[e];for(const a of s){let s=a["@id"];r.isBlankNode(a)&&(s=c.getId(s)),l.createNodeMap(a,t,n,c,s),i.addValue(p[s],e,o,{propertyIsArray:!0,allowDuplicate:!1})}}continue}if("@graph"===a){d in t||(t[d]={}),l.createNodeMap(e[a],t,d,c);continue}if("@included"===a){l.createNodeMap(e[a],t,n,c);continue}if("@type"!==a&&o(a)){if("@index"===a&&a in h&&(e[a]!==h[a]||e[a]["@id"]!==h[a]["@id"]))throw new s("Invalid JSON-LD syntax; conflicting @index property detected.","jsonld.SyntaxError",{code:"conflicting indexes",subject:h});h[a]=e[a];continue}const u=e[a];if(0===a.indexOf("_:")&&(a=c.getId(a)),0!==u.length)for(let e of u)if("@type"===a&&(e=0===e.indexOf("_:")?c.getId(e):e),r.isSubject(e)||r.isSubjectReference(e)){if("@id"in e&&!e["@id"])continue;const o=r.isBlankNode(e)?c.getId(e["@id"]):e["@id"];i.addValue(h,a,{"@id":o},{propertyIsArray:!0,allowDuplicate:!1}),l.createNodeMap(e,t,n,c,o)}else if(r.isValue(e))i.addValue(h,a,e,{propertyIsArray:!0,allowDuplicate:!1});else if(r.isList(e)){const o=[];l.createNodeMap(e["@list"],t,n,c,d,o),e={"@list":o},i.addValue(h,a,e,{propertyIsArray:!0,allowDuplicate:!1})}else l.createNodeMap(e,t,n,c,d),i.addValue(h,a,e,{propertyIsArray:!0,allowDuplicate:!1});else i.addValue(h,a,[],{propertyIsArray:!0})}},l.mergeNodeMapGraphs=e=>{const t={};for(const n of Object.keys(e).sort())for(const r of Object.keys(e[n]).sort()){const a=e[n][r];r in t||(t[r]={"@id":r});const s=t[r];for(const e of Object.keys(a).sort())if(o(e)&&"@type"!==e)s[e]=i.clone(a[e]);else for(const t of a[e])i.addValue(s,e,i.clone(t),{propertyIsArray:!0,allowDuplicate:!1})}return t},l.mergeNodeMaps=e=>{const t=e["@default"],n=Object.keys(e).sort();for(const o of n){if("@default"===o)continue;const n=e[o];let a=t[o];a?"@graph"in a||(a["@graph"]=[]):t[o]=a={"@id":o,"@graph":[]};const i=a["@graph"];for(const e of Object.keys(n).sort()){const t=n[e];r.isSubjectReference(t)||i.push(t)}}return t}},701:(e,t,n)=>{"use strict";const o=n(6957),r={};e.exports=r,r.setupDocumentLoaders=function(e){"undefined"!=typeof XMLHttpRequest&&(e.documentLoaders.xhr=o,e.useDocumentLoader("xhr"))},r.setupGlobals=function(e){void 0===globalThis.JsonLdProcessor&&Object.defineProperty(globalThis,"JsonLdProcessor",{writable:!0,enumerable:!1,configurable:!0,value:e.JsonLdProcessor})}},9180:(e,t,n)=>{"use strict";const{createNodeMap:o}=n(9233),{isKeyword:r}=n(1972),a=n(3978),i=n(2341),s=n(2207),l=n(7382),c=n(9263),{handleEvent:d}=n(2246),{RDF_FIRST:u,RDF_REST:p,RDF_NIL:h,RDF_TYPE:f,RDF_JSON_LITERAL:v,RDF_LANGSTRING:g,XSD_BOOLEAN:y,XSD_DOUBLE:m,XSD_INTEGER:x,XSD_STRING:b}=n(9378),{isAbsolute:w}=n(470),j={};function I(e,t,n,o,a){const i=Object.keys(t).sort();for(const s of i){const i=t[s],l=Object.keys(i).sort();for(let t of l){const l=i[t];if("@type"===t)t=f;else if(r(t))continue;for(const r of l){const i={termType:s.startsWith("_:")?"BlankNode":"NamedNode",value:s};if(!w(s)){a.eventHandler&&d({event:{type:["JsonLdEvent"],code:"relative subject reference",level:"warning",message:"Relative subject reference found.",details:{subject:s}},options:a});continue}const l={termType:t.startsWith("_:")?"BlankNode":"NamedNode",value:t};if(!w(t)){a.eventHandler&&d({event:{type:["JsonLdEvent"],code:"relative predicate reference",level:"warning",message:"Relative predicate reference found.",details:{predicate:t}},options:a});continue}if("BlankNode"===l.termType&&!a.produceGeneralizedRdf){a.eventHandler&&d({event:{type:["JsonLdEvent"],code:"blank node predicate",level:"warning",message:"Dropping blank node predicate.",details:{property:o.getOldIds().find((e=>o.getId(e)===t))}},options:a});continue}const c=N(r,o,e,n,a.rdfDirection,a);c&&e.push({subject:i,predicate:l,object:c,graph:n})}}}}function N(e,t,n,o,r,c){const f={};if(a.isValue(e)){f.termType="Literal",f.value=void 0,f.datatype={termType:"NamedNode"};let t=e["@value"];const n=e["@type"]||null;if("@json"===n)f.value=i(t),f.datatype.value=v;else if(l.isBoolean(t))f.value=t.toString(),f.datatype.value=n||y;else if(l.isDouble(t)||n===m)l.isDouble(t)||(t=parseFloat(t)),f.value=t.toExponential(15).replace(/(\d)0*e\+?/,"$1E"),f.datatype.value=n||m;else if(l.isNumber(t))f.value=t.toFixed(0),f.datatype.value=n||x;else if("@direction"in e&&"i18n-datatype"===r){const n=`https://www.w3.org/ns/i18n#${(e["@language"]||"").toLowerCase()}_${e["@direction"]}`;f.datatype.value=n,f.value=t}else{if("@direction"in e&&"compound-literal"===r)throw new s("Unsupported rdfDirection value.","jsonld.InvalidRdfDirection",{value:r});if("@direction"in e&&r)throw new s("Unknown rdfDirection value.","jsonld.InvalidRdfDirection",{value:r});"@language"in e?("@direction"in e&&!r&&c.eventHandler&&d({event:{type:["JsonLdEvent"],code:"rdfDirection not set",level:"warning",message:"rdfDirection not set for @direction.",details:{object:f.value}},options:c}),f.value=t,f.datatype.value=n||g,f.language=e["@language"]):("@direction"in e&&!r&&c.eventHandler&&d({event:{type:["JsonLdEvent"],code:"rdfDirection not set",level:"warning",message:"rdfDirection not set for @direction.",details:{object:f.value}},options:c}),f.value=t,f.datatype.value=n||b)}}else if(a.isList(e)){const a=function(e,t,n,o,r,a){const i={termType:"NamedNode",value:u},s={termType:"NamedNode",value:p},l={termType:"NamedNode",value:h},c=e.pop(),d=c?{termType:"BlankNode",value:t.getId()}:l;let f=d;for(const l of e){const e=N(l,t,n,o,r,a),c={termType:"BlankNode",value:t.getId()};n.push({subject:f,predicate:i,object:e,graph:o}),n.push({subject:f,predicate:s,object:c,graph:o}),f=c}if(c){const e=N(c,t,n,o,r,a);n.push({subject:f,predicate:i,object:e,graph:o}),n.push({subject:f,predicate:s,object:l,graph:o})}return d}(e["@list"],t,n,o,r,c);f.termType=a.termType,f.value=a.value}else{const t=l.isObject(e)?e["@id"]:e;f.termType=t.startsWith("_:")?"BlankNode":"NamedNode",f.value=t}return"NamedNode"!==f.termType||w(f.value)?f:(c.eventHandler&&d({event:{type:["JsonLdEvent"],code:"relative object reference",level:"warning",message:"Relative object reference found.",details:{object:f.value}},options:c}),null)}e.exports=j,j.toRDF=(e,t)=>{const n=new c.IdentifierIssuer("_:b"),r={"@default":{}};o(e,r,"@default",n);const a=[],i=Object.keys(r).sort();for(const e of i){let o;if("@default"===e)o={termType:"DefaultGraph",value:""};else{if(!w(e)){t.eventHandler&&d({event:{type:["JsonLdEvent"],code:"relative graph reference",level:"warning",message:"Relative graph reference found.",details:{graph:e}},options:t});continue}o=e.startsWith("_:")?{termType:"BlankNode"}:{termType:"NamedNode"},o.value=e}I(a,r[e],o,n,t)}return a}},7382:e=>{"use strict";const t={};e.exports=t,t.isArray=Array.isArray,t.isBoolean=e=>"boolean"==typeof e||"[object Boolean]"===Object.prototype.toString.call(e),t.isDouble=e=>t.isNumber(e)&&(-1!==String(e).indexOf(".")||Math.abs(e)>=1e21),t.isEmptyObject=e=>t.isObject(e)&&0===Object.keys(e).length,t.isNumber=e=>"number"==typeof e||"[object Number]"===Object.prototype.toString.call(e),t.isNumeric=e=>!isNaN(parseFloat(e))&&isFinite(e),t.isObject=e=>"[object Object]"===Object.prototype.toString.call(e),t.isString=e=>"string"==typeof e||"[object String]"===Object.prototype.toString.call(e),t.isUndefined=e=>void 0===e},470:(e,t,n)=>{"use strict";const o=n(7382),r={};e.exports=r,r.parsers={simple:{keys:["href","scheme","authority","path","query","fragment"],regex:/^(?:([^:\/?#]+):)?(?:\/\/([^\/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?/},full:{keys:["href","protocol","scheme","authority","auth","user","password","hostname","port","path","directory","file","query","fragment"],regex:/^(([a-zA-Z][a-zA-Z0-9+-.]*):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?(?:(((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/}},r.parse=(e,t)=>{const n={},o=r.parsers[t||"full"],a=o.regex.exec(e);let i=o.keys.length;for(;i--;)n[o.keys[i]]=void 0===a[i]?null:a[i];return("https"===n.scheme&&"443"===n.port||"http"===n.scheme&&"80"===n.port)&&(n.href=n.href.replace(":"+n.port,""),n.authority=n.authority.replace(":"+n.port,""),n.port=null),n.normalizedPath=r.removeDotSegments(n.path),n},r.prependBase=(e,t)=>{if(null===e)return t;if(r.isAbsolute(t))return t;e&&!o.isString(e)||(e=r.parse(e||""));const n=r.parse(t),a={protocol:e.protocol||""};if(null!==n.authority)a.authority=n.authority,a.path=n.path,a.query=n.query;else if(a.authority=e.authority,""===n.path)a.path=e.path,null!==n.query?a.query=n.query:a.query=e.query;else{if(0===n.path.indexOf("/"))a.path=n.path;else{let t=e.path;t=t.substr(0,t.lastIndexOf("/")+1),(t.length>0||e.authority)&&"/"!==t.substr(-1)&&(t+="/"),t+=n.path,a.path=t}a.query=n.query}""!==n.path&&(a.path=r.removeDotSegments(a.path));let i=a.protocol;return null!==a.authority&&(i+="//"+a.authority),i+=a.path,null!==a.query&&(i+="?"+a.query),null!==n.fragment&&(i+="#"+n.fragment),""===i&&(i="./"),i},r.removeBase=(e,t)=>{if(null===e)return t;e&&!o.isString(e)||(e=r.parse(e||""));let n="";if(""!==e.href?n+=(e.protocol||"")+"//"+(e.authority||""):t.indexOf("//")&&(n+="//"),0!==t.indexOf(n))return t;const a=r.parse(t.substr(n.length)),i=e.normalizedPath.split("/"),s=a.normalizedPath.split("/"),l=a.fragment||a.query?0:1;for(;i.length>0&&s.length>l&&i[0]===s[0];)i.shift(),s.shift();let c="";if(i.length>0){i.pop();for(let e=0;e{if(0===e.length)return"";const t=e.split("/"),n=[];for(;t.length>0;){const e=t.shift(),o=0===t.length;"."!==e?".."!==e?n.push(e):(n.pop(),o&&n.push("")):o&&n.push("")}return"/"===e[0]&&n.length>0&&""!==n[0]&&n.unshift(""),1===n.length&&""===n[0]?"/":n.join("/")};const a=/^([A-Za-z][A-Za-z0-9+-.]*|_):[^\s]*$/;r.isAbsolute=e=>o.isString(e)&&a.test(e),r.isRelative=e=>o.isString(e)},9263:(e,t,n)=>{"use strict";const o=n(3978),r=n(7382),a=n(989).IdentifierIssuer,i=n(2207),s=/(?:<[^>]*?>|"[^"]*?"|[^,])+/g,l=/\s*<([^>]*?)>\s*(?:;\s*(.*))?/,c=/(.*?)=(?:(?:"([^"]*?)")|([^"]*?))\s*(?:(?:;\s*)|$)/g,d="application/ld+json, application/json",u={};function p(e,t){if(r.isArray(t))for(let n=0;n{if(Object.keys(e).some((e=>"accept"===e.toLowerCase())))throw new RangeError('Accept header may not be specified; only "'+d+'" is supported.');return Object.assign({Accept:d},e)},u.parseLinkHeader=e=>{const t={},n=e.match(s);for(let e=0;e{if(!(r.isString(e)||r.isArray(e)&&e.every((e=>r.isString(e))))){if(t&&r.isObject(e))switch(Object.keys(e).length){case 0:return;case 1:if("@default"in e&&u.asArray(e["@default"]).every((e=>r.isString(e))))return}throw new i('Invalid JSON-LD syntax; "@type" value must a string, an array of strings, an empty object, or a default object.',"jsonld.SyntaxError",{code:"invalid type value",value:e})}},u.hasProperty=(e,t)=>{if(e.hasOwnProperty(t)){const n=e[t];return!r.isArray(n)||n.length>0}return!1},u.hasValue=(e,t,n)=>{if(u.hasProperty(e,t)){let a=e[t];const i=o.isList(a);if(r.isArray(a)||i){i&&(a=a["@list"]);for(let e=0;e{if("propertyIsArray"in(o=o||{})||(o.propertyIsArray=!1),"valueIsArray"in o||(o.valueIsArray=!1),"allowDuplicate"in o||(o.allowDuplicate=!0),"prependValue"in o||(o.prependValue=!1),o.valueIsArray)e[t]=n;else if(r.isArray(n)){0===n.length&&o.propertyIsArray&&!e.hasOwnProperty(t)&&(e[t]=[]),o.prependValue&&(n=n.concat(e[t]),e[t]=[]);for(let r=0;r[].concat(e[t]||[]),u.removeProperty=(e,t)=>{delete e[t]},u.removeValue=(e,t,n,o)=>{"propertyIsArray"in(o=o||{})||(o.propertyIsArray=!1);const r=u.getValues(e,t).filter((e=>!u.compareValues(e,n)));0===r.length?u.removeProperty(e,t):1!==r.length||o.propertyIsArray?e[t]=r:e[t]=r[0]},u.relabelBlankNodes=(e,t)=>p((t=t||{}).issuer||new a("_:b"),e),u.compareValues=(e,t)=>e===t||!(!o.isValue(e)||!o.isValue(t)||e["@value"]!==t["@value"]||e["@type"]!==t["@type"]||e["@language"]!==t["@language"]||e["@index"]!==t["@index"])||!!(r.isObject(e)&&"@id"in e&&r.isObject(t)&&"@id"in t)&&e["@id"]===t["@id"],u.compareShortestLeast=(e,t)=>e.length{"use strict";const o=n(8799),r=Symbol("max"),a=Symbol("length"),i=Symbol("lengthCalculator"),s=Symbol("allowStale"),l=Symbol("maxAge"),c=Symbol("dispose"),d=Symbol("noDisposeOnSet"),u=Symbol("lruList"),p=Symbol("cache"),h=Symbol("updateAgeOnGet"),f=()=>1,v=(e,t,n)=>{const o=e[p].get(t);if(o){const t=o.value;if(g(e,t)){if(m(e,o),!e[s])return}else n&&(e[h]&&(o.value.now=Date.now()),e[u].unshiftNode(o));return t.value}},g=(e,t)=>{if(!t||!t.maxAge&&!e[l])return!1;const n=Date.now()-t.now;return t.maxAge?n>t.maxAge:e[l]&&n>e[l]},y=e=>{if(e[a]>e[r])for(let t=e[u].tail;e[a]>e[r]&&null!==t;){const n=t.prev;m(e,t),t=n}},m=(e,t)=>{if(t){const n=t.value;e[c]&&e[c](n.key,n.value),e[a]-=n.length,e[p].delete(n.key),e[u].removeNode(t)}};class x{constructor(e,t,n,o,r){this.key=e,this.value=t,this.length=n,this.now=o,this.maxAge=r||0}}const b=(e,t,n,o)=>{let r=n.value;g(e,r)&&(m(e,n),e[s]||(r=void 0)),r&&t.call(o,r.value,r.key,e)};e.exports=class{constructor(e){if("number"==typeof e&&(e={max:e}),e||(e={}),e.max&&("number"!=typeof e.max||e.max<0))throw new TypeError("max must be a non-negative number");this[r]=e.max||1/0;const t=e.length||f;if(this[i]="function"!=typeof t?f:t,this[s]=e.stale||!1,e.maxAge&&"number"!=typeof e.maxAge)throw new TypeError("maxAge must be a number");this[l]=e.maxAge||0,this[c]=e.dispose,this[d]=e.noDisposeOnSet||!1,this[h]=e.updateAgeOnGet||!1,this.reset()}set max(e){if("number"!=typeof e||e<0)throw new TypeError("max must be a non-negative number");this[r]=e||1/0,y(this)}get max(){return this[r]}set allowStale(e){this[s]=!!e}get allowStale(){return this[s]}set maxAge(e){if("number"!=typeof e)throw new TypeError("maxAge must be a non-negative number");this[l]=e,y(this)}get maxAge(){return this[l]}set lengthCalculator(e){"function"!=typeof e&&(e=f),e!==this[i]&&(this[i]=e,this[a]=0,this[u].forEach((e=>{e.length=this[i](e.value,e.key),this[a]+=e.length}))),y(this)}get lengthCalculator(){return this[i]}get length(){return this[a]}get itemCount(){return this[u].length}rforEach(e,t){t=t||this;for(let n=this[u].tail;null!==n;){const o=n.prev;b(this,e,n,t),n=o}}forEach(e,t){t=t||this;for(let n=this[u].head;null!==n;){const o=n.next;b(this,e,n,t),n=o}}keys(){return this[u].toArray().map((e=>e.key))}values(){return this[u].toArray().map((e=>e.value))}reset(){this[c]&&this[u]&&this[u].length&&this[u].forEach((e=>this[c](e.key,e.value))),this[p]=new Map,this[u]=new o,this[a]=0}dump(){return this[u].map((e=>!g(this,e)&&{k:e.key,v:e.value,e:e.now+(e.maxAge||0)})).toArray().filter((e=>e))}dumpLru(){return this[u]}set(e,t,n){if((n=n||this[l])&&"number"!=typeof n)throw new TypeError("maxAge must be a number");const o=n?Date.now():0,s=this[i](t,e);if(this[p].has(e)){if(s>this[r])return m(this,this[p].get(e)),!1;const i=this[p].get(e).value;return this[c]&&(this[d]||this[c](e,i.value)),i.now=o,i.maxAge=n,i.value=t,this[a]+=s-i.length,i.length=s,this.get(e),y(this),!0}const h=new x(e,t,s,o,n);return h.length>this[r]?(this[c]&&this[c](e,t),!1):(this[a]+=h.length,this[u].unshift(h),this[p].set(e,this[u].head),y(this),!0)}has(e){if(!this[p].has(e))return!1;const t=this[p].get(e).value;return!g(this,t)}get(e){return v(this,e,!0)}peek(e){return v(this,e,!1)}pop(){const e=this[u].tail;return e?(m(this,e),e.value):null}del(e){m(this,this[p].get(e))}load(e){this.reset();const t=Date.now();for(let n=e.length-1;n>=0;n--){const o=e[n],r=o.e||0;if(0===r)this.set(o.k,o.v);else{const e=r-t;e>0&&this.set(o.k,o.v,e)}}}prune(){this[p].forEach(((e,t)=>v(this,t,!1)))}}},989:(e,t,n)=>{e.exports=n(4005)},2985:e=>{"use strict";e.exports=class e{constructor(e,t=new Map,n=0){this.prefix=e,this._existing=t,this.counter=n}clone(){const{prefix:t,_existing:n,counter:o}=this;return new e(t,new Map(n),o)}getId(e){const t=e&&this._existing.get(e);if(t)return t;const n=this.prefix+this.counter;return this.counter++,e&&this._existing.set(e,n),n}hasId(e){return this._existing.has(e)}getOldIds(){return[...this._existing.keys()]}}},3751:(e,t,n)=>{"use strict";n(2791);const o=self.crypto||self.msCrypto;e.exports=class{constructor(e){if(!o||!o.subtle)throw new Error("crypto.subtle not found.");if("sha256"===e)this.algorithm={name:"SHA-256"};else{if("sha1"!==e)throw new Error(`Unsupported algorithm "${e}".`);this.algorithm={name:"SHA-1"}}this._content=""}update(e){this._content+=e}async digest(){const e=(new TextEncoder).encode(this._content),t=new Uint8Array(await o.subtle.digest(this.algorithm,e));let n="";for(let e=0;e{"use strict";const t="http://www.w3.org/1999/02/22-rdf-syntax-ns#langString",n="http://www.w3.org/2001/XMLSchema#string",o="NamedNode",r="BlankNode",a="Literal",i="DefaultGraph",s={};(()=>{const e="(?:<([^:]+:[^>]*)>)",t="A-Za-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�_",n=t+"0-9-·̀-ͯ‿-⁀",o="(_:(?:["+t+"0-9])(?:(?:["+n+".])*(?:["+n+"]))?)",r="[ \\t]+",a="[ \\t]*",i="(?:"+e+"|"+o+")"+r,l=e+r,c="(?:"+e+"|"+o+'|(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"(?:(?:\\^\\^'+e+")|(?:@([a-zA-Z]+(?:-[a-zA-Z0-9]+)*)))?))"+a,d="(?:\\.|(?:(?:"+e+"|"+o+")"+a+"\\.))";s.eoln=/(?:\r\n)|(?:\n)|(?:\r)/g,s.empty=new RegExp("^"+a+"$"),s.quad=new RegExp("^"+a+i+l+c+d+a+"$")})(),e.exports=class e{static parse(e){const l=[],d={},u=e.split(s.eoln);let p=0;for(const e of u){if(p++,s.empty.test(e))continue;const u=e.match(s.quad);if(null===u)throw new Error("N-Quads parse error on line "+p+".");const v={subject:null,predicate:null,object:null,graph:null};if(void 0!==u[1]?v.subject={termType:o,value:u[1]}:v.subject={termType:r,value:u[2]},v.predicate={termType:o,value:u[3]},void 0!==u[4]?v.object={termType:o,value:u[4]}:void 0!==u[5]?v.object={termType:r,value:u[5]}:(v.object={termType:a,value:void 0,datatype:{termType:o}},void 0!==u[7]?v.object.datatype.value=u[7]:void 0!==u[8]?(v.object.datatype.value=t,v.object.language=u[8]):v.object.datatype.value=n,v.object.value=u[6].replace(c,(function(e,t,n,o){if(t)switch(t){case"t":return"\t";case"b":return"\b";case"n":return"\n";case"r":return"\r";case"f":return"\f";case'"':return'"';case"'":return"'";case"\\":return"\\"}if(n)return String.fromCharCode(parseInt(n,16));if(o)throw new Error("Unsupported U escape")}))),void 0!==u[9]?v.graph={termType:o,value:u[9]}:void 0!==u[10]?v.graph={termType:r,value:u[10]}:v.graph={termType:i,value:""},v.graph.value in d){let e=!0;const t=d[v.graph.value];for(const n of t)if(f=v,(h=n).subject.termType===f.subject.termType&&h.object.termType===f.object.termType&&h.subject.value===f.subject.value&&h.predicate.value===f.predicate.value&&h.object.value===f.object.value&&(h.object.termType!==a||h.object.datatype.termType===f.object.datatype.termType&&h.object.language===f.object.language&&h.object.datatype.value===f.object.datatype.value)){e=!1;break}e&&(t.push(v),l.push(v))}else d[v.graph.value]=[v],l.push(v)}var h,f;return l}static serialize(t){Array.isArray(t)||(t=e.legacyDatasetToQuads(t));const n=[];for(const o of t)n.push(e.serializeQuad(o));return n.sort().join("")}static serializeQuadComponents(e,a,i,s){let c="";return e.termType===o?c+=`<${e.value}>`:c+=`${e.value}`,c+=` <${a.value}> `,i.termType===o?c+=`<${i.value}>`:i.termType===r?c+=i.value:(c+=`"${function(e){return e.replace(l,(function(e){switch(e){case'"':return'\\"';case"\\":return"\\\\";case"\n":return"\\n";case"\r":return"\\r"}}))}(i.value)}"`,i.datatype.value===t?i.language&&(c+=`@${i.language}`):i.datatype.value!==n&&(c+=`^^<${i.datatype.value}>`)),s.termType===o?c+=` <${s.value}>`:s.termType===r&&(c+=` ${s.value}`),c+=" .\n",c}static serializeQuad(t){return e.serializeQuadComponents(t.subject,t.predicate,t.object,t.graph)}static legacyDatasetToQuads(e){const s=[],l={"blank node":r,IRI:o,literal:a};for(const c in e)e[c].forEach((e=>{const d={};for(const r in e){const i=e[r],s={termType:l[i.type],value:i.value};s.termType===a&&(s.datatype={termType:o},"datatype"in i&&(s.datatype.value=i.datatype),"language"in i?("datatype"in i||(s.datatype.value=t),s.language=i.language):"datatype"in i||(s.datatype.value=n)),d[r]=s}d.graph="@default"===c?{termType:i,value:""}:{termType:c.startsWith("_:")?r:o,value:c},s.push(d)}));return s}};const l=/["\\\n\r]/g,c=/(?:\\([tbnrf"'\\]))|(?:\\u([0-9A-Fa-f]{4}))|(?:\\U([0-9A-Fa-f]{8}))/g},9925:e=>{"use strict";e.exports=class{constructor(e){this.current=e.sort(),this.done=!1,this.dir=new Map;for(let t=0;to)&&(s&&n>0&&i>e[n-1]||!s&&ne[n+1])&&(o=i,r=n)}if(null===o)this.done=!0;else{const n=t.get(o)?r-1:r+1;e[r]=e[n],e[n]=o;for(const n of e)n>o&&t.set(n,!t.get(n))}return n}}},3513:(e,t,n)=>{"use strict";const o=n(2985),r=n(3751),a=n(9925),i=n(1227);function s(e,t){return e.hasht.hash?1:0}e.exports=class{constructor({createMessageDigest:e=(()=>new r("sha256")),canonicalIdMap:t=new Map,maxDeepIterations:n=1/0}={}){this.name="URDNA2015",this.blankNodeInfo=new Map,this.canonicalIssuer=new o("_:c14n",t),this.createMessageDigest=e,this.maxDeepIterations=n,this.quads=null,this.deepIterations=null}async main(e){this.deepIterations=new Map,this.quads=e;for(const t of e)this._addBlankNodeQuadInfo({quad:t,component:t.subject}),this._addBlankNodeQuadInfo({quad:t,component:t.object}),this._addBlankNodeQuadInfo({quad:t,component:t.graph});const t=new Map,n=[...this.blankNodeInfo.keys()];let r=0;for(const e of n)++r%100==0&&await this._yield(),await this._hashAndTrackBlankNode({id:e,hashToBlankNodes:t});const a=[...t.keys()].sort(),l=[];for(const e of a){const n=t.get(e);if(n.length>1){l.push(n);continue}const o=n[0];this.canonicalIssuer.getId(o)}for(const e of l){const t=[];for(const n of e){if(this.canonicalIssuer.hasId(n))continue;const e=new o("_:b");e.getId(n);const r=await this.hashNDegreeQuads(n,e);t.push(r)}t.sort(s);for(const e of t){const t=e.issuer.getOldIds();for(const e of t)this.canonicalIssuer.getId(e)}}const c=[];for(const e of this.quads){const t=i.serializeQuadComponents(this._componentWithCanonicalId(e.subject),e.predicate,this._componentWithCanonicalId(e.object),this._componentWithCanonicalId(e.graph));c.push(t)}return c.sort(),c.join("")}async hashFirstDegreeQuads(e){const t=[],n=this.blankNodeInfo.get(e),o=n.quads;for(const n of o){const o={subject:null,predicate:n.predicate,object:null,graph:null};o.subject=this.modifyFirstDegreeComponent(e,n.subject,"subject"),o.object=this.modifyFirstDegreeComponent(e,n.object,"object"),o.graph=this.modifyFirstDegreeComponent(e,n.graph,"graph"),t.push(i.serializeQuad(o))}t.sort();const r=this.createMessageDigest();for(const e of t)r.update(e);return n.hash=await r.digest(),n.hash}async hashRelatedBlankNode(e,t,n,o){let r;r=this.canonicalIssuer.hasId(e)?this.canonicalIssuer.getId(e):n.hasId(e)?n.getId(e):this.blankNodeInfo.get(e).hash;const a=this.createMessageDigest();return a.update(o),"g"!==o&&a.update(this.getRelatedPredicate(t)),a.update(r),a.digest()}async hashNDegreeQuads(e,t){const n=this.deepIterations.get(e)||0;if(n>this.maxDeepIterations)throw new Error(`Maximum deep iterations (${this.maxDeepIterations}) exceeded.`);this.deepIterations.set(e,n+1);const o=this.createMessageDigest(),r=await this.createHashToRelated(e,t),i=[...r.keys()].sort();for(const e of i){o.update(e);let n,i="";const s=new a(r.get(e));let l=0;for(;s.hasNext();){const e=s.next();++l%3==0&&await this._yield();let o=t.clone(),r="";const a=[];let c=!1;for(const t of e)if(this.canonicalIssuer.hasId(t)?r+=this.canonicalIssuer.getId(t):(o.hasId(t)||a.push(t),r+=o.getId(t)),0!==i.length&&r>i){c=!0;break}if(!c){for(const e of a){const t=await this.hashNDegreeQuads(e,o);if(r+=o.getId(e),r+=`<${t.hash}>`,o=t.issuer,0!==i.length&&r>i){c=!0;break}}c||(0===i.length||r`}async createHashToRelated(e,t){const n=new Map,o=this.blankNodeInfo.get(e).quads;let r=0;for(const a of o)++r%100==0&&await this._yield(),await Promise.all([this._addRelatedBlankNodeHash({quad:a,component:a.subject,position:"s",id:e,issuer:t,hashToRelated:n}),this._addRelatedBlankNodeHash({quad:a,component:a.object,position:"o",id:e,issuer:t,hashToRelated:n}),this._addRelatedBlankNodeHash({quad:a,component:a.graph,position:"g",id:e,issuer:t,hashToRelated:n})]);return n}async _hashAndTrackBlankNode({id:e,hashToBlankNodes:t}){const n=await this.hashFirstDegreeQuads(e),o=t.get(n);o?o.push(e):t.set(n,[e])}_addBlankNodeQuadInfo({quad:e,component:t}){if("BlankNode"!==t.termType)return;const n=t.value,o=this.blankNodeInfo.get(n);o?o.quads.add(e):this.blankNodeInfo.set(n,{quads:new Set([e]),hash:null})}async _addRelatedBlankNodeHash({quad:e,component:t,position:n,id:o,issuer:r,hashToRelated:a}){if("BlankNode"!==t.termType||t.value===o)return;const i=t.value,s=await this.hashRelatedBlankNode(i,e,r,n),l=a.get(s);l?l.push(i):a.set(s,[i])}_componentWithCanonicalId(e){return"BlankNode"!==e.termType||e.value.startsWith(this.canonicalIssuer.prefix)?e:{termType:"BlankNode",value:this.canonicalIssuer.getId(e.value)}}async _yield(){return new Promise((e=>setImmediate(e)))}}},2438:(e,t,n)=>{"use strict";const o=n(2985),r=n(3751),a=n(9925),i=n(1227);function s(e,t){return e.hasht.hash?1:0}e.exports=class{constructor({createMessageDigest:e=(()=>new r("sha256")),canonicalIdMap:t=new Map,maxDeepIterations:n=1/0}={}){this.name="URDNA2015",this.blankNodeInfo=new Map,this.canonicalIssuer=new o("_:c14n",t),this.createMessageDigest=e,this.maxDeepIterations=n,this.quads=null,this.deepIterations=null}main(e){this.deepIterations=new Map,this.quads=e;for(const t of e)this._addBlankNodeQuadInfo({quad:t,component:t.subject}),this._addBlankNodeQuadInfo({quad:t,component:t.object}),this._addBlankNodeQuadInfo({quad:t,component:t.graph});const t=new Map,n=[...this.blankNodeInfo.keys()];for(const e of n)this._hashAndTrackBlankNode({id:e,hashToBlankNodes:t});const r=[...t.keys()].sort(),a=[];for(const e of r){const n=t.get(e);if(n.length>1){a.push(n);continue}const o=n[0];this.canonicalIssuer.getId(o)}for(const e of a){const t=[];for(const n of e){if(this.canonicalIssuer.hasId(n))continue;const e=new o("_:b");e.getId(n);const r=this.hashNDegreeQuads(n,e);t.push(r)}t.sort(s);for(const e of t){const t=e.issuer.getOldIds();for(const e of t)this.canonicalIssuer.getId(e)}}const l=[];for(const e of this.quads){const t=i.serializeQuadComponents(this._componentWithCanonicalId({component:e.subject}),e.predicate,this._componentWithCanonicalId({component:e.object}),this._componentWithCanonicalId({component:e.graph}));l.push(t)}return l.sort(),l.join("")}hashFirstDegreeQuads(e){const t=[],n=this.blankNodeInfo.get(e),o=n.quads;for(const n of o){const o={subject:null,predicate:n.predicate,object:null,graph:null};o.subject=this.modifyFirstDegreeComponent(e,n.subject,"subject"),o.object=this.modifyFirstDegreeComponent(e,n.object,"object"),o.graph=this.modifyFirstDegreeComponent(e,n.graph,"graph"),t.push(i.serializeQuad(o))}t.sort();const r=this.createMessageDigest();for(const e of t)r.update(e);return n.hash=r.digest(),n.hash}hashRelatedBlankNode(e,t,n,o){let r;r=this.canonicalIssuer.hasId(e)?this.canonicalIssuer.getId(e):n.hasId(e)?n.getId(e):this.blankNodeInfo.get(e).hash;const a=this.createMessageDigest();return a.update(o),"g"!==o&&a.update(this.getRelatedPredicate(t)),a.update(r),a.digest()}hashNDegreeQuads(e,t){const n=this.deepIterations.get(e)||0;if(n>this.maxDeepIterations)throw new Error(`Maximum deep iterations (${this.maxDeepIterations}) exceeded.`);this.deepIterations.set(e,n+1);const o=this.createMessageDigest(),r=this.createHashToRelated(e,t),i=[...r.keys()].sort();for(const e of i){o.update(e);let n,i="";const s=new a(r.get(e));for(;s.hasNext();){const e=s.next();let o=t.clone(),r="";const a=[];let l=!1;for(const t of e)if(this.canonicalIssuer.hasId(t)?r+=this.canonicalIssuer.getId(t):(o.hasId(t)||a.push(t),r+=o.getId(t)),0!==i.length&&r>i){l=!0;break}if(!l){for(const e of a){const t=this.hashNDegreeQuads(e,o);if(r+=o.getId(e),r+=`<${t.hash}>`,o=t.issuer,0!==i.length&&r>i){l=!0;break}}l||(0===i.length||r`}createHashToRelated(e,t){const n=new Map,o=this.blankNodeInfo.get(e).quads;for(const r of o)this._addRelatedBlankNodeHash({quad:r,component:r.subject,position:"s",id:e,issuer:t,hashToRelated:n}),this._addRelatedBlankNodeHash({quad:r,component:r.object,position:"o",id:e,issuer:t,hashToRelated:n}),this._addRelatedBlankNodeHash({quad:r,component:r.graph,position:"g",id:e,issuer:t,hashToRelated:n});return n}_hashAndTrackBlankNode({id:e,hashToBlankNodes:t}){const n=this.hashFirstDegreeQuads(e),o=t.get(n);o?o.push(e):t.set(n,[e])}_addBlankNodeQuadInfo({quad:e,component:t}){if("BlankNode"!==t.termType)return;const n=t.value,o=this.blankNodeInfo.get(n);o?o.quads.add(e):this.blankNodeInfo.set(n,{quads:new Set([e]),hash:null})}_addRelatedBlankNodeHash({quad:e,component:t,position:n,id:o,issuer:r,hashToRelated:a}){if("BlankNode"!==t.termType||t.value===o)return;const i=t.value,s=this.hashRelatedBlankNode(i,e,r,n),l=a.get(s);l?l.push(i):a.set(s,[i])}_componentWithCanonicalId({component:e}){return"BlankNode"!==e.termType||e.value.startsWith(this.canonicalIssuer.prefix)?e:{termType:"BlankNode",value:this.canonicalIssuer.getId(e.value)}}}},3845:(e,t,n)=>{"use strict";const o=n(3751),r=n(3513);e.exports=class extends r{constructor(){super(),this.name="URGNA2012",this.createMessageDigest=()=>new o("sha1")}modifyFirstDegreeComponent(e,t,n){return"BlankNode"!==t.termType?t:"graph"===n?{termType:"BlankNode",value:"_:g"}:{termType:"BlankNode",value:t.value===e?"_:a":"_:z"}}getRelatedPredicate(e){return e.predicate.value}async createHashToRelated(e,t){const n=new Map,o=this.blankNodeInfo.get(e).quads;let r=0;for(const a of o){let o,i;if("BlankNode"===a.subject.termType&&a.subject.value!==e)i=a.subject.value,o="p";else{if("BlankNode"!==a.object.termType||a.object.value===e)continue;i=a.object.value,o="r"}++r%100==0&&await this._yield();const s=await this.hashRelatedBlankNode(i,a,t,o),l=n.get(s);l?l.push(i):n.set(s,[i])}return n}}},378:(e,t,n)=>{"use strict";const o=n(3751),r=n(2438);e.exports=class extends r{constructor(){super(),this.name="URGNA2012",this.createMessageDigest=()=>new o("sha1")}modifyFirstDegreeComponent(e,t,n){return"BlankNode"!==t.termType?t:"graph"===n?{termType:"BlankNode",value:"_:g"}:{termType:"BlankNode",value:t.value===e?"_:a":"_:z"}}getRelatedPredicate(e){return e.predicate.value}createHashToRelated(e,t){const n=new Map,o=this.blankNodeInfo.get(e).quads;for(const r of o){let o,a;if("BlankNode"===r.subject.termType&&r.subject.value!==e)a=r.subject.value,o="p";else{if("BlankNode"!==r.object.termType||r.object.value===e)continue;a=r.object.value,o="r"}const i=this.hashRelatedBlankNode(a,r,t,o),s=n.get(i);s?s.push(a):n.set(i,[a])}return n}}},4005:(e,t,n)=>{"use strict";const o=n(3513),r=n(3845),a=n(2438),i=n(378);let s;try{s=n(7789)}catch(e){}function l(e){return Array.isArray(e)?e:t.NQuads.legacyDatasetToQuads(e)}t.NQuads=n(1227),t.IdentifierIssuer=n(2985),t._rdfCanonizeNative=function(e){return e&&(s=e),s},t.canonize=async function(e,t){const n=l(e);if(t.useNative){if(!s)throw new Error("rdf-canonize-native not available");if(t.createMessageDigest)throw new Error('"createMessageDigest" cannot be used with "useNative".');return new Promise(((e,o)=>s.canonize(n,t,((t,n)=>t?o(t):e(n)))))}if("URDNA2015"===t.algorithm)return new o(t).main(n);if("URGNA2012"===t.algorithm){if(t.createMessageDigest)throw new Error('"createMessageDigest" cannot be used with "URGNA2012".');return new r(t).main(n)}if(!("algorithm"in t))throw new Error("No RDF Dataset Canonicalization algorithm specified.");throw new Error("Invalid RDF Dataset Canonicalization algorithm: "+t.algorithm)},t._canonizeSync=function(e,t){const n=l(e);if(t.useNative){if(!s)throw new Error("rdf-canonize-native not available");if(t.createMessageDigest)throw new Error('"createMessageDigest" cannot be used with "useNative".');return s.canonizeSync(n,t)}if("URDNA2015"===t.algorithm)return new a(t).main(n);if("URGNA2012"===t.algorithm){if(t.createMessageDigest)throw new Error('"createMessageDigest" cannot be used with "URGNA2012".');return new i(t).main(n)}if(!("algorithm"in t))throw new Error("No RDF Dataset Canonicalization algorithm specified.");throw new Error("Invalid RDF Dataset Canonicalization algorithm: "+t.algorithm)}},2791:function(e,t,n){var o=n(5606);!function(e,t){"use strict";if(!e.setImmediate){var n,r,a,i,s,l=1,c={},d=!1,u=e.document,p=Object.getPrototypeOf&&Object.getPrototypeOf(e);p=p&&p.setTimeout?p:e,"[object process]"==={}.toString.call(e.process)?n=function(e){o.nextTick((function(){f(e)}))}:function(){if(e.postMessage&&!e.importScripts){var t=!0,n=e.onmessage;return e.onmessage=function(){t=!1},e.postMessage("","*"),e.onmessage=n,t}}()?(i="setImmediate$"+Math.random()+"$",s=function(t){t.source===e&&"string"==typeof t.data&&0===t.data.indexOf(i)&&f(+t.data.slice(i.length))},e.addEventListener?e.addEventListener("message",s,!1):e.attachEvent("onmessage",s),n=function(t){e.postMessage(i+t,"*")}):e.MessageChannel?((a=new MessageChannel).port1.onmessage=function(e){f(e.data)},n=function(e){a.port2.postMessage(e)}):u&&"onreadystatechange"in u.createElement("script")?(r=u.documentElement,n=function(e){var t=u.createElement("script");t.onreadystatechange=function(){f(e),t.onreadystatechange=null,r.removeChild(t),t=null},r.appendChild(t)}):n=function(e){setTimeout(f,0,e)},p.setImmediate=function(e){"function"!=typeof e&&(e=new Function(""+e));for(var t=new Array(arguments.length-1),o=0;o{"use strict";e.exports=function(e){e.prototype[Symbol.iterator]=function*(){for(let e=this.head;e;e=e.next)yield e.value}}},8799:(e,t,n)=>{"use strict";function o(e){var t=this;if(t instanceof o||(t=new o),t.tail=null,t.head=null,t.length=0,e&&"function"==typeof e.forEach)e.forEach((function(e){t.push(e)}));else if(arguments.length>0)for(var n=0,r=arguments.length;n1)n=t;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");o=this.head.next,n=this.head.value}for(var r=0;null!==o;r++)n=e(n,o.value,r),o=o.next;return n},o.prototype.reduceReverse=function(e,t){var n,o=this.tail;if(arguments.length>1)n=t;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");o=this.tail.prev,n=this.tail.value}for(var r=this.length-1;null!==o;r--)n=e(n,o.value,r),o=o.prev;return n},o.prototype.toArray=function(){for(var e=new Array(this.length),t=0,n=this.head;null!==n;t++)e[t]=n.value,n=n.next;return e},o.prototype.toArrayReverse=function(){for(var e=new Array(this.length),t=0,n=this.tail;null!==n;t++)e[t]=n.value,n=n.prev;return e},o.prototype.slice=function(e,t){(t=t||this.length)<0&&(t+=this.length),(e=e||0)<0&&(e+=this.length);var n=new o;if(tthis.length&&(t=this.length);for(var r=0,a=this.head;null!==a&&rthis.length&&(t=this.length);for(var r=this.length,a=this.tail;null!==a&&r>t;r--)a=a.prev;for(;null!==a&&r>e;r--,a=a.prev)n.push(a.value);return n},o.prototype.splice=function(e,t,...n){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);for(var o=0,a=this.head;null!==a&&o {\n const comma = ci === 0 ? '' : ',';\n const value = cv === undefined || typeof cv === 'symbol' ? null : cv;\n return t + comma + serialize(value);\n }, '') + ']';\n }\n\n return '{' + Object.keys(object).sort().reduce((t, cv, ci) => {\n if (object[cv] === undefined ||\n typeof object[cv] === 'symbol') {\n return t;\n }\n const comma = t.length === 0 ? '' : ',';\n return t + comma + serialize(cv) + ':' + serialize(object[cv]);\n }, '') + '}';\n};\n","/*\n * Copyright (c) 2019 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst {\n isArray: _isArray,\n isObject: _isObject,\n isString: _isString,\n} = require('./types');\nconst {\n asArray: _asArray\n} = require('./util');\nconst {prependBase} = require('./url');\nconst JsonLdError = require('./JsonLdError');\nconst ResolvedContext = require('./ResolvedContext');\n\nconst MAX_CONTEXT_URLS = 10;\n\nmodule.exports = class ContextResolver {\n /**\n * Creates a ContextResolver.\n *\n * @param sharedCache a shared LRU cache with `get` and `set` APIs.\n */\n constructor({sharedCache}) {\n this.perOpCache = new Map();\n this.sharedCache = sharedCache;\n }\n\n async resolve({\n activeCtx, context, documentLoader, base, cycles = new Set()\n }) {\n // process `@context`\n if(context && _isObject(context) && context['@context']) {\n context = context['@context'];\n }\n\n // context is one or more contexts\n context = _asArray(context);\n\n // resolve each context in the array\n const allResolved = [];\n for(const ctx of context) {\n if(_isString(ctx)) {\n // see if `ctx` has been resolved before...\n let resolved = this._get(ctx);\n if(!resolved) {\n // not resolved yet, resolve\n resolved = await this._resolveRemoteContext(\n {activeCtx, url: ctx, documentLoader, base, cycles});\n }\n\n // add to output and continue\n if(_isArray(resolved)) {\n allResolved.push(...resolved);\n } else {\n allResolved.push(resolved);\n }\n continue;\n }\n if(ctx === null) {\n // handle `null` context, nothing to cache\n allResolved.push(new ResolvedContext({document: null}));\n continue;\n }\n if(!_isObject(ctx)) {\n _throwInvalidLocalContext(context);\n }\n // context is an object, get/create `ResolvedContext` for it\n const key = JSON.stringify(ctx);\n let resolved = this._get(key);\n if(!resolved) {\n // create a new static `ResolvedContext` and cache it\n resolved = new ResolvedContext({document: ctx});\n this._cacheResolvedContext({key, resolved, tag: 'static'});\n }\n allResolved.push(resolved);\n }\n\n return allResolved;\n }\n\n _get(key) {\n // get key from per operation cache; no `tag` is used with this cache so\n // any retrieved context will always be the same during a single operation\n let resolved = this.perOpCache.get(key);\n if(!resolved) {\n // see if the shared cache has a `static` entry for this URL\n const tagMap = this.sharedCache.get(key);\n if(tagMap) {\n resolved = tagMap.get('static');\n if(resolved) {\n this.perOpCache.set(key, resolved);\n }\n }\n }\n return resolved;\n }\n\n _cacheResolvedContext({key, resolved, tag}) {\n this.perOpCache.set(key, resolved);\n if(tag !== undefined) {\n let tagMap = this.sharedCache.get(key);\n if(!tagMap) {\n tagMap = new Map();\n this.sharedCache.set(key, tagMap);\n }\n tagMap.set(tag, resolved);\n }\n return resolved;\n }\n\n async _resolveRemoteContext({activeCtx, url, documentLoader, base, cycles}) {\n // resolve relative URL and fetch context\n url = prependBase(base, url);\n const {context, remoteDoc} = await this._fetchContext(\n {activeCtx, url, documentLoader, cycles});\n\n // update base according to remote document and resolve any relative URLs\n base = remoteDoc.documentUrl || url;\n _resolveContextUrls({context, base});\n\n // resolve, cache, and return context\n const resolved = await this.resolve(\n {activeCtx, context, documentLoader, base, cycles});\n this._cacheResolvedContext({key: url, resolved, tag: remoteDoc.tag});\n return resolved;\n }\n\n async _fetchContext({activeCtx, url, documentLoader, cycles}) {\n // check for max context URLs fetched during a resolve operation\n if(cycles.size > MAX_CONTEXT_URLS) {\n throw new JsonLdError(\n 'Maximum number of @context URLs exceeded.',\n 'jsonld.ContextUrlError',\n {\n code: activeCtx.processingMode === 'json-ld-1.0' ?\n 'loading remote context failed' :\n 'context overflow',\n max: MAX_CONTEXT_URLS\n });\n }\n\n // check for context URL cycle\n // shortcut to avoid extra work that would eventually hit the max above\n if(cycles.has(url)) {\n throw new JsonLdError(\n 'Cyclical @context URLs detected.',\n 'jsonld.ContextUrlError',\n {\n code: activeCtx.processingMode === 'json-ld-1.0' ?\n 'recursive context inclusion' :\n 'context overflow',\n url\n });\n }\n\n // track cycles\n cycles.add(url);\n\n let context;\n let remoteDoc;\n\n try {\n remoteDoc = await documentLoader(url);\n context = remoteDoc.document || null;\n // parse string context as JSON\n if(_isString(context)) {\n context = JSON.parse(context);\n }\n } catch(e) {\n throw new JsonLdError(\n 'Dereferencing a URL did not result in a valid JSON-LD object. ' +\n 'Possible causes are an inaccessible URL perhaps due to ' +\n 'a same-origin policy (ensure the server uses CORS if you are ' +\n 'using client-side JavaScript), too many redirects, a ' +\n 'non-JSON response, or more than one HTTP Link Header was ' +\n 'provided for a remote context.',\n 'jsonld.InvalidUrl',\n {code: 'loading remote context failed', url, cause: e});\n }\n\n // ensure ctx is an object\n if(!_isObject(context)) {\n throw new JsonLdError(\n 'Dereferencing a URL did not result in a JSON object. The ' +\n 'response was valid JSON, but it was not a JSON object.',\n 'jsonld.InvalidUrl', {code: 'invalid remote context', url});\n }\n\n // use empty context if no @context key is present\n if(!('@context' in context)) {\n context = {'@context': {}};\n } else {\n context = {'@context': context['@context']};\n }\n\n // append @context URL to context if given\n if(remoteDoc.contextUrl) {\n if(!_isArray(context['@context'])) {\n context['@context'] = [context['@context']];\n }\n context['@context'].push(remoteDoc.contextUrl);\n }\n\n return {context, remoteDoc};\n }\n};\n\nfunction _throwInvalidLocalContext(ctx) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @context must be an object.',\n 'jsonld.SyntaxError', {\n code: 'invalid local context', context: ctx\n });\n}\n\n/**\n * Resolve all relative `@context` URLs in the given context by inline\n * replacing them with absolute URLs.\n *\n * @param context the context.\n * @param base the base IRI to use to resolve relative IRIs.\n */\nfunction _resolveContextUrls({context, base}) {\n if(!context) {\n return;\n }\n\n const ctx = context['@context'];\n\n if(_isString(ctx)) {\n context['@context'] = prependBase(base, ctx);\n return;\n }\n\n if(_isArray(ctx)) {\n for(let i = 0; i < ctx.length; ++i) {\n const element = ctx[i];\n if(_isString(element)) {\n ctx[i] = prependBase(base, element);\n continue;\n }\n if(_isObject(element)) {\n _resolveContextUrls({context: {'@context': element}, base});\n }\n }\n return;\n }\n\n if(!_isObject(ctx)) {\n // no @context URLs can be found in non-object\n return;\n }\n\n // ctx is an object, resolve any context URLs in terms\n for(const term in ctx) {\n _resolveContextUrls({context: ctx[term], base});\n }\n}\n","/*\n * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nmodule.exports = class JsonLdError extends Error {\n /**\n * Creates a JSON-LD Error.\n *\n * @param msg the error message.\n * @param type the error type.\n * @param details the error details.\n */\n constructor(\n message = 'An unspecified JSON-LD error occurred.',\n name = 'jsonld.Error',\n details = {}) {\n super(message);\n this.name = name;\n this.message = message;\n this.details = details;\n }\n};\n","/*\n * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nmodule.exports = jsonld => {\n class JsonLdProcessor {\n toString() {\n return '[object JsonLdProcessor]';\n }\n }\n Object.defineProperty(JsonLdProcessor, 'prototype', {\n writable: false,\n enumerable: false\n });\n Object.defineProperty(JsonLdProcessor.prototype, 'constructor', {\n writable: true,\n enumerable: false,\n configurable: true,\n value: JsonLdProcessor\n });\n\n // The Web IDL test harness will check the number of parameters defined in\n // the functions below. The number of parameters must exactly match the\n // required (non-optional) parameters of the JsonLdProcessor interface as\n // defined here:\n // https://www.w3.org/TR/json-ld-api/#the-jsonldprocessor-interface\n\n JsonLdProcessor.compact = function(input, ctx) {\n if(arguments.length < 2) {\n return Promise.reject(\n new TypeError('Could not compact, too few arguments.'));\n }\n return jsonld.compact(input, ctx);\n };\n JsonLdProcessor.expand = function(input) {\n if(arguments.length < 1) {\n return Promise.reject(\n new TypeError('Could not expand, too few arguments.'));\n }\n return jsonld.expand(input);\n };\n JsonLdProcessor.flatten = function(input) {\n if(arguments.length < 1) {\n return Promise.reject(\n new TypeError('Could not flatten, too few arguments.'));\n }\n return jsonld.flatten(input);\n };\n\n return JsonLdProcessor;\n};\n","/*\n * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\n// TODO: move `NQuads` to its own package\nmodule.exports = require('rdf-canonize').NQuads;\n","/*\n * Copyright (c) 2017-2019 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nmodule.exports = class RequestQueue {\n /**\n * Creates a simple queue for requesting documents.\n */\n constructor() {\n this._requests = {};\n }\n\n wrapLoader(loader) {\n const self = this;\n self._loader = loader;\n return function(/* url */) {\n return self.add.apply(self, arguments);\n };\n }\n\n async add(url) {\n let promise = this._requests[url];\n if(promise) {\n // URL already queued, wait for it to load\n return Promise.resolve(promise);\n }\n\n // queue URL and load it\n promise = this._requests[url] = this._loader(url);\n\n try {\n return await promise;\n } finally {\n delete this._requests[url];\n }\n }\n};\n","/*\n * Copyright (c) 2019 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst LRU = require('lru-cache');\n\nconst MAX_ACTIVE_CONTEXTS = 10;\n\nmodule.exports = class ResolvedContext {\n /**\n * Creates a ResolvedContext.\n *\n * @param document the context document.\n */\n constructor({document}) {\n this.document = document;\n // TODO: enable customization of processed context cache\n // TODO: limit based on size of processed contexts vs. number of them\n this.cache = new LRU({max: MAX_ACTIVE_CONTEXTS});\n }\n\n getProcessed(activeCtx) {\n return this.cache.get(activeCtx);\n }\n\n setProcessed(activeCtx, processedCtx) {\n this.cache.set(activeCtx, processedCtx);\n }\n};\n","/*\n * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst JsonLdError = require('./JsonLdError');\n\nconst {\n isArray: _isArray,\n isObject: _isObject,\n isString: _isString,\n isUndefined: _isUndefined\n} = require('./types');\n\nconst {\n isList: _isList,\n isValue: _isValue,\n isGraph: _isGraph,\n isSimpleGraph: _isSimpleGraph,\n isSubjectReference: _isSubjectReference\n} = require('./graphTypes');\n\nconst {\n expandIri: _expandIri,\n getContextValue: _getContextValue,\n isKeyword: _isKeyword,\n process: _processContext,\n processingMode: _processingMode\n} = require('./context');\n\nconst {\n removeBase: _removeBase,\n prependBase: _prependBase\n} = require('./url');\n\nconst {\n REGEX_KEYWORD,\n addValue: _addValue,\n asArray: _asArray,\n compareShortestLeast: _compareShortestLeast\n} = require('./util');\n\nconst api = {};\nmodule.exports = api;\n\n/**\n * Recursively compacts an element using the given active context. All values\n * must be in expanded form before this method is called.\n *\n * @param activeCtx the active context to use.\n * @param activeProperty the compacted property associated with the element\n * to compact, null for none.\n * @param element the element to compact.\n * @param options the compaction options.\n *\n * @return a promise that resolves to the compacted value.\n */\napi.compact = async ({\n activeCtx,\n activeProperty = null,\n element,\n options = {}\n}) => {\n // recursively compact array\n if(_isArray(element)) {\n let rval = [];\n for(let i = 0; i < element.length; ++i) {\n const compacted = await api.compact({\n activeCtx,\n activeProperty,\n element: element[i],\n options\n });\n if(compacted === null) {\n // FIXME: need event?\n continue;\n }\n rval.push(compacted);\n }\n if(options.compactArrays && rval.length === 1) {\n // use single element if no container is specified\n const container = _getContextValue(\n activeCtx, activeProperty, '@container') || [];\n if(container.length === 0) {\n rval = rval[0];\n }\n }\n return rval;\n }\n\n // use any scoped context on activeProperty\n const ctx = _getContextValue(activeCtx, activeProperty, '@context');\n if(!_isUndefined(ctx)) {\n activeCtx = await _processContext({\n activeCtx,\n localCtx: ctx,\n propagate: true,\n overrideProtected: true,\n options\n });\n }\n\n // recursively compact object\n if(_isObject(element)) {\n if(options.link && '@id' in element &&\n options.link.hasOwnProperty(element['@id'])) {\n // check for a linked element to reuse\n const linked = options.link[element['@id']];\n for(let i = 0; i < linked.length; ++i) {\n if(linked[i].expanded === element) {\n return linked[i].compacted;\n }\n }\n }\n\n // do value compaction on @values and subject references\n if(_isValue(element) || _isSubjectReference(element)) {\n const rval =\n api.compactValue({activeCtx, activeProperty, value: element, options});\n if(options.link && _isSubjectReference(element)) {\n // store linked element\n if(!(options.link.hasOwnProperty(element['@id']))) {\n options.link[element['@id']] = [];\n }\n options.link[element['@id']].push({expanded: element, compacted: rval});\n }\n return rval;\n }\n\n // if expanded property is @list and we're contained within a list\n // container, recursively compact this item to an array\n if(_isList(element)) {\n const container = _getContextValue(\n activeCtx, activeProperty, '@container') || [];\n if(container.includes('@list')) {\n return api.compact({\n activeCtx,\n activeProperty,\n element: element['@list'],\n options\n });\n }\n }\n\n // FIXME: avoid misuse of active property as an expanded property?\n const insideReverse = (activeProperty === '@reverse');\n\n const rval = {};\n\n // original context before applying property-scoped and local contexts\n const inputCtx = activeCtx;\n\n // revert to previous context, if there is one,\n // and element is not a value object or a node reference\n if(!_isValue(element) && !_isSubjectReference(element)) {\n activeCtx = activeCtx.revertToPreviousContext();\n }\n\n // apply property-scoped context after reverting term-scoped context\n const propertyScopedCtx =\n _getContextValue(inputCtx, activeProperty, '@context');\n if(!_isUndefined(propertyScopedCtx)) {\n activeCtx = await _processContext({\n activeCtx,\n localCtx: propertyScopedCtx,\n propagate: true,\n overrideProtected: true,\n options\n });\n }\n\n if(options.link && '@id' in element) {\n // store linked element\n if(!options.link.hasOwnProperty(element['@id'])) {\n options.link[element['@id']] = [];\n }\n options.link[element['@id']].push({expanded: element, compacted: rval});\n }\n\n // apply any context defined on an alias of @type\n // if key is @type and any compacted value is a term having a local\n // context, overlay that context\n let types = element['@type'] || [];\n if(types.length > 1) {\n types = Array.from(types).sort();\n }\n // find all type-scoped contexts based on current context, prior to\n // updating it\n const typeContext = activeCtx;\n for(const type of types) {\n const compactedType = api.compactIri(\n {activeCtx: typeContext, iri: type, relativeTo: {vocab: true}});\n\n // Use any type-scoped context defined on this value\n const ctx = _getContextValue(inputCtx, compactedType, '@context');\n if(!_isUndefined(ctx)) {\n activeCtx = await _processContext({\n activeCtx,\n localCtx: ctx,\n options,\n propagate: false\n });\n }\n }\n\n // process element keys in order\n const keys = Object.keys(element).sort();\n for(const expandedProperty of keys) {\n const expandedValue = element[expandedProperty];\n\n // compact @id\n if(expandedProperty === '@id') {\n let compactedValue = _asArray(expandedValue).map(\n expandedIri => api.compactIri({\n activeCtx,\n iri: expandedIri,\n relativeTo: {vocab: false},\n base: options.base\n }));\n if(compactedValue.length === 1) {\n compactedValue = compactedValue[0];\n }\n\n // use keyword alias and add value\n const alias = api.compactIri(\n {activeCtx, iri: '@id', relativeTo: {vocab: true}});\n\n rval[alias] = compactedValue;\n continue;\n }\n\n // compact @type(s)\n if(expandedProperty === '@type') {\n // resolve type values against previous context\n let compactedValue = _asArray(expandedValue).map(\n expandedIri => api.compactIri({\n activeCtx: inputCtx,\n iri: expandedIri,\n relativeTo: {vocab: true}\n }));\n if(compactedValue.length === 1) {\n compactedValue = compactedValue[0];\n }\n\n // use keyword alias and add value\n const alias = api.compactIri(\n {activeCtx, iri: '@type', relativeTo: {vocab: true}});\n const container = _getContextValue(\n activeCtx, alias, '@container') || [];\n\n // treat as array for @type if @container includes @set\n const typeAsSet =\n container.includes('@set') &&\n _processingMode(activeCtx, 1.1);\n const isArray =\n typeAsSet || (_isArray(compactedValue) && expandedValue.length === 0);\n _addValue(rval, alias, compactedValue, {propertyIsArray: isArray});\n continue;\n }\n\n // handle @reverse\n if(expandedProperty === '@reverse') {\n // recursively compact expanded value\n const compactedValue = await api.compact({\n activeCtx,\n activeProperty: '@reverse',\n element: expandedValue,\n options\n });\n\n // handle double-reversed properties\n for(const compactedProperty in compactedValue) {\n if(activeCtx.mappings.has(compactedProperty) &&\n activeCtx.mappings.get(compactedProperty).reverse) {\n const value = compactedValue[compactedProperty];\n const container = _getContextValue(\n activeCtx, compactedProperty, '@container') || [];\n const useArray = (\n container.includes('@set') || !options.compactArrays);\n _addValue(\n rval, compactedProperty, value, {propertyIsArray: useArray});\n delete compactedValue[compactedProperty];\n }\n }\n\n if(Object.keys(compactedValue).length > 0) {\n // use keyword alias and add value\n const alias = api.compactIri({\n activeCtx,\n iri: expandedProperty,\n relativeTo: {vocab: true}\n });\n _addValue(rval, alias, compactedValue);\n }\n\n continue;\n }\n\n if(expandedProperty === '@preserve') {\n // compact using activeProperty\n const compactedValue = await api.compact({\n activeCtx,\n activeProperty,\n element: expandedValue,\n options\n });\n\n if(!(_isArray(compactedValue) && compactedValue.length === 0)) {\n _addValue(rval, expandedProperty, compactedValue);\n }\n continue;\n }\n\n // handle @index property\n if(expandedProperty === '@index') {\n // drop @index if inside an @index container\n const container = _getContextValue(\n activeCtx, activeProperty, '@container') || [];\n if(container.includes('@index')) {\n continue;\n }\n\n // use keyword alias and add value\n const alias = api.compactIri({\n activeCtx,\n iri: expandedProperty,\n relativeTo: {vocab: true}\n });\n _addValue(rval, alias, expandedValue);\n continue;\n }\n\n // skip array processing for keywords that aren't\n // @graph, @list, or @included\n if(expandedProperty !== '@graph' && expandedProperty !== '@list' &&\n expandedProperty !== '@included' &&\n _isKeyword(expandedProperty)) {\n // use keyword alias and add value as is\n const alias = api.compactIri({\n activeCtx,\n iri: expandedProperty,\n relativeTo: {vocab: true}\n });\n _addValue(rval, alias, expandedValue);\n continue;\n }\n\n // Note: expanded value must be an array due to expansion algorithm.\n if(!_isArray(expandedValue)) {\n throw new JsonLdError(\n 'JSON-LD expansion error; expanded value must be an array.',\n 'jsonld.SyntaxError');\n }\n\n // preserve empty arrays\n if(expandedValue.length === 0) {\n const itemActiveProperty = api.compactIri({\n activeCtx,\n iri: expandedProperty,\n value: expandedValue,\n relativeTo: {vocab: true},\n reverse: insideReverse\n });\n const nestProperty = activeCtx.mappings.has(itemActiveProperty) ?\n activeCtx.mappings.get(itemActiveProperty)['@nest'] : null;\n let nestResult = rval;\n if(nestProperty) {\n _checkNestProperty(activeCtx, nestProperty, options);\n if(!_isObject(rval[nestProperty])) {\n rval[nestProperty] = {};\n }\n nestResult = rval[nestProperty];\n }\n _addValue(\n nestResult, itemActiveProperty, expandedValue, {\n propertyIsArray: true\n });\n }\n\n // recusively process array values\n for(const expandedItem of expandedValue) {\n // compact property and get container type\n const itemActiveProperty = api.compactIri({\n activeCtx,\n iri: expandedProperty,\n value: expandedItem,\n relativeTo: {vocab: true},\n reverse: insideReverse\n });\n\n // if itemActiveProperty is a @nest property, add values to nestResult,\n // otherwise rval\n const nestProperty = activeCtx.mappings.has(itemActiveProperty) ?\n activeCtx.mappings.get(itemActiveProperty)['@nest'] : null;\n let nestResult = rval;\n if(nestProperty) {\n _checkNestProperty(activeCtx, nestProperty, options);\n if(!_isObject(rval[nestProperty])) {\n rval[nestProperty] = {};\n }\n nestResult = rval[nestProperty];\n }\n\n const container = _getContextValue(\n activeCtx, itemActiveProperty, '@container') || [];\n\n // get simple @graph or @list value if appropriate\n const isGraph = _isGraph(expandedItem);\n const isList = _isList(expandedItem);\n let inner;\n if(isList) {\n inner = expandedItem['@list'];\n } else if(isGraph) {\n inner = expandedItem['@graph'];\n }\n\n // recursively compact expanded item\n let compactedItem = await api.compact({\n activeCtx,\n activeProperty: itemActiveProperty,\n element: (isList || isGraph) ? inner : expandedItem,\n options\n });\n\n // handle @list\n if(isList) {\n // ensure @list value is an array\n if(!_isArray(compactedItem)) {\n compactedItem = [compactedItem];\n }\n\n if(!container.includes('@list')) {\n // wrap using @list alias\n compactedItem = {\n [api.compactIri({\n activeCtx,\n iri: '@list',\n relativeTo: {vocab: true}\n })]: compactedItem\n };\n\n // include @index from expanded @list, if any\n if('@index' in expandedItem) {\n compactedItem[api.compactIri({\n activeCtx,\n iri: '@index',\n relativeTo: {vocab: true}\n })] = expandedItem['@index'];\n }\n } else {\n _addValue(nestResult, itemActiveProperty, compactedItem, {\n valueIsArray: true,\n allowDuplicate: true\n });\n continue;\n }\n }\n\n // Graph object compaction cases\n if(isGraph) {\n if(container.includes('@graph') && (container.includes('@id') ||\n container.includes('@index') && _isSimpleGraph(expandedItem))) {\n // get or create the map object\n let mapObject;\n if(nestResult.hasOwnProperty(itemActiveProperty)) {\n mapObject = nestResult[itemActiveProperty];\n } else {\n nestResult[itemActiveProperty] = mapObject = {};\n }\n\n // index on @id or @index or alias of @none\n const key = (container.includes('@id') ?\n expandedItem['@id'] : expandedItem['@index']) ||\n api.compactIri({activeCtx, iri: '@none',\n relativeTo: {vocab: true}});\n // add compactedItem to map, using value of `@id` or a new blank\n // node identifier\n\n _addValue(\n mapObject, key, compactedItem, {\n propertyIsArray:\n (!options.compactArrays || container.includes('@set'))\n });\n } else if(container.includes('@graph') &&\n _isSimpleGraph(expandedItem)) {\n // container includes @graph but not @id or @index and value is a\n // simple graph object add compact value\n // if compactedItem contains multiple values, it is wrapped in\n // `@included`\n if(_isArray(compactedItem) && compactedItem.length > 1) {\n compactedItem = {'@included': compactedItem};\n }\n _addValue(\n nestResult, itemActiveProperty, compactedItem, {\n propertyIsArray:\n (!options.compactArrays || container.includes('@set'))\n });\n } else {\n // wrap using @graph alias, remove array if only one item and\n // compactArrays not set\n if(_isArray(compactedItem) && compactedItem.length === 1 &&\n options.compactArrays) {\n compactedItem = compactedItem[0];\n }\n compactedItem = {\n [api.compactIri({\n activeCtx,\n iri: '@graph',\n relativeTo: {vocab: true}\n })]: compactedItem\n };\n\n // include @id from expanded graph, if any\n if('@id' in expandedItem) {\n compactedItem[api.compactIri({\n activeCtx,\n iri: '@id',\n relativeTo: {vocab: true}\n })] = expandedItem['@id'];\n }\n\n // include @index from expanded graph, if any\n if('@index' in expandedItem) {\n compactedItem[api.compactIri({\n activeCtx,\n iri: '@index',\n relativeTo: {vocab: true}\n })] = expandedItem['@index'];\n }\n _addValue(\n nestResult, itemActiveProperty, compactedItem, {\n propertyIsArray:\n (!options.compactArrays || container.includes('@set'))\n });\n }\n } else if(container.includes('@language') ||\n container.includes('@index') || container.includes('@id') ||\n container.includes('@type')) {\n // handle language and index maps\n // get or create the map object\n let mapObject;\n if(nestResult.hasOwnProperty(itemActiveProperty)) {\n mapObject = nestResult[itemActiveProperty];\n } else {\n nestResult[itemActiveProperty] = mapObject = {};\n }\n\n let key;\n if(container.includes('@language')) {\n // if container is a language map, simplify compacted value to\n // a simple string\n if(_isValue(compactedItem)) {\n compactedItem = compactedItem['@value'];\n }\n key = expandedItem['@language'];\n } else if(container.includes('@index')) {\n const indexKey = _getContextValue(\n activeCtx, itemActiveProperty, '@index') || '@index';\n const containerKey = api.compactIri(\n {activeCtx, iri: indexKey, relativeTo: {vocab: true}});\n if(indexKey === '@index') {\n key = expandedItem['@index'];\n delete compactedItem[containerKey];\n } else {\n let others;\n [key, ...others] = _asArray(compactedItem[indexKey] || []);\n if(!_isString(key)) {\n // Will use @none if it isn't a string.\n key = null;\n } else {\n switch(others.length) {\n case 0:\n delete compactedItem[indexKey];\n break;\n case 1:\n compactedItem[indexKey] = others[0];\n break;\n default:\n compactedItem[indexKey] = others;\n break;\n }\n }\n }\n } else if(container.includes('@id')) {\n const idKey = api.compactIri({activeCtx, iri: '@id',\n relativeTo: {vocab: true}});\n key = compactedItem[idKey];\n delete compactedItem[idKey];\n } else if(container.includes('@type')) {\n const typeKey = api.compactIri({\n activeCtx,\n iri: '@type',\n relativeTo: {vocab: true}\n });\n let types;\n [key, ...types] = _asArray(compactedItem[typeKey] || []);\n switch(types.length) {\n case 0:\n delete compactedItem[typeKey];\n break;\n case 1:\n compactedItem[typeKey] = types[0];\n break;\n default:\n compactedItem[typeKey] = types;\n break;\n }\n\n // If compactedItem contains a single entry\n // whose key maps to @id, recompact without @type\n if(Object.keys(compactedItem).length === 1 &&\n '@id' in expandedItem) {\n compactedItem = await api.compact({\n activeCtx,\n activeProperty: itemActiveProperty,\n element: {'@id': expandedItem['@id']},\n options\n });\n }\n }\n\n // if compacting this value which has no key, index on @none\n if(!key) {\n key = api.compactIri({activeCtx, iri: '@none',\n relativeTo: {vocab: true}});\n }\n // add compact value to map object using key from expanded value\n // based on the container type\n _addValue(\n mapObject, key, compactedItem, {\n propertyIsArray: container.includes('@set')\n });\n } else {\n // use an array if: compactArrays flag is false,\n // @container is @set or @list , value is an empty\n // array, or key is @graph\n const isArray = (!options.compactArrays ||\n container.includes('@set') || container.includes('@list') ||\n (_isArray(compactedItem) && compactedItem.length === 0) ||\n expandedProperty === '@list' || expandedProperty === '@graph');\n\n // add compact value\n _addValue(\n nestResult, itemActiveProperty, compactedItem,\n {propertyIsArray: isArray});\n }\n }\n }\n\n return rval;\n }\n\n // only primitives remain which are already compact\n return element;\n};\n\n/**\n * Compacts an IRI or keyword into a term or prefix if it can be. If the\n * IRI has an associated value it may be passed.\n *\n * @param activeCtx the active context to use.\n * @param iri the IRI to compact.\n * @param value the value to check or null.\n * @param relativeTo options for how to compact IRIs:\n * vocab: true to split after @vocab, false not to.\n * @param reverse true if a reverse property is being compacted, false if not.\n * @param base the absolute URL to use for compacting document-relative IRIs.\n *\n * @return the compacted term, prefix, keyword alias, or the original IRI.\n */\napi.compactIri = ({\n activeCtx,\n iri,\n value = null,\n relativeTo = {vocab: false},\n reverse = false,\n base = null\n}) => {\n // can't compact null\n if(iri === null) {\n return iri;\n }\n\n // if context is from a property term scoped context composed with a\n // type-scoped context, then use the previous context instead\n if(activeCtx.isPropertyTermScoped && activeCtx.previousContext) {\n activeCtx = activeCtx.previousContext;\n }\n\n const inverseCtx = activeCtx.getInverse();\n\n // if term is a keyword, it may be compacted to a simple alias\n if(_isKeyword(iri) &&\n iri in inverseCtx &&\n '@none' in inverseCtx[iri] &&\n '@type' in inverseCtx[iri]['@none'] &&\n '@none' in inverseCtx[iri]['@none']['@type']) {\n return inverseCtx[iri]['@none']['@type']['@none'];\n }\n\n // use inverse context to pick a term if iri is relative to vocab\n if(relativeTo.vocab && iri in inverseCtx) {\n const defaultLanguage = activeCtx['@language'] || '@none';\n\n // prefer @index if available in value\n const containers = [];\n if(_isObject(value) && '@index' in value && !('@graph' in value)) {\n containers.push('@index', '@index@set');\n }\n\n // if value is a preserve object, use its value\n if(_isObject(value) && '@preserve' in value) {\n value = value['@preserve'][0];\n }\n\n // prefer most specific container including @graph, prefering @set\n // variations\n if(_isGraph(value)) {\n // favor indexmap if the graph is indexed\n if('@index' in value) {\n containers.push(\n '@graph@index', '@graph@index@set', '@index', '@index@set');\n }\n // favor idmap if the graph is has an @id\n if('@id' in value) {\n containers.push(\n '@graph@id', '@graph@id@set');\n }\n containers.push('@graph', '@graph@set', '@set');\n // allow indexmap if the graph is not indexed\n if(!('@index' in value)) {\n containers.push(\n '@graph@index', '@graph@index@set', '@index', '@index@set');\n }\n // allow idmap if the graph does not have an @id\n if(!('@id' in value)) {\n containers.push('@graph@id', '@graph@id@set');\n }\n } else if(_isObject(value) && !_isValue(value)) {\n containers.push('@id', '@id@set', '@type', '@set@type');\n }\n\n // defaults for term selection based on type/language\n let typeOrLanguage = '@language';\n let typeOrLanguageValue = '@null';\n\n if(reverse) {\n typeOrLanguage = '@type';\n typeOrLanguageValue = '@reverse';\n containers.push('@set');\n } else if(_isList(value)) {\n // choose the most specific term that works for all elements in @list\n // only select @list containers if @index is NOT in value\n if(!('@index' in value)) {\n containers.push('@list');\n }\n const list = value['@list'];\n if(list.length === 0) {\n // any empty list can be matched against any term that uses the\n // @list container regardless of @type or @language\n typeOrLanguage = '@any';\n typeOrLanguageValue = '@none';\n } else {\n let commonLanguage = (list.length === 0) ? defaultLanguage : null;\n let commonType = null;\n for(let i = 0; i < list.length; ++i) {\n const item = list[i];\n let itemLanguage = '@none';\n let itemType = '@none';\n if(_isValue(item)) {\n if('@direction' in item) {\n const lang = (item['@language'] || '').toLowerCase();\n const dir = item['@direction'];\n itemLanguage = `${lang}_${dir}`;\n } else if('@language' in item) {\n itemLanguage = item['@language'].toLowerCase();\n } else if('@type' in item) {\n itemType = item['@type'];\n } else {\n // plain literal\n itemLanguage = '@null';\n }\n } else {\n itemType = '@id';\n }\n if(commonLanguage === null) {\n commonLanguage = itemLanguage;\n } else if(itemLanguage !== commonLanguage && _isValue(item)) {\n commonLanguage = '@none';\n }\n if(commonType === null) {\n commonType = itemType;\n } else if(itemType !== commonType) {\n commonType = '@none';\n }\n // there are different languages and types in the list, so choose\n // the most generic term, no need to keep iterating the list\n if(commonLanguage === '@none' && commonType === '@none') {\n break;\n }\n }\n commonLanguage = commonLanguage || '@none';\n commonType = commonType || '@none';\n if(commonType !== '@none') {\n typeOrLanguage = '@type';\n typeOrLanguageValue = commonType;\n } else {\n typeOrLanguageValue = commonLanguage;\n }\n }\n } else {\n if(_isValue(value)) {\n if('@language' in value && !('@index' in value)) {\n containers.push('@language', '@language@set');\n typeOrLanguageValue = value['@language'];\n const dir = value['@direction'];\n if(dir) {\n typeOrLanguageValue = `${typeOrLanguageValue}_${dir}`;\n }\n } else if('@direction' in value && !('@index' in value)) {\n typeOrLanguageValue = `_${value['@direction']}`;\n } else if('@type' in value) {\n typeOrLanguage = '@type';\n typeOrLanguageValue = value['@type'];\n }\n } else {\n typeOrLanguage = '@type';\n typeOrLanguageValue = '@id';\n }\n containers.push('@set');\n }\n\n // do term selection\n containers.push('@none');\n\n // an index map can be used to index values using @none, so add as a low\n // priority\n if(_isObject(value) && !('@index' in value)) {\n // allow indexing even if no @index present\n containers.push('@index', '@index@set');\n }\n\n // values without type or language can use @language map\n if(_isValue(value) && Object.keys(value).length === 1) {\n // allow indexing even if no @index present\n containers.push('@language', '@language@set');\n }\n\n const term = _selectTerm(\n activeCtx, iri, value, containers, typeOrLanguage, typeOrLanguageValue);\n if(term !== null) {\n return term;\n }\n }\n\n // no term match, use @vocab if available\n if(relativeTo.vocab) {\n if('@vocab' in activeCtx) {\n // determine if vocab is a prefix of the iri\n const vocab = activeCtx['@vocab'];\n if(iri.indexOf(vocab) === 0 && iri !== vocab) {\n // use suffix as relative iri if it is not a term in the active context\n const suffix = iri.substr(vocab.length);\n if(!activeCtx.mappings.has(suffix)) {\n return suffix;\n }\n }\n }\n }\n\n // no term or @vocab match, check for possible CURIEs\n let choice = null;\n // TODO: make FastCurieMap a class with a method to do this lookup\n const partialMatches = [];\n let iriMap = activeCtx.fastCurieMap;\n // check for partial matches of against `iri`, which means look until\n // iri.length - 1, not full length\n const maxPartialLength = iri.length - 1;\n for(let i = 0; i < maxPartialLength && iri[i] in iriMap; ++i) {\n iriMap = iriMap[iri[i]];\n if('' in iriMap) {\n partialMatches.push(iriMap[''][0]);\n }\n }\n // check partial matches in reverse order to prefer longest ones first\n for(let i = partialMatches.length - 1; i >= 0; --i) {\n const entry = partialMatches[i];\n const terms = entry.terms;\n for(const term of terms) {\n // a CURIE is usable if:\n // 1. it has no mapping, OR\n // 2. value is null, which means we're not compacting an @value, AND\n // the mapping matches the IRI\n const curie = term + ':' + iri.substr(entry.iri.length);\n const isUsableCurie = (activeCtx.mappings.get(term)._prefix &&\n (!activeCtx.mappings.has(curie) ||\n (value === null && activeCtx.mappings.get(curie)['@id'] === iri)));\n\n // select curie if it is shorter or the same length but lexicographically\n // less than the current choice\n if(isUsableCurie && (choice === null ||\n _compareShortestLeast(curie, choice) < 0)) {\n choice = curie;\n }\n }\n }\n\n // return chosen curie\n if(choice !== null) {\n return choice;\n }\n\n // If iri could be confused with a compact IRI using a term in this context,\n // signal an error\n for(const [term, td] of activeCtx.mappings) {\n if(td && td._prefix && iri.startsWith(term + ':')) {\n throw new JsonLdError(\n `Absolute IRI \"${iri}\" confused with prefix \"${term}\".`,\n 'jsonld.SyntaxError',\n {code: 'IRI confused with prefix', context: activeCtx});\n }\n }\n\n // compact IRI relative to base\n if(!relativeTo.vocab) {\n if('@base' in activeCtx) {\n if(!activeCtx['@base']) {\n // The None case preserves rval as potentially relative\n return iri;\n } else {\n const _iri = _removeBase(_prependBase(base, activeCtx['@base']), iri);\n return REGEX_KEYWORD.test(_iri) ? `./${_iri}` : _iri;\n }\n } else {\n return _removeBase(base, iri);\n }\n }\n\n // return IRI as is\n return iri;\n};\n\n/**\n * Performs value compaction on an object with '@value' or '@id' as the only\n * property.\n *\n * @param activeCtx the active context.\n * @param activeProperty the active property that points to the value.\n * @param value the value to compact.\n * @param {Object} [options] - processing options.\n *\n * @return the compaction result.\n */\napi.compactValue = ({activeCtx, activeProperty, value, options}) => {\n // value is a @value\n if(_isValue(value)) {\n // get context rules\n const type = _getContextValue(activeCtx, activeProperty, '@type');\n const language = _getContextValue(activeCtx, activeProperty, '@language');\n const direction = _getContextValue(activeCtx, activeProperty, '@direction');\n const container =\n _getContextValue(activeCtx, activeProperty, '@container') || [];\n\n // whether or not the value has an @index that must be preserved\n const preserveIndex = '@index' in value && !container.includes('@index');\n\n // if there's no @index to preserve ...\n if(!preserveIndex && type !== '@none') {\n // matching @type or @language specified in context, compact value\n if(value['@type'] === type) {\n return value['@value'];\n }\n if('@language' in value && value['@language'] === language &&\n '@direction' in value && value['@direction'] === direction) {\n return value['@value'];\n }\n if('@language' in value && value['@language'] === language) {\n return value['@value'];\n }\n if('@direction' in value && value['@direction'] === direction) {\n return value['@value'];\n }\n }\n\n // return just the value of @value if all are true:\n // 1. @value is the only key or @index isn't being preserved\n // 2. there is no default language or @value is not a string or\n // the key has a mapping with a null @language\n const keyCount = Object.keys(value).length;\n const isValueOnlyKey = (keyCount === 1 ||\n (keyCount === 2 && '@index' in value && !preserveIndex));\n const hasDefaultLanguage = ('@language' in activeCtx);\n const isValueString = _isString(value['@value']);\n const hasNullMapping = (activeCtx.mappings.has(activeProperty) &&\n activeCtx.mappings.get(activeProperty)['@language'] === null);\n if(isValueOnlyKey &&\n type !== '@none' &&\n (!hasDefaultLanguage || !isValueString || hasNullMapping)) {\n return value['@value'];\n }\n\n const rval = {};\n\n // preserve @index\n if(preserveIndex) {\n rval[api.compactIri({\n activeCtx,\n iri: '@index',\n relativeTo: {vocab: true}\n })] = value['@index'];\n }\n\n if('@type' in value) {\n // compact @type IRI\n rval[api.compactIri({\n activeCtx,\n iri: '@type',\n relativeTo: {vocab: true}\n })] = api.compactIri(\n {activeCtx, iri: value['@type'], relativeTo: {vocab: true}});\n } else if('@language' in value) {\n // alias @language\n rval[api.compactIri({\n activeCtx,\n iri: '@language',\n relativeTo: {vocab: true}\n })] = value['@language'];\n }\n\n if('@direction' in value) {\n // alias @direction\n rval[api.compactIri({\n activeCtx,\n iri: '@direction',\n relativeTo: {vocab: true}\n })] = value['@direction'];\n }\n\n // alias @value\n rval[api.compactIri({\n activeCtx,\n iri: '@value',\n relativeTo: {vocab: true}\n })] = value['@value'];\n\n return rval;\n }\n\n // value is a subject reference\n const expandedProperty = _expandIri(activeCtx, activeProperty, {vocab: true},\n options);\n const type = _getContextValue(activeCtx, activeProperty, '@type');\n const compacted = api.compactIri({\n activeCtx,\n iri: value['@id'],\n relativeTo: {vocab: type === '@vocab'},\n base: options.base});\n\n // compact to scalar\n if(type === '@id' || type === '@vocab' || expandedProperty === '@graph') {\n return compacted;\n }\n\n return {\n [api.compactIri({\n activeCtx,\n iri: '@id',\n relativeTo: {vocab: true}\n })]: compacted\n };\n};\n\n/**\n * Picks the preferred compaction term from the given inverse context entry.\n *\n * @param activeCtx the active context.\n * @param iri the IRI to pick the term for.\n * @param value the value to pick the term for.\n * @param containers the preferred containers.\n * @param typeOrLanguage either '@type' or '@language'.\n * @param typeOrLanguageValue the preferred value for '@type' or '@language'.\n *\n * @return the preferred term.\n */\nfunction _selectTerm(\n activeCtx, iri, value, containers, typeOrLanguage, typeOrLanguageValue) {\n if(typeOrLanguageValue === null) {\n typeOrLanguageValue = '@null';\n }\n\n // preferences for the value of @type or @language\n const prefs = [];\n\n // determine prefs for @id based on whether or not value compacts to a term\n if((typeOrLanguageValue === '@id' || typeOrLanguageValue === '@reverse') &&\n _isObject(value) && '@id' in value) {\n // prefer @reverse first\n if(typeOrLanguageValue === '@reverse') {\n prefs.push('@reverse');\n }\n // try to compact value to a term\n const term = api.compactIri(\n {activeCtx, iri: value['@id'], relativeTo: {vocab: true}});\n if(activeCtx.mappings.has(term) &&\n activeCtx.mappings.get(term) &&\n activeCtx.mappings.get(term)['@id'] === value['@id']) {\n // prefer @vocab\n prefs.push.apply(prefs, ['@vocab', '@id']);\n } else {\n // prefer @id\n prefs.push.apply(prefs, ['@id', '@vocab']);\n }\n } else {\n prefs.push(typeOrLanguageValue);\n\n // consider direction only\n const langDir = prefs.find(el => el.includes('_'));\n if(langDir) {\n // consider _dir portion\n prefs.push(langDir.replace(/^[^_]+_/, '_'));\n }\n }\n prefs.push('@none');\n\n const containerMap = activeCtx.inverse[iri];\n for(const container of containers) {\n // if container not available in the map, continue\n if(!(container in containerMap)) {\n continue;\n }\n\n const typeOrLanguageValueMap = containerMap[container][typeOrLanguage];\n for(const pref of prefs) {\n // if type/language option not available in the map, continue\n if(!(pref in typeOrLanguageValueMap)) {\n continue;\n }\n\n // select term\n return typeOrLanguageValueMap[pref];\n }\n }\n\n return null;\n}\n\n/**\n * The value of `@nest` in the term definition must either be `@nest`, or a term\n * which resolves to `@nest`.\n *\n * @param activeCtx the active context.\n * @param nestProperty a term in the active context or `@nest`.\n * @param {Object} [options] - processing options.\n */\nfunction _checkNestProperty(activeCtx, nestProperty, options) {\n if(_expandIri(activeCtx, nestProperty, {vocab: true}, options) !== '@nest') {\n throw new JsonLdError(\n 'JSON-LD compact error; nested property must have an @nest value ' +\n 'resolving to @nest.',\n 'jsonld.SyntaxError', {code: 'invalid @nest value'});\n }\n}\n","/*\n * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';\nconst XSD = 'http://www.w3.org/2001/XMLSchema#';\n\nmodule.exports = {\n // TODO: Deprecated and will be removed later. Use LINK_HEADER_CONTEXT.\n LINK_HEADER_REL: 'http://www.w3.org/ns/json-ld#context',\n\n LINK_HEADER_CONTEXT: 'http://www.w3.org/ns/json-ld#context',\n\n RDF,\n RDF_LIST: RDF + 'List',\n RDF_FIRST: RDF + 'first',\n RDF_REST: RDF + 'rest',\n RDF_NIL: RDF + 'nil',\n RDF_TYPE: RDF + 'type',\n RDF_PLAIN_LITERAL: RDF + 'PlainLiteral',\n RDF_XML_LITERAL: RDF + 'XMLLiteral',\n RDF_JSON_LITERAL: RDF + 'JSON',\n RDF_OBJECT: RDF + 'object',\n RDF_LANGSTRING: RDF + 'langString',\n\n XSD,\n XSD_BOOLEAN: XSD + 'boolean',\n XSD_DOUBLE: XSD + 'double',\n XSD_INTEGER: XSD + 'integer',\n XSD_STRING: XSD + 'string',\n};\n","/*\n * Copyright (c) 2017-2019 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst util = require('./util');\nconst JsonLdError = require('./JsonLdError');\n\nconst {\n isArray: _isArray,\n isObject: _isObject,\n isString: _isString,\n isUndefined: _isUndefined\n} = require('./types');\n\nconst {\n isAbsolute: _isAbsoluteIri,\n isRelative: _isRelativeIri,\n prependBase\n} = require('./url');\n\nconst {\n handleEvent: _handleEvent\n} = require('./events');\n\nconst {\n REGEX_BCP47,\n REGEX_KEYWORD,\n asArray: _asArray,\n compareShortestLeast: _compareShortestLeast\n} = require('./util');\n\nconst INITIAL_CONTEXT_CACHE = new Map();\nconst INITIAL_CONTEXT_CACHE_MAX_SIZE = 10000;\n\nconst api = {};\nmodule.exports = api;\n\n/**\n * Processes a local context and returns a new active context.\n *\n * @param activeCtx the current active context.\n * @param localCtx the local context to process.\n * @param options the context processing options.\n * @param propagate `true` if `false`, retains any previously defined term,\n * which can be rolled back when the descending into a new node object.\n * @param overrideProtected `false` allows protected terms to be modified.\n *\n * @return a Promise that resolves to the new active context.\n */\napi.process = async ({\n activeCtx, localCtx, options,\n propagate = true,\n overrideProtected = false,\n cycles = new Set()\n}) => {\n // normalize local context to an array of @context objects\n if(_isObject(localCtx) && '@context' in localCtx &&\n _isArray(localCtx['@context'])) {\n localCtx = localCtx['@context'];\n }\n const ctxs = _asArray(localCtx);\n\n // no contexts in array, return current active context w/o changes\n if(ctxs.length === 0) {\n return activeCtx;\n }\n\n // event handler for capturing events to replay when using a cached context\n const events = [];\n const eventCaptureHandler = [\n ({event, next}) => {\n events.push(event);\n next();\n }\n ];\n // chain to original handler\n if(options.eventHandler) {\n eventCaptureHandler.push(options.eventHandler);\n }\n // store original options to use when replaying events\n const originalOptions = options;\n // shallow clone options with event capture handler\n options = {...options, eventHandler: eventCaptureHandler};\n\n // resolve contexts\n const resolved = await options.contextResolver.resolve({\n activeCtx,\n context: localCtx,\n documentLoader: options.documentLoader,\n base: options.base\n });\n\n // override propagate if first resolved context has `@propagate`\n if(_isObject(resolved[0].document) &&\n typeof resolved[0].document['@propagate'] === 'boolean') {\n // retrieve early, error checking done later\n propagate = resolved[0].document['@propagate'];\n }\n\n // process each context in order, update active context\n // on each iteration to ensure proper caching\n let rval = activeCtx;\n\n // track the previous context\n // if not propagating, make sure rval has a previous context\n if(!propagate && !rval.previousContext) {\n // clone `rval` context before updating\n rval = rval.clone();\n rval.previousContext = activeCtx;\n }\n\n for(const resolvedContext of resolved) {\n let {document: ctx} = resolvedContext;\n\n // update active context to one computed from last iteration\n activeCtx = rval;\n\n // reset to initial context\n if(ctx === null) {\n // We can't nullify if there are protected terms and we're\n // not allowing overrides (e.g. processing a property term scoped context)\n if(!overrideProtected && Object.keys(activeCtx.protected).length !== 0) {\n throw new JsonLdError(\n 'Tried to nullify a context with protected terms outside of ' +\n 'a term definition.',\n 'jsonld.SyntaxError',\n {code: 'invalid context nullification'});\n }\n rval = activeCtx = api.getInitialContext(options).clone();\n continue;\n }\n\n // get processed context from cache if available\n const processed = resolvedContext.getProcessed(activeCtx);\n if(processed) {\n if(originalOptions.eventHandler) {\n // replay events with original non-capturing options\n for(const event of processed.events) {\n _handleEvent({event, options: originalOptions});\n }\n }\n\n rval = activeCtx = processed.context;\n continue;\n }\n\n // dereference @context key if present\n if(_isObject(ctx) && '@context' in ctx) {\n ctx = ctx['@context'];\n }\n\n // context must be an object by now, all URLs retrieved before this call\n if(!_isObject(ctx)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @context must be an object.',\n 'jsonld.SyntaxError', {code: 'invalid local context', context: ctx});\n }\n\n // TODO: there is likely a `previousContext` cloning optimization that\n // could be applied here (no need to copy it under certain conditions)\n\n // clone context before updating it\n rval = rval.clone();\n\n // define context mappings for keys in local context\n const defined = new Map();\n\n // handle @version\n if('@version' in ctx) {\n if(ctx['@version'] !== 1.1) {\n throw new JsonLdError(\n 'Unsupported JSON-LD version: ' + ctx['@version'],\n 'jsonld.UnsupportedVersion',\n {code: 'invalid @version value', context: ctx});\n }\n if(activeCtx.processingMode &&\n activeCtx.processingMode === 'json-ld-1.0') {\n throw new JsonLdError(\n '@version: ' + ctx['@version'] + ' not compatible with ' +\n activeCtx.processingMode,\n 'jsonld.ProcessingModeConflict',\n {code: 'processing mode conflict', context: ctx});\n }\n rval.processingMode = 'json-ld-1.1';\n rval['@version'] = ctx['@version'];\n defined.set('@version', true);\n }\n\n // if not set explicitly, set processingMode to \"json-ld-1.1\"\n rval.processingMode =\n rval.processingMode || activeCtx.processingMode;\n\n // handle @base\n if('@base' in ctx) {\n let base = ctx['@base'];\n\n if(base === null || _isAbsoluteIri(base)) {\n // no action\n } else if(_isRelativeIri(base)) {\n base = prependBase(rval['@base'], base);\n } else {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; the value of \"@base\" in a ' +\n '@context must be an absolute IRI, a relative IRI, or null.',\n 'jsonld.SyntaxError', {code: 'invalid base IRI', context: ctx});\n }\n\n rval['@base'] = base;\n defined.set('@base', true);\n }\n\n // handle @vocab\n if('@vocab' in ctx) {\n const value = ctx['@vocab'];\n if(value === null) {\n delete rval['@vocab'];\n } else if(!_isString(value)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; the value of \"@vocab\" in a ' +\n '@context must be a string or null.',\n 'jsonld.SyntaxError', {code: 'invalid vocab mapping', context: ctx});\n } else if(!_isAbsoluteIri(value) && api.processingMode(rval, 1.0)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; the value of \"@vocab\" in a ' +\n '@context must be an absolute IRI.',\n 'jsonld.SyntaxError', {code: 'invalid vocab mapping', context: ctx});\n } else {\n const vocab = _expandIri(rval, value, {vocab: true, base: true},\n undefined, undefined, options);\n if(!_isAbsoluteIri(vocab)) {\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'relative @vocab reference',\n level: 'warning',\n message: 'Relative @vocab reference found.',\n details: {\n vocab\n }\n },\n options\n });\n }\n }\n rval['@vocab'] = vocab;\n }\n defined.set('@vocab', true);\n }\n\n // handle @language\n if('@language' in ctx) {\n const value = ctx['@language'];\n if(value === null) {\n delete rval['@language'];\n } else if(!_isString(value)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; the value of \"@language\" in a ' +\n '@context must be a string or null.',\n 'jsonld.SyntaxError',\n {code: 'invalid default language', context: ctx});\n } else {\n if(!value.match(REGEX_BCP47)) {\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'invalid @language value',\n level: 'warning',\n message: '@language value must be valid BCP47.',\n details: {\n language: value\n }\n },\n options\n });\n }\n }\n rval['@language'] = value.toLowerCase();\n }\n defined.set('@language', true);\n }\n\n // handle @direction\n if('@direction' in ctx) {\n const value = ctx['@direction'];\n if(activeCtx.processingMode === 'json-ld-1.0') {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @direction not compatible with ' +\n activeCtx.processingMode,\n 'jsonld.SyntaxError',\n {code: 'invalid context member', context: ctx});\n }\n if(value === null) {\n delete rval['@direction'];\n } else if(value !== 'ltr' && value !== 'rtl') {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; the value of \"@direction\" in a ' +\n '@context must be null, \"ltr\", or \"rtl\".',\n 'jsonld.SyntaxError',\n {code: 'invalid base direction', context: ctx});\n } else {\n rval['@direction'] = value;\n }\n defined.set('@direction', true);\n }\n\n // handle @propagate\n // note: we've already extracted it, here we just do error checking\n if('@propagate' in ctx) {\n const value = ctx['@propagate'];\n if(activeCtx.processingMode === 'json-ld-1.0') {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @propagate not compatible with ' +\n activeCtx.processingMode,\n 'jsonld.SyntaxError',\n {code: 'invalid context entry', context: ctx});\n }\n if(typeof value !== 'boolean') {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @propagate value must be a boolean.',\n 'jsonld.SyntaxError',\n {code: 'invalid @propagate value', context: localCtx});\n }\n defined.set('@propagate', true);\n }\n\n // handle @import\n if('@import' in ctx) {\n const value = ctx['@import'];\n if(activeCtx.processingMode === 'json-ld-1.0') {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @import not compatible with ' +\n activeCtx.processingMode,\n 'jsonld.SyntaxError',\n {code: 'invalid context entry', context: ctx});\n }\n if(!_isString(value)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @import must be a string.',\n 'jsonld.SyntaxError',\n {code: 'invalid @import value', context: localCtx});\n }\n\n // resolve contexts\n const resolvedImport = await options.contextResolver.resolve({\n activeCtx,\n context: value,\n documentLoader: options.documentLoader,\n base: options.base\n });\n if(resolvedImport.length !== 1) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @import must reference a single context.',\n 'jsonld.SyntaxError',\n {code: 'invalid remote context', context: localCtx});\n }\n const processedImport = resolvedImport[0].getProcessed(activeCtx);\n if(processedImport) {\n // Note: if the same context were used in this active context\n // as a reference context, then processed_input might not\n // be a dict.\n ctx = processedImport;\n } else {\n const importCtx = resolvedImport[0].document;\n if('@import' in importCtx) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax: ' +\n 'imported context must not include @import.',\n 'jsonld.SyntaxError',\n {code: 'invalid context entry', context: localCtx});\n }\n\n // merge ctx into importCtx and replace rval with the result\n for(const key in importCtx) {\n if(!ctx.hasOwnProperty(key)) {\n ctx[key] = importCtx[key];\n }\n }\n\n // Note: this could potenially conflict if the import\n // were used in the same active context as a referenced\n // context and an import. In this case, we\n // could override the cached result, but seems unlikely.\n resolvedImport[0].setProcessed(activeCtx, ctx);\n }\n\n defined.set('@import', true);\n }\n\n // handle @protected; determine whether this sub-context is declaring\n // all its terms to be \"protected\" (exceptions can be made on a\n // per-definition basis)\n defined.set('@protected', ctx['@protected'] || false);\n\n // process all other keys\n for(const key in ctx) {\n api.createTermDefinition({\n activeCtx: rval,\n localCtx: ctx,\n term: key,\n defined,\n options,\n overrideProtected\n });\n\n if(_isObject(ctx[key]) && '@context' in ctx[key]) {\n const keyCtx = ctx[key]['@context'];\n let process = true;\n if(_isString(keyCtx)) {\n const url = prependBase(options.base, keyCtx);\n // track processed contexts to avoid scoped context recursion\n if(cycles.has(url)) {\n process = false;\n } else {\n cycles.add(url);\n }\n }\n // parse context to validate\n if(process) {\n try {\n await api.process({\n activeCtx: rval.clone(),\n localCtx: ctx[key]['@context'],\n overrideProtected: true,\n options,\n cycles\n });\n } catch(e) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; invalid scoped context.',\n 'jsonld.SyntaxError',\n {\n code: 'invalid scoped context',\n context: ctx[key]['@context'],\n term: key\n });\n }\n }\n }\n }\n\n // cache processed result\n resolvedContext.setProcessed(activeCtx, {\n context: rval,\n events\n });\n }\n\n return rval;\n};\n\n/**\n * Creates a term definition during context processing.\n *\n * @param activeCtx the current active context.\n * @param localCtx the local context being processed.\n * @param term the term in the local context to define the mapping for.\n * @param defined a map of defining/defined keys to detect cycles and prevent\n * double definitions.\n * @param {Object} [options] - creation options.\n * @param overrideProtected `false` allows protected terms to be modified.\n */\napi.createTermDefinition = ({\n activeCtx,\n localCtx,\n term,\n defined,\n options,\n overrideProtected = false,\n}) => {\n if(defined.has(term)) {\n // term already defined\n if(defined.get(term)) {\n return;\n }\n // cycle detected\n throw new JsonLdError(\n 'Cyclical context definition detected.',\n 'jsonld.CyclicalContext',\n {code: 'cyclic IRI mapping', context: localCtx, term});\n }\n\n // now defining term\n defined.set(term, false);\n\n // get context term value\n let value;\n if(localCtx.hasOwnProperty(term)) {\n value = localCtx[term];\n }\n\n if(term === '@type' &&\n _isObject(value) &&\n (value['@container'] || '@set') === '@set' &&\n api.processingMode(activeCtx, 1.1)) {\n\n const validKeys = ['@container', '@id', '@protected'];\n const keys = Object.keys(value);\n if(keys.length === 0 || keys.some(k => !validKeys.includes(k))) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; keywords cannot be overridden.',\n 'jsonld.SyntaxError',\n {code: 'keyword redefinition', context: localCtx, term});\n }\n } else if(api.isKeyword(term)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; keywords cannot be overridden.',\n 'jsonld.SyntaxError',\n {code: 'keyword redefinition', context: localCtx, term});\n } else if(term.match(REGEX_KEYWORD)) {\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'reserved term',\n level: 'warning',\n message:\n 'Terms beginning with \"@\" are ' +\n 'reserved for future use and dropped.',\n details: {\n term\n }\n },\n options\n });\n }\n return;\n } else if(term === '') {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; a term cannot be an empty string.',\n 'jsonld.SyntaxError',\n {code: 'invalid term definition', context: localCtx});\n }\n\n // keep reference to previous mapping for potential `@protected` check\n const previousMapping = activeCtx.mappings.get(term);\n\n // remove old mapping\n if(activeCtx.mappings.has(term)) {\n activeCtx.mappings.delete(term);\n }\n\n // convert short-hand value to object w/@id\n let simpleTerm = false;\n if(_isString(value) || value === null) {\n simpleTerm = true;\n value = {'@id': value};\n }\n\n if(!_isObject(value)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @context term values must be ' +\n 'strings or objects.',\n 'jsonld.SyntaxError',\n {code: 'invalid term definition', context: localCtx});\n }\n\n // create new mapping\n const mapping = {};\n activeCtx.mappings.set(term, mapping);\n mapping.reverse = false;\n\n // make sure term definition only has expected keywords\n const validKeys = ['@container', '@id', '@language', '@reverse', '@type'];\n\n // JSON-LD 1.1 support\n if(api.processingMode(activeCtx, 1.1)) {\n validKeys.push(\n '@context', '@direction', '@index', '@nest', '@prefix', '@protected');\n }\n\n for(const kw in value) {\n if(!validKeys.includes(kw)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; a term definition must not contain ' + kw,\n 'jsonld.SyntaxError',\n {code: 'invalid term definition', context: localCtx});\n }\n }\n\n // always compute whether term has a colon as an optimization for\n // _compactIri\n const colon = term.indexOf(':');\n mapping._termHasColon = (colon > 0);\n\n if('@reverse' in value) {\n if('@id' in value) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; a @reverse term definition must not ' +\n 'contain @id.', 'jsonld.SyntaxError',\n {code: 'invalid reverse property', context: localCtx});\n }\n if('@nest' in value) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; a @reverse term definition must not ' +\n 'contain @nest.', 'jsonld.SyntaxError',\n {code: 'invalid reverse property', context: localCtx});\n }\n const reverse = value['@reverse'];\n if(!_isString(reverse)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; a @context @reverse value must be a string.',\n 'jsonld.SyntaxError', {code: 'invalid IRI mapping', context: localCtx});\n }\n\n if(reverse.match(REGEX_KEYWORD)) {\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'reserved @reverse value',\n level: 'warning',\n message:\n '@reverse values beginning with \"@\" are ' +\n 'reserved for future use and dropped.',\n details: {\n reverse\n }\n },\n options\n });\n }\n if(previousMapping) {\n activeCtx.mappings.set(term, previousMapping);\n } else {\n activeCtx.mappings.delete(term);\n }\n return;\n }\n\n // expand and add @id mapping\n const id = _expandIri(\n activeCtx, reverse, {vocab: true, base: false}, localCtx, defined,\n options);\n if(!_isAbsoluteIri(id)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; a @context @reverse value must be an ' +\n 'absolute IRI or a blank node identifier.',\n 'jsonld.SyntaxError', {code: 'invalid IRI mapping', context: localCtx});\n }\n\n mapping['@id'] = id;\n mapping.reverse = true;\n } else if('@id' in value) {\n let id = value['@id'];\n if(id && !_isString(id)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; a @context @id value must be an array ' +\n 'of strings or a string.',\n 'jsonld.SyntaxError', {code: 'invalid IRI mapping', context: localCtx});\n }\n if(id === null) {\n // reserve a null term, which may be protected\n mapping['@id'] = null;\n } else if(!api.isKeyword(id) && id.match(REGEX_KEYWORD)) {\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'reserved @id value',\n level: 'warning',\n message:\n '@id values beginning with \"@\" are ' +\n 'reserved for future use and dropped.',\n details: {\n id\n }\n },\n options\n });\n }\n if(previousMapping) {\n activeCtx.mappings.set(term, previousMapping);\n } else {\n activeCtx.mappings.delete(term);\n }\n return;\n } else if(id !== term) {\n // expand and add @id mapping\n id = _expandIri(\n activeCtx, id, {vocab: true, base: false}, localCtx, defined, options);\n if(!_isAbsoluteIri(id) && !api.isKeyword(id)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; a @context @id value must be an ' +\n 'absolute IRI, a blank node identifier, or a keyword.',\n 'jsonld.SyntaxError',\n {code: 'invalid IRI mapping', context: localCtx});\n }\n\n // if term has the form of an IRI it must map the same\n if(term.match(/(?::[^:])|\\//)) {\n const termDefined = new Map(defined).set(term, true);\n const termIri = _expandIri(\n activeCtx, term, {vocab: true, base: false},\n localCtx, termDefined, options);\n if(termIri !== id) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; term in form of IRI must ' +\n 'expand to definition.',\n 'jsonld.SyntaxError',\n {code: 'invalid IRI mapping', context: localCtx});\n }\n }\n\n mapping['@id'] = id;\n // indicate if this term may be used as a compact IRI prefix\n mapping._prefix = (simpleTerm &&\n !mapping._termHasColon &&\n id.match(/[:\\/\\?#\\[\\]@]$/) !== null);\n }\n }\n\n if(!('@id' in mapping)) {\n // see if the term has a prefix\n if(mapping._termHasColon) {\n const prefix = term.substr(0, colon);\n if(localCtx.hasOwnProperty(prefix)) {\n // define parent prefix\n api.createTermDefinition({\n activeCtx, localCtx, term: prefix, defined, options\n });\n }\n\n if(activeCtx.mappings.has(prefix)) {\n // set @id based on prefix parent\n const suffix = term.substr(colon + 1);\n mapping['@id'] = activeCtx.mappings.get(prefix)['@id'] + suffix;\n } else {\n // term is an absolute IRI\n mapping['@id'] = term;\n }\n } else if(term === '@type') {\n // Special case, were we've previously determined that container is @set\n mapping['@id'] = term;\n } else {\n // non-IRIs *must* define @ids if @vocab is not available\n if(!('@vocab' in activeCtx)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @context terms must define an @id.',\n 'jsonld.SyntaxError',\n {code: 'invalid IRI mapping', context: localCtx, term});\n }\n // prepend vocab to term\n mapping['@id'] = activeCtx['@vocab'] + term;\n }\n }\n\n // Handle term protection\n if(value['@protected'] === true ||\n (defined.get('@protected') === true && value['@protected'] !== false)) {\n activeCtx.protected[term] = true;\n mapping.protected = true;\n }\n\n // IRI mapping now defined\n defined.set(term, true);\n\n if('@type' in value) {\n let type = value['@type'];\n if(!_isString(type)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; an @context @type value must be a string.',\n 'jsonld.SyntaxError',\n {code: 'invalid type mapping', context: localCtx});\n }\n\n if((type === '@json' || type === '@none')) {\n if(api.processingMode(activeCtx, 1.0)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; an @context @type value must not be ' +\n `\"${type}\" in JSON-LD 1.0 mode.`,\n 'jsonld.SyntaxError',\n {code: 'invalid type mapping', context: localCtx});\n }\n } else if(type !== '@id' && type !== '@vocab') {\n // expand @type to full IRI\n type = _expandIri(\n activeCtx, type, {vocab: true, base: false}, localCtx, defined,\n options);\n if(!_isAbsoluteIri(type)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; an @context @type value must be an ' +\n 'absolute IRI.',\n 'jsonld.SyntaxError',\n {code: 'invalid type mapping', context: localCtx});\n }\n if(type.indexOf('_:') === 0) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; an @context @type value must be an IRI, ' +\n 'not a blank node identifier.',\n 'jsonld.SyntaxError',\n {code: 'invalid type mapping', context: localCtx});\n }\n }\n\n // add @type to mapping\n mapping['@type'] = type;\n }\n\n if('@container' in value) {\n // normalize container to an array form\n const container = _isString(value['@container']) ?\n [value['@container']] : (value['@container'] || []);\n const validContainers = ['@list', '@set', '@index', '@language'];\n let isValid = true;\n const hasSet = container.includes('@set');\n\n // JSON-LD 1.1 support\n if(api.processingMode(activeCtx, 1.1)) {\n validContainers.push('@graph', '@id', '@type');\n\n // check container length\n if(container.includes('@list')) {\n if(container.length !== 1) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @context @container with @list must ' +\n 'have no other values',\n 'jsonld.SyntaxError',\n {code: 'invalid container mapping', context: localCtx});\n }\n } else if(container.includes('@graph')) {\n if(container.some(key =>\n key !== '@graph' && key !== '@id' && key !== '@index' &&\n key !== '@set')) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @context @container with @graph must ' +\n 'have no other values other than @id, @index, and @set',\n 'jsonld.SyntaxError',\n {code: 'invalid container mapping', context: localCtx});\n }\n } else {\n // otherwise, container may also include @set\n isValid &= container.length <= (hasSet ? 2 : 1);\n }\n\n if(container.includes('@type')) {\n // If mapping does not have an @type,\n // set it to @id\n mapping['@type'] = mapping['@type'] || '@id';\n\n // type mapping must be either @id or @vocab\n if(!['@id', '@vocab'].includes(mapping['@type'])) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; container: @type requires @type to be ' +\n '@id or @vocab.',\n 'jsonld.SyntaxError',\n {code: 'invalid type mapping', context: localCtx});\n }\n }\n } else {\n // in JSON-LD 1.0, container must not be an array (it must be a string,\n // which is one of the validContainers)\n isValid &= !_isArray(value['@container']);\n\n // check container length\n isValid &= container.length <= 1;\n }\n\n // check against valid containers\n isValid &= container.every(c => validContainers.includes(c));\n\n // @set not allowed with @list\n isValid &= !(hasSet && container.includes('@list'));\n\n if(!isValid) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @context @container value must be ' +\n 'one of the following: ' + validContainers.join(', '),\n 'jsonld.SyntaxError',\n {code: 'invalid container mapping', context: localCtx});\n }\n\n if(mapping.reverse &&\n !container.every(c => ['@index', '@set'].includes(c))) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @context @container value for a @reverse ' +\n 'type definition must be @index or @set.', 'jsonld.SyntaxError',\n {code: 'invalid reverse property', context: localCtx});\n }\n\n // add @container to mapping\n mapping['@container'] = container;\n }\n\n // property indexing\n if('@index' in value) {\n if(!('@container' in value) || !mapping['@container'].includes('@index')) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @index without @index in @container: ' +\n `\"${value['@index']}\" on term \"${term}\".`, 'jsonld.SyntaxError',\n {code: 'invalid term definition', context: localCtx});\n }\n if(!_isString(value['@index']) || value['@index'].indexOf('@') === 0) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @index must expand to an IRI: ' +\n `\"${value['@index']}\" on term \"${term}\".`, 'jsonld.SyntaxError',\n {code: 'invalid term definition', context: localCtx});\n }\n mapping['@index'] = value['@index'];\n }\n\n // scoped contexts\n if('@context' in value) {\n mapping['@context'] = value['@context'];\n }\n\n if('@language' in value && !('@type' in value)) {\n let language = value['@language'];\n if(language !== null && !_isString(language)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @context @language value must be ' +\n 'a string or null.', 'jsonld.SyntaxError',\n {code: 'invalid language mapping', context: localCtx});\n }\n\n // add @language to mapping\n if(language !== null) {\n language = language.toLowerCase();\n }\n mapping['@language'] = language;\n }\n\n // term may be used as a prefix\n if('@prefix' in value) {\n if(term.match(/:|\\//)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @context @prefix used on a compact IRI term',\n 'jsonld.SyntaxError',\n {code: 'invalid term definition', context: localCtx});\n }\n if(api.isKeyword(mapping['@id'])) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; keywords may not be used as prefixes',\n 'jsonld.SyntaxError',\n {code: 'invalid term definition', context: localCtx});\n }\n if(typeof value['@prefix'] === 'boolean') {\n mapping._prefix = value['@prefix'] === true;\n } else {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @context value for @prefix must be boolean',\n 'jsonld.SyntaxError',\n {code: 'invalid @prefix value', context: localCtx});\n }\n }\n\n if('@direction' in value) {\n const direction = value['@direction'];\n if(direction !== null && direction !== 'ltr' && direction !== 'rtl') {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @direction value must be ' +\n 'null, \"ltr\", or \"rtl\".',\n 'jsonld.SyntaxError',\n {code: 'invalid base direction', context: localCtx});\n }\n mapping['@direction'] = direction;\n }\n\n if('@nest' in value) {\n const nest = value['@nest'];\n if(!_isString(nest) || (nest !== '@nest' && nest.indexOf('@') === 0)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @context @nest value must be ' +\n 'a string which is not a keyword other than @nest.',\n 'jsonld.SyntaxError',\n {code: 'invalid @nest value', context: localCtx});\n }\n mapping['@nest'] = nest;\n }\n\n // disallow aliasing @context and @preserve\n const id = mapping['@id'];\n if(id === '@context' || id === '@preserve') {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @context and @preserve cannot be aliased.',\n 'jsonld.SyntaxError', {code: 'invalid keyword alias', context: localCtx});\n }\n\n // Check for overriding protected terms\n if(previousMapping && previousMapping.protected && !overrideProtected) {\n // force new term to continue to be protected and see if the mappings would\n // be equal\n activeCtx.protected[term] = true;\n mapping.protected = true;\n if(!_deepCompare(previousMapping, mapping)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; tried to redefine a protected term.',\n 'jsonld.SyntaxError',\n {code: 'protected term redefinition', context: localCtx, term});\n }\n }\n};\n\n/**\n * Expands a string to a full IRI. The string may be a term, a prefix, a\n * relative IRI, or an absolute IRI. The associated absolute IRI will be\n * returned.\n *\n * @param activeCtx the current active context.\n * @param value the string to expand.\n * @param relativeTo options for how to resolve relative IRIs:\n * base: true to resolve against the base IRI, false not to.\n * vocab: true to concatenate after @vocab, false not to.\n * @param {Object} [options] - processing options.\n *\n * @return the expanded value.\n */\napi.expandIri = (activeCtx, value, relativeTo, options) => {\n return _expandIri(activeCtx, value, relativeTo, undefined, undefined,\n options);\n};\n\n/**\n * Expands a string to a full IRI. The string may be a term, a prefix, a\n * relative IRI, or an absolute IRI. The associated absolute IRI will be\n * returned.\n *\n * @param activeCtx the current active context.\n * @param value the string to expand.\n * @param relativeTo options for how to resolve relative IRIs:\n * base: true to resolve against the base IRI, false not to.\n * vocab: true to concatenate after @vocab, false not to.\n * @param localCtx the local context being processed (only given if called\n * during context processing).\n * @param defined a map for tracking cycles in context definitions (only given\n * if called during context processing).\n * @param {Object} [options] - processing options.\n *\n * @return the expanded value.\n */\nfunction _expandIri(activeCtx, value, relativeTo, localCtx, defined, options) {\n // already expanded\n if(value === null || !_isString(value) || api.isKeyword(value)) {\n return value;\n }\n\n // ignore non-keyword things that look like a keyword\n if(value.match(REGEX_KEYWORD)) {\n return null;\n }\n\n // define term dependency if not defined\n if(localCtx && localCtx.hasOwnProperty(value) &&\n defined.get(value) !== true) {\n api.createTermDefinition({\n activeCtx, localCtx, term: value, defined, options\n });\n }\n\n relativeTo = relativeTo || {};\n if(relativeTo.vocab) {\n const mapping = activeCtx.mappings.get(value);\n\n // value is explicitly ignored with a null mapping\n if(mapping === null) {\n return null;\n }\n\n if(_isObject(mapping) && '@id' in mapping) {\n // value is a term\n return mapping['@id'];\n }\n }\n\n // split value into prefix:suffix\n const colon = value.indexOf(':');\n if(colon > 0) {\n const prefix = value.substr(0, colon);\n const suffix = value.substr(colon + 1);\n\n // do not expand blank nodes (prefix of '_') or already-absolute\n // IRIs (suffix of '//')\n if(prefix === '_' || suffix.indexOf('//') === 0) {\n return value;\n }\n\n // prefix dependency not defined, define it\n if(localCtx && localCtx.hasOwnProperty(prefix)) {\n api.createTermDefinition({\n activeCtx, localCtx, term: prefix, defined, options\n });\n }\n\n // use mapping if prefix is defined\n const mapping = activeCtx.mappings.get(prefix);\n if(mapping && mapping._prefix) {\n return mapping['@id'] + suffix;\n }\n\n // already absolute IRI\n if(_isAbsoluteIri(value)) {\n return value;\n }\n }\n\n // A flag that captures whether the iri being expanded is\n // the value for an @type\n //let typeExpansion = false;\n\n //if(options !== undefined && options.typeExpansion !== undefined) {\n // typeExpansion = options.typeExpansion;\n //}\n\n if(relativeTo.vocab && '@vocab' in activeCtx) {\n // prepend vocab\n const prependedResult = activeCtx['@vocab'] + value;\n // FIXME: needed? may be better as debug event.\n /*\n if(options && options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'prepending @vocab during expansion',\n level: 'info',\n message: 'Prepending @vocab during expansion.',\n details: {\n type: '@vocab',\n vocab: activeCtx['@vocab'],\n value,\n result: prependedResult,\n typeExpansion\n }\n },\n options\n });\n }\n */\n // the null case preserves value as potentially relative\n value = prependedResult;\n } else if(relativeTo.base) {\n // prepend base\n let prependedResult;\n let base;\n if('@base' in activeCtx) {\n if(activeCtx['@base']) {\n base = prependBase(options.base, activeCtx['@base']);\n prependedResult = prependBase(base, value);\n } else {\n base = activeCtx['@base'];\n prependedResult = value;\n }\n } else {\n base = options.base;\n prependedResult = prependBase(options.base, value);\n }\n // FIXME: needed? may be better as debug event.\n /*\n if(options && options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'prepending @base during expansion',\n level: 'info',\n message: 'Prepending @base during expansion.',\n details: {\n type: '@base',\n base,\n value,\n result: prependedResult,\n typeExpansion\n }\n },\n options\n });\n }\n */\n // the null case preserves value as potentially relative\n value = prependedResult;\n }\n\n // FIXME: duplicate? needed? maybe just enable in a verbose debug mode\n /*\n if(!_isAbsoluteIri(value) && options && options.eventHandler) {\n // emit event indicating a relative IRI was found, which can result in it\n // being dropped when converting to other RDF representations\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'relative IRI after expansion',\n // FIXME: what level?\n level: 'warning',\n message: 'Relative IRI after expansion.',\n details: {\n relativeIri: value,\n typeExpansion\n }\n },\n options\n });\n // NOTE: relative reference events emitted at calling sites as needed\n }\n */\n\n return value;\n}\n\n/**\n * Gets the initial context.\n *\n * @param options the options to use:\n * [base] the document base IRI.\n *\n * @return the initial context.\n */\napi.getInitialContext = options => {\n const key = JSON.stringify({processingMode: options.processingMode});\n const cached = INITIAL_CONTEXT_CACHE.get(key);\n if(cached) {\n return cached;\n }\n\n const initialContext = {\n processingMode: options.processingMode,\n mappings: new Map(),\n inverse: null,\n getInverse: _createInverseContext,\n clone: _cloneActiveContext,\n revertToPreviousContext: _revertToPreviousContext,\n protected: {}\n };\n // TODO: consider using LRU cache instead\n if(INITIAL_CONTEXT_CACHE.size === INITIAL_CONTEXT_CACHE_MAX_SIZE) {\n // clear whole cache -- assumes scenario where the cache fills means\n // the cache isn't being used very efficiently anyway\n INITIAL_CONTEXT_CACHE.clear();\n }\n INITIAL_CONTEXT_CACHE.set(key, initialContext);\n return initialContext;\n\n /**\n * Generates an inverse context for use in the compaction algorithm, if\n * not already generated for the given active context.\n *\n * @return the inverse context.\n */\n function _createInverseContext() {\n const activeCtx = this;\n\n // lazily create inverse\n if(activeCtx.inverse) {\n return activeCtx.inverse;\n }\n const inverse = activeCtx.inverse = {};\n\n // variables for building fast CURIE map\n const fastCurieMap = activeCtx.fastCurieMap = {};\n const irisToTerms = {};\n\n // handle default language\n const defaultLanguage = (activeCtx['@language'] || '@none').toLowerCase();\n\n // handle default direction\n const defaultDirection = activeCtx['@direction'];\n\n // create term selections for each mapping in the context, ordered by\n // shortest and then lexicographically least\n const mappings = activeCtx.mappings;\n const terms = [...mappings.keys()].sort(_compareShortestLeast);\n for(const term of terms) {\n const mapping = mappings.get(term);\n if(mapping === null) {\n continue;\n }\n\n let container = mapping['@container'] || '@none';\n container = [].concat(container).sort().join('');\n\n if(mapping['@id'] === null) {\n continue;\n }\n // iterate over every IRI in the mapping\n const ids = _asArray(mapping['@id']);\n for(const iri of ids) {\n let entry = inverse[iri];\n const isKeyword = api.isKeyword(iri);\n\n if(!entry) {\n // initialize entry\n inverse[iri] = entry = {};\n\n if(!isKeyword && !mapping._termHasColon) {\n // init IRI to term map and fast CURIE prefixes\n irisToTerms[iri] = [term];\n const fastCurieEntry = {iri, terms: irisToTerms[iri]};\n if(iri[0] in fastCurieMap) {\n fastCurieMap[iri[0]].push(fastCurieEntry);\n } else {\n fastCurieMap[iri[0]] = [fastCurieEntry];\n }\n }\n } else if(!isKeyword && !mapping._termHasColon) {\n // add IRI to term match\n irisToTerms[iri].push(term);\n }\n\n // add new entry\n if(!entry[container]) {\n entry[container] = {\n '@language': {},\n '@type': {},\n '@any': {}\n };\n }\n entry = entry[container];\n _addPreferredTerm(term, entry['@any'], '@none');\n\n if(mapping.reverse) {\n // term is preferred for values using @reverse\n _addPreferredTerm(term, entry['@type'], '@reverse');\n } else if(mapping['@type'] === '@none') {\n _addPreferredTerm(term, entry['@any'], '@none');\n _addPreferredTerm(term, entry['@language'], '@none');\n _addPreferredTerm(term, entry['@type'], '@none');\n } else if('@type' in mapping) {\n // term is preferred for values using specific type\n _addPreferredTerm(term, entry['@type'], mapping['@type']);\n } else if('@language' in mapping && '@direction' in mapping) {\n // term is preferred for values using specific language and direction\n const language = mapping['@language'];\n const direction = mapping['@direction'];\n if(language && direction) {\n _addPreferredTerm(term, entry['@language'],\n `${language}_${direction}`.toLowerCase());\n } else if(language) {\n _addPreferredTerm(term, entry['@language'], language.toLowerCase());\n } else if(direction) {\n _addPreferredTerm(term, entry['@language'], `_${direction}`);\n } else {\n _addPreferredTerm(term, entry['@language'], '@null');\n }\n } else if('@language' in mapping) {\n _addPreferredTerm(term, entry['@language'],\n (mapping['@language'] || '@null').toLowerCase());\n } else if('@direction' in mapping) {\n if(mapping['@direction']) {\n _addPreferredTerm(term, entry['@language'],\n `_${mapping['@direction']}`);\n } else {\n _addPreferredTerm(term, entry['@language'], '@none');\n }\n } else if(defaultDirection) {\n _addPreferredTerm(term, entry['@language'], `_${defaultDirection}`);\n _addPreferredTerm(term, entry['@language'], '@none');\n _addPreferredTerm(term, entry['@type'], '@none');\n } else {\n // add entries for no type and no language\n _addPreferredTerm(term, entry['@language'], defaultLanguage);\n _addPreferredTerm(term, entry['@language'], '@none');\n _addPreferredTerm(term, entry['@type'], '@none');\n }\n }\n }\n\n // build fast CURIE map\n for(const key in fastCurieMap) {\n _buildIriMap(fastCurieMap, key, 1);\n }\n\n return inverse;\n }\n\n /**\n * Runs a recursive algorithm to build a lookup map for quickly finding\n * potential CURIEs.\n *\n * @param iriMap the map to build.\n * @param key the current key in the map to work on.\n * @param idx the index into the IRI to compare.\n */\n function _buildIriMap(iriMap, key, idx) {\n const entries = iriMap[key];\n const next = iriMap[key] = {};\n\n let iri;\n let letter;\n for(const entry of entries) {\n iri = entry.iri;\n if(idx >= iri.length) {\n letter = '';\n } else {\n letter = iri[idx];\n }\n if(letter in next) {\n next[letter].push(entry);\n } else {\n next[letter] = [entry];\n }\n }\n\n for(const key in next) {\n if(key === '') {\n continue;\n }\n _buildIriMap(next, key, idx + 1);\n }\n }\n\n /**\n * Adds the term for the given entry if not already added.\n *\n * @param term the term to add.\n * @param entry the inverse context typeOrLanguage entry to add to.\n * @param typeOrLanguageValue the key in the entry to add to.\n */\n function _addPreferredTerm(term, entry, typeOrLanguageValue) {\n if(!entry.hasOwnProperty(typeOrLanguageValue)) {\n entry[typeOrLanguageValue] = term;\n }\n }\n\n /**\n * Clones an active context, creating a child active context.\n *\n * @return a clone (child) of the active context.\n */\n function _cloneActiveContext() {\n const child = {};\n child.mappings = util.clone(this.mappings);\n child.clone = this.clone;\n child.inverse = null;\n child.getInverse = this.getInverse;\n child.protected = util.clone(this.protected);\n if(this.previousContext) {\n child.previousContext = this.previousContext.clone();\n }\n child.revertToPreviousContext = this.revertToPreviousContext;\n if('@base' in this) {\n child['@base'] = this['@base'];\n }\n if('@language' in this) {\n child['@language'] = this['@language'];\n }\n if('@vocab' in this) {\n child['@vocab'] = this['@vocab'];\n }\n return child;\n }\n\n /**\n * Reverts any type-scoped context in this active context to the previous\n * context.\n */\n function _revertToPreviousContext() {\n if(!this.previousContext) {\n return this;\n }\n return this.previousContext.clone();\n }\n};\n\n/**\n * Gets the value for the given active context key and type, null if none is\n * set or undefined if none is set and type is '@context'.\n *\n * @param ctx the active context.\n * @param key the context key.\n * @param [type] the type of value to get (eg: '@id', '@type'), if not\n * specified gets the entire entry for a key, null if not found.\n *\n * @return the value, null, or undefined.\n */\napi.getContextValue = (ctx, key, type) => {\n // invalid key\n if(key === null) {\n if(type === '@context') {\n return undefined;\n }\n return null;\n }\n\n // get specific entry information\n if(ctx.mappings.has(key)) {\n const entry = ctx.mappings.get(key);\n\n if(_isUndefined(type)) {\n // return whole entry\n return entry;\n }\n if(entry.hasOwnProperty(type)) {\n // return entry value for type\n return entry[type];\n }\n }\n\n // get default language\n if(type === '@language' && type in ctx) {\n return ctx[type];\n }\n\n // get default direction\n if(type === '@direction' && type in ctx) {\n return ctx[type];\n }\n\n if(type === '@context') {\n return undefined;\n }\n return null;\n};\n\n/**\n * Processing Mode check.\n *\n * @param activeCtx the current active context.\n * @param version the string or numeric version to check.\n *\n * @return boolean.\n */\napi.processingMode = (activeCtx, version) => {\n if(version.toString() >= '1.1') {\n return !activeCtx.processingMode ||\n activeCtx.processingMode >= 'json-ld-' + version.toString();\n } else {\n return activeCtx.processingMode === 'json-ld-1.0';\n }\n};\n\n/**\n * Returns whether or not the given value is a keyword.\n *\n * @param v the value to check.\n *\n * @return true if the value is a keyword, false if not.\n */\napi.isKeyword = v => {\n if(!_isString(v) || v[0] !== '@') {\n return false;\n }\n switch(v) {\n case '@base':\n case '@container':\n case '@context':\n case '@default':\n case '@direction':\n case '@embed':\n case '@explicit':\n case '@graph':\n case '@id':\n case '@included':\n case '@index':\n case '@json':\n case '@language':\n case '@list':\n case '@nest':\n case '@none':\n case '@omitDefault':\n case '@prefix':\n case '@preserve':\n case '@protected':\n case '@requireAll':\n case '@reverse':\n case '@set':\n case '@type':\n case '@value':\n case '@version':\n case '@vocab':\n return true;\n }\n return false;\n};\n\nfunction _deepCompare(x1, x2) {\n // compare `null` or primitive types directly\n if((!(x1 && typeof x1 === 'object')) ||\n (!(x2 && typeof x2 === 'object'))) {\n return x1 === x2;\n }\n // x1 and x2 are objects (also potentially arrays)\n const x1Array = Array.isArray(x1);\n if(x1Array !== Array.isArray(x2)) {\n return false;\n }\n if(x1Array) {\n if(x1.length !== x2.length) {\n return false;\n }\n for(let i = 0; i < x1.length; ++i) {\n if(!_deepCompare(x1[i], x2[i])) {\n return false;\n }\n }\n return true;\n }\n // x1 and x2 are non-array objects\n const k1s = Object.keys(x1);\n const k2s = Object.keys(x2);\n if(k1s.length !== k2s.length) {\n return false;\n }\n for(const k1 in x1) {\n let v1 = x1[k1];\n let v2 = x2[k1];\n // special case: `@container` can be in any order\n if(k1 === '@container') {\n if(Array.isArray(v1) && Array.isArray(v2)) {\n v1 = v1.slice().sort();\n v2 = v2.slice().sort();\n }\n }\n if(!_deepCompare(v1, v2)) {\n return false;\n }\n }\n return true;\n}\n","/*\n * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst {parseLinkHeader, buildHeaders} = require('../util');\nconst {LINK_HEADER_CONTEXT} = require('../constants');\nconst JsonLdError = require('../JsonLdError');\nconst RequestQueue = require('../RequestQueue');\nconst {prependBase} = require('../url');\n\nconst REGEX_LINK_HEADER = /(^|(\\r\\n))link:/i;\n\n/**\n * Creates a built-in XMLHttpRequest document loader.\n *\n * @param options the options to use:\n * secure: require all URLs to use HTTPS.\n * headers: an object (map) of headers which will be passed as request\n * headers for the requested document. Accept is not allowed.\n * [xhr]: the XMLHttpRequest API to use.\n *\n * @return the XMLHttpRequest document loader.\n */\nmodule.exports = ({\n secure,\n headers = {},\n xhr\n} = {headers: {}}) => {\n headers = buildHeaders(headers);\n const queue = new RequestQueue();\n return queue.wrapLoader(loader);\n\n async function loader(url) {\n if(url.indexOf('http:') !== 0 && url.indexOf('https:') !== 0) {\n throw new JsonLdError(\n 'URL could not be dereferenced; only \"http\" and \"https\" URLs are ' +\n 'supported.',\n 'jsonld.InvalidUrl', {code: 'loading document failed', url});\n }\n if(secure && url.indexOf('https') !== 0) {\n throw new JsonLdError(\n 'URL could not be dereferenced; secure mode is enabled and ' +\n 'the URL\\'s scheme is not \"https\".',\n 'jsonld.InvalidUrl', {code: 'loading document failed', url});\n }\n\n let req;\n try {\n req = await _get(xhr, url, headers);\n } catch(e) {\n throw new JsonLdError(\n 'URL could not be dereferenced, an error occurred.',\n 'jsonld.LoadDocumentError',\n {code: 'loading document failed', url, cause: e});\n }\n\n if(req.status >= 400) {\n throw new JsonLdError(\n 'URL could not be dereferenced: ' + req.statusText,\n 'jsonld.LoadDocumentError', {\n code: 'loading document failed',\n url,\n httpStatusCode: req.status\n });\n }\n\n let doc = {contextUrl: null, documentUrl: url, document: req.response};\n let alternate = null;\n\n // handle Link Header (avoid unsafe header warning by existence testing)\n const contentType = req.getResponseHeader('Content-Type');\n let linkHeader;\n if(REGEX_LINK_HEADER.test(req.getAllResponseHeaders())) {\n linkHeader = req.getResponseHeader('Link');\n }\n if(linkHeader && contentType !== 'application/ld+json') {\n // only 1 related link header permitted\n const linkHeaders = parseLinkHeader(linkHeader);\n const linkedContext = linkHeaders[LINK_HEADER_CONTEXT];\n if(Array.isArray(linkedContext)) {\n throw new JsonLdError(\n 'URL could not be dereferenced, it has more than one ' +\n 'associated HTTP Link Header.',\n 'jsonld.InvalidUrl',\n {code: 'multiple context link headers', url});\n }\n if(linkedContext) {\n doc.contextUrl = linkedContext.target;\n }\n\n // \"alternate\" link header is a redirect\n alternate = linkHeaders.alternate;\n if(alternate &&\n alternate.type == 'application/ld+json' &&\n !(contentType || '').match(/^application\\/(\\w*\\+)?json$/)) {\n doc = await loader(prependBase(url, alternate.target));\n }\n }\n\n return doc;\n }\n};\n\nfunction _get(xhr, url, headers) {\n xhr = xhr || XMLHttpRequest;\n const req = new xhr();\n return new Promise((resolve, reject) => {\n req.onload = () => resolve(req);\n req.onerror = err => reject(err);\n req.open('GET', url, true);\n for(const k in headers) {\n req.setRequestHeader(k, headers[k]);\n }\n req.send();\n });\n}\n","/*\n * Copyright (c) 2020 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst JsonLdError = require('./JsonLdError');\n\nconst {\n isArray: _isArray\n} = require('./types');\n\nconst {\n asArray: _asArray\n} = require('./util');\n\nconst api = {};\nmodule.exports = api;\n\n// default handler, store as null or an array\n// exposed to allow fast external pre-handleEvent() checks\napi.defaultEventHandler = null;\n\n/**\n * Setup event handler.\n *\n * Return an array event handler constructed from an optional safe mode\n * handler, an optional options event handler, and an optional default handler.\n *\n * @param {object} options - processing options\n * {function|object|array} [eventHandler] - an event handler.\n *\n * @return an array event handler.\n */\napi.setupEventHandler = ({options = {}}) => {\n // build in priority order\n const eventHandler = [].concat(\n options.safe ? api.safeEventHandler : [],\n options.eventHandler ? _asArray(options.eventHandler) : [],\n api.defaultEventHandler ? api.defaultEventHandler : []\n );\n // null if no handlers\n return eventHandler.length === 0 ? null : eventHandler;\n};\n\n/**\n * Handle an event.\n *\n * Top level APIs have a common 'eventHandler' option. This option can be a\n * function, array of functions, object mapping event.code to functions (with a\n * default to call next()), or any combination of such handlers. Handlers will\n * be called with an object with an 'event' entry and a 'next' function. Custom\n * handlers should process the event as appropriate. The 'next()' function\n * should be called to let the next handler process the event.\n *\n * NOTE: Only call this function if options.eventHandler is set and is an\n * array of hanlers. This is an optimization. Callers are expected to check\n * for an event handler before constructing events and calling this function.\n *\n * @param {object} event - event structure:\n * {string} code - event code\n * {string} level - severity level, one of: ['warning']\n * {string} message - human readable message\n * {object} details - event specific details\n * @param {object} options - processing options\n * {array} eventHandler - an event handler array.\n */\napi.handleEvent = ({\n event,\n options\n}) => {\n _handle({event, handlers: options.eventHandler});\n};\n\nfunction _handle({event, handlers}) {\n let doNext = true;\n for(let i = 0; doNext && i < handlers.length; ++i) {\n doNext = false;\n const handler = handlers[i];\n if(_isArray(handler)) {\n doNext = _handle({event, handlers: handler});\n } else if(typeof handler === 'function') {\n handler({event, next: () => {\n doNext = true;\n }});\n } else if(typeof handler === 'object') {\n if(event.code in handler) {\n handler[event.code]({event, next: () => {\n doNext = true;\n }});\n } else {\n doNext = true;\n }\n } else {\n throw new JsonLdError(\n 'Invalid event handler.',\n 'jsonld.InvalidEventHandler',\n {event});\n }\n }\n return doNext;\n}\n\nconst _notSafeEventCodes = new Set([\n 'empty object',\n 'free-floating scalar',\n 'invalid @language value',\n 'invalid property',\n // NOTE: spec edge case\n 'null @id value',\n 'null @value value',\n 'object with only @id',\n 'object with only @language',\n 'object with only @list',\n 'object with only @value',\n 'relative @id reference',\n 'relative @type reference',\n 'relative @vocab reference',\n 'reserved @id value',\n 'reserved @reverse value',\n 'reserved term',\n // toRDF\n 'blank node predicate',\n 'relative graph reference',\n 'relative object reference',\n 'relative predicate reference',\n 'relative subject reference',\n // toRDF / fromRDF\n 'rdfDirection not set'\n]);\n\n// safe handler that rejects unsafe warning conditions\napi.safeEventHandler = function safeEventHandler({event, next}) {\n // fail on all unsafe warnings\n if(event.level === 'warning' && _notSafeEventCodes.has(event.code)) {\n throw new JsonLdError(\n 'Safe mode validation error.',\n 'jsonld.ValidationError',\n {event}\n );\n }\n next();\n};\n\n// logs all events and continues\napi.logEventHandler = function logEventHandler({event, next}) {\n console.log(`EVENT: ${event.message}`, {event});\n next();\n};\n\n// log 'warning' level events\napi.logWarningEventHandler = function logWarningEventHandler({event, next}) {\n if(event.level === 'warning') {\n console.warn(`WARNING: ${event.message}`, {event});\n }\n next();\n};\n\n// fallback to throw errors for any unhandled events\napi.unhandledEventHandler = function unhandledEventHandler({event}) {\n throw new JsonLdError(\n 'No handler for event.',\n 'jsonld.UnhandledEvent',\n {event}\n );\n};\n\n/**\n * Set default event handler.\n *\n * By default, all event are unhandled. It is recommended to pass in an\n * eventHandler into each call. However, this call allows using a default\n * eventHandler when one is not otherwise provided.\n *\n * @param {object} options - default handler options:\n * {function|object|array} eventHandler - a default event handler.\n * falsey to unset.\n */\napi.setDefaultEventHandler = function({eventHandler} = {}) {\n api.defaultEventHandler = eventHandler ? _asArray(eventHandler) : null;\n};\n","/*\n * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst JsonLdError = require('./JsonLdError');\n\nconst {\n isArray: _isArray,\n isObject: _isObject,\n isEmptyObject: _isEmptyObject,\n isString: _isString,\n isUndefined: _isUndefined\n} = require('./types');\n\nconst {\n isList: _isList,\n isValue: _isValue,\n isGraph: _isGraph,\n isSubject: _isSubject\n} = require('./graphTypes');\n\nconst {\n expandIri: _expandIri,\n getContextValue: _getContextValue,\n isKeyword: _isKeyword,\n process: _processContext,\n processingMode: _processingMode\n} = require('./context');\n\nconst {\n isAbsolute: _isAbsoluteIri\n} = require('./url');\n\nconst {\n REGEX_BCP47,\n REGEX_KEYWORD,\n addValue: _addValue,\n asArray: _asArray,\n getValues: _getValues,\n validateTypeValue: _validateTypeValue\n} = require('./util');\n\nconst {\n handleEvent: _handleEvent\n} = require('./events');\n\nconst api = {};\nmodule.exports = api;\n\n/**\n * Recursively expands an element using the given context. Any context in\n * the element will be removed. All context URLs must have been retrieved\n * before calling this method.\n *\n * @param activeCtx the context to use.\n * @param activeProperty the property for the element, null for none.\n * @param element the element to expand.\n * @param options the expansion options.\n * @param insideList true if the element is a list, false if not.\n * @param insideIndex true if the element is inside an index container,\n * false if not.\n * @param typeScopedContext an optional type-scoped active context for\n * expanding values of nodes that were expressed according to\n * a type-scoped context.\n *\n * @return a Promise that resolves to the expanded value.\n */\napi.expand = async ({\n activeCtx,\n activeProperty = null,\n element,\n options = {},\n insideList = false,\n insideIndex = false,\n typeScopedContext = null\n}) => {\n // nothing to expand\n if(element === null || element === undefined) {\n return null;\n }\n\n // disable framing if activeProperty is @default\n if(activeProperty === '@default') {\n options = Object.assign({}, options, {isFrame: false});\n }\n\n if(!_isArray(element) && !_isObject(element)) {\n // drop free-floating scalars that are not in lists\n if(!insideList && (activeProperty === null ||\n _expandIri(activeCtx, activeProperty, {vocab: true},\n options) === '@graph')) {\n // FIXME\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'free-floating scalar',\n level: 'warning',\n message: 'Dropping free-floating scalar not in a list.',\n details: {\n value: element\n //activeProperty\n //insideList\n }\n },\n options\n });\n }\n return null;\n }\n\n // expand element according to value expansion rules\n return _expandValue({activeCtx, activeProperty, value: element, options});\n }\n\n // recursively expand array\n if(_isArray(element)) {\n let rval = [];\n const container = _getContextValue(\n activeCtx, activeProperty, '@container') || [];\n insideList = insideList || container.includes('@list');\n for(let i = 0; i < element.length; ++i) {\n // expand element\n let e = await api.expand({\n activeCtx,\n activeProperty,\n element: element[i],\n options,\n insideIndex,\n typeScopedContext\n });\n if(insideList && _isArray(e)) {\n e = {'@list': e};\n }\n\n if(e === null) {\n // FIXME: add debug event?\n //unmappedValue: element[i],\n //activeProperty,\n //parent: element,\n //index: i,\n //expandedParent: rval,\n //insideList\n\n // NOTE: no-value events emitted at calling sites as needed\n continue;\n }\n\n if(_isArray(e)) {\n rval = rval.concat(e);\n } else {\n rval.push(e);\n }\n }\n return rval;\n }\n\n // recursively expand object:\n\n // first, expand the active property\n const expandedActiveProperty = _expandIri(\n activeCtx, activeProperty, {vocab: true}, options);\n\n // Get any property-scoped context for activeProperty\n const propertyScopedCtx =\n _getContextValue(activeCtx, activeProperty, '@context');\n\n // second, determine if any type-scoped context should be reverted; it\n // should only be reverted when the following are all true:\n // 1. `element` is not a value or subject reference\n // 2. `insideIndex` is false\n typeScopedContext = typeScopedContext ||\n (activeCtx.previousContext ? activeCtx : null);\n let keys = Object.keys(element).sort();\n let mustRevert = !insideIndex;\n if(mustRevert && typeScopedContext && keys.length <= 2 &&\n !keys.includes('@context')) {\n for(const key of keys) {\n const expandedProperty = _expandIri(\n typeScopedContext, key, {vocab: true}, options);\n if(expandedProperty === '@value') {\n // value found, ensure type-scoped context is used to expand it\n mustRevert = false;\n activeCtx = typeScopedContext;\n break;\n }\n if(expandedProperty === '@id' && keys.length === 1) {\n // subject reference found, do not revert\n mustRevert = false;\n break;\n }\n }\n }\n\n if(mustRevert) {\n // revert type scoped context\n activeCtx = activeCtx.revertToPreviousContext();\n }\n\n // apply property-scoped context after reverting term-scoped context\n if(!_isUndefined(propertyScopedCtx)) {\n activeCtx = await _processContext({\n activeCtx,\n localCtx: propertyScopedCtx,\n propagate: true,\n overrideProtected: true,\n options\n });\n }\n\n // if element has a context, process it\n if('@context' in element) {\n activeCtx = await _processContext(\n {activeCtx, localCtx: element['@context'], options});\n }\n\n // set the type-scoped context to the context on input, for use later\n typeScopedContext = activeCtx;\n\n // Remember the first key found expanding to @type\n let typeKey = null;\n\n // look for scoped contexts on `@type`\n for(const key of keys) {\n const expandedProperty = _expandIri(activeCtx, key, {vocab: true}, options);\n if(expandedProperty === '@type') {\n // set scoped contexts from @type\n // avoid sorting if possible\n typeKey = typeKey || key;\n const value = element[key];\n const types =\n Array.isArray(value) ?\n (value.length > 1 ? value.slice().sort() : value) : [value];\n for(const type of types) {\n const ctx = _getContextValue(typeScopedContext, type, '@context');\n if(!_isUndefined(ctx)) {\n activeCtx = await _processContext({\n activeCtx,\n localCtx: ctx,\n options,\n propagate: false\n });\n }\n }\n }\n }\n\n // process each key and value in element, ignoring @nest content\n let rval = {};\n await _expandObject({\n activeCtx,\n activeProperty,\n expandedActiveProperty,\n element,\n expandedParent: rval,\n options,\n insideList,\n typeKey,\n typeScopedContext\n });\n\n // get property count on expanded output\n keys = Object.keys(rval);\n let count = keys.length;\n\n if('@value' in rval) {\n // @value must only have @language or @type\n if('@type' in rval && ('@language' in rval || '@direction' in rval)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; an element containing \"@value\" may not ' +\n 'contain both \"@type\" and either \"@language\" or \"@direction\".',\n 'jsonld.SyntaxError', {code: 'invalid value object', element: rval});\n }\n let validCount = count - 1;\n if('@type' in rval) {\n validCount -= 1;\n }\n if('@index' in rval) {\n validCount -= 1;\n }\n if('@language' in rval) {\n validCount -= 1;\n }\n if('@direction' in rval) {\n validCount -= 1;\n }\n if(validCount !== 0) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; an element containing \"@value\" may only ' +\n 'have an \"@index\" property and either \"@type\" ' +\n 'or either or both \"@language\" or \"@direction\".',\n 'jsonld.SyntaxError', {code: 'invalid value object', element: rval});\n }\n const values = rval['@value'] === null ? [] : _asArray(rval['@value']);\n const types = _getValues(rval, '@type');\n\n // drop null @values\n if(_processingMode(activeCtx, 1.1) && types.includes('@json') &&\n types.length === 1) {\n // Any value of @value is okay if @type: @json\n } else if(values.length === 0) {\n // FIXME\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'null @value value',\n level: 'warning',\n message: 'Dropping null @value value.',\n details: {\n value: rval\n }\n },\n options\n });\n }\n rval = null;\n } else if(!values.every(v => (_isString(v) || _isEmptyObject(v))) &&\n '@language' in rval) {\n // if @language is present, @value must be a string\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; only strings may be language-tagged.',\n 'jsonld.SyntaxError',\n {code: 'invalid language-tagged value', element: rval});\n } else if(!types.every(t =>\n (_isAbsoluteIri(t) && !(_isString(t) && t.indexOf('_:') === 0) ||\n _isEmptyObject(t)))) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; an element containing \"@value\" and \"@type\" ' +\n 'must have an absolute IRI for the value of \"@type\".',\n 'jsonld.SyntaxError', {code: 'invalid typed value', element: rval});\n }\n } else if('@type' in rval && !_isArray(rval['@type'])) {\n // convert @type to an array\n rval['@type'] = [rval['@type']];\n } else if('@set' in rval || '@list' in rval) {\n // handle @set and @list\n if(count > 1 && !(count === 2 && '@index' in rval)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; if an element has the property \"@set\" ' +\n 'or \"@list\", then it can have at most one other property that is ' +\n '\"@index\".', 'jsonld.SyntaxError',\n {code: 'invalid set or list object', element: rval});\n }\n // optimize away @set\n if('@set' in rval) {\n rval = rval['@set'];\n keys = Object.keys(rval);\n count = keys.length;\n }\n } else if(count === 1 && '@language' in rval) {\n // drop objects with only @language\n // FIXME\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'object with only @language',\n level: 'warning',\n message: 'Dropping object with only @language.',\n details: {\n value: rval\n }\n },\n options\n });\n }\n rval = null;\n }\n\n // drop certain top-level objects that do not occur in lists\n if(_isObject(rval) &&\n !options.keepFreeFloatingNodes && !insideList &&\n (activeProperty === null ||\n expandedActiveProperty === '@graph' ||\n (_getContextValue(activeCtx, activeProperty, '@container') || [])\n .includes('@graph')\n )) {\n // drop empty object, top-level @value/@list, or object with only @id\n rval = _dropUnsafeObject({value: rval, count, options});\n }\n\n return rval;\n};\n\n/**\n * Drop empty object, top-level @value/@list, or object with only @id\n *\n * @param value Value to check.\n * @param count Number of properties in object.\n * @param options The expansion options.\n *\n * @return null if dropped, value otherwise.\n */\nfunction _dropUnsafeObject({\n value,\n count,\n options\n}) {\n if(count === 0 || '@value' in value || '@list' in value ||\n (count === 1 && '@id' in value)) {\n // FIXME\n if(options.eventHandler) {\n // FIXME: one event or diff event for empty, @v/@l, {@id}?\n let code;\n let message;\n if(count === 0) {\n code = 'empty object';\n message = 'Dropping empty object.';\n } else if('@value' in value) {\n code = 'object with only @value';\n message = 'Dropping object with only @value.';\n } else if('@list' in value) {\n code = 'object with only @list';\n message = 'Dropping object with only @list.';\n } else if(count === 1 && '@id' in value) {\n code = 'object with only @id';\n message = 'Dropping object with only @id.';\n }\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code,\n level: 'warning',\n message,\n details: {\n value\n }\n },\n options\n });\n }\n return null;\n }\n return value;\n}\n\n/**\n * Expand each key and value of element adding to result\n *\n * @param activeCtx the context to use.\n * @param activeProperty the property for the element.\n * @param expandedActiveProperty the expansion of activeProperty\n * @param element the element to expand.\n * @param expandedParent the expanded result into which to add values.\n * @param options the expansion options.\n * @param insideList true if the element is a list, false if not.\n * @param typeKey first key found expanding to @type.\n * @param typeScopedContext the context before reverting.\n */\nasync function _expandObject({\n activeCtx,\n activeProperty,\n expandedActiveProperty,\n element,\n expandedParent,\n options = {},\n insideList,\n typeKey,\n typeScopedContext\n}) {\n const keys = Object.keys(element).sort();\n const nests = [];\n let unexpandedValue;\n\n // Figure out if this is the type for a JSON literal\n const isJsonType = element[typeKey] &&\n _expandIri(activeCtx,\n (_isArray(element[typeKey]) ? element[typeKey][0] : element[typeKey]),\n {vocab: true}, {\n ...options,\n typeExpansion: true\n }) === '@json';\n\n for(const key of keys) {\n let value = element[key];\n let expandedValue;\n\n // skip @context\n if(key === '@context') {\n continue;\n }\n\n // expand property\n const expandedProperty = _expandIri(activeCtx, key, {vocab: true}, options);\n\n // drop non-absolute IRI keys that aren't keywords\n if(expandedProperty === null ||\n !(_isAbsoluteIri(expandedProperty) || _isKeyword(expandedProperty))) {\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'invalid property',\n level: 'warning',\n message: 'Dropping property that did not expand into an ' +\n 'absolute IRI or keyword.',\n details: {\n property: key,\n expandedProperty\n }\n },\n options\n });\n }\n continue;\n }\n\n if(_isKeyword(expandedProperty)) {\n if(expandedActiveProperty === '@reverse') {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; a keyword cannot be used as a @reverse ' +\n 'property.', 'jsonld.SyntaxError',\n {code: 'invalid reverse property map', value});\n }\n if(expandedProperty in expandedParent &&\n expandedProperty !== '@included' &&\n expandedProperty !== '@type') {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; colliding keywords detected.',\n 'jsonld.SyntaxError',\n {code: 'colliding keywords', keyword: expandedProperty});\n }\n }\n\n // syntax error if @id is not a string\n if(expandedProperty === '@id') {\n if(!_isString(value)) {\n if(!options.isFrame) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@id\" value must a string.',\n 'jsonld.SyntaxError', {code: 'invalid @id value', value});\n }\n if(_isObject(value)) {\n // empty object is a wildcard\n if(!_isEmptyObject(value)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@id\" value an empty object or array ' +\n 'of strings, if framing',\n 'jsonld.SyntaxError', {code: 'invalid @id value', value});\n }\n } else if(_isArray(value)) {\n if(!value.every(v => _isString(v))) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@id\" value an empty object or array ' +\n 'of strings, if framing',\n 'jsonld.SyntaxError', {code: 'invalid @id value', value});\n }\n } else {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@id\" value an empty object or array ' +\n 'of strings, if framing',\n 'jsonld.SyntaxError', {code: 'invalid @id value', value});\n }\n }\n\n _addValue(\n expandedParent, '@id',\n _asArray(value).map(v => {\n if(_isString(v)) {\n const ve = _expandIri(activeCtx, v, {base: true}, options);\n if(options.eventHandler) {\n if(ve === null) {\n // NOTE: spec edge case\n // See https://github.com/w3c/json-ld-api/issues/480\n if(v === null) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'null @id value',\n level: 'warning',\n message: 'Null @id found.',\n details: {\n id: v\n }\n },\n options\n });\n } else {\n // matched KEYWORD regex\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'reserved @id value',\n level: 'warning',\n message: 'Reserved @id found.',\n details: {\n id: v\n }\n },\n options\n });\n }\n } else if(!_isAbsoluteIri(ve)) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'relative @id reference',\n level: 'warning',\n message: 'Relative @id reference found.',\n details: {\n id: v,\n expandedId: ve\n }\n },\n options\n });\n }\n }\n return ve;\n }\n return v;\n }),\n {propertyIsArray: options.isFrame});\n continue;\n }\n\n if(expandedProperty === '@type') {\n // if framing, can be a default object, but need to expand\n // key to determine that\n if(_isObject(value)) {\n value = Object.fromEntries(Object.entries(value).map(([k, v]) => [\n _expandIri(typeScopedContext, k, {vocab: true}),\n _asArray(v).map(vv =>\n _expandIri(typeScopedContext, vv, {base: true, vocab: true},\n {...options, typeExpansion: true})\n )\n ]));\n }\n _validateTypeValue(value, options.isFrame);\n _addValue(\n expandedParent, '@type',\n _asArray(value).map(v => {\n if(_isString(v)) {\n const ve = _expandIri(typeScopedContext, v,\n {base: true, vocab: true},\n {...options, typeExpansion: true});\n if(ve !== '@json' && !_isAbsoluteIri(ve)) {\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'relative @type reference',\n level: 'warning',\n message: 'Relative @type reference found.',\n details: {\n type: v\n }\n },\n options\n });\n }\n }\n return ve;\n }\n return v;\n }),\n {propertyIsArray: !!options.isFrame});\n continue;\n }\n\n // Included blocks are treated as an array of separate object nodes sharing\n // the same referencing active_property.\n // For 1.0, it is skipped as are other unknown keywords\n if(expandedProperty === '@included' && _processingMode(activeCtx, 1.1)) {\n const includedResult = _asArray(await api.expand({\n activeCtx,\n activeProperty,\n element: value,\n options\n }));\n\n // Expanded values must be node objects\n if(!includedResult.every(v => _isSubject(v))) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; ' +\n 'values of @included must expand to node objects.',\n 'jsonld.SyntaxError', {code: 'invalid @included value', value});\n }\n\n _addValue(\n expandedParent, '@included', includedResult, {propertyIsArray: true});\n continue;\n }\n\n // @graph must be an array or an object\n if(expandedProperty === '@graph' &&\n !(_isObject(value) || _isArray(value))) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@graph\" value must not be an ' +\n 'object or an array.',\n 'jsonld.SyntaxError', {code: 'invalid @graph value', value});\n }\n\n if(expandedProperty === '@value') {\n // capture value for later\n // \"colliding keywords\" check prevents this from being set twice\n unexpandedValue = value;\n if(isJsonType && _processingMode(activeCtx, 1.1)) {\n // no coercion to array, and retain all values\n expandedParent['@value'] = value;\n } else {\n _addValue(\n expandedParent, '@value', value, {propertyIsArray: options.isFrame});\n }\n continue;\n }\n\n // @language must be a string\n // it should match BCP47\n if(expandedProperty === '@language') {\n if(value === null) {\n // drop null @language values, they expand as if they didn't exist\n continue;\n }\n if(!_isString(value) && !options.isFrame) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@language\" value must be a string.',\n 'jsonld.SyntaxError',\n {code: 'invalid language-tagged string', value});\n }\n // ensure language value is lowercase\n value = _asArray(value).map(v => _isString(v) ? v.toLowerCase() : v);\n\n // ensure language tag matches BCP47\n for(const language of value) {\n if(_isString(language) && !language.match(REGEX_BCP47)) {\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'invalid @language value',\n level: 'warning',\n message: '@language value must be valid BCP47.',\n details: {\n language\n }\n },\n options\n });\n }\n }\n }\n\n _addValue(\n expandedParent, '@language', value, {propertyIsArray: options.isFrame});\n continue;\n }\n\n // @direction must be \"ltr\" or \"rtl\"\n if(expandedProperty === '@direction') {\n if(!_isString(value) && !options.isFrame) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@direction\" value must be a string.',\n 'jsonld.SyntaxError',\n {code: 'invalid base direction', value});\n }\n\n value = _asArray(value);\n\n // ensure direction is \"ltr\" or \"rtl\"\n for(const dir of value) {\n if(_isString(dir) && dir !== 'ltr' && dir !== 'rtl') {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@direction\" must be \"ltr\" or \"rtl\".',\n 'jsonld.SyntaxError',\n {code: 'invalid base direction', value});\n }\n }\n\n _addValue(\n expandedParent, '@direction', value,\n {propertyIsArray: options.isFrame});\n continue;\n }\n\n // @index must be a string\n if(expandedProperty === '@index') {\n if(!_isString(value)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@index\" value must be a string.',\n 'jsonld.SyntaxError',\n {code: 'invalid @index value', value});\n }\n _addValue(expandedParent, '@index', value);\n continue;\n }\n\n // @reverse must be an object\n if(expandedProperty === '@reverse') {\n if(!_isObject(value)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@reverse\" value must be an object.',\n 'jsonld.SyntaxError', {code: 'invalid @reverse value', value});\n }\n\n expandedValue = await api.expand({\n activeCtx,\n activeProperty: '@reverse',\n element: value,\n options\n });\n // properties double-reversed\n if('@reverse' in expandedValue) {\n for(const property in expandedValue['@reverse']) {\n _addValue(\n expandedParent, property, expandedValue['@reverse'][property],\n {propertyIsArray: true});\n }\n }\n\n // FIXME: can this be merged with code below to simplify?\n // merge in all reversed properties\n let reverseMap = expandedParent['@reverse'] || null;\n for(const property in expandedValue) {\n if(property === '@reverse') {\n continue;\n }\n if(reverseMap === null) {\n reverseMap = expandedParent['@reverse'] = {};\n }\n _addValue(reverseMap, property, [], {propertyIsArray: true});\n const items = expandedValue[property];\n for(let ii = 0; ii < items.length; ++ii) {\n const item = items[ii];\n if(_isValue(item) || _isList(item)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@reverse\" value must not be a ' +\n '@value or an @list.', 'jsonld.SyntaxError',\n {code: 'invalid reverse property value', value: expandedValue});\n }\n _addValue(reverseMap, property, item, {propertyIsArray: true});\n }\n }\n\n continue;\n }\n\n // nested keys\n if(expandedProperty === '@nest') {\n nests.push(key);\n continue;\n }\n\n // use potential scoped context for key\n let termCtx = activeCtx;\n const ctx = _getContextValue(activeCtx, key, '@context');\n if(!_isUndefined(ctx)) {\n termCtx = await _processContext({\n activeCtx,\n localCtx: ctx,\n propagate: true,\n overrideProtected: true,\n options\n });\n }\n\n const container = _getContextValue(activeCtx, key, '@container') || [];\n\n if(container.includes('@language') && _isObject(value)) {\n const direction = _getContextValue(termCtx, key, '@direction');\n // handle language map container (skip if value is not an object)\n expandedValue = _expandLanguageMap(termCtx, value, direction, options);\n } else if(container.includes('@index') && _isObject(value)) {\n // handle index container (skip if value is not an object)\n const asGraph = container.includes('@graph');\n const indexKey = _getContextValue(termCtx, key, '@index') || '@index';\n const propertyIndex = indexKey !== '@index' &&\n _expandIri(activeCtx, indexKey, {vocab: true}, options);\n\n expandedValue = await _expandIndexMap({\n activeCtx: termCtx,\n options,\n activeProperty: key,\n value,\n asGraph,\n indexKey,\n propertyIndex\n });\n } else if(container.includes('@id') && _isObject(value)) {\n // handle id container (skip if value is not an object)\n const asGraph = container.includes('@graph');\n expandedValue = await _expandIndexMap({\n activeCtx: termCtx,\n options,\n activeProperty: key,\n value,\n asGraph,\n indexKey: '@id'\n });\n } else if(container.includes('@type') && _isObject(value)) {\n // handle type container (skip if value is not an object)\n expandedValue = await _expandIndexMap({\n // since container is `@type`, revert type scoped context when expanding\n activeCtx: termCtx.revertToPreviousContext(),\n options,\n activeProperty: key,\n value,\n asGraph: false,\n indexKey: '@type'\n });\n } else {\n // recurse into @list or @set\n const isList = expandedProperty === '@list';\n if(isList || expandedProperty === '@set') {\n let nextActiveProperty = activeProperty;\n if(isList && expandedActiveProperty === '@graph') {\n nextActiveProperty = null;\n }\n expandedValue = await api.expand({\n activeCtx: termCtx,\n activeProperty: nextActiveProperty,\n element: value,\n options,\n insideList: isList\n });\n } else if(\n _getContextValue(activeCtx, key, '@type') === '@json') {\n expandedValue = {\n '@type': '@json',\n '@value': value\n };\n } else {\n // recursively expand value with key as new active property\n expandedValue = await api.expand({\n activeCtx: termCtx,\n activeProperty: key,\n element: value,\n options,\n insideList: false\n });\n }\n }\n\n // drop null values if property is not @value\n if(expandedValue === null && expandedProperty !== '@value') {\n // FIXME: event?\n //unmappedValue: value,\n //expandedProperty,\n //key,\n continue;\n }\n\n // convert expanded value to @list if container specifies it\n if(expandedProperty !== '@list' && !_isList(expandedValue) &&\n container.includes('@list')) {\n // ensure expanded value in @list is an array\n expandedValue = {'@list': _asArray(expandedValue)};\n }\n\n // convert expanded value to @graph if container specifies it\n // and value is not, itself, a graph\n // index cases handled above\n if(container.includes('@graph') &&\n !container.some(key => key === '@id' || key === '@index')) {\n // ensure expanded values are in an array\n expandedValue = _asArray(expandedValue);\n if(!options.isFrame) {\n // drop items if needed\n expandedValue = expandedValue.filter(v => {\n const count = Object.keys(v).length;\n return _dropUnsafeObject({value: v, count, options}) !== null;\n });\n }\n if(expandedValue.length === 0) {\n // all items dropped, skip adding and continue\n continue;\n }\n // convert to graph\n expandedValue = expandedValue.map(v => ({'@graph': _asArray(v)}));\n }\n\n // FIXME: can this be merged with code above to simplify?\n // merge in reverse properties\n if(termCtx.mappings.has(key) && termCtx.mappings.get(key).reverse) {\n const reverseMap =\n expandedParent['@reverse'] = expandedParent['@reverse'] || {};\n expandedValue = _asArray(expandedValue);\n for(let ii = 0; ii < expandedValue.length; ++ii) {\n const item = expandedValue[ii];\n if(_isValue(item) || _isList(item)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@reverse\" value must not be a ' +\n '@value or an @list.', 'jsonld.SyntaxError',\n {code: 'invalid reverse property value', value: expandedValue});\n }\n _addValue(reverseMap, expandedProperty, item, {propertyIsArray: true});\n }\n continue;\n }\n\n // add value for property\n // special keywords handled above\n _addValue(expandedParent, expandedProperty, expandedValue, {\n propertyIsArray: true\n });\n }\n\n // @value must not be an object or an array (unless framing) or if @type is\n // @json\n if('@value' in expandedParent) {\n if(expandedParent['@type'] === '@json' && _processingMode(activeCtx, 1.1)) {\n // allow any value, to be verified when the object is fully expanded and\n // the @type is @json.\n } else if((_isObject(unexpandedValue) || _isArray(unexpandedValue)) &&\n !options.isFrame) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@value\" value must not be an ' +\n 'object or an array.',\n 'jsonld.SyntaxError',\n {code: 'invalid value object value', value: unexpandedValue});\n }\n }\n\n // expand each nested key\n for(const key of nests) {\n const nestedValues = _isArray(element[key]) ? element[key] : [element[key]];\n for(const nv of nestedValues) {\n if(!_isObject(nv) || Object.keys(nv).some(k =>\n _expandIri(activeCtx, k, {vocab: true}, options) === '@value')) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; nested value must be a node object.',\n 'jsonld.SyntaxError',\n {code: 'invalid @nest value', value: nv});\n }\n await _expandObject({\n activeCtx,\n activeProperty,\n expandedActiveProperty,\n element: nv,\n expandedParent,\n options,\n insideList,\n typeScopedContext,\n typeKey\n });\n }\n }\n}\n\n/**\n * Expands the given value by using the coercion and keyword rules in the\n * given context.\n *\n * @param activeCtx the active context to use.\n * @param activeProperty the active property the value is associated with.\n * @param value the value to expand.\n * @param {Object} [options] - processing options.\n *\n * @return the expanded value.\n */\nfunction _expandValue({activeCtx, activeProperty, value, options}) {\n // nothing to expand\n if(value === null || value === undefined) {\n return null;\n }\n\n // special-case expand @id and @type (skips '@id' expansion)\n const expandedProperty = _expandIri(\n activeCtx, activeProperty, {vocab: true}, options);\n if(expandedProperty === '@id') {\n return _expandIri(activeCtx, value, {base: true}, options);\n } else if(expandedProperty === '@type') {\n return _expandIri(activeCtx, value, {vocab: true, base: true},\n {...options, typeExpansion: true});\n }\n\n // get type definition from context\n const type = _getContextValue(activeCtx, activeProperty, '@type');\n\n // do @id expansion (automatic for @graph)\n if((type === '@id' || expandedProperty === '@graph') && _isString(value)) {\n const expandedValue = _expandIri(activeCtx, value, {base: true}, options);\n // NOTE: handle spec edge case and avoid invalid {\"@id\": null}\n if(expandedValue === null && value.match(REGEX_KEYWORD)) {\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'reserved @id value',\n level: 'warning',\n message: 'Reserved @id found.',\n details: {\n id: activeProperty\n }\n },\n options\n });\n }\n }\n return {'@id': expandedValue};\n }\n // do @id expansion w/vocab\n if(type === '@vocab' && _isString(value)) {\n return {\n '@id': _expandIri(activeCtx, value, {vocab: true, base: true}, options)\n };\n }\n\n // do not expand keyword values\n if(_isKeyword(expandedProperty)) {\n return value;\n }\n\n const rval = {};\n\n if(type && !['@id', '@vocab', '@none'].includes(type)) {\n // other type\n rval['@type'] = type;\n } else if(_isString(value)) {\n // check for language tagging for strings\n const language = _getContextValue(activeCtx, activeProperty, '@language');\n if(language !== null) {\n rval['@language'] = language;\n }\n const direction = _getContextValue(activeCtx, activeProperty, '@direction');\n if(direction !== null) {\n rval['@direction'] = direction;\n }\n }\n // do conversion of values that aren't basic JSON types to strings\n if(!['boolean', 'number', 'string'].includes(typeof value)) {\n value = value.toString();\n }\n rval['@value'] = value;\n\n return rval;\n}\n\n/**\n * Expands a language map.\n *\n * @param activeCtx the active context to use.\n * @param languageMap the language map to expand.\n * @param direction the direction to apply to values.\n * @param {Object} [options] - processing options.\n *\n * @return the expanded language map.\n */\nfunction _expandLanguageMap(activeCtx, languageMap, direction, options) {\n const rval = [];\n const keys = Object.keys(languageMap).sort();\n for(const key of keys) {\n const expandedKey = _expandIri(activeCtx, key, {vocab: true}, options);\n let val = languageMap[key];\n if(!_isArray(val)) {\n val = [val];\n }\n for(const item of val) {\n if(item === null) {\n // null values are allowed (8.5) but ignored (3.1)\n continue;\n }\n if(!_isString(item)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; language map values must be strings.',\n 'jsonld.SyntaxError',\n {code: 'invalid language map value', languageMap});\n }\n const val = {'@value': item};\n if(expandedKey !== '@none') {\n if(!key.match(REGEX_BCP47)) {\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'invalid @language value',\n level: 'warning',\n message: '@language value must be valid BCP47.',\n details: {\n language: key\n }\n },\n options\n });\n }\n }\n val['@language'] = key.toLowerCase();\n }\n if(direction) {\n val['@direction'] = direction;\n }\n rval.push(val);\n }\n }\n return rval;\n}\n\nasync function _expandIndexMap({\n activeCtx, options, activeProperty, value, asGraph, indexKey, propertyIndex\n}) {\n const rval = [];\n const keys = Object.keys(value).sort();\n const isTypeIndex = indexKey === '@type';\n for(let key of keys) {\n // if indexKey is @type, there may be a context defined for it\n if(isTypeIndex) {\n const ctx = _getContextValue(activeCtx, key, '@context');\n if(!_isUndefined(ctx)) {\n activeCtx = await _processContext({\n activeCtx,\n localCtx: ctx,\n propagate: false,\n options\n });\n }\n }\n\n let val = value[key];\n if(!_isArray(val)) {\n val = [val];\n }\n\n val = await api.expand({\n activeCtx,\n activeProperty,\n element: val,\n options,\n insideList: false,\n insideIndex: true\n });\n\n // expand for @type, but also for @none\n let expandedKey;\n if(propertyIndex) {\n if(key === '@none') {\n expandedKey = '@none';\n } else {\n expandedKey = _expandValue(\n {activeCtx, activeProperty: indexKey, value: key, options});\n }\n } else {\n expandedKey = _expandIri(activeCtx, key, {vocab: true}, options);\n }\n\n if(indexKey === '@id') {\n // expand document relative\n key = _expandIri(activeCtx, key, {base: true}, options);\n } else if(isTypeIndex) {\n key = expandedKey;\n }\n\n for(let item of val) {\n // If this is also a @graph container, turn items into graphs\n if(asGraph && !_isGraph(item)) {\n item = {'@graph': [item]};\n }\n if(indexKey === '@type') {\n if(expandedKey === '@none') {\n // ignore @none\n } else if(item['@type']) {\n item['@type'] = [key].concat(item['@type']);\n } else {\n item['@type'] = [key];\n }\n } else if(_isValue(item) &&\n !['@language', '@type', '@index'].includes(indexKey)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; Attempt to add illegal key to value ' +\n `object: \"${indexKey}\".`,\n 'jsonld.SyntaxError',\n {code: 'invalid value object', value: item});\n } else if(propertyIndex) {\n // index is a property to be expanded, and values interpreted for that\n // property\n if(expandedKey !== '@none') {\n // expand key as a value\n _addValue(item, propertyIndex, expandedKey, {\n propertyIsArray: true,\n prependValue: true\n });\n }\n } else if(expandedKey !== '@none' && !(indexKey in item)) {\n item[indexKey] = key;\n }\n rval.push(item);\n }\n }\n return rval;\n}\n","/*\n * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst {\n isSubjectReference: _isSubjectReference\n} = require('./graphTypes');\n\nconst {\n createMergedNodeMap: _createMergedNodeMap\n} = require('./nodeMap');\n\nconst api = {};\nmodule.exports = api;\n\n/**\n * Performs JSON-LD flattening.\n *\n * @param input the expanded JSON-LD to flatten.\n *\n * @return the flattened output.\n */\napi.flatten = input => {\n const defaultGraph = _createMergedNodeMap(input);\n\n // produce flattened output\n const flattened = [];\n const keys = Object.keys(defaultGraph).sort();\n for(let ki = 0; ki < keys.length; ++ki) {\n const node = defaultGraph[keys[ki]];\n // only add full subjects to top-level\n if(!_isSubjectReference(node)) {\n flattened.push(node);\n }\n }\n return flattened;\n};\n","/*\n * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst {isKeyword} = require('./context');\nconst graphTypes = require('./graphTypes');\nconst types = require('./types');\nconst util = require('./util');\nconst url = require('./url');\nconst JsonLdError = require('./JsonLdError');\nconst {\n createNodeMap: _createNodeMap,\n mergeNodeMapGraphs: _mergeNodeMapGraphs\n} = require('./nodeMap');\n\nconst api = {};\nmodule.exports = api;\n\n/**\n * Performs JSON-LD `merged` framing.\n *\n * @param input the expanded JSON-LD to frame.\n * @param frame the expanded JSON-LD frame to use.\n * @param options the framing options.\n *\n * @return the framed output.\n */\napi.frameMergedOrDefault = (input, frame, options) => {\n // create framing state\n const state = {\n options,\n embedded: false,\n graph: '@default',\n graphMap: {'@default': {}},\n subjectStack: [],\n link: {},\n bnodeMap: {}\n };\n\n // produce a map of all graphs and name each bnode\n // FIXME: currently uses subjects from @merged graph only\n const issuer = new util.IdentifierIssuer('_:b');\n _createNodeMap(input, state.graphMap, '@default', issuer);\n if(options.merged) {\n state.graphMap['@merged'] = _mergeNodeMapGraphs(state.graphMap);\n state.graph = '@merged';\n }\n state.subjects = state.graphMap[state.graph];\n\n // frame the subjects\n const framed = [];\n api.frame(state, Object.keys(state.subjects).sort(), frame, framed);\n\n // If pruning blank nodes, find those to prune\n if(options.pruneBlankNodeIdentifiers) {\n // remove all blank nodes appearing only once, done in compaction\n options.bnodesToClear =\n Object.keys(state.bnodeMap).filter(id => state.bnodeMap[id].length === 1);\n }\n\n // remove @preserve from results\n options.link = {};\n return _cleanupPreserve(framed, options);\n};\n\n/**\n * Frames subjects according to the given frame.\n *\n * @param state the current framing state.\n * @param subjects the subjects to filter.\n * @param frame the frame.\n * @param parent the parent subject or top-level array.\n * @param property the parent property, initialized to null.\n */\napi.frame = (state, subjects, frame, parent, property = null) => {\n // validate the frame\n _validateFrame(frame);\n frame = frame[0];\n\n // get flags for current frame\n const options = state.options;\n const flags = {\n embed: _getFrameFlag(frame, options, 'embed'),\n explicit: _getFrameFlag(frame, options, 'explicit'),\n requireAll: _getFrameFlag(frame, options, 'requireAll')\n };\n\n // get link for current graph\n if(!state.link.hasOwnProperty(state.graph)) {\n state.link[state.graph] = {};\n }\n const link = state.link[state.graph];\n\n // filter out subjects that match the frame\n const matches = _filterSubjects(state, subjects, frame, flags);\n\n // add matches to output\n const ids = Object.keys(matches).sort();\n for(const id of ids) {\n const subject = matches[id];\n\n /* Note: In order to treat each top-level match as a compartmentalized\n result, clear the unique embedded subjects map when the property is null,\n which only occurs at the top-level. */\n if(property === null) {\n state.uniqueEmbeds = {[state.graph]: {}};\n } else {\n state.uniqueEmbeds[state.graph] = state.uniqueEmbeds[state.graph] || {};\n }\n\n if(flags.embed === '@link' && id in link) {\n // TODO: may want to also match an existing linked subject against\n // the current frame ... so different frames could produce different\n // subjects that are only shared in-memory when the frames are the same\n\n // add existing linked subject\n _addFrameOutput(parent, property, link[id]);\n continue;\n }\n\n // start output for subject\n const output = {'@id': id};\n if(id.indexOf('_:') === 0) {\n util.addValue(state.bnodeMap, id, output, {propertyIsArray: true});\n }\n link[id] = output;\n\n // validate @embed\n if((flags.embed === '@first' || flags.embed === '@last') && state.is11) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; invalid value of @embed.',\n 'jsonld.SyntaxError', {code: 'invalid @embed value', frame});\n }\n\n if(!state.embedded && state.uniqueEmbeds[state.graph].hasOwnProperty(id)) {\n // skip adding this node object to the top level, as it was\n // already included in another node object\n continue;\n }\n\n // if embed is @never or if a circular reference would be created by an\n // embed, the subject cannot be embedded, just add the reference;\n // note that a circular reference won't occur when the embed flag is\n // `@link` as the above check will short-circuit before reaching this point\n if(state.embedded &&\n (flags.embed === '@never' ||\n _createsCircularReference(subject, state.graph, state.subjectStack))) {\n _addFrameOutput(parent, property, output);\n continue;\n }\n\n // if only the first (or once) should be embedded\n if(state.embedded &&\n (flags.embed == '@first' || flags.embed == '@once') &&\n state.uniqueEmbeds[state.graph].hasOwnProperty(id)) {\n _addFrameOutput(parent, property, output);\n continue;\n }\n\n // if only the last match should be embedded\n if(flags.embed === '@last') {\n // remove any existing embed\n if(id in state.uniqueEmbeds[state.graph]) {\n _removeEmbed(state, id);\n }\n }\n\n state.uniqueEmbeds[state.graph][id] = {parent, property};\n\n // push matching subject onto stack to enable circular embed checks\n state.subjectStack.push({subject, graph: state.graph});\n\n // subject is also the name of a graph\n if(id in state.graphMap) {\n let recurse = false;\n let subframe = null;\n if(!('@graph' in frame)) {\n recurse = state.graph !== '@merged';\n subframe = {};\n } else {\n subframe = frame['@graph'][0];\n recurse = !(id === '@merged' || id === '@default');\n if(!types.isObject(subframe)) {\n subframe = {};\n }\n }\n\n if(recurse) {\n // recurse into graph\n api.frame(\n {...state, graph: id, embedded: false},\n Object.keys(state.graphMap[id]).sort(), [subframe], output, '@graph');\n }\n }\n\n // if frame has @included, recurse over its sub-frame\n if('@included' in frame) {\n api.frame(\n {...state, embedded: false},\n subjects, frame['@included'], output, '@included');\n }\n\n // iterate over subject properties\n for(const prop of Object.keys(subject).sort()) {\n // copy keywords to output\n if(isKeyword(prop)) {\n output[prop] = util.clone(subject[prop]);\n\n if(prop === '@type') {\n // count bnode values of @type\n for(const type of subject['@type']) {\n if(type.indexOf('_:') === 0) {\n util.addValue(\n state.bnodeMap, type, output, {propertyIsArray: true});\n }\n }\n }\n continue;\n }\n\n // explicit is on and property isn't in the frame, skip processing\n if(flags.explicit && !(prop in frame)) {\n continue;\n }\n\n // add objects\n for(const o of subject[prop]) {\n const subframe = (prop in frame ?\n frame[prop] : _createImplicitFrame(flags));\n\n // recurse into list\n if(graphTypes.isList(o)) {\n const subframe =\n (frame[prop] && frame[prop][0] && frame[prop][0]['@list']) ?\n frame[prop][0]['@list'] :\n _createImplicitFrame(flags);\n\n // add empty list\n const list = {'@list': []};\n _addFrameOutput(output, prop, list);\n\n // add list objects\n const src = o['@list'];\n for(const oo of src) {\n if(graphTypes.isSubjectReference(oo)) {\n // recurse into subject reference\n api.frame(\n {...state, embedded: true},\n [oo['@id']], subframe, list, '@list');\n } else {\n // include other values automatically\n _addFrameOutput(list, '@list', util.clone(oo));\n }\n }\n } else if(graphTypes.isSubjectReference(o)) {\n // recurse into subject reference\n api.frame(\n {...state, embedded: true},\n [o['@id']], subframe, output, prop);\n } else if(_valueMatch(subframe[0], o)) {\n // include other values, if they match\n _addFrameOutput(output, prop, util.clone(o));\n }\n }\n }\n\n // handle defaults\n for(const prop of Object.keys(frame).sort()) {\n // skip keywords\n if(prop === '@type') {\n if(!types.isObject(frame[prop][0]) ||\n !('@default' in frame[prop][0])) {\n continue;\n }\n // allow through default types\n } else if(isKeyword(prop)) {\n continue;\n }\n\n // if omit default is off, then include default values for properties\n // that appear in the next frame but are not in the matching subject\n const next = frame[prop][0] || {};\n const omitDefaultOn = _getFrameFlag(next, options, 'omitDefault');\n if(!omitDefaultOn && !(prop in output)) {\n let preserve = '@null';\n if('@default' in next) {\n preserve = util.clone(next['@default']);\n }\n if(!types.isArray(preserve)) {\n preserve = [preserve];\n }\n output[prop] = [{'@preserve': preserve}];\n }\n }\n\n // if embed reverse values by finding nodes having this subject as a value\n // of the associated property\n for(const reverseProp of Object.keys(frame['@reverse'] || {}).sort()) {\n const subframe = frame['@reverse'][reverseProp];\n for(const subject of Object.keys(state.subjects)) {\n const nodeValues =\n util.getValues(state.subjects[subject], reverseProp);\n if(nodeValues.some(v => v['@id'] === id)) {\n // node has property referencing this subject, recurse\n output['@reverse'] = output['@reverse'] || {};\n util.addValue(\n output['@reverse'], reverseProp, [], {propertyIsArray: true});\n api.frame(\n {...state, embedded: true},\n [subject], subframe, output['@reverse'][reverseProp],\n property);\n }\n }\n }\n\n // add output to parent\n _addFrameOutput(parent, property, output);\n\n // pop matching subject from circular ref-checking stack\n state.subjectStack.pop();\n }\n};\n\n/**\n * Replace `@null` with `null`, removing it from arrays.\n *\n * @param input the framed, compacted output.\n * @param options the framing options used.\n *\n * @return the resulting output.\n */\napi.cleanupNull = (input, options) => {\n // recurse through arrays\n if(types.isArray(input)) {\n const noNulls = input.map(v => api.cleanupNull(v, options));\n return noNulls.filter(v => v); // removes nulls from array\n }\n\n if(input === '@null') {\n return null;\n }\n\n if(types.isObject(input)) {\n // handle in-memory linked nodes\n if('@id' in input) {\n const id = input['@id'];\n if(options.link.hasOwnProperty(id)) {\n const idx = options.link[id].indexOf(input);\n if(idx !== -1) {\n // already visited\n return options.link[id][idx];\n }\n // prevent circular visitation\n options.link[id].push(input);\n } else {\n // prevent circular visitation\n options.link[id] = [input];\n }\n }\n\n for(const key in input) {\n input[key] = api.cleanupNull(input[key], options);\n }\n }\n return input;\n};\n\n/**\n * Creates an implicit frame when recursing through subject matches. If\n * a frame doesn't have an explicit frame for a particular property, then\n * a wildcard child frame will be created that uses the same flags that the\n * parent frame used.\n *\n * @param flags the current framing flags.\n *\n * @return the implicit frame.\n */\nfunction _createImplicitFrame(flags) {\n const frame = {};\n for(const key in flags) {\n if(flags[key] !== undefined) {\n frame['@' + key] = [flags[key]];\n }\n }\n return [frame];\n}\n\n/**\n * Checks the current subject stack to see if embedding the given subject\n * would cause a circular reference.\n *\n * @param subjectToEmbed the subject to embed.\n * @param graph the graph the subject to embed is in.\n * @param subjectStack the current stack of subjects.\n *\n * @return true if a circular reference would be created, false if not.\n */\nfunction _createsCircularReference(subjectToEmbed, graph, subjectStack) {\n for(let i = subjectStack.length - 1; i >= 0; --i) {\n const subject = subjectStack[i];\n if(subject.graph === graph &&\n subject.subject['@id'] === subjectToEmbed['@id']) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Gets the frame flag value for the given flag name.\n *\n * @param frame the frame.\n * @param options the framing options.\n * @param name the flag name.\n *\n * @return the flag value.\n */\nfunction _getFrameFlag(frame, options, name) {\n const flag = '@' + name;\n let rval = (flag in frame ? frame[flag][0] : options[name]);\n if(name === 'embed') {\n // default is \"@last\"\n // backwards-compatibility support for \"embed\" maps:\n // true => \"@last\"\n // false => \"@never\"\n if(rval === true) {\n rval = '@once';\n } else if(rval === false) {\n rval = '@never';\n } else if(rval !== '@always' && rval !== '@never' && rval !== '@link' &&\n rval !== '@first' && rval !== '@last' && rval !== '@once') {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; invalid value of @embed.',\n 'jsonld.SyntaxError', {code: 'invalid @embed value', frame});\n }\n }\n return rval;\n}\n\n/**\n * Validates a JSON-LD frame, throwing an exception if the frame is invalid.\n *\n * @param frame the frame to validate.\n */\nfunction _validateFrame(frame) {\n if(!types.isArray(frame) || frame.length !== 1 || !types.isObject(frame[0])) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; a JSON-LD frame must be a single object.',\n 'jsonld.SyntaxError', {frame});\n }\n\n if('@id' in frame[0]) {\n for(const id of util.asArray(frame[0]['@id'])) {\n // @id must be wildcard or an IRI\n if(!(types.isObject(id) || url.isAbsolute(id)) ||\n (types.isString(id) && id.indexOf('_:') === 0)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; invalid @id in frame.',\n 'jsonld.SyntaxError', {code: 'invalid frame', frame});\n }\n }\n }\n\n if('@type' in frame[0]) {\n for(const type of util.asArray(frame[0]['@type'])) {\n // @type must be wildcard, IRI, or @json\n if(!(types.isObject(type) || url.isAbsolute(type) ||\n (type === '@json')) ||\n (types.isString(type) && type.indexOf('_:') === 0)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; invalid @type in frame.',\n 'jsonld.SyntaxError', {code: 'invalid frame', frame});\n }\n }\n }\n}\n\n/**\n * Returns a map of all of the subjects that match a parsed frame.\n *\n * @param state the current framing state.\n * @param subjects the set of subjects to filter.\n * @param frame the parsed frame.\n * @param flags the frame flags.\n *\n * @return all of the matched subjects.\n */\nfunction _filterSubjects(state, subjects, frame, flags) {\n // filter subjects in @id order\n const rval = {};\n for(const id of subjects) {\n const subject = state.graphMap[state.graph][id];\n if(_filterSubject(state, subject, frame, flags)) {\n rval[id] = subject;\n }\n }\n return rval;\n}\n\n/**\n * Returns true if the given subject matches the given frame.\n *\n * Matches either based on explicit type inclusion where the node has any\n * type listed in the frame. If the frame has empty types defined matches\n * nodes not having a @type. If the frame has a type of {} defined matches\n * nodes having any type defined.\n *\n * Otherwise, does duck typing, where the node must have all of the\n * properties defined in the frame.\n *\n * @param state the current framing state.\n * @param subject the subject to check.\n * @param frame the frame to check.\n * @param flags the frame flags.\n *\n * @return true if the subject matches, false if not.\n */\nfunction _filterSubject(state, subject, frame, flags) {\n // check ducktype\n let wildcard = true;\n let matchesSome = false;\n\n for(const key in frame) {\n let matchThis = false;\n const nodeValues = util.getValues(subject, key);\n const isEmpty = util.getValues(frame, key).length === 0;\n\n if(key === '@id') {\n // match on no @id or any matching @id, including wildcard\n if(types.isEmptyObject(frame['@id'][0] || {})) {\n matchThis = true;\n } else if(frame['@id'].length >= 0) {\n matchThis = frame['@id'].includes(nodeValues[0]);\n }\n if(!flags.requireAll) {\n return matchThis;\n }\n } else if(key === '@type') {\n // check @type (object value means 'any' type,\n // fall through to ducktyping)\n wildcard = false;\n if(isEmpty) {\n if(nodeValues.length > 0) {\n // don't match on no @type\n return false;\n }\n matchThis = true;\n } else if(frame['@type'].length === 1 &&\n types.isEmptyObject(frame['@type'][0])) {\n // match on wildcard @type if there is a type\n matchThis = nodeValues.length > 0;\n } else {\n // match on a specific @type\n for(const type of frame['@type']) {\n if(types.isObject(type) && '@default' in type) {\n // match on default object\n matchThis = true;\n } else {\n matchThis = matchThis || nodeValues.some(tt => tt === type);\n }\n }\n }\n if(!flags.requireAll) {\n return matchThis;\n }\n } else if(isKeyword(key)) {\n continue;\n } else {\n // Force a copy of this frame entry so it can be manipulated\n const thisFrame = util.getValues(frame, key)[0];\n let hasDefault = false;\n if(thisFrame) {\n _validateFrame([thisFrame]);\n hasDefault = '@default' in thisFrame;\n }\n\n // no longer a wildcard pattern if frame has any non-keyword properties\n wildcard = false;\n\n // skip, but allow match if node has no value for property, and frame has\n // a default value\n if(nodeValues.length === 0 && hasDefault) {\n continue;\n }\n\n // if frame value is empty, don't match if subject has any value\n if(nodeValues.length > 0 && isEmpty) {\n return false;\n }\n\n if(thisFrame === undefined) {\n // node does not match if values is not empty and the value of property\n // in frame is match none.\n if(nodeValues.length > 0) {\n return false;\n }\n matchThis = true;\n } else {\n if(graphTypes.isList(thisFrame)) {\n const listValue = thisFrame['@list'][0];\n if(graphTypes.isList(nodeValues[0])) {\n const nodeListValues = nodeValues[0]['@list'];\n\n if(graphTypes.isValue(listValue)) {\n // match on any matching value\n matchThis = nodeListValues.some(lv => _valueMatch(listValue, lv));\n } else if(graphTypes.isSubject(listValue) ||\n graphTypes.isSubjectReference(listValue)) {\n matchThis = nodeListValues.some(lv => _nodeMatch(\n state, listValue, lv, flags));\n }\n }\n } else if(graphTypes.isValue(thisFrame)) {\n matchThis = nodeValues.some(nv => _valueMatch(thisFrame, nv));\n } else if(graphTypes.isSubjectReference(thisFrame)) {\n matchThis =\n nodeValues.some(nv => _nodeMatch(state, thisFrame, nv, flags));\n } else if(types.isObject(thisFrame)) {\n matchThis = nodeValues.length > 0;\n } else {\n matchThis = false;\n }\n }\n }\n\n // all non-defaulted values must match if requireAll is set\n if(!matchThis && flags.requireAll) {\n return false;\n }\n\n matchesSome = matchesSome || matchThis;\n }\n\n // return true if wildcard or subject matches some properties\n return wildcard || matchesSome;\n}\n\n/**\n * Removes an existing embed.\n *\n * @param state the current framing state.\n * @param id the @id of the embed to remove.\n */\nfunction _removeEmbed(state, id) {\n // get existing embed\n const embeds = state.uniqueEmbeds[state.graph];\n const embed = embeds[id];\n const parent = embed.parent;\n const property = embed.property;\n\n // create reference to replace embed\n const subject = {'@id': id};\n\n // remove existing embed\n if(types.isArray(parent)) {\n // replace subject with reference\n for(let i = 0; i < parent.length; ++i) {\n if(util.compareValues(parent[i], subject)) {\n parent[i] = subject;\n break;\n }\n }\n } else {\n // replace subject with reference\n const useArray = types.isArray(parent[property]);\n util.removeValue(parent, property, subject, {propertyIsArray: useArray});\n util.addValue(parent, property, subject, {propertyIsArray: useArray});\n }\n\n // recursively remove dependent dangling embeds\n const removeDependents = id => {\n // get embed keys as a separate array to enable deleting keys in map\n const ids = Object.keys(embeds);\n for(const next of ids) {\n if(next in embeds && types.isObject(embeds[next].parent) &&\n embeds[next].parent['@id'] === id) {\n delete embeds[next];\n removeDependents(next);\n }\n }\n };\n removeDependents(id);\n}\n\n/**\n * Removes the @preserve keywords from expanded result of framing.\n *\n * @param input the framed, framed output.\n * @param options the framing options used.\n *\n * @return the resulting output.\n */\nfunction _cleanupPreserve(input, options) {\n // recurse through arrays\n if(types.isArray(input)) {\n return input.map(value => _cleanupPreserve(value, options));\n }\n\n if(types.isObject(input)) {\n // remove @preserve\n if('@preserve' in input) {\n return input['@preserve'][0];\n }\n\n // skip @values\n if(graphTypes.isValue(input)) {\n return input;\n }\n\n // recurse through @lists\n if(graphTypes.isList(input)) {\n input['@list'] = _cleanupPreserve(input['@list'], options);\n return input;\n }\n\n // handle in-memory linked nodes\n if('@id' in input) {\n const id = input['@id'];\n if(options.link.hasOwnProperty(id)) {\n const idx = options.link[id].indexOf(input);\n if(idx !== -1) {\n // already visited\n return options.link[id][idx];\n }\n // prevent circular visitation\n options.link[id].push(input);\n } else {\n // prevent circular visitation\n options.link[id] = [input];\n }\n }\n\n // recurse through properties\n for(const prop in input) {\n // potentially remove the id, if it is an unreference bnode\n if(prop === '@id' && options.bnodesToClear.includes(input[prop])) {\n delete input['@id'];\n continue;\n }\n\n input[prop] = _cleanupPreserve(input[prop], options);\n }\n }\n return input;\n}\n\n/**\n * Adds framing output to the given parent.\n *\n * @param parent the parent to add to.\n * @param property the parent property.\n * @param output the output to add.\n */\nfunction _addFrameOutput(parent, property, output) {\n if(types.isObject(parent)) {\n util.addValue(parent, property, output, {propertyIsArray: true});\n } else {\n parent.push(output);\n }\n}\n\n/**\n * Node matches if it is a node, and matches the pattern as a frame.\n *\n * @param state the current framing state.\n * @param pattern used to match value\n * @param value to check\n * @param flags the frame flags.\n */\nfunction _nodeMatch(state, pattern, value, flags) {\n if(!('@id' in value)) {\n return false;\n }\n const nodeObject = state.subjects[value['@id']];\n return nodeObject && _filterSubject(state, nodeObject, pattern, flags);\n}\n\n/**\n * Value matches if it is a value and matches the value pattern\n *\n * * `pattern` is empty\n * * @values are the same, or `pattern[@value]` is a wildcard, and\n * * @types are the same or `value[@type]` is not null\n * and `pattern[@type]` is `{}`, or `value[@type]` is null\n * and `pattern[@type]` is null or `[]`, and\n * * @languages are the same or `value[@language]` is not null\n * and `pattern[@language]` is `{}`, or `value[@language]` is null\n * and `pattern[@language]` is null or `[]`.\n *\n * @param pattern used to match value\n * @param value to check\n */\nfunction _valueMatch(pattern, value) {\n const v1 = value['@value'];\n const t1 = value['@type'];\n const l1 = value['@language'];\n const v2 = pattern['@value'] ?\n (types.isArray(pattern['@value']) ?\n pattern['@value'] : [pattern['@value']]) :\n [];\n const t2 = pattern['@type'] ?\n (types.isArray(pattern['@type']) ?\n pattern['@type'] : [pattern['@type']]) :\n [];\n const l2 = pattern['@language'] ?\n (types.isArray(pattern['@language']) ?\n pattern['@language'] : [pattern['@language']]) :\n [];\n\n if(v2.length === 0 && t2.length === 0 && l2.length === 0) {\n return true;\n }\n if(!(v2.includes(v1) || types.isEmptyObject(v2[0]))) {\n return false;\n }\n if(!(!t1 && t2.length === 0 || t2.includes(t1) || t1 &&\n types.isEmptyObject(t2[0]))) {\n return false;\n }\n if(!(!l1 && l2.length === 0 || l2.includes(l1) || l1 &&\n types.isEmptyObject(l2[0]))) {\n return false;\n }\n return true;\n}\n","/*\n * Copyright (c) 2017-2023 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst JsonLdError = require('./JsonLdError');\nconst graphTypes = require('./graphTypes');\nconst types = require('./types');\n\nconst {\n REGEX_BCP47,\n addValue: _addValue\n} = require('./util');\n\nconst {\n handleEvent: _handleEvent\n} = require('./events');\n\n// constants\nconst {\n // RDF,\n RDF_LIST,\n RDF_FIRST,\n RDF_REST,\n RDF_NIL,\n RDF_TYPE,\n // RDF_PLAIN_LITERAL,\n // RDF_XML_LITERAL,\n RDF_JSON_LITERAL,\n // RDF_OBJECT,\n // RDF_LANGSTRING,\n\n // XSD,\n XSD_BOOLEAN,\n XSD_DOUBLE,\n XSD_INTEGER,\n XSD_STRING,\n} = require('./constants');\n\nconst api = {};\nmodule.exports = api;\n\n/**\n * Converts an RDF dataset to JSON-LD.\n *\n * @param dataset the RDF dataset.\n * @param options the RDF serialization options.\n *\n * @return a Promise that resolves to the JSON-LD output.\n */\napi.fromRDF = async (\n dataset,\n options\n) => {\n const {\n useRdfType = false,\n useNativeTypes = false,\n rdfDirection = null\n } = options;\n // FIXME: use Maps?\n const defaultGraph = {};\n const graphMap = {'@default': defaultGraph};\n const referencedOnce = {};\n if(rdfDirection) {\n if(rdfDirection === 'compound-literal') {\n throw new JsonLdError(\n 'Unsupported rdfDirection value.',\n 'jsonld.InvalidRdfDirection',\n {value: rdfDirection});\n } else if(rdfDirection !== 'i18n-datatype') {\n throw new JsonLdError(\n 'Unknown rdfDirection value.',\n 'jsonld.InvalidRdfDirection',\n {value: rdfDirection});\n }\n }\n\n for(const quad of dataset) {\n // TODO: change 'name' to 'graph'\n const name = (quad.graph.termType === 'DefaultGraph') ?\n '@default' : quad.graph.value;\n if(!(name in graphMap)) {\n graphMap[name] = {};\n }\n if(name !== '@default' && !(name in defaultGraph)) {\n defaultGraph[name] = {'@id': name};\n }\n\n const nodeMap = graphMap[name];\n\n // get subject, predicate, object\n const s = quad.subject.value;\n const p = quad.predicate.value;\n const o = quad.object;\n\n if(!(s in nodeMap)) {\n nodeMap[s] = {'@id': s};\n }\n const node = nodeMap[s];\n\n const objectIsNode = o.termType.endsWith('Node');\n if(objectIsNode && !(o.value in nodeMap)) {\n nodeMap[o.value] = {'@id': o.value};\n }\n\n if(p === RDF_TYPE && !useRdfType && objectIsNode) {\n _addValue(node, '@type', o.value, {propertyIsArray: true});\n continue;\n }\n\n const value = _RDFToObject(o, useNativeTypes, rdfDirection, options);\n _addValue(node, p, value, {propertyIsArray: true});\n\n // object may be an RDF list/partial list node but we can't know easily\n // until all triples are read\n if(objectIsNode) {\n if(o.value === RDF_NIL) {\n // track rdf:nil uniquely per graph\n const object = nodeMap[o.value];\n if(!('usages' in object)) {\n object.usages = [];\n }\n object.usages.push({\n node,\n property: p,\n value\n });\n } else if(o.value in referencedOnce) {\n // object referenced more than once\n referencedOnce[o.value] = false;\n } else {\n // keep track of single reference\n referencedOnce[o.value] = {\n node,\n property: p,\n value\n };\n }\n }\n }\n\n /*\n for(let name in dataset) {\n const graph = dataset[name];\n if(!(name in graphMap)) {\n graphMap[name] = {};\n }\n if(name !== '@default' && !(name in defaultGraph)) {\n defaultGraph[name] = {'@id': name};\n }\n const nodeMap = graphMap[name];\n for(let ti = 0; ti < graph.length; ++ti) {\n const triple = graph[ti];\n\n // get subject, predicate, object\n const s = triple.subject.value;\n const p = triple.predicate.value;\n const o = triple.object;\n\n if(!(s in nodeMap)) {\n nodeMap[s] = {'@id': s};\n }\n const node = nodeMap[s];\n\n const objectIsId = (o.type === 'IRI' || o.type === 'blank node');\n if(objectIsId && !(o.value in nodeMap)) {\n nodeMap[o.value] = {'@id': o.value};\n }\n\n if(p === RDF_TYPE && !useRdfType && objectIsId) {\n _addValue(node, '@type', o.value, {propertyIsArray: true});\n continue;\n }\n\n const value = _RDFToObject(o, useNativeTypes);\n _addValue(node, p, value, {propertyIsArray: true});\n\n // object may be an RDF list/partial list node but we can't know easily\n // until all triples are read\n if(objectIsId) {\n if(o.value === RDF_NIL) {\n // track rdf:nil uniquely per graph\n const object = nodeMap[o.value];\n if(!('usages' in object)) {\n object.usages = [];\n }\n object.usages.push({\n node: node,\n property: p,\n value: value\n });\n } else if(o.value in referencedOnce) {\n // object referenced more than once\n referencedOnce[o.value] = false;\n } else {\n // keep track of single reference\n referencedOnce[o.value] = {\n node: node,\n property: p,\n value: value\n };\n }\n }\n }\n }*/\n\n // convert linked lists to @list arrays\n for(const name in graphMap) {\n const graphObject = graphMap[name];\n\n // no @lists to be converted, continue\n if(!(RDF_NIL in graphObject)) {\n continue;\n }\n\n // iterate backwards through each RDF list\n const nil = graphObject[RDF_NIL];\n if(!nil.usages) {\n continue;\n }\n for(let usage of nil.usages) {\n let node = usage.node;\n let property = usage.property;\n let head = usage.value;\n const list = [];\n const listNodes = [];\n\n // ensure node is a well-formed list node; it must:\n // 1. Be referenced only once.\n // 2. Have an array for rdf:first that has 1 item.\n // 3. Have an array for rdf:rest that has 1 item.\n // 4. Have no keys other than: @id, rdf:first, rdf:rest, and,\n // optionally, @type where the value is rdf:List.\n let nodeKeyCount = Object.keys(node).length;\n while(property === RDF_REST &&\n types.isObject(referencedOnce[node['@id']]) &&\n types.isArray(node[RDF_FIRST]) && node[RDF_FIRST].length === 1 &&\n types.isArray(node[RDF_REST]) && node[RDF_REST].length === 1 &&\n (nodeKeyCount === 3 ||\n (nodeKeyCount === 4 && types.isArray(node['@type']) &&\n node['@type'].length === 1 && node['@type'][0] === RDF_LIST))) {\n list.push(node[RDF_FIRST][0]);\n listNodes.push(node['@id']);\n\n // get next node, moving backwards through list\n usage = referencedOnce[node['@id']];\n node = usage.node;\n property = usage.property;\n head = usage.value;\n nodeKeyCount = Object.keys(node).length;\n\n // if node is not a blank node, then list head found\n if(!graphTypes.isBlankNode(node)) {\n break;\n }\n }\n\n // transform list into @list object\n delete head['@id'];\n head['@list'] = list.reverse();\n for(const listNode of listNodes) {\n delete graphObject[listNode];\n }\n }\n\n delete nil.usages;\n }\n\n const result = [];\n const subjects = Object.keys(defaultGraph).sort();\n for(const subject of subjects) {\n const node = defaultGraph[subject];\n if(subject in graphMap) {\n const graph = node['@graph'] = [];\n const graphObject = graphMap[subject];\n const graphSubjects = Object.keys(graphObject).sort();\n for(const graphSubject of graphSubjects) {\n const node = graphObject[graphSubject];\n // only add full subjects to top-level\n if(!graphTypes.isSubjectReference(node)) {\n graph.push(node);\n }\n }\n }\n // only add full subjects to top-level\n if(!graphTypes.isSubjectReference(node)) {\n result.push(node);\n }\n }\n\n return result;\n};\n\n/**\n * Converts an RDF triple object to a JSON-LD object.\n *\n * @param o the RDF triple object to convert.\n * @param useNativeTypes true to output native types, false not to.\n * @param rdfDirection text direction mode [null, i18n-datatype]\n * @param options top level API options\n *\n * @return the JSON-LD object.\n */\nfunction _RDFToObject(o, useNativeTypes, rdfDirection, options) {\n // convert NamedNode/BlankNode object to JSON-LD\n if(o.termType.endsWith('Node')) {\n return {'@id': o.value};\n }\n\n // convert literal to JSON-LD\n const rval = {'@value': o.value};\n\n // add language\n if(o.language) {\n if(!o.language.match(REGEX_BCP47)) {\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'invalid @language value',\n level: 'warning',\n message: '@language value must be valid BCP47.',\n details: {\n language: o.language\n }\n },\n options\n });\n }\n }\n rval['@language'] = o.language;\n } else {\n let type = o.datatype.value;\n if(!type) {\n type = XSD_STRING;\n }\n if(type === RDF_JSON_LITERAL) {\n type = '@json';\n try {\n rval['@value'] = JSON.parse(rval['@value']);\n } catch(e) {\n throw new JsonLdError(\n 'JSON literal could not be parsed.',\n 'jsonld.InvalidJsonLiteral',\n {code: 'invalid JSON literal', value: rval['@value'], cause: e});\n }\n }\n // use native types for certain xsd types\n if(useNativeTypes) {\n if(type === XSD_BOOLEAN) {\n if(rval['@value'] === 'true') {\n rval['@value'] = true;\n } else if(rval['@value'] === 'false') {\n rval['@value'] = false;\n }\n } else if(types.isNumeric(rval['@value'])) {\n if(type === XSD_INTEGER) {\n const i = parseInt(rval['@value'], 10);\n if(i.toFixed(0) === rval['@value']) {\n rval['@value'] = i;\n }\n } else if(type === XSD_DOUBLE) {\n rval['@value'] = parseFloat(rval['@value']);\n }\n }\n // do not add native type\n if(![XSD_BOOLEAN, XSD_INTEGER, XSD_DOUBLE, XSD_STRING].includes(type)) {\n rval['@type'] = type;\n }\n } else if(rdfDirection === 'i18n-datatype' &&\n type.startsWith('https://www.w3.org/ns/i18n#')) {\n const [, language, direction] = type.split(/[#_]/);\n if(language.length > 0) {\n rval['@language'] = language;\n if(!language.match(REGEX_BCP47)) {\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'invalid @language value',\n level: 'warning',\n message: '@language value must be valid BCP47.',\n details: {\n language\n }\n },\n options\n });\n }\n }\n }\n rval['@direction'] = direction;\n } else if(type !== XSD_STRING) {\n rval['@type'] = type;\n }\n }\n\n return rval;\n}\n","/*\n * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst types = require('./types');\n\nconst api = {};\nmodule.exports = api;\n\n/**\n * Returns true if the given value is a subject with properties.\n *\n * @param v the value to check.\n *\n * @return true if the value is a subject with properties, false if not.\n */\napi.isSubject = v => {\n // Note: A value is a subject if all of these hold true:\n // 1. It is an Object.\n // 2. It is not a @value, @set, or @list.\n // 3. It has more than 1 key OR any existing key is not @id.\n if(types.isObject(v) &&\n !(('@value' in v) || ('@set' in v) || ('@list' in v))) {\n const keyCount = Object.keys(v).length;\n return (keyCount > 1 || !('@id' in v));\n }\n return false;\n};\n\n/**\n * Returns true if the given value is a subject reference.\n *\n * @param v the value to check.\n *\n * @return true if the value is a subject reference, false if not.\n */\napi.isSubjectReference = v =>\n // Note: A value is a subject reference if all of these hold true:\n // 1. It is an Object.\n // 2. It has a single key: @id.\n (types.isObject(v) && Object.keys(v).length === 1 && ('@id' in v));\n\n/**\n * Returns true if the given value is a @value.\n *\n * @param v the value to check.\n *\n * @return true if the value is a @value, false if not.\n */\napi.isValue = v =>\n // Note: A value is a @value if all of these hold true:\n // 1. It is an Object.\n // 2. It has the @value property.\n types.isObject(v) && ('@value' in v);\n\n/**\n * Returns true if the given value is a @list.\n *\n * @param v the value to check.\n *\n * @return true if the value is a @list, false if not.\n */\napi.isList = v =>\n // Note: A value is a @list if all of these hold true:\n // 1. It is an Object.\n // 2. It has the @list property.\n types.isObject(v) && ('@list' in v);\n\n/**\n * Returns true if the given value is a @graph.\n *\n * @return true if the value is a @graph, false if not.\n */\napi.isGraph = v => {\n // Note: A value is a graph if all of these hold true:\n // 1. It is an object.\n // 2. It has an `@graph` key.\n // 3. It may have '@id' or '@index'\n return types.isObject(v) &&\n '@graph' in v &&\n Object.keys(v)\n .filter(key => key !== '@id' && key !== '@index').length === 1;\n};\n\n/**\n * Returns true if the given value is a simple @graph.\n *\n * @return true if the value is a simple @graph, false if not.\n */\napi.isSimpleGraph = v => {\n // Note: A value is a simple graph if all of these hold true:\n // 1. It is an object.\n // 2. It has an `@graph` key.\n // 3. It has only 1 key or 2 keys where one of them is `@index`.\n return api.isGraph(v) && !('@id' in v);\n};\n\n/**\n * Returns true if the given value is a blank node.\n *\n * @param v the value to check.\n *\n * @return true if the value is a blank node, false if not.\n */\napi.isBlankNode = v => {\n // Note: A value is a blank node if all of these hold true:\n // 1. It is an Object.\n // 2. If it has an @id key that is not a string OR begins with '_:'.\n // 3. It has no keys OR is not a @value, @set, or @list.\n if(types.isObject(v)) {\n if('@id' in v) {\n const id = v['@id'];\n return !types.isString(id) || id.indexOf('_:') === 0;\n }\n return (Object.keys(v).length === 0 ||\n !(('@value' in v) || ('@set' in v) || ('@list' in v)));\n }\n return false;\n};\n","/**\n * A JavaScript implementation of the JSON-LD API.\n *\n * @author Dave Longley\n *\n * @license BSD 3-Clause License\n * Copyright (c) 2011-2022 Digital Bazaar, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * Neither the name of the Digital Bazaar, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nconst canonize = require('rdf-canonize');\nconst platform = require('./platform');\nconst util = require('./util');\nconst ContextResolver = require('./ContextResolver');\nconst IdentifierIssuer = util.IdentifierIssuer;\nconst JsonLdError = require('./JsonLdError');\nconst LRU = require('lru-cache');\nconst NQuads = require('./NQuads');\n\nconst {expand: _expand} = require('./expand');\nconst {flatten: _flatten} = require('./flatten');\nconst {fromRDF: _fromRDF} = require('./fromRdf');\nconst {toRDF: _toRDF} = require('./toRdf');\n\nconst {\n frameMergedOrDefault: _frameMergedOrDefault,\n cleanupNull: _cleanupNull\n} = require('./frame');\n\nconst {\n isArray: _isArray,\n isObject: _isObject,\n isString: _isString\n} = require('./types');\n\nconst {\n isSubjectReference: _isSubjectReference,\n} = require('./graphTypes');\n\nconst {\n expandIri: _expandIri,\n getInitialContext: _getInitialContext,\n process: _processContext,\n processingMode: _processingMode\n} = require('./context');\n\nconst {\n compact: _compact,\n compactIri: _compactIri\n} = require('./compact');\n\nconst {\n createNodeMap: _createNodeMap,\n createMergedNodeMap: _createMergedNodeMap,\n mergeNodeMaps: _mergeNodeMaps\n} = require('./nodeMap');\n\nconst {\n logEventHandler: _logEventHandler,\n logWarningEventHandler: _logWarningEventHandler,\n safeEventHandler: _safeEventHandler,\n setDefaultEventHandler: _setDefaultEventHandler,\n setupEventHandler: _setupEventHandler,\n strictEventHandler: _strictEventHandler,\n unhandledEventHandler: _unhandledEventHandler\n} = require('./events');\n\n/* eslint-disable indent */\n// attaches jsonld API to the given object\nconst wrapper = function(jsonld) {\n\n/** Registered RDF dataset parsers hashed by content-type. */\nconst _rdfParsers = {};\n\n// resolved context cache\n// TODO: consider basing max on context size rather than number\nconst RESOLVED_CONTEXT_CACHE_MAX_SIZE = 100;\nconst _resolvedContextCache = new LRU({max: RESOLVED_CONTEXT_CACHE_MAX_SIZE});\n\n/* Core API */\n\n/**\n * Performs JSON-LD compaction.\n *\n * @param input the JSON-LD input to compact.\n * @param ctx the context to compact with.\n * @param [options] options to use:\n * [base] the base IRI to use.\n * [compactArrays] true to compact arrays to single values when\n * appropriate, false not to (default: true).\n * [compactToRelative] true to compact IRIs to be relative to document\n * base, false to keep absolute (default: true)\n * [graph] true to always output a top-level graph (default: false).\n * [expandContext] a context to expand with.\n * [skipExpansion] true to assume the input is expanded and skip\n * expansion, false not to, defaults to false. Some well-formed\n * and safe-mode checks may be omitted.\n * [documentLoader(url, options)] the document loader.\n * [framing] true if compaction is occuring during a framing operation.\n * [safe] true to use safe mode. (default: false)\n * [contextResolver] internal use only.\n *\n * @return a Promise that resolves to the compacted output.\n */\njsonld.compact = async function(input, ctx, options) {\n if(arguments.length < 2) {\n throw new TypeError('Could not compact, too few arguments.');\n }\n\n if(ctx === null) {\n throw new JsonLdError(\n 'The compaction context must not be null.',\n 'jsonld.CompactError', {code: 'invalid local context'});\n }\n\n // nothing to compact\n if(input === null) {\n return null;\n }\n\n // set default options\n options = _setDefaults(options, {\n base: _isString(input) ? input : '',\n compactArrays: true,\n compactToRelative: true,\n graph: false,\n skipExpansion: false,\n link: false,\n issuer: new IdentifierIssuer('_:b'),\n contextResolver: new ContextResolver(\n {sharedCache: _resolvedContextCache})\n });\n if(options.link) {\n // force skip expansion when linking, \"link\" is not part of the public\n // API, it should only be called from framing\n options.skipExpansion = true;\n }\n if(!options.compactToRelative) {\n delete options.base;\n }\n\n // expand input\n let expanded;\n if(options.skipExpansion) {\n expanded = input;\n } else {\n expanded = await jsonld.expand(input, options);\n }\n\n // process context\n const activeCtx = await jsonld.processContext(\n _getInitialContext(options), ctx, options);\n\n // do compaction\n let compacted = await _compact({\n activeCtx,\n element: expanded,\n options\n });\n\n // perform clean up\n if(options.compactArrays && !options.graph && _isArray(compacted)) {\n if(compacted.length === 1) {\n // simplify to a single item\n compacted = compacted[0];\n } else if(compacted.length === 0) {\n // simplify to an empty object\n compacted = {};\n }\n } else if(options.graph && _isObject(compacted)) {\n // always use array if graph option is on\n compacted = [compacted];\n }\n\n // follow @context key\n if(_isObject(ctx) && '@context' in ctx) {\n ctx = ctx['@context'];\n }\n\n // build output context\n ctx = util.clone(ctx);\n if(!_isArray(ctx)) {\n ctx = [ctx];\n }\n // remove empty contexts\n const tmp = ctx;\n ctx = [];\n for(let i = 0; i < tmp.length; ++i) {\n if(!_isObject(tmp[i]) || Object.keys(tmp[i]).length > 0) {\n ctx.push(tmp[i]);\n }\n }\n\n // remove array if only one context\n const hasContext = (ctx.length > 0);\n if(ctx.length === 1) {\n ctx = ctx[0];\n }\n\n // add context and/or @graph\n if(_isArray(compacted)) {\n // use '@graph' keyword\n const graphAlias = _compactIri({\n activeCtx, iri: '@graph', relativeTo: {vocab: true}\n });\n const graph = compacted;\n compacted = {};\n if(hasContext) {\n compacted['@context'] = ctx;\n }\n compacted[graphAlias] = graph;\n } else if(_isObject(compacted) && hasContext) {\n // reorder keys so @context is first\n const graph = compacted;\n compacted = {'@context': ctx};\n for(const key in graph) {\n compacted[key] = graph[key];\n }\n }\n\n return compacted;\n};\n\n/**\n * Performs JSON-LD expansion.\n *\n * @param input the JSON-LD input to expand.\n * @param [options] the options to use:\n * [base] the base IRI to use.\n * [expandContext] a context to expand with.\n * [keepFreeFloatingNodes] true to keep free-floating nodes,\n * false not to, defaults to false.\n * [documentLoader(url, options)] the document loader.\n * [safe] true to use safe mode. (default: false)\n * [contextResolver] internal use only.\n *\n * @return a Promise that resolves to the expanded output.\n */\njsonld.expand = async function(input, options) {\n if(arguments.length < 1) {\n throw new TypeError('Could not expand, too few arguments.');\n }\n\n // set default options\n options = _setDefaults(options, {\n keepFreeFloatingNodes: false,\n contextResolver: new ContextResolver(\n {sharedCache: _resolvedContextCache})\n });\n\n // build set of objects that may have @contexts to resolve\n const toResolve = {};\n\n // build set of contexts to process prior to expansion\n const contextsToProcess = [];\n\n // if an `expandContext` has been given ensure it gets resolved\n if('expandContext' in options) {\n const expandContext = util.clone(options.expandContext);\n if(_isObject(expandContext) && '@context' in expandContext) {\n toResolve.expandContext = expandContext;\n } else {\n toResolve.expandContext = {'@context': expandContext};\n }\n contextsToProcess.push(toResolve.expandContext);\n }\n\n // if input is a string, attempt to dereference remote document\n let defaultBase;\n if(!_isString(input)) {\n // input is not a URL, do not need to retrieve it first\n toResolve.input = util.clone(input);\n } else {\n // load remote doc\n const remoteDoc = await jsonld.get(input, options);\n defaultBase = remoteDoc.documentUrl;\n toResolve.input = remoteDoc.document;\n if(remoteDoc.contextUrl) {\n // context included in HTTP link header and must be resolved\n toResolve.remoteContext = {'@context': remoteDoc.contextUrl};\n contextsToProcess.push(toResolve.remoteContext);\n }\n }\n\n // set default base\n if(!('base' in options)) {\n options.base = defaultBase || '';\n }\n\n // process any additional contexts\n let activeCtx = _getInitialContext(options);\n for(const localCtx of contextsToProcess) {\n activeCtx = await _processContext({activeCtx, localCtx, options});\n }\n\n // expand resolved input\n let expanded = await _expand({\n activeCtx,\n element: toResolve.input,\n options\n });\n\n // optimize away @graph with no other properties\n if(_isObject(expanded) && ('@graph' in expanded) &&\n Object.keys(expanded).length === 1) {\n expanded = expanded['@graph'];\n } else if(expanded === null) {\n expanded = [];\n }\n\n // normalize to an array\n if(!_isArray(expanded)) {\n expanded = [expanded];\n }\n\n return expanded;\n};\n\n/**\n * Performs JSON-LD flattening.\n *\n * @param input the JSON-LD to flatten.\n * @param ctx the context to use to compact the flattened output, or null.\n * @param [options] the options to use:\n * [base] the base IRI to use.\n * [expandContext] a context to expand with.\n * [documentLoader(url, options)] the document loader.\n * [contextResolver] internal use only.\n *\n * @return a Promise that resolves to the flattened output.\n */\njsonld.flatten = async function(input, ctx, options) {\n if(arguments.length < 1) {\n return new TypeError('Could not flatten, too few arguments.');\n }\n\n if(typeof ctx === 'function') {\n ctx = null;\n } else {\n ctx = ctx || null;\n }\n\n // set default options\n options = _setDefaults(options, {\n base: _isString(input) ? input : '',\n contextResolver: new ContextResolver(\n {sharedCache: _resolvedContextCache})\n });\n\n // expand input\n const expanded = await jsonld.expand(input, options);\n\n // do flattening\n const flattened = _flatten(expanded);\n\n if(ctx === null) {\n // no compaction required\n return flattened;\n }\n\n // compact result (force @graph option to true, skip expansion)\n options.graph = true;\n options.skipExpansion = true;\n const compacted = await jsonld.compact(flattened, ctx, options);\n\n return compacted;\n};\n\n/**\n * Performs JSON-LD framing.\n *\n * @param input the JSON-LD input to frame.\n * @param frame the JSON-LD frame to use.\n * @param [options] the framing options.\n * [base] the base IRI to use.\n * [expandContext] a context to expand with.\n * [embed] default @embed flag: '@last', '@always', '@never', '@link'\n * (default: '@last').\n * [explicit] default @explicit flag (default: false).\n * [requireAll] default @requireAll flag (default: true).\n * [omitDefault] default @omitDefault flag (default: false).\n * [documentLoader(url, options)] the document loader.\n * [safe] true to use safe mode. (default: false)\n * [contextResolver] internal use only.\n *\n * @return a Promise that resolves to the framed output.\n */\njsonld.frame = async function(input, frame, options) {\n if(arguments.length < 2) {\n throw new TypeError('Could not frame, too few arguments.');\n }\n\n // set default options\n options = _setDefaults(options, {\n base: _isString(input) ? input : '',\n embed: '@once',\n explicit: false,\n requireAll: false,\n omitDefault: false,\n bnodesToClear: [],\n contextResolver: new ContextResolver(\n {sharedCache: _resolvedContextCache})\n });\n\n // if frame is a string, attempt to dereference remote document\n if(_isString(frame)) {\n // load remote doc\n const remoteDoc = await jsonld.get(frame, options);\n frame = remoteDoc.document;\n\n if(remoteDoc.contextUrl) {\n // inject link header @context into frame\n let ctx = frame['@context'];\n if(!ctx) {\n ctx = remoteDoc.contextUrl;\n } else if(_isArray(ctx)) {\n ctx.push(remoteDoc.contextUrl);\n } else {\n ctx = [ctx, remoteDoc.contextUrl];\n }\n frame['@context'] = ctx;\n }\n }\n\n const frameContext = frame ? frame['@context'] || {} : {};\n\n // process context\n const activeCtx = await jsonld.processContext(\n _getInitialContext(options), frameContext, options);\n\n // mode specific defaults\n if(!options.hasOwnProperty('omitGraph')) {\n options.omitGraph = _processingMode(activeCtx, 1.1);\n }\n if(!options.hasOwnProperty('pruneBlankNodeIdentifiers')) {\n options.pruneBlankNodeIdentifiers = _processingMode(activeCtx, 1.1);\n }\n\n // expand input\n const expanded = await jsonld.expand(input, options);\n\n // expand frame\n const opts = {...options};\n opts.isFrame = true;\n opts.keepFreeFloatingNodes = true;\n const expandedFrame = await jsonld.expand(frame, opts);\n\n // if the unexpanded frame includes a key expanding to @graph, frame the\n // default graph, otherwise, the merged graph\n const frameKeys = Object.keys(frame)\n .map(key => _expandIri(activeCtx, key, {vocab: true}));\n opts.merged = !frameKeys.includes('@graph');\n opts.is11 = _processingMode(activeCtx, 1.1);\n\n // do framing\n const framed = _frameMergedOrDefault(expanded, expandedFrame, opts);\n\n opts.graph = !options.omitGraph;\n opts.skipExpansion = true;\n opts.link = {};\n opts.framing = true;\n let compacted = await jsonld.compact(framed, frameContext, opts);\n\n // replace @null with null, compacting arrays\n opts.link = {};\n compacted = _cleanupNull(compacted, opts);\n\n return compacted;\n};\n\n/**\n * **Experimental**\n *\n * Links a JSON-LD document's nodes in memory.\n *\n * @param input the JSON-LD document to link.\n * @param [ctx] the JSON-LD context to apply.\n * @param [options] the options to use:\n * [base] the base IRI to use.\n * [expandContext] a context to expand with.\n * [documentLoader(url, options)] the document loader.\n * [safe] true to use safe mode. (default: false)\n * [contextResolver] internal use only.\n *\n * @return a Promise that resolves to the linked output.\n */\njsonld.link = async function(input, ctx, options) {\n // API matches running frame with a wildcard frame and embed: '@link'\n // get arguments\n const frame = {};\n if(ctx) {\n frame['@context'] = ctx;\n }\n frame['@embed'] = '@link';\n return jsonld.frame(input, frame, options);\n};\n\n/**\n * Performs RDF dataset normalization on the given input. The input is JSON-LD\n * unless the 'inputFormat' option is used. The output is an RDF dataset\n * unless the 'format' option is used.\n *\n * Note: Canonicalization sets `safe` to `true` and `base` to `null` by\n * default in order to produce safe outputs and \"fail closed\" by default. This\n * is different from the other API transformations in this version which\n * allow unsafe defaults (for cryptographic usage) in order to comply with the\n * JSON-LD 1.1 specification.\n *\n * @param input the input to normalize as JSON-LD or as a format specified by\n * the 'inputFormat' option.\n * @param [options] the options to use:\n * [algorithm] the normalization algorithm to use, `URDNA2015` or\n * `URGNA2012` (default: `URDNA2015`).\n * [base] the base IRI to use (default: `null`).\n * [expandContext] a context to expand with.\n * [skipExpansion] true to assume the input is expanded and skip\n * expansion, false not to, defaults to false. Some well-formed\n * and safe-mode checks may be omitted.\n * [inputFormat] the format if input is not JSON-LD:\n * 'application/n-quads' for N-Quads.\n * [format] the format if output is a string:\n * 'application/n-quads' for N-Quads.\n * [documentLoader(url, options)] the document loader.\n * [useNative] true to use a native canonize algorithm\n * [rdfDirection] null or 'i18n-datatype' to support RDF\n * transformation of @direction (default: null).\n * [safe] true to use safe mode. (default: true).\n * [contextResolver] internal use only.\n *\n * @return a Promise that resolves to the normalized output.\n */\njsonld.normalize = jsonld.canonize = async function(input, options) {\n if(arguments.length < 1) {\n throw new TypeError('Could not canonize, too few arguments.');\n }\n\n // set default options\n options = _setDefaults(options, {\n base: _isString(input) ? input : null,\n algorithm: 'URDNA2015',\n skipExpansion: false,\n safe: true,\n contextResolver: new ContextResolver(\n {sharedCache: _resolvedContextCache})\n });\n if('inputFormat' in options) {\n if(options.inputFormat !== 'application/n-quads' &&\n options.inputFormat !== 'application/nquads') {\n throw new JsonLdError(\n 'Unknown canonicalization input format.',\n 'jsonld.CanonizeError');\n }\n // TODO: `await` for async parsers\n const parsedInput = NQuads.parse(input);\n\n // do canonicalization\n return canonize.canonize(parsedInput, options);\n }\n\n // convert to RDF dataset then do normalization\n const opts = {...options};\n delete opts.format;\n opts.produceGeneralizedRdf = false;\n const dataset = await jsonld.toRDF(input, opts);\n\n // do canonicalization\n return canonize.canonize(dataset, options);\n};\n\n/**\n * Converts an RDF dataset to JSON-LD.\n *\n * @param dataset a serialized string of RDF in a format specified by the\n * format option or an RDF dataset to convert.\n * @param [options] the options to use:\n * [format] the format if dataset param must first be parsed:\n * 'application/n-quads' for N-Quads (default).\n * [rdfParser] a custom RDF-parser to use to parse the dataset.\n * [useRdfType] true to use rdf:type, false to use @type\n * (default: false).\n * [useNativeTypes] true to convert XSD types into native types\n * (boolean, integer, double), false not to (default: false).\n * [rdfDirection] null or 'i18n-datatype' to support RDF\n * transformation of @direction (default: null).\n * [safe] true to use safe mode. (default: false)\n *\n * @return a Promise that resolves to the JSON-LD document.\n */\njsonld.fromRDF = async function(dataset, options) {\n if(arguments.length < 1) {\n throw new TypeError('Could not convert from RDF, too few arguments.');\n }\n\n // set default options\n options = _setDefaults(options, {\n format: _isString(dataset) ? 'application/n-quads' : undefined\n });\n\n const {format} = options;\n let {rdfParser} = options;\n\n // handle special format\n if(format) {\n // check supported formats\n rdfParser = rdfParser || _rdfParsers[format];\n if(!rdfParser) {\n throw new JsonLdError(\n 'Unknown input format.',\n 'jsonld.UnknownFormat', {format});\n }\n } else {\n // no-op parser, assume dataset already parsed\n rdfParser = () => dataset;\n }\n\n // rdfParser must be synchronous or return a promise, no callback support\n const parsedDataset = await rdfParser(dataset);\n return _fromRDF(parsedDataset, options);\n};\n\n/**\n * Outputs the RDF dataset found in the given JSON-LD object.\n *\n * @param input the JSON-LD input.\n * @param [options] the options to use:\n * [base] the base IRI to use.\n * [expandContext] a context to expand with.\n * [skipExpansion] true to assume the input is expanded and skip\n * expansion, false not to, defaults to false. Some well-formed\n * and safe-mode checks may be omitted.\n * [format] the format to use to output a string:\n * 'application/n-quads' for N-Quads.\n * [produceGeneralizedRdf] true to output generalized RDF, false\n * to produce only standard RDF (default: false).\n * [documentLoader(url, options)] the document loader.\n * [safe] true to use safe mode. (default: false)\n * [rdfDirection] null or 'i18n-datatype' to support RDF\n * transformation of @direction (default: null).\n * [contextResolver] internal use only.\n *\n * @return a Promise that resolves to the RDF dataset.\n */\njsonld.toRDF = async function(input, options) {\n if(arguments.length < 1) {\n throw new TypeError('Could not convert to RDF, too few arguments.');\n }\n\n // set default options\n options = _setDefaults(options, {\n base: _isString(input) ? input : '',\n skipExpansion: false,\n contextResolver: new ContextResolver(\n {sharedCache: _resolvedContextCache})\n });\n\n // TODO: support toRDF custom map?\n let expanded;\n if(options.skipExpansion) {\n expanded = input;\n } else {\n // expand input\n expanded = await jsonld.expand(input, options);\n }\n\n // output RDF dataset\n const dataset = _toRDF(expanded, options);\n if(options.format) {\n if(options.format === 'application/n-quads' ||\n options.format === 'application/nquads') {\n return NQuads.serialize(dataset);\n }\n throw new JsonLdError(\n 'Unknown output format.',\n 'jsonld.UnknownFormat', {format: options.format});\n }\n\n return dataset;\n};\n\n/**\n * **Experimental**\n *\n * Recursively flattens the nodes in the given JSON-LD input into a merged\n * map of node ID => node. All graphs will be merged into the default graph.\n *\n * @param input the JSON-LD input.\n * @param [options] the options to use:\n * [base] the base IRI to use.\n * [expandContext] a context to expand with.\n * [issuer] a jsonld.IdentifierIssuer to use to label blank nodes.\n * [documentLoader(url, options)] the document loader.\n * [contextResolver] internal use only.\n *\n * @return a Promise that resolves to the merged node map.\n */\njsonld.createNodeMap = async function(input, options) {\n if(arguments.length < 1) {\n throw new TypeError('Could not create node map, too few arguments.');\n }\n\n // set default options\n options = _setDefaults(options, {\n base: _isString(input) ? input : '',\n contextResolver: new ContextResolver(\n {sharedCache: _resolvedContextCache})\n });\n\n // expand input\n const expanded = await jsonld.expand(input, options);\n\n return _createMergedNodeMap(expanded, options);\n};\n\n/**\n * **Experimental**\n *\n * Merges two or more JSON-LD documents into a single flattened document.\n *\n * @param docs the JSON-LD documents to merge together.\n * @param ctx the context to use to compact the merged result, or null.\n * @param [options] the options to use:\n * [base] the base IRI to use.\n * [expandContext] a context to expand with.\n * [issuer] a jsonld.IdentifierIssuer to use to label blank nodes.\n * [mergeNodes] true to merge properties for nodes with the same ID,\n * false to ignore new properties for nodes with the same ID once\n * the ID has been defined; note that this may not prevent merging\n * new properties where a node is in the `object` position\n * (default: true).\n * [documentLoader(url, options)] the document loader.\n * [safe] true to use safe mode. (default: false)\n * [contextResolver] internal use only.\n *\n * @return a Promise that resolves to the merged output.\n */\njsonld.merge = async function(docs, ctx, options) {\n if(arguments.length < 1) {\n throw new TypeError('Could not merge, too few arguments.');\n }\n if(!_isArray(docs)) {\n throw new TypeError('Could not merge, \"docs\" must be an array.');\n }\n\n if(typeof ctx === 'function') {\n ctx = null;\n } else {\n ctx = ctx || null;\n }\n\n // set default options\n options = _setDefaults(options, {\n contextResolver: new ContextResolver(\n {sharedCache: _resolvedContextCache})\n });\n\n // expand all documents\n const expanded = await Promise.all(docs.map(doc => {\n const opts = {...options};\n return jsonld.expand(doc, opts);\n }));\n\n let mergeNodes = true;\n if('mergeNodes' in options) {\n mergeNodes = options.mergeNodes;\n }\n\n const issuer = options.issuer || new IdentifierIssuer('_:b');\n const graphs = {'@default': {}};\n\n for(let i = 0; i < expanded.length; ++i) {\n // uniquely relabel blank nodes\n const doc = util.relabelBlankNodes(expanded[i], {\n issuer: new IdentifierIssuer('_:b' + i + '-')\n });\n\n // add nodes to the shared node map graphs if merging nodes, to a\n // separate graph set if not\n const _graphs = (mergeNodes || i === 0) ? graphs : {'@default': {}};\n _createNodeMap(doc, _graphs, '@default', issuer);\n\n if(_graphs !== graphs) {\n // merge document graphs but don't merge existing nodes\n for(const graphName in _graphs) {\n const _nodeMap = _graphs[graphName];\n if(!(graphName in graphs)) {\n graphs[graphName] = _nodeMap;\n continue;\n }\n const nodeMap = graphs[graphName];\n for(const key in _nodeMap) {\n if(!(key in nodeMap)) {\n nodeMap[key] = _nodeMap[key];\n }\n }\n }\n }\n }\n\n // add all non-default graphs to default graph\n const defaultGraph = _mergeNodeMaps(graphs);\n\n // produce flattened output\n const flattened = [];\n const keys = Object.keys(defaultGraph).sort();\n for(let ki = 0; ki < keys.length; ++ki) {\n const node = defaultGraph[keys[ki]];\n // only add full subjects to top-level\n if(!_isSubjectReference(node)) {\n flattened.push(node);\n }\n }\n\n if(ctx === null) {\n return flattened;\n }\n\n // compact result (force @graph option to true, skip expansion)\n options.graph = true;\n options.skipExpansion = true;\n const compacted = await jsonld.compact(flattened, ctx, options);\n\n return compacted;\n};\n\n/**\n * The default document loader for external documents.\n *\n * @param url the URL to load.\n *\n * @return a promise that resolves to the remote document.\n */\nObject.defineProperty(jsonld, 'documentLoader', {\n get: () => jsonld._documentLoader,\n set: v => jsonld._documentLoader = v\n});\n// default document loader not implemented\njsonld.documentLoader = async url => {\n throw new JsonLdError(\n 'Could not retrieve a JSON-LD document from the URL. URL ' +\n 'dereferencing not implemented.', 'jsonld.LoadDocumentError',\n {code: 'loading document failed', url});\n};\n\n/**\n * Gets a remote JSON-LD document using the default document loader or\n * one given in the passed options.\n *\n * @param url the URL to fetch.\n * @param [options] the options to use:\n * [documentLoader] the document loader to use.\n *\n * @return a Promise that resolves to the retrieved remote document.\n */\njsonld.get = async function(url, options) {\n let load;\n if(typeof options.documentLoader === 'function') {\n load = options.documentLoader;\n } else {\n load = jsonld.documentLoader;\n }\n\n const remoteDoc = await load(url);\n\n try {\n if(!remoteDoc.document) {\n throw new JsonLdError(\n 'No remote document found at the given URL.',\n 'jsonld.NullRemoteDocument');\n }\n if(_isString(remoteDoc.document)) {\n remoteDoc.document = JSON.parse(remoteDoc.document);\n }\n } catch(e) {\n throw new JsonLdError(\n 'Could not retrieve a JSON-LD document from the URL.',\n 'jsonld.LoadDocumentError', {\n code: 'loading document failed',\n cause: e,\n remoteDoc\n });\n }\n\n return remoteDoc;\n};\n\n/**\n * Processes a local context, resolving any URLs as necessary, and returns a\n * new active context.\n *\n * @param activeCtx the current active context.\n * @param localCtx the local context to process.\n * @param [options] the options to use:\n * [documentLoader(url, options)] the document loader.\n * [safe] true to use safe mode. (default: false)\n * [contextResolver] internal use only.\n *\n * @return a Promise that resolves to the new active context.\n */\njsonld.processContext = async function(\n activeCtx, localCtx, options) {\n // set default options\n options = _setDefaults(options, {\n base: '',\n contextResolver: new ContextResolver(\n {sharedCache: _resolvedContextCache})\n });\n\n // return initial context early for null context\n if(localCtx === null) {\n return _getInitialContext(options);\n }\n\n // get URLs in localCtx\n localCtx = util.clone(localCtx);\n if(!(_isObject(localCtx) && '@context' in localCtx)) {\n localCtx = {'@context': localCtx};\n }\n\n return _processContext({activeCtx, localCtx, options});\n};\n\n// backwards compatibility\njsonld.getContextValue = require('./context').getContextValue;\n\n/**\n * Document loaders.\n */\njsonld.documentLoaders = {};\n\n/**\n * Assigns the default document loader for external document URLs to a built-in\n * default. Supported types currently include: 'xhr' and 'node'.\n *\n * @param type the type to set.\n * @param [params] the parameters required to use the document loader.\n */\njsonld.useDocumentLoader = function(type) {\n if(!(type in jsonld.documentLoaders)) {\n throw new JsonLdError(\n 'Unknown document loader type: \"' + type + '\"',\n 'jsonld.UnknownDocumentLoader',\n {type});\n }\n\n // set document loader\n jsonld.documentLoader = jsonld.documentLoaders[type].apply(\n jsonld, Array.prototype.slice.call(arguments, 1));\n};\n\n/**\n * Registers an RDF dataset parser by content-type, for use with\n * jsonld.fromRDF. An RDF dataset parser will always be given one parameter,\n * a string of input. An RDF dataset parser can be synchronous or\n * asynchronous (by returning a promise).\n *\n * @param contentType the content-type for the parser.\n * @param parser(input) the parser function (takes a string as a parameter\n * and either returns an RDF dataset or a Promise that resolves to one.\n */\njsonld.registerRDFParser = function(contentType, parser) {\n _rdfParsers[contentType] = parser;\n};\n\n/**\n * Unregisters an RDF dataset parser by content-type.\n *\n * @param contentType the content-type for the parser.\n */\njsonld.unregisterRDFParser = function(contentType) {\n delete _rdfParsers[contentType];\n};\n\n// register the N-Quads RDF parser\njsonld.registerRDFParser('application/n-quads', NQuads.parse);\njsonld.registerRDFParser('application/nquads', NQuads.parse);\n\n/* URL API */\njsonld.url = require('./url');\n\n/* Events API and handlers */\njsonld.logEventHandler = _logEventHandler;\njsonld.logWarningEventHandler = _logWarningEventHandler;\njsonld.safeEventHandler = _safeEventHandler;\njsonld.setDefaultEventHandler = _setDefaultEventHandler;\njsonld.strictEventHandler = _strictEventHandler;\njsonld.unhandledEventHandler = _unhandledEventHandler;\n\n/* Utility API */\njsonld.util = util;\n// backwards compatibility\nObject.assign(jsonld, util);\n\n// reexpose API as jsonld.promises for backwards compatability\njsonld.promises = jsonld;\n\n// backwards compatibility\njsonld.RequestQueue = require('./RequestQueue');\n\n/* WebIDL API */\njsonld.JsonLdProcessor = require('./JsonLdProcessor')(jsonld);\n\nplatform.setupGlobals(jsonld);\nplatform.setupDocumentLoaders(jsonld);\n\nfunction _setDefaults(options, {\n documentLoader = jsonld.documentLoader,\n ...defaults\n}) {\n // fail if obsolete options present\n if(options && 'compactionMap' in options) {\n throw new JsonLdError(\n '\"compactionMap\" not supported.',\n 'jsonld.OptionsError');\n }\n if(options && 'expansionMap' in options) {\n throw new JsonLdError(\n '\"expansionMap\" not supported.',\n 'jsonld.OptionsError');\n }\n return Object.assign(\n {},\n {documentLoader},\n defaults,\n options,\n {eventHandler: _setupEventHandler({options})}\n );\n}\n\n// end of jsonld API `wrapper` factory\nreturn jsonld;\n};\n\n// external APIs:\n\n// used to generate a new jsonld API instance\nconst factory = function() {\n return wrapper(function() {\n return factory();\n });\n};\n\n// wrap the main jsonld API instance\nwrapper(factory);\n// export API\nmodule.exports = factory;\n","/*\n * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst {isKeyword} = require('./context');\nconst graphTypes = require('./graphTypes');\nconst types = require('./types');\nconst util = require('./util');\nconst JsonLdError = require('./JsonLdError');\n\nconst api = {};\nmodule.exports = api;\n\n/**\n * Creates a merged JSON-LD node map (node ID => node).\n *\n * @param input the expanded JSON-LD to create a node map of.\n * @param [options] the options to use:\n * [issuer] a jsonld.IdentifierIssuer to use to label blank nodes.\n *\n * @return the node map.\n */\napi.createMergedNodeMap = (input, options) => {\n options = options || {};\n\n // produce a map of all subjects and name each bnode\n const issuer = options.issuer || new util.IdentifierIssuer('_:b');\n const graphs = {'@default': {}};\n api.createNodeMap(input, graphs, '@default', issuer);\n\n // add all non-default graphs to default graph\n return api.mergeNodeMaps(graphs);\n};\n\n/**\n * Recursively flattens the subjects in the given JSON-LD expanded input\n * into a node map.\n *\n * @param input the JSON-LD expanded input.\n * @param graphs a map of graph name to subject map.\n * @param graph the name of the current graph.\n * @param issuer the blank node identifier issuer.\n * @param name the name assigned to the current input if it is a bnode.\n * @param list the list to append to, null for none.\n */\napi.createNodeMap = (input, graphs, graph, issuer, name, list) => {\n // recurse through array\n if(types.isArray(input)) {\n for(const node of input) {\n api.createNodeMap(node, graphs, graph, issuer, undefined, list);\n }\n return;\n }\n\n // add non-object to list\n if(!types.isObject(input)) {\n if(list) {\n list.push(input);\n }\n return;\n }\n\n // add values to list\n if(graphTypes.isValue(input)) {\n if('@type' in input) {\n let type = input['@type'];\n // rename @type blank node\n if(type.indexOf('_:') === 0) {\n input['@type'] = type = issuer.getId(type);\n }\n }\n if(list) {\n list.push(input);\n }\n return;\n } else if(list && graphTypes.isList(input)) {\n const _list = [];\n api.createNodeMap(input['@list'], graphs, graph, issuer, name, _list);\n list.push({'@list': _list});\n return;\n }\n\n // Note: At this point, input must be a subject.\n\n // spec requires @type to be named first, so assign names early\n if('@type' in input) {\n const types = input['@type'];\n for(const type of types) {\n if(type.indexOf('_:') === 0) {\n issuer.getId(type);\n }\n }\n }\n\n // get name for subject\n if(types.isUndefined(name)) {\n name = graphTypes.isBlankNode(input) ?\n issuer.getId(input['@id']) : input['@id'];\n }\n\n // add subject reference to list\n if(list) {\n list.push({'@id': name});\n }\n\n // create new subject or merge into existing one\n const subjects = graphs[graph];\n const subject = subjects[name] = subjects[name] || {};\n subject['@id'] = name;\n const properties = Object.keys(input).sort();\n for(let property of properties) {\n // skip @id\n if(property === '@id') {\n continue;\n }\n\n // handle reverse properties\n if(property === '@reverse') {\n const referencedNode = {'@id': name};\n const reverseMap = input['@reverse'];\n for(const reverseProperty in reverseMap) {\n const items = reverseMap[reverseProperty];\n for(const item of items) {\n let itemName = item['@id'];\n if(graphTypes.isBlankNode(item)) {\n itemName = issuer.getId(itemName);\n }\n api.createNodeMap(item, graphs, graph, issuer, itemName);\n util.addValue(\n subjects[itemName], reverseProperty, referencedNode,\n {propertyIsArray: true, allowDuplicate: false});\n }\n }\n continue;\n }\n\n // recurse into graph\n if(property === '@graph') {\n // add graph subjects map entry\n if(!(name in graphs)) {\n graphs[name] = {};\n }\n api.createNodeMap(input[property], graphs, name, issuer);\n continue;\n }\n\n // recurse into included\n if(property === '@included') {\n api.createNodeMap(input[property], graphs, graph, issuer);\n continue;\n }\n\n // copy non-@type keywords\n if(property !== '@type' && isKeyword(property)) {\n if(property === '@index' && property in subject &&\n (input[property] !== subject[property] ||\n input[property]['@id'] !== subject[property]['@id'])) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; conflicting @index property detected.',\n 'jsonld.SyntaxError',\n {code: 'conflicting indexes', subject});\n }\n subject[property] = input[property];\n continue;\n }\n\n // iterate over objects\n const objects = input[property];\n\n // if property is a bnode, assign it a new id\n if(property.indexOf('_:') === 0) {\n property = issuer.getId(property);\n }\n\n // ensure property is added for empty arrays\n if(objects.length === 0) {\n util.addValue(subject, property, [], {propertyIsArray: true});\n continue;\n }\n for(let o of objects) {\n if(property === '@type') {\n // rename @type blank nodes\n o = (o.indexOf('_:') === 0) ? issuer.getId(o) : o;\n }\n\n // handle embedded subject or subject reference\n if(graphTypes.isSubject(o) || graphTypes.isSubjectReference(o)) {\n // skip null @id\n if('@id' in o && !o['@id']) {\n continue;\n }\n\n // relabel blank node @id\n const id = graphTypes.isBlankNode(o) ?\n issuer.getId(o['@id']) : o['@id'];\n\n // add reference and recurse\n util.addValue(\n subject, property, {'@id': id},\n {propertyIsArray: true, allowDuplicate: false});\n api.createNodeMap(o, graphs, graph, issuer, id);\n } else if(graphTypes.isValue(o)) {\n util.addValue(\n subject, property, o,\n {propertyIsArray: true, allowDuplicate: false});\n } else if(graphTypes.isList(o)) {\n // handle @list\n const _list = [];\n api.createNodeMap(o['@list'], graphs, graph, issuer, name, _list);\n o = {'@list': _list};\n util.addValue(\n subject, property, o,\n {propertyIsArray: true, allowDuplicate: false});\n } else {\n // handle @value\n api.createNodeMap(o, graphs, graph, issuer, name);\n util.addValue(\n subject, property, o, {propertyIsArray: true, allowDuplicate: false});\n }\n }\n }\n};\n\n/**\n * Merge separate named graphs into a single merged graph including\n * all nodes from the default graph and named graphs.\n *\n * @param graphs a map of graph name to subject map.\n *\n * @return the merged graph map.\n */\napi.mergeNodeMapGraphs = graphs => {\n const merged = {};\n for(const name of Object.keys(graphs).sort()) {\n for(const id of Object.keys(graphs[name]).sort()) {\n const node = graphs[name][id];\n if(!(id in merged)) {\n merged[id] = {'@id': id};\n }\n const mergedNode = merged[id];\n\n for(const property of Object.keys(node).sort()) {\n if(isKeyword(property) && property !== '@type') {\n // copy keywords\n mergedNode[property] = util.clone(node[property]);\n } else {\n // merge objects\n for(const value of node[property]) {\n util.addValue(\n mergedNode, property, util.clone(value),\n {propertyIsArray: true, allowDuplicate: false});\n }\n }\n }\n }\n }\n\n return merged;\n};\n\napi.mergeNodeMaps = graphs => {\n // add all non-default graphs to default graph\n const defaultGraph = graphs['@default'];\n const graphNames = Object.keys(graphs).sort();\n for(const graphName of graphNames) {\n if(graphName === '@default') {\n continue;\n }\n const nodeMap = graphs[graphName];\n let subject = defaultGraph[graphName];\n if(!subject) {\n defaultGraph[graphName] = subject = {\n '@id': graphName,\n '@graph': []\n };\n } else if(!('@graph' in subject)) {\n subject['@graph'] = [];\n }\n const graph = subject['@graph'];\n for(const id of Object.keys(nodeMap).sort()) {\n const node = nodeMap[id];\n // only add full subjects\n if(!graphTypes.isSubjectReference(node)) {\n graph.push(node);\n }\n }\n }\n return defaultGraph;\n};\n","/*\n * Copyright (c) 2021 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst xhrLoader = require('./documentLoaders/xhr');\n\nconst api = {};\nmodule.exports = api;\n\n/**\n * Setup browser document loaders.\n *\n * @param jsonld the jsonld api.\n */\napi.setupDocumentLoaders = function(jsonld) {\n if(typeof XMLHttpRequest !== 'undefined') {\n jsonld.documentLoaders.xhr = xhrLoader;\n // use xhr document loader by default\n jsonld.useDocumentLoader('xhr');\n }\n};\n\n/**\n * Setup browser globals.\n *\n * @param jsonld the jsonld api.\n */\napi.setupGlobals = function(jsonld) {\n // setup browser global JsonLdProcessor\n if(typeof globalThis.JsonLdProcessor === 'undefined') {\n Object.defineProperty(globalThis, 'JsonLdProcessor', {\n writable: true,\n enumerable: false,\n configurable: true,\n value: jsonld.JsonLdProcessor\n });\n }\n};\n","/*\n * Copyright (c) 2017-2023 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst {createNodeMap} = require('./nodeMap');\nconst {isKeyword} = require('./context');\nconst graphTypes = require('./graphTypes');\nconst jsonCanonicalize = require('canonicalize');\nconst JsonLdError = require('./JsonLdError');\nconst types = require('./types');\nconst util = require('./util');\n\nconst {\n handleEvent: _handleEvent\n} = require('./events');\n\nconst {\n // RDF,\n // RDF_LIST,\n RDF_FIRST,\n RDF_REST,\n RDF_NIL,\n RDF_TYPE,\n // RDF_PLAIN_LITERAL,\n // RDF_XML_LITERAL,\n RDF_JSON_LITERAL,\n // RDF_OBJECT,\n RDF_LANGSTRING,\n\n // XSD,\n XSD_BOOLEAN,\n XSD_DOUBLE,\n XSD_INTEGER,\n XSD_STRING,\n} = require('./constants');\n\nconst {\n isAbsolute: _isAbsoluteIri\n} = require('./url');\n\nconst api = {};\nmodule.exports = api;\n\n/**\n * Outputs an RDF dataset for the expanded JSON-LD input.\n *\n * @param input the expanded JSON-LD input.\n * @param options the RDF serialization options.\n *\n * @return the RDF dataset.\n */\napi.toRDF = (input, options) => {\n // create node map for default graph (and any named graphs)\n const issuer = new util.IdentifierIssuer('_:b');\n const nodeMap = {'@default': {}};\n createNodeMap(input, nodeMap, '@default', issuer);\n\n const dataset = [];\n const graphNames = Object.keys(nodeMap).sort();\n for(const graphName of graphNames) {\n let graphTerm;\n if(graphName === '@default') {\n graphTerm = {termType: 'DefaultGraph', value: ''};\n } else if(_isAbsoluteIri(graphName)) {\n if(graphName.startsWith('_:')) {\n graphTerm = {termType: 'BlankNode'};\n } else {\n graphTerm = {termType: 'NamedNode'};\n }\n graphTerm.value = graphName;\n } else {\n // skip relative IRIs (not valid RDF)\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'relative graph reference',\n level: 'warning',\n message: 'Relative graph reference found.',\n details: {\n graph: graphName\n }\n },\n options\n });\n }\n continue;\n }\n _graphToRDF(dataset, nodeMap[graphName], graphTerm, issuer, options);\n }\n\n return dataset;\n};\n\n/**\n * Adds RDF quads for a particular graph to the given dataset.\n *\n * @param dataset the dataset to append RDF quads to.\n * @param graph the graph to create RDF quads for.\n * @param graphTerm the graph term for each quad.\n * @param issuer a IdentifierIssuer for assigning blank node names.\n * @param options the RDF serialization options.\n *\n * @return the array of RDF triples for the given graph.\n */\nfunction _graphToRDF(dataset, graph, graphTerm, issuer, options) {\n const ids = Object.keys(graph).sort();\n for(const id of ids) {\n const node = graph[id];\n const properties = Object.keys(node).sort();\n for(let property of properties) {\n const items = node[property];\n if(property === '@type') {\n property = RDF_TYPE;\n } else if(isKeyword(property)) {\n continue;\n }\n\n for(const item of items) {\n // RDF subject\n const subject = {\n termType: id.startsWith('_:') ? 'BlankNode' : 'NamedNode',\n value: id\n };\n\n // skip relative IRI subjects (not valid RDF)\n if(!_isAbsoluteIri(id)) {\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'relative subject reference',\n level: 'warning',\n message: 'Relative subject reference found.',\n details: {\n subject: id\n }\n },\n options\n });\n }\n continue;\n }\n\n // RDF predicate\n const predicate = {\n termType: property.startsWith('_:') ? 'BlankNode' : 'NamedNode',\n value: property\n };\n\n // skip relative IRI predicates (not valid RDF)\n if(!_isAbsoluteIri(property)) {\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'relative predicate reference',\n level: 'warning',\n message: 'Relative predicate reference found.',\n details: {\n predicate: property\n }\n },\n options\n });\n }\n continue;\n }\n\n // skip blank node predicates unless producing generalized RDF\n if(predicate.termType === 'BlankNode' &&\n !options.produceGeneralizedRdf) {\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'blank node predicate',\n level: 'warning',\n message: 'Dropping blank node predicate.',\n details: {\n // FIXME: add better issuer API to get reverse mapping\n property: issuer.getOldIds()\n .find(key => issuer.getId(key) === property)\n }\n },\n options\n });\n }\n continue;\n }\n\n // convert list, value or node object to triple\n const object = _objectToRDF(\n item, issuer, dataset, graphTerm, options.rdfDirection, options);\n // skip null objects (they are relative IRIs)\n if(object) {\n dataset.push({\n subject,\n predicate,\n object,\n graph: graphTerm\n });\n }\n }\n }\n }\n}\n\n/**\n * Converts a @list value into linked list of blank node RDF quads\n * (an RDF collection).\n *\n * @param list the @list value.\n * @param issuer a IdentifierIssuer for assigning blank node names.\n * @param dataset the array of quads to append to.\n * @param graphTerm the graph term for each quad.\n * @param options the RDF serialization options.\n *\n * @return the head of the list.\n */\nfunction _listToRDF(list, issuer, dataset, graphTerm, rdfDirection, options) {\n const first = {termType: 'NamedNode', value: RDF_FIRST};\n const rest = {termType: 'NamedNode', value: RDF_REST};\n const nil = {termType: 'NamedNode', value: RDF_NIL};\n\n const last = list.pop();\n // Result is the head of the list\n const result = last ? {termType: 'BlankNode', value: issuer.getId()} : nil;\n let subject = result;\n\n for(const item of list) {\n const object = _objectToRDF(\n item, issuer, dataset, graphTerm, rdfDirection, options);\n const next = {termType: 'BlankNode', value: issuer.getId()};\n dataset.push({\n subject,\n predicate: first,\n object,\n graph: graphTerm\n });\n dataset.push({\n subject,\n predicate: rest,\n object: next,\n graph: graphTerm\n });\n subject = next;\n }\n\n // Tail of list\n if(last) {\n const object = _objectToRDF(\n last, issuer, dataset, graphTerm, rdfDirection, options);\n dataset.push({\n subject,\n predicate: first,\n object,\n graph: graphTerm\n });\n dataset.push({\n subject,\n predicate: rest,\n object: nil,\n graph: graphTerm\n });\n }\n\n return result;\n}\n\n/**\n * Converts a JSON-LD value object to an RDF literal or a JSON-LD string,\n * node object to an RDF resource, or adds a list.\n *\n * @param item the JSON-LD value or node object.\n * @param issuer a IdentifierIssuer for assigning blank node names.\n * @param dataset the dataset to append RDF quads to.\n * @param graphTerm the graph term for each quad.\n * @param options the RDF serialization options.\n *\n * @return the RDF literal or RDF resource.\n */\nfunction _objectToRDF(\n item, issuer, dataset, graphTerm, rdfDirection, options\n) {\n const object = {};\n\n // convert value object to RDF\n if(graphTypes.isValue(item)) {\n object.termType = 'Literal';\n object.value = undefined;\n object.datatype = {\n termType: 'NamedNode'\n };\n let value = item['@value'];\n const datatype = item['@type'] || null;\n\n // convert to XSD/JSON datatypes as appropriate\n if(datatype === '@json') {\n object.value = jsonCanonicalize(value);\n object.datatype.value = RDF_JSON_LITERAL;\n } else if(types.isBoolean(value)) {\n object.value = value.toString();\n object.datatype.value = datatype || XSD_BOOLEAN;\n } else if(types.isDouble(value) || datatype === XSD_DOUBLE) {\n if(!types.isDouble(value)) {\n value = parseFloat(value);\n }\n // canonical double representation\n object.value = value.toExponential(15).replace(/(\\d)0*e\\+?/, '$1E');\n object.datatype.value = datatype || XSD_DOUBLE;\n } else if(types.isNumber(value)) {\n object.value = value.toFixed(0);\n object.datatype.value = datatype || XSD_INTEGER;\n } else if('@direction' in item && rdfDirection === 'i18n-datatype') {\n const language = (item['@language'] || '').toLowerCase();\n const direction = item['@direction'];\n const datatype = `https://www.w3.org/ns/i18n#${language}_${direction}`;\n object.datatype.value = datatype;\n object.value = value;\n } else if('@direction' in item && rdfDirection === 'compound-literal') {\n throw new JsonLdError(\n 'Unsupported rdfDirection value.',\n 'jsonld.InvalidRdfDirection',\n {value: rdfDirection});\n } else if('@direction' in item && rdfDirection) {\n throw new JsonLdError(\n 'Unknown rdfDirection value.',\n 'jsonld.InvalidRdfDirection',\n {value: rdfDirection});\n } else if('@language' in item) {\n if('@direction' in item && !rdfDirection) {\n if(options.eventHandler) {\n // FIXME: only emit once?\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'rdfDirection not set',\n level: 'warning',\n message: 'rdfDirection not set for @direction.',\n details: {\n object: object.value\n }\n },\n options\n });\n }\n }\n object.value = value;\n object.datatype.value = datatype || RDF_LANGSTRING;\n object.language = item['@language'];\n } else {\n if('@direction' in item && !rdfDirection) {\n if(options.eventHandler) {\n // FIXME: only emit once?\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'rdfDirection not set',\n level: 'warning',\n message: 'rdfDirection not set for @direction.',\n details: {\n object: object.value\n }\n },\n options\n });\n }\n }\n object.value = value;\n object.datatype.value = datatype || XSD_STRING;\n }\n } else if(graphTypes.isList(item)) {\n const _list = _listToRDF(\n item['@list'], issuer, dataset, graphTerm, rdfDirection, options);\n object.termType = _list.termType;\n object.value = _list.value;\n } else {\n // convert string/node object to RDF\n const id = types.isObject(item) ? item['@id'] : item;\n object.termType = id.startsWith('_:') ? 'BlankNode' : 'NamedNode';\n object.value = id;\n }\n\n // skip relative IRIs, not valid RDF\n if(object.termType === 'NamedNode' && !_isAbsoluteIri(object.value)) {\n if(options.eventHandler) {\n _handleEvent({\n event: {\n type: ['JsonLdEvent'],\n code: 'relative object reference',\n level: 'warning',\n message: 'Relative object reference found.',\n details: {\n object: object.value\n }\n },\n options\n });\n }\n return null;\n }\n\n return object;\n}\n","/*\n * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst api = {};\nmodule.exports = api;\n\n/**\n * Returns true if the given value is an Array.\n *\n * @param v the value to check.\n *\n * @return true if the value is an Array, false if not.\n */\napi.isArray = Array.isArray;\n\n/**\n * Returns true if the given value is a Boolean.\n *\n * @param v the value to check.\n *\n * @return true if the value is a Boolean, false if not.\n */\napi.isBoolean = v => (typeof v === 'boolean' ||\n Object.prototype.toString.call(v) === '[object Boolean]');\n\n/**\n * Returns true if the given value is a double.\n *\n * @param v the value to check.\n *\n * @return true if the value is a double, false if not.\n */\napi.isDouble = v => api.isNumber(v) &&\n (String(v).indexOf('.') !== -1 || Math.abs(v) >= 1e21);\n\n/**\n * Returns true if the given value is an empty Object.\n *\n * @param v the value to check.\n *\n * @return true if the value is an empty Object, false if not.\n */\napi.isEmptyObject = v => api.isObject(v) && Object.keys(v).length === 0;\n\n/**\n * Returns true if the given value is a Number.\n *\n * @param v the value to check.\n *\n * @return true if the value is a Number, false if not.\n */\napi.isNumber = v => (typeof v === 'number' ||\n Object.prototype.toString.call(v) === '[object Number]');\n\n/**\n * Returns true if the given value is numeric.\n *\n * @param v the value to check.\n *\n * @return true if the value is numeric, false if not.\n */\napi.isNumeric = v => !isNaN(parseFloat(v)) && isFinite(v);\n\n/**\n * Returns true if the given value is an Object.\n *\n * @param v the value to check.\n *\n * @return true if the value is an Object, false if not.\n */\napi.isObject = v => Object.prototype.toString.call(v) === '[object Object]';\n\n/**\n * Returns true if the given value is a String.\n *\n * @param v the value to check.\n *\n * @return true if the value is a String, false if not.\n */\napi.isString = v => (typeof v === 'string' ||\n Object.prototype.toString.call(v) === '[object String]');\n\n/**\n * Returns true if the given value is undefined.\n *\n * @param v the value to check.\n *\n * @return true if the value is undefined, false if not.\n */\napi.isUndefined = v => typeof v === 'undefined';\n","/*\n * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst types = require('./types');\n\nconst api = {};\nmodule.exports = api;\n\n// define URL parser\n// parseUri 1.2.2\n// (c) Steven Levithan \n// MIT License\n// with local jsonld.js modifications\napi.parsers = {\n simple: {\n // RFC 3986 basic parts\n keys: [\n 'href', 'scheme', 'authority', 'path', 'query', 'fragment'\n ],\n /* eslint-disable-next-line max-len */\n regex: /^(?:([^:\\/?#]+):)?(?:\\/\\/([^\\/?#]*))?([^?#]*)(?:\\?([^#]*))?(?:#(.*))?/\n },\n full: {\n keys: [\n 'href', 'protocol', 'scheme', 'authority', 'auth', 'user', 'password',\n 'hostname', 'port', 'path', 'directory', 'file', 'query', 'fragment'\n ],\n /* eslint-disable-next-line max-len */\n regex: /^(([a-zA-Z][a-zA-Z0-9+-.]*):)?(?:\\/\\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\\/?#]*)(?::(\\d*))?))?(?:(((?:[^?#\\/]*\\/)*)([^?#]*))(?:\\?([^#]*))?(?:#(.*))?)/\n }\n};\napi.parse = (str, parser) => {\n const parsed = {};\n const o = api.parsers[parser || 'full'];\n const m = o.regex.exec(str);\n let i = o.keys.length;\n while(i--) {\n parsed[o.keys[i]] = (m[i] === undefined) ? null : m[i];\n }\n\n // remove default ports in found in URLs\n if((parsed.scheme === 'https' && parsed.port === '443') ||\n (parsed.scheme === 'http' && parsed.port === '80')) {\n parsed.href = parsed.href.replace(':' + parsed.port, '');\n parsed.authority = parsed.authority.replace(':' + parsed.port, '');\n parsed.port = null;\n }\n\n parsed.normalizedPath = api.removeDotSegments(parsed.path);\n return parsed;\n};\n\n/**\n * Prepends a base IRI to the given relative IRI.\n *\n * @param base the base IRI.\n * @param iri the relative IRI.\n *\n * @return the absolute IRI.\n */\napi.prependBase = (base, iri) => {\n // skip IRI processing\n if(base === null) {\n return iri;\n }\n // already an absolute IRI\n if(api.isAbsolute(iri)) {\n return iri;\n }\n\n // parse base if it is a string\n if(!base || types.isString(base)) {\n base = api.parse(base || '');\n }\n\n // parse given IRI\n const rel = api.parse(iri);\n\n // per RFC3986 5.2.2\n const transform = {\n protocol: base.protocol || ''\n };\n\n if(rel.authority !== null) {\n transform.authority = rel.authority;\n transform.path = rel.path;\n transform.query = rel.query;\n } else {\n transform.authority = base.authority;\n\n if(rel.path === '') {\n transform.path = base.path;\n if(rel.query !== null) {\n transform.query = rel.query;\n } else {\n transform.query = base.query;\n }\n } else {\n if(rel.path.indexOf('/') === 0) {\n // IRI represents an absolute path\n transform.path = rel.path;\n } else {\n // merge paths\n let path = base.path;\n\n // append relative path to the end of the last directory from base\n path = path.substr(0, path.lastIndexOf('/') + 1);\n if((path.length > 0 || base.authority) && path.substr(-1) !== '/') {\n path += '/';\n }\n path += rel.path;\n\n transform.path = path;\n }\n transform.query = rel.query;\n }\n }\n\n if(rel.path !== '') {\n // remove slashes and dots in path\n transform.path = api.removeDotSegments(transform.path);\n }\n\n // construct URL\n let rval = transform.protocol;\n if(transform.authority !== null) {\n rval += '//' + transform.authority;\n }\n rval += transform.path;\n if(transform.query !== null) {\n rval += '?' + transform.query;\n }\n if(rel.fragment !== null) {\n rval += '#' + rel.fragment;\n }\n\n // handle empty base\n if(rval === '') {\n rval = './';\n }\n\n return rval;\n};\n\n/**\n * Removes a base IRI from the given absolute IRI.\n *\n * @param base the base IRI.\n * @param iri the absolute IRI.\n *\n * @return the relative IRI if relative to base, otherwise the absolute IRI.\n */\napi.removeBase = (base, iri) => {\n // skip IRI processing\n if(base === null) {\n return iri;\n }\n\n if(!base || types.isString(base)) {\n base = api.parse(base || '');\n }\n\n // establish base root\n let root = '';\n if(base.href !== '') {\n root += (base.protocol || '') + '//' + (base.authority || '');\n } else if(iri.indexOf('//')) {\n // support network-path reference with empty base\n root += '//';\n }\n\n // IRI not relative to base\n if(iri.indexOf(root) !== 0) {\n return iri;\n }\n\n // remove root from IRI and parse remainder\n const rel = api.parse(iri.substr(root.length));\n\n // remove path segments that match (do not remove last segment unless there\n // is a hash or query)\n const baseSegments = base.normalizedPath.split('/');\n const iriSegments = rel.normalizedPath.split('/');\n const last = (rel.fragment || rel.query) ? 0 : 1;\n while(baseSegments.length > 0 && iriSegments.length > last) {\n if(baseSegments[0] !== iriSegments[0]) {\n break;\n }\n baseSegments.shift();\n iriSegments.shift();\n }\n\n // use '../' for each non-matching base segment\n let rval = '';\n if(baseSegments.length > 0) {\n // don't count the last segment (if it ends with '/' last path doesn't\n // count and if it doesn't end with '/' it isn't a path)\n baseSegments.pop();\n for(let i = 0; i < baseSegments.length; ++i) {\n rval += '../';\n }\n }\n\n // prepend remaining segments\n rval += iriSegments.join('/');\n\n // add query and hash\n if(rel.query !== null) {\n rval += '?' + rel.query;\n }\n if(rel.fragment !== null) {\n rval += '#' + rel.fragment;\n }\n\n // handle empty base\n if(rval === '') {\n rval = './';\n }\n\n return rval;\n};\n\n/**\n * Removes dot segments from a URL path.\n *\n * @param path the path to remove dot segments from.\n */\napi.removeDotSegments = path => {\n // RFC 3986 5.2.4 (reworked)\n\n // empty path shortcut\n if(path.length === 0) {\n return '';\n }\n\n const input = path.split('/');\n const output = [];\n\n while(input.length > 0) {\n const next = input.shift();\n const done = input.length === 0;\n\n if(next === '.') {\n if(done) {\n // ensure output has trailing /\n output.push('');\n }\n continue;\n }\n\n if(next === '..') {\n output.pop();\n if(done) {\n // ensure output has trailing /\n output.push('');\n }\n continue;\n }\n\n output.push(next);\n }\n\n // if path was absolute, ensure output has leading /\n if(path[0] === '/' && output.length > 0 && output[0] !== '') {\n output.unshift('');\n }\n if(output.length === 1 && output[0] === '') {\n return '/';\n }\n\n return output.join('/');\n};\n\n// TODO: time better isAbsolute/isRelative checks using full regexes:\n// http://jmrware.com/articles/2009/uri_regexp/URI_regex.html\n\n// regex to check for absolute IRI (starting scheme and ':') or blank node IRI\nconst isAbsoluteRegex = /^([A-Za-z][A-Za-z0-9+-.]*|_):[^\\s]*$/;\n\n/**\n * Returns true if the given value is an absolute IRI or blank node IRI, false\n * if not.\n * Note: This weak check only checks for a correct starting scheme.\n *\n * @param v the value to check.\n *\n * @return true if the value is an absolute IRI, false if not.\n */\napi.isAbsolute = v => types.isString(v) && isAbsoluteRegex.test(v);\n\n/**\n * Returns true if the given value is a relative IRI, false if not.\n * Note: this is a weak check.\n *\n * @param v the value to check.\n *\n * @return true if the value is a relative IRI, false if not.\n */\napi.isRelative = v => types.isString(v);\n","/*\n * Copyright (c) 2017-2019 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst graphTypes = require('./graphTypes');\nconst types = require('./types');\n// TODO: move `IdentifierIssuer` to its own package\nconst IdentifierIssuer = require('rdf-canonize').IdentifierIssuer;\nconst JsonLdError = require('./JsonLdError');\n\n// constants\nconst REGEX_BCP47 = /^[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*$/;\nconst REGEX_LINK_HEADERS = /(?:<[^>]*?>|\"[^\"]*?\"|[^,])+/g;\nconst REGEX_LINK_HEADER = /\\s*<([^>]*?)>\\s*(?:;\\s*(.*))?/;\nconst REGEX_LINK_HEADER_PARAMS =\n /(.*?)=(?:(?:\"([^\"]*?)\")|([^\"]*?))\\s*(?:(?:;\\s*)|$)/g;\nconst REGEX_KEYWORD = /^@[a-zA-Z]+$/;\n\nconst DEFAULTS = {\n headers: {\n accept: 'application/ld+json, application/json'\n }\n};\n\nconst api = {};\nmodule.exports = api;\napi.IdentifierIssuer = IdentifierIssuer;\napi.REGEX_BCP47 = REGEX_BCP47;\napi.REGEX_KEYWORD = REGEX_KEYWORD;\n\n/**\n * Clones an object, array, Map, Set, or string/number. If a typed JavaScript\n * object is given, such as a Date, it will be converted to a string.\n *\n * @param value the value to clone.\n *\n * @return the cloned value.\n */\napi.clone = function(value) {\n if(value && typeof value === 'object') {\n let rval;\n if(types.isArray(value)) {\n rval = [];\n for(let i = 0; i < value.length; ++i) {\n rval[i] = api.clone(value[i]);\n }\n } else if(value instanceof Map) {\n rval = new Map();\n for(const [k, v] of value) {\n rval.set(k, api.clone(v));\n }\n } else if(value instanceof Set) {\n rval = new Set();\n for(const v of value) {\n rval.add(api.clone(v));\n }\n } else if(types.isObject(value)) {\n rval = {};\n for(const key in value) {\n rval[key] = api.clone(value[key]);\n }\n } else {\n rval = value.toString();\n }\n return rval;\n }\n return value;\n};\n\n/**\n * Ensure a value is an array. If the value is an array, it is returned.\n * Otherwise, it is wrapped in an array.\n *\n * @param value the value to return as an array.\n *\n * @return the value as an array.\n */\napi.asArray = function(value) {\n return Array.isArray(value) ? value : [value];\n};\n\n/**\n * Builds an HTTP headers object for making a JSON-LD request from custom\n * headers and asserts the `accept` header isn't overridden.\n *\n * @param headers an object of headers with keys as header names and values\n * as header values.\n *\n * @return an object of headers with a valid `accept` header.\n */\napi.buildHeaders = (headers = {}) => {\n const hasAccept = Object.keys(headers).some(\n h => h.toLowerCase() === 'accept');\n\n if(hasAccept) {\n throw new RangeError(\n 'Accept header may not be specified; only \"' +\n DEFAULTS.headers.accept + '\" is supported.');\n }\n\n return Object.assign({Accept: DEFAULTS.headers.accept}, headers);\n};\n\n/**\n * Parses a link header. The results will be key'd by the value of \"rel\".\n *\n * Link: ;\n * rel=\"http://www.w3.org/ns/json-ld#context\"; type=\"application/ld+json\"\n *\n * Parses as: {\n * 'http://www.w3.org/ns/json-ld#context': {\n * target: http://json-ld.org/contexts/person.jsonld,\n * type: 'application/ld+json'\n * }\n * }\n *\n * If there is more than one \"rel\" with the same IRI, then entries in the\n * resulting map for that \"rel\" will be arrays.\n *\n * @param header the link header to parse.\n */\napi.parseLinkHeader = header => {\n const rval = {};\n // split on unbracketed/unquoted commas\n const entries = header.match(REGEX_LINK_HEADERS);\n for(let i = 0; i < entries.length; ++i) {\n let match = entries[i].match(REGEX_LINK_HEADER);\n if(!match) {\n continue;\n }\n const result = {target: match[1]};\n const params = match[2];\n while((match = REGEX_LINK_HEADER_PARAMS.exec(params))) {\n result[match[1]] = (match[2] === undefined) ? match[3] : match[2];\n }\n const rel = result.rel || '';\n if(Array.isArray(rval[rel])) {\n rval[rel].push(result);\n } else if(rval.hasOwnProperty(rel)) {\n rval[rel] = [rval[rel], result];\n } else {\n rval[rel] = result;\n }\n }\n return rval;\n};\n\n/**\n * Throws an exception if the given value is not a valid @type value.\n *\n * @param v the value to check.\n */\napi.validateTypeValue = (v, isFrame) => {\n if(types.isString(v)) {\n return;\n }\n\n if(types.isArray(v) && v.every(vv => types.isString(vv))) {\n return;\n }\n if(isFrame && types.isObject(v)) {\n switch(Object.keys(v).length) {\n case 0:\n // empty object is wildcard\n return;\n case 1:\n // default entry is all strings\n if('@default' in v &&\n api.asArray(v['@default']).every(vv => types.isString(vv))) {\n return;\n }\n }\n }\n\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@type\" value must a string, an array of ' +\n 'strings, an empty object, ' +\n 'or a default object.', 'jsonld.SyntaxError',\n {code: 'invalid type value', value: v});\n};\n\n/**\n * Returns true if the given subject has the given property.\n *\n * @param subject the subject to check.\n * @param property the property to look for.\n *\n * @return true if the subject has the given property, false if not.\n */\napi.hasProperty = (subject, property) => {\n if(subject.hasOwnProperty(property)) {\n const value = subject[property];\n return (!types.isArray(value) || value.length > 0);\n }\n return false;\n};\n\n/**\n * Determines if the given value is a property of the given subject.\n *\n * @param subject the subject to check.\n * @param property the property to check.\n * @param value the value to check.\n *\n * @return true if the value exists, false if not.\n */\napi.hasValue = (subject, property, value) => {\n if(api.hasProperty(subject, property)) {\n let val = subject[property];\n const isList = graphTypes.isList(val);\n if(types.isArray(val) || isList) {\n if(isList) {\n val = val['@list'];\n }\n for(let i = 0; i < val.length; ++i) {\n if(api.compareValues(value, val[i])) {\n return true;\n }\n }\n } else if(!types.isArray(value)) {\n // avoid matching the set of values with an array value parameter\n return api.compareValues(value, val);\n }\n }\n return false;\n};\n\n/**\n * Adds a value to a subject. If the value is an array, all values in the\n * array will be added.\n *\n * @param subject the subject to add the value to.\n * @param property the property that relates the value to the subject.\n * @param value the value to add.\n * @param [options] the options to use:\n * [propertyIsArray] true if the property is always an array, false\n * if not (default: false).\n * [valueIsArray] true if the value to be added should be preserved as\n * an array (lists) (default: false).\n * [allowDuplicate] true to allow duplicates, false not to (uses a\n * simple shallow comparison of subject ID or value) (default: true).\n * [prependValue] false to prepend value to any existing values.\n * (default: false)\n */\napi.addValue = (subject, property, value, options) => {\n options = options || {};\n if(!('propertyIsArray' in options)) {\n options.propertyIsArray = false;\n }\n if(!('valueIsArray' in options)) {\n options.valueIsArray = false;\n }\n if(!('allowDuplicate' in options)) {\n options.allowDuplicate = true;\n }\n if(!('prependValue' in options)) {\n options.prependValue = false;\n }\n\n if(options.valueIsArray) {\n subject[property] = value;\n } else if(types.isArray(value)) {\n if(value.length === 0 && options.propertyIsArray &&\n !subject.hasOwnProperty(property)) {\n subject[property] = [];\n }\n if(options.prependValue) {\n value = value.concat(subject[property]);\n subject[property] = [];\n }\n for(let i = 0; i < value.length; ++i) {\n api.addValue(subject, property, value[i], options);\n }\n } else if(subject.hasOwnProperty(property)) {\n // check if subject already has value if duplicates not allowed\n const hasValue = (!options.allowDuplicate &&\n api.hasValue(subject, property, value));\n\n // make property an array if value not present or always an array\n if(!types.isArray(subject[property]) &&\n (!hasValue || options.propertyIsArray)) {\n subject[property] = [subject[property]];\n }\n\n // add new value\n if(!hasValue) {\n if(options.prependValue) {\n subject[property].unshift(value);\n } else {\n subject[property].push(value);\n }\n }\n } else {\n // add new value as set or single value\n subject[property] = options.propertyIsArray ? [value] : value;\n }\n};\n\n/**\n * Gets all of the values for a subject's property as an array.\n *\n * @param subject the subject.\n * @param property the property.\n *\n * @return all of the values for a subject's property as an array.\n */\napi.getValues = (subject, property) => [].concat(subject[property] || []);\n\n/**\n * Removes a property from a subject.\n *\n * @param subject the subject.\n * @param property the property.\n */\napi.removeProperty = (subject, property) => {\n delete subject[property];\n};\n\n/**\n * Removes a value from a subject.\n *\n * @param subject the subject.\n * @param property the property that relates the value to the subject.\n * @param value the value to remove.\n * @param [options] the options to use:\n * [propertyIsArray] true if the property is always an array, false\n * if not (default: false).\n */\napi.removeValue = (subject, property, value, options) => {\n options = options || {};\n if(!('propertyIsArray' in options)) {\n options.propertyIsArray = false;\n }\n\n // filter out value\n const values = api.getValues(subject, property).filter(\n e => !api.compareValues(e, value));\n\n if(values.length === 0) {\n api.removeProperty(subject, property);\n } else if(values.length === 1 && !options.propertyIsArray) {\n subject[property] = values[0];\n } else {\n subject[property] = values;\n }\n};\n\n/**\n * Relabels all blank nodes in the given JSON-LD input.\n *\n * @param input the JSON-LD input.\n * @param [options] the options to use:\n * [issuer] an IdentifierIssuer to use to label blank nodes.\n */\napi.relabelBlankNodes = (input, options) => {\n options = options || {};\n const issuer = options.issuer || new IdentifierIssuer('_:b');\n return _labelBlankNodes(issuer, input);\n};\n\n/**\n * Compares two JSON-LD values for equality. Two JSON-LD values will be\n * considered equal if:\n *\n * 1. They are both primitives of the same type and value.\n * 2. They are both @values with the same @value, @type, @language,\n * and @index, OR\n * 3. They both have @ids they are the same.\n *\n * @param v1 the first value.\n * @param v2 the second value.\n *\n * @return true if v1 and v2 are considered equal, false if not.\n */\napi.compareValues = (v1, v2) => {\n // 1. equal primitives\n if(v1 === v2) {\n return true;\n }\n\n // 2. equal @values\n if(graphTypes.isValue(v1) && graphTypes.isValue(v2) &&\n v1['@value'] === v2['@value'] &&\n v1['@type'] === v2['@type'] &&\n v1['@language'] === v2['@language'] &&\n v1['@index'] === v2['@index']) {\n return true;\n }\n\n // 3. equal @ids\n if(types.isObject(v1) &&\n ('@id' in v1) &&\n types.isObject(v2) &&\n ('@id' in v2)) {\n return v1['@id'] === v2['@id'];\n }\n\n return false;\n};\n\n/**\n * Compares two strings first based on length and then lexicographically.\n *\n * @param a the first string.\n * @param b the second string.\n *\n * @return -1 if a < b, 1 if a > b, 0 if a === b.\n */\napi.compareShortestLeast = (a, b) => {\n if(a.length < b.length) {\n return -1;\n }\n if(b.length < a.length) {\n return 1;\n }\n if(a === b) {\n return 0;\n }\n return (a < b) ? -1 : 1;\n};\n\n/**\n * Labels the blank nodes in the given value using the given IdentifierIssuer.\n *\n * @param issuer the IdentifierIssuer to use.\n * @param element the element with blank nodes to rename.\n *\n * @return the element.\n */\nfunction _labelBlankNodes(issuer, element) {\n if(types.isArray(element)) {\n for(let i = 0; i < element.length; ++i) {\n element[i] = _labelBlankNodes(issuer, element[i]);\n }\n } else if(graphTypes.isList(element)) {\n element['@list'] = _labelBlankNodes(issuer, element['@list']);\n } else if(types.isObject(element)) {\n // relabel blank node\n if(graphTypes.isBlankNode(element)) {\n element['@id'] = issuer.getId(element['@id']);\n }\n\n // recursively apply to all keys\n const keys = Object.keys(element).sort();\n for(let ki = 0; ki < keys.length; ++ki) {\n const key = keys[ki];\n if(key !== '@id') {\n element[key] = _labelBlankNodes(issuer, element[key]);\n }\n }\n }\n\n return element;\n}\n","'use strict'\n\n// A linked list to keep track of recently-used-ness\nconst Yallist = require('yallist')\n\nconst MAX = Symbol('max')\nconst LENGTH = Symbol('length')\nconst LENGTH_CALCULATOR = Symbol('lengthCalculator')\nconst ALLOW_STALE = Symbol('allowStale')\nconst MAX_AGE = Symbol('maxAge')\nconst DISPOSE = Symbol('dispose')\nconst NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet')\nconst LRU_LIST = Symbol('lruList')\nconst CACHE = Symbol('cache')\nconst UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet')\n\nconst naiveLength = () => 1\n\n// lruList is a yallist where the head is the youngest\n// item, and the tail is the oldest. the list contains the Hit\n// objects as the entries.\n// Each Hit object has a reference to its Yallist.Node. This\n// never changes.\n//\n// cache is a Map (or PseudoMap) that matches the keys to\n// the Yallist.Node object.\nclass LRUCache {\n constructor (options) {\n if (typeof options === 'number')\n options = { max: options }\n\n if (!options)\n options = {}\n\n if (options.max && (typeof options.max !== 'number' || options.max < 0))\n throw new TypeError('max must be a non-negative number')\n // Kind of weird to have a default max of Infinity, but oh well.\n const max = this[MAX] = options.max || Infinity\n\n const lc = options.length || naiveLength\n this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc\n this[ALLOW_STALE] = options.stale || false\n if (options.maxAge && typeof options.maxAge !== 'number')\n throw new TypeError('maxAge must be a number')\n this[MAX_AGE] = options.maxAge || 0\n this[DISPOSE] = options.dispose\n this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false\n this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false\n this.reset()\n }\n\n // resize the cache when the max changes.\n set max (mL) {\n if (typeof mL !== 'number' || mL < 0)\n throw new TypeError('max must be a non-negative number')\n\n this[MAX] = mL || Infinity\n trim(this)\n }\n get max () {\n return this[MAX]\n }\n\n set allowStale (allowStale) {\n this[ALLOW_STALE] = !!allowStale\n }\n get allowStale () {\n return this[ALLOW_STALE]\n }\n\n set maxAge (mA) {\n if (typeof mA !== 'number')\n throw new TypeError('maxAge must be a non-negative number')\n\n this[MAX_AGE] = mA\n trim(this)\n }\n get maxAge () {\n return this[MAX_AGE]\n }\n\n // resize the cache when the lengthCalculator changes.\n set lengthCalculator (lC) {\n if (typeof lC !== 'function')\n lC = naiveLength\n\n if (lC !== this[LENGTH_CALCULATOR]) {\n this[LENGTH_CALCULATOR] = lC\n this[LENGTH] = 0\n this[LRU_LIST].forEach(hit => {\n hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key)\n this[LENGTH] += hit.length\n })\n }\n trim(this)\n }\n get lengthCalculator () { return this[LENGTH_CALCULATOR] }\n\n get length () { return this[LENGTH] }\n get itemCount () { return this[LRU_LIST].length }\n\n rforEach (fn, thisp) {\n thisp = thisp || this\n for (let walker = this[LRU_LIST].tail; walker !== null;) {\n const prev = walker.prev\n forEachStep(this, fn, walker, thisp)\n walker = prev\n }\n }\n\n forEach (fn, thisp) {\n thisp = thisp || this\n for (let walker = this[LRU_LIST].head; walker !== null;) {\n const next = walker.next\n forEachStep(this, fn, walker, thisp)\n walker = next\n }\n }\n\n keys () {\n return this[LRU_LIST].toArray().map(k => k.key)\n }\n\n values () {\n return this[LRU_LIST].toArray().map(k => k.value)\n }\n\n reset () {\n if (this[DISPOSE] &&\n this[LRU_LIST] &&\n this[LRU_LIST].length) {\n this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value))\n }\n\n this[CACHE] = new Map() // hash of items by key\n this[LRU_LIST] = new Yallist() // list of items in order of use recency\n this[LENGTH] = 0 // length of items in the list\n }\n\n dump () {\n return this[LRU_LIST].map(hit =>\n isStale(this, hit) ? false : {\n k: hit.key,\n v: hit.value,\n e: hit.now + (hit.maxAge || 0)\n }).toArray().filter(h => h)\n }\n\n dumpLru () {\n return this[LRU_LIST]\n }\n\n set (key, value, maxAge) {\n maxAge = maxAge || this[MAX_AGE]\n\n if (maxAge && typeof maxAge !== 'number')\n throw new TypeError('maxAge must be a number')\n\n const now = maxAge ? Date.now() : 0\n const len = this[LENGTH_CALCULATOR](value, key)\n\n if (this[CACHE].has(key)) {\n if (len > this[MAX]) {\n del(this, this[CACHE].get(key))\n return false\n }\n\n const node = this[CACHE].get(key)\n const item = node.value\n\n // dispose of the old one before overwriting\n // split out into 2 ifs for better coverage tracking\n if (this[DISPOSE]) {\n if (!this[NO_DISPOSE_ON_SET])\n this[DISPOSE](key, item.value)\n }\n\n item.now = now\n item.maxAge = maxAge\n item.value = value\n this[LENGTH] += len - item.length\n item.length = len\n this.get(key)\n trim(this)\n return true\n }\n\n const hit = new Entry(key, value, len, now, maxAge)\n\n // oversized objects fall out of cache automatically.\n if (hit.length > this[MAX]) {\n if (this[DISPOSE])\n this[DISPOSE](key, value)\n\n return false\n }\n\n this[LENGTH] += hit.length\n this[LRU_LIST].unshift(hit)\n this[CACHE].set(key, this[LRU_LIST].head)\n trim(this)\n return true\n }\n\n has (key) {\n if (!this[CACHE].has(key)) return false\n const hit = this[CACHE].get(key).value\n return !isStale(this, hit)\n }\n\n get (key) {\n return get(this, key, true)\n }\n\n peek (key) {\n return get(this, key, false)\n }\n\n pop () {\n const node = this[LRU_LIST].tail\n if (!node)\n return null\n\n del(this, node)\n return node.value\n }\n\n del (key) {\n del(this, this[CACHE].get(key))\n }\n\n load (arr) {\n // reset the cache\n this.reset()\n\n const now = Date.now()\n // A previous serialized cache has the most recent items first\n for (let l = arr.length - 1; l >= 0; l--) {\n const hit = arr[l]\n const expiresAt = hit.e || 0\n if (expiresAt === 0)\n // the item was created without expiration in a non aged cache\n this.set(hit.k, hit.v)\n else {\n const maxAge = expiresAt - now\n // dont add already expired items\n if (maxAge > 0) {\n this.set(hit.k, hit.v, maxAge)\n }\n }\n }\n }\n\n prune () {\n this[CACHE].forEach((value, key) => get(this, key, false))\n }\n}\n\nconst get = (self, key, doUse) => {\n const node = self[CACHE].get(key)\n if (node) {\n const hit = node.value\n if (isStale(self, hit)) {\n del(self, node)\n if (!self[ALLOW_STALE])\n return undefined\n } else {\n if (doUse) {\n if (self[UPDATE_AGE_ON_GET])\n node.value.now = Date.now()\n self[LRU_LIST].unshiftNode(node)\n }\n }\n return hit.value\n }\n}\n\nconst isStale = (self, hit) => {\n if (!hit || (!hit.maxAge && !self[MAX_AGE]))\n return false\n\n const diff = Date.now() - hit.now\n return hit.maxAge ? diff > hit.maxAge\n : self[MAX_AGE] && (diff > self[MAX_AGE])\n}\n\nconst trim = self => {\n if (self[LENGTH] > self[MAX]) {\n for (let walker = self[LRU_LIST].tail;\n self[LENGTH] > self[MAX] && walker !== null;) {\n // We know that we're about to delete this one, and also\n // what the next least recently used key will be, so just\n // go ahead and set it now.\n const prev = walker.prev\n del(self, walker)\n walker = prev\n }\n }\n}\n\nconst del = (self, node) => {\n if (node) {\n const hit = node.value\n if (self[DISPOSE])\n self[DISPOSE](hit.key, hit.value)\n\n self[LENGTH] -= hit.length\n self[CACHE].delete(hit.key)\n self[LRU_LIST].removeNode(node)\n }\n}\n\nclass Entry {\n constructor (key, value, length, now, maxAge) {\n this.key = key\n this.value = value\n this.length = length\n this.now = now\n this.maxAge = maxAge || 0\n }\n}\n\nconst forEachStep = (self, fn, node, thisp) => {\n let hit = node.value\n if (isStale(self, hit)) {\n del(self, node)\n if (!self[ALLOW_STALE])\n hit = undefined\n }\n if (hit)\n fn.call(thisp, hit.value, hit.key, self)\n}\n\nmodule.exports = LRUCache\n","/**\n * An implementation of the RDF Dataset Normalization specification.\n *\n * @author Dave Longley\n *\n * Copyright 2010-2021 Digital Bazaar, Inc.\n */\nmodule.exports = require('./lib');\n","/*\n * Copyright (c) 2016-2021 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nmodule.exports = class IdentifierIssuer {\n /**\n * Creates a new IdentifierIssuer. A IdentifierIssuer issues unique\n * identifiers, keeping track of any previously issued identifiers.\n *\n * @param prefix the prefix to use ('').\n * @param existing an existing Map to use.\n * @param counter the counter to use.\n */\n constructor(prefix, existing = new Map(), counter = 0) {\n this.prefix = prefix;\n this._existing = existing;\n this.counter = counter;\n }\n\n /**\n * Copies this IdentifierIssuer.\n *\n * @return a copy of this IdentifierIssuer.\n */\n clone() {\n const {prefix, _existing, counter} = this;\n return new IdentifierIssuer(prefix, new Map(_existing), counter);\n }\n\n /**\n * Gets the new identifier for the given old identifier, where if no old\n * identifier is given a new identifier will be generated.\n *\n * @param [old] the old identifier to get the new identifier for.\n *\n * @return the new identifier.\n */\n getId(old) {\n // return existing old identifier\n const existing = old && this._existing.get(old);\n if(existing) {\n return existing;\n }\n\n // get next identifier\n const identifier = this.prefix + this.counter;\n this.counter++;\n\n // save mapping\n if(old) {\n this._existing.set(old, identifier);\n }\n\n return identifier;\n }\n\n /**\n * Returns true if the given old identifer has already been assigned a new\n * identifier.\n *\n * @param old the old identifier to check.\n *\n * @return true if the old identifier has been assigned a new identifier,\n * false if not.\n */\n hasId(old) {\n return this._existing.has(old);\n }\n\n /**\n * Returns all of the IDs that have been issued new IDs in the order in\n * which they were issued new IDs.\n *\n * @return the list of old IDs that has been issued new IDs in order.\n */\n getOldIds() {\n return [...this._existing.keys()];\n }\n};\n","/*!\n * Copyright (c) 2016-2022 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nrequire('setimmediate');\n\nconst crypto = self.crypto || self.msCrypto;\n\nmodule.exports = class MessageDigest {\n /**\n * Creates a new MessageDigest.\n *\n * @param algorithm the algorithm to use.\n */\n constructor(algorithm) {\n // check if crypto.subtle is available\n // check is here rather than top-level to only fail if class is used\n if(!(crypto && crypto.subtle)) {\n throw new Error('crypto.subtle not found.');\n }\n if(algorithm === 'sha256') {\n this.algorithm = {name: 'SHA-256'};\n } else if(algorithm === 'sha1') {\n this.algorithm = {name: 'SHA-1'};\n } else {\n throw new Error(`Unsupported algorithm \"${algorithm}\".`);\n }\n this._content = '';\n }\n\n update(msg) {\n this._content += msg;\n }\n\n async digest() {\n const data = new TextEncoder().encode(this._content);\n const buffer = new Uint8Array(\n await crypto.subtle.digest(this.algorithm, data));\n // return digest in hex\n let hex = '';\n for(let i = 0; i < buffer.length; ++i) {\n hex += buffer[i].toString(16).padStart(2, '0');\n }\n return hex;\n }\n};\n","/*!\n * Copyright (c) 2016-2022 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\n// eslint-disable-next-line no-unused-vars\nconst TERMS = ['subject', 'predicate', 'object', 'graph'];\nconst RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';\nconst RDF_LANGSTRING = RDF + 'langString';\nconst XSD_STRING = 'http://www.w3.org/2001/XMLSchema#string';\n\nconst TYPE_NAMED_NODE = 'NamedNode';\nconst TYPE_BLANK_NODE = 'BlankNode';\nconst TYPE_LITERAL = 'Literal';\nconst TYPE_DEFAULT_GRAPH = 'DefaultGraph';\n\n// build regexes\nconst REGEX = {};\n(() => {\n const iri = '(?:<([^:]+:[^>]*)>)';\n // https://www.w3.org/TR/turtle/#grammar-production-BLANK_NODE_LABEL\n const PN_CHARS_BASE =\n 'A-Z' + 'a-z' +\n '\\u00C0-\\u00D6' +\n '\\u00D8-\\u00F6' +\n '\\u00F8-\\u02FF' +\n '\\u0370-\\u037D' +\n '\\u037F-\\u1FFF' +\n '\\u200C-\\u200D' +\n '\\u2070-\\u218F' +\n '\\u2C00-\\u2FEF' +\n '\\u3001-\\uD7FF' +\n '\\uF900-\\uFDCF' +\n '\\uFDF0-\\uFFFD';\n // TODO:\n //'\\u10000-\\uEFFFF';\n const PN_CHARS_U =\n PN_CHARS_BASE +\n '_';\n const PN_CHARS =\n PN_CHARS_U +\n '0-9' +\n '-' +\n '\\u00B7' +\n '\\u0300-\\u036F' +\n '\\u203F-\\u2040';\n const BLANK_NODE_LABEL =\n '(_:' +\n '(?:[' + PN_CHARS_U + '0-9])' +\n '(?:(?:[' + PN_CHARS + '.])*(?:[' + PN_CHARS + ']))?' +\n ')';\n const bnode = BLANK_NODE_LABEL;\n const plain = '\"([^\"\\\\\\\\]*(?:\\\\\\\\.[^\"\\\\\\\\]*)*)\"';\n const datatype = '(?:\\\\^\\\\^' + iri + ')';\n const language = '(?:@([a-zA-Z]+(?:-[a-zA-Z0-9]+)*))';\n const literal = '(?:' + plain + '(?:' + datatype + '|' + language + ')?)';\n const ws = '[ \\\\t]+';\n const wso = '[ \\\\t]*';\n\n // define quad part regexes\n const subject = '(?:' + iri + '|' + bnode + ')' + ws;\n const property = iri + ws;\n const object = '(?:' + iri + '|' + bnode + '|' + literal + ')' + wso;\n const graphName = '(?:\\\\.|(?:(?:' + iri + '|' + bnode + ')' + wso + '\\\\.))';\n\n // end of line and empty regexes\n REGEX.eoln = /(?:\\r\\n)|(?:\\n)|(?:\\r)/g;\n REGEX.empty = new RegExp('^' + wso + '$');\n\n // full quad regex\n REGEX.quad = new RegExp(\n '^' + wso + subject + property + object + graphName + wso + '$');\n})();\n\nmodule.exports = class NQuads {\n /**\n * Parses RDF in the form of N-Quads.\n *\n * @param input the N-Quads input to parse.\n *\n * @return an RDF dataset (an array of quads per http://rdf.js.org/).\n */\n static parse(input) {\n // build RDF dataset\n const dataset = [];\n\n const graphs = {};\n\n // split N-Quad input into lines\n const lines = input.split(REGEX.eoln);\n let lineNumber = 0;\n for(const line of lines) {\n lineNumber++;\n\n // skip empty lines\n if(REGEX.empty.test(line)) {\n continue;\n }\n\n // parse quad\n const match = line.match(REGEX.quad);\n if(match === null) {\n throw new Error('N-Quads parse error on line ' + lineNumber + '.');\n }\n\n // create RDF quad\n const quad = {subject: null, predicate: null, object: null, graph: null};\n\n // get subject\n if(match[1] !== undefined) {\n quad.subject = {termType: TYPE_NAMED_NODE, value: match[1]};\n } else {\n quad.subject = {termType: TYPE_BLANK_NODE, value: match[2]};\n }\n\n // get predicate\n quad.predicate = {termType: TYPE_NAMED_NODE, value: match[3]};\n\n // get object\n if(match[4] !== undefined) {\n quad.object = {termType: TYPE_NAMED_NODE, value: match[4]};\n } else if(match[5] !== undefined) {\n quad.object = {termType: TYPE_BLANK_NODE, value: match[5]};\n } else {\n quad.object = {\n termType: TYPE_LITERAL,\n value: undefined,\n datatype: {\n termType: TYPE_NAMED_NODE\n }\n };\n if(match[7] !== undefined) {\n quad.object.datatype.value = match[7];\n } else if(match[8] !== undefined) {\n quad.object.datatype.value = RDF_LANGSTRING;\n quad.object.language = match[8];\n } else {\n quad.object.datatype.value = XSD_STRING;\n }\n quad.object.value = _unescape(match[6]);\n }\n\n // get graph\n if(match[9] !== undefined) {\n quad.graph = {\n termType: TYPE_NAMED_NODE,\n value: match[9]\n };\n } else if(match[10] !== undefined) {\n quad.graph = {\n termType: TYPE_BLANK_NODE,\n value: match[10]\n };\n } else {\n quad.graph = {\n termType: TYPE_DEFAULT_GRAPH,\n value: ''\n };\n }\n\n // only add quad if it is unique in its graph\n if(!(quad.graph.value in graphs)) {\n graphs[quad.graph.value] = [quad];\n dataset.push(quad);\n } else {\n let unique = true;\n const quads = graphs[quad.graph.value];\n for(const q of quads) {\n if(_compareTriples(q, quad)) {\n unique = false;\n break;\n }\n }\n if(unique) {\n quads.push(quad);\n dataset.push(quad);\n }\n }\n }\n\n return dataset;\n }\n\n /**\n * Converts an RDF dataset to N-Quads.\n *\n * @param dataset (array of quads) the RDF dataset to convert.\n *\n * @return the N-Quads string.\n */\n static serialize(dataset) {\n if(!Array.isArray(dataset)) {\n dataset = NQuads.legacyDatasetToQuads(dataset);\n }\n const quads = [];\n for(const quad of dataset) {\n quads.push(NQuads.serializeQuad(quad));\n }\n return quads.sort().join('');\n }\n\n /**\n * Converts RDF quad components to an N-Quad string (a single quad).\n *\n * @param {Object} s - N-Quad subject component.\n * @param {Object} p - N-Quad predicate component.\n * @param {Object} o - N-Quad object component.\n * @param {Object} g - N-Quad graph component.\n *\n * @return {string} the N-Quad.\n */\n static serializeQuadComponents(s, p, o, g) {\n let nquad = '';\n\n // subject can only be NamedNode or BlankNode\n if(s.termType === TYPE_NAMED_NODE) {\n nquad += `<${s.value}>`;\n } else {\n nquad += `${s.value}`;\n }\n\n // predicate can only be NamedNode\n nquad += ` <${p.value}> `;\n\n // object is NamedNode, BlankNode, or Literal\n if(o.termType === TYPE_NAMED_NODE) {\n nquad += `<${o.value}>`;\n } else if(o.termType === TYPE_BLANK_NODE) {\n nquad += o.value;\n } else {\n nquad += `\"${_escape(o.value)}\"`;\n if(o.datatype.value === RDF_LANGSTRING) {\n if(o.language) {\n nquad += `@${o.language}`;\n }\n } else if(o.datatype.value !== XSD_STRING) {\n nquad += `^^<${o.datatype.value}>`;\n }\n }\n\n // graph can only be NamedNode or BlankNode (or DefaultGraph, but that\n // does not add to `nquad`)\n if(g.termType === TYPE_NAMED_NODE) {\n nquad += ` <${g.value}>`;\n } else if(g.termType === TYPE_BLANK_NODE) {\n nquad += ` ${g.value}`;\n }\n\n nquad += ' .\\n';\n return nquad;\n }\n\n /**\n * Converts an RDF quad to an N-Quad string (a single quad).\n *\n * @param quad the RDF quad convert.\n *\n * @return the N-Quad string.\n */\n static serializeQuad(quad) {\n return NQuads.serializeQuadComponents(\n quad.subject, quad.predicate, quad.object, quad.graph);\n }\n\n /**\n * Converts a legacy-formatted dataset to an array of quads dataset per\n * http://rdf.js.org/.\n *\n * @param dataset the legacy dataset to convert.\n *\n * @return the array of quads dataset.\n */\n static legacyDatasetToQuads(dataset) {\n const quads = [];\n\n const termTypeMap = {\n 'blank node': TYPE_BLANK_NODE,\n IRI: TYPE_NAMED_NODE,\n literal: TYPE_LITERAL\n };\n\n for(const graphName in dataset) {\n const triples = dataset[graphName];\n triples.forEach(triple => {\n const quad = {};\n for(const componentName in triple) {\n const oldComponent = triple[componentName];\n const newComponent = {\n termType: termTypeMap[oldComponent.type],\n value: oldComponent.value\n };\n if(newComponent.termType === TYPE_LITERAL) {\n newComponent.datatype = {\n termType: TYPE_NAMED_NODE\n };\n if('datatype' in oldComponent) {\n newComponent.datatype.value = oldComponent.datatype;\n }\n if('language' in oldComponent) {\n if(!('datatype' in oldComponent)) {\n newComponent.datatype.value = RDF_LANGSTRING;\n }\n newComponent.language = oldComponent.language;\n } else if(!('datatype' in oldComponent)) {\n newComponent.datatype.value = XSD_STRING;\n }\n }\n quad[componentName] = newComponent;\n }\n if(graphName === '@default') {\n quad.graph = {\n termType: TYPE_DEFAULT_GRAPH,\n value: ''\n };\n } else {\n quad.graph = {\n termType: graphName.startsWith('_:') ?\n TYPE_BLANK_NODE : TYPE_NAMED_NODE,\n value: graphName\n };\n }\n quads.push(quad);\n });\n }\n\n return quads;\n }\n};\n\n/**\n * Compares two RDF triples for equality.\n *\n * @param t1 the first triple.\n * @param t2 the second triple.\n *\n * @return true if the triples are the same, false if not.\n */\nfunction _compareTriples(t1, t2) {\n // compare subject and object types first as it is the quickest check\n if(!(t1.subject.termType === t2.subject.termType &&\n t1.object.termType === t2.object.termType)) {\n return false;\n }\n // compare values\n if(!(t1.subject.value === t2.subject.value &&\n t1.predicate.value === t2.predicate.value &&\n t1.object.value === t2.object.value)) {\n return false;\n }\n if(t1.object.termType !== TYPE_LITERAL) {\n // no `datatype` or `language` to check\n return true;\n }\n return (\n (t1.object.datatype.termType === t2.object.datatype.termType) &&\n (t1.object.language === t2.object.language) &&\n (t1.object.datatype.value === t2.object.datatype.value)\n );\n}\n\nconst _escapeRegex = /[\"\\\\\\n\\r]/g;\n/**\n * Escape string to N-Quads literal\n */\nfunction _escape(s) {\n return s.replace(_escapeRegex, function(match) {\n switch(match) {\n case '\"': return '\\\\\"';\n case '\\\\': return '\\\\\\\\';\n case '\\n': return '\\\\n';\n case '\\r': return '\\\\r';\n }\n });\n}\n\nconst _unescapeRegex =\n /(?:\\\\([tbnrf\"'\\\\]))|(?:\\\\u([0-9A-Fa-f]{4}))|(?:\\\\U([0-9A-Fa-f]{8}))/g;\n/**\n * Unescape N-Quads literal to string\n */\nfunction _unescape(s) {\n return s.replace(_unescapeRegex, function(match, code, u, U) {\n if(code) {\n switch(code) {\n case 't': return '\\t';\n case 'b': return '\\b';\n case 'n': return '\\n';\n case 'r': return '\\r';\n case 'f': return '\\f';\n case '\"': return '\"';\n case '\\'': return '\\'';\n case '\\\\': return '\\\\';\n }\n }\n if(u) {\n return String.fromCharCode(parseInt(u, 16));\n }\n if(U) {\n // FIXME: support larger values\n throw new Error('Unsupported U escape');\n }\n });\n}\n","/*!\n * Copyright (c) 2016-2022 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nmodule.exports = class Permuter {\n /**\n * A Permuter iterates over all possible permutations of the given array\n * of elements.\n *\n * @param list the array of elements to iterate over.\n */\n constructor(list) {\n // original array\n this.current = list.sort();\n // indicates whether there are more permutations\n this.done = false;\n // directional info for permutation algorithm\n this.dir = new Map();\n for(let i = 0; i < list.length; ++i) {\n this.dir.set(list[i], true);\n }\n }\n\n /**\n * Returns true if there is another permutation.\n *\n * @return true if there is another permutation, false if not.\n */\n hasNext() {\n return !this.done;\n }\n\n /**\n * Gets the next permutation. Call hasNext() to ensure there is another one\n * first.\n *\n * @return the next permutation.\n */\n next() {\n // copy current permutation to return it\n const {current, dir} = this;\n const rval = current.slice();\n\n /* Calculate the next permutation using the Steinhaus-Johnson-Trotter\n permutation algorithm. */\n\n // get largest mobile element k\n // (mobile: element is greater than the one it is looking at)\n let k = null;\n let pos = 0;\n const length = current.length;\n for(let i = 0; i < length; ++i) {\n const element = current[i];\n const left = dir.get(element);\n if((k === null || element > k) &&\n ((left && i > 0 && element > current[i - 1]) ||\n (!left && i < (length - 1) && element > current[i + 1]))) {\n k = element;\n pos = i;\n }\n }\n\n // no more permutations\n if(k === null) {\n this.done = true;\n } else {\n // swap k and the element it is looking at\n const swap = dir.get(k) ? pos - 1 : pos + 1;\n current[pos] = current[swap];\n current[swap] = k;\n\n // reverse the direction of all elements larger than k\n for(const element of current) {\n if(element > k) {\n dir.set(element, !dir.get(element));\n }\n }\n }\n\n return rval;\n }\n};\n","/*!\n * Copyright (c) 2016-2022 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst IdentifierIssuer = require('./IdentifierIssuer');\nconst MessageDigest = require('./MessageDigest');\nconst Permuter = require('./Permuter');\nconst NQuads = require('./NQuads');\n\nmodule.exports = class URDNA2015 {\n constructor({\n createMessageDigest = () => new MessageDigest('sha256'),\n canonicalIdMap = new Map(),\n maxDeepIterations = Infinity\n } = {}) {\n this.name = 'URDNA2015';\n this.blankNodeInfo = new Map();\n this.canonicalIssuer = new IdentifierIssuer('_:c14n', canonicalIdMap);\n this.createMessageDigest = createMessageDigest;\n this.maxDeepIterations = maxDeepIterations;\n this.quads = null;\n this.deepIterations = null;\n }\n\n // 4.4) Normalization Algorithm\n async main(dataset) {\n this.deepIterations = new Map();\n this.quads = dataset;\n\n // 1) Create the normalization state.\n // 2) For every quad in input dataset:\n for(const quad of dataset) {\n // 2.1) For each blank node that occurs in the quad, add a reference\n // to the quad using the blank node identifier in the blank node to\n // quads map, creating a new entry if necessary.\n this._addBlankNodeQuadInfo({quad, component: quad.subject});\n this._addBlankNodeQuadInfo({quad, component: quad.object});\n this._addBlankNodeQuadInfo({quad, component: quad.graph});\n }\n\n // 3) Create a list of non-normalized blank node identifiers\n // non-normalized identifiers and populate it using the keys from the\n // blank node to quads map.\n // Note: We use a map here and it was generated during step 2.\n\n // 4) `simple` flag is skipped -- loop is optimized away. This optimization\n // is permitted because there was a typo in the hash first degree quads\n // algorithm in the URDNA2015 spec that was implemented widely making it\n // such that it could not be fixed; the result was that the loop only\n // needs to be run once and the first degree quad hashes will never change.\n // 5.1-5.2 are skipped; first degree quad hashes are generated just once\n // for all non-normalized blank nodes.\n\n // 5.3) For each blank node identifier identifier in non-normalized\n // identifiers:\n const hashToBlankNodes = new Map();\n const nonNormalized = [...this.blankNodeInfo.keys()];\n let i = 0;\n for(const id of nonNormalized) {\n // Note: batch hashing first degree quads 100 at a time\n if(++i % 100 === 0) {\n await this._yield();\n }\n // steps 5.3.1 and 5.3.2:\n await this._hashAndTrackBlankNode({id, hashToBlankNodes});\n }\n\n // 5.4) For each hash to identifier list mapping in hash to blank\n // nodes map, lexicographically-sorted by hash:\n const hashes = [...hashToBlankNodes.keys()].sort();\n // optimize away second sort, gather non-unique hashes in order as we go\n const nonUnique = [];\n for(const hash of hashes) {\n // 5.4.1) If the length of identifier list is greater than 1,\n // continue to the next mapping.\n const idList = hashToBlankNodes.get(hash);\n if(idList.length > 1) {\n nonUnique.push(idList);\n continue;\n }\n\n // 5.4.2) Use the Issue Identifier algorithm, passing canonical\n // issuer and the single blank node identifier in identifier\n // list, identifier, to issue a canonical replacement identifier\n // for identifier.\n const id = idList[0];\n this.canonicalIssuer.getId(id);\n\n // Note: These steps are skipped, optimized away since the loop\n // only needs to be run once.\n // 5.4.3) Remove identifier from non-normalized identifiers.\n // 5.4.4) Remove hash from the hash to blank nodes map.\n // 5.4.5) Set simple to true.\n }\n\n // 6) For each hash to identifier list mapping in hash to blank nodes map,\n // lexicographically-sorted by hash:\n // Note: sort optimized away, use `nonUnique`.\n for(const idList of nonUnique) {\n // 6.1) Create hash path list where each item will be a result of\n // running the Hash N-Degree Quads algorithm.\n const hashPathList = [];\n\n // 6.2) For each blank node identifier identifier in identifier list:\n for(const id of idList) {\n // 6.2.1) If a canonical identifier has already been issued for\n // identifier, continue to the next identifier.\n if(this.canonicalIssuer.hasId(id)) {\n continue;\n }\n\n // 6.2.2) Create temporary issuer, an identifier issuer\n // initialized with the prefix _:b.\n const issuer = new IdentifierIssuer('_:b');\n\n // 6.2.3) Use the Issue Identifier algorithm, passing temporary\n // issuer and identifier, to issue a new temporary blank node\n // identifier for identifier.\n issuer.getId(id);\n\n // 6.2.4) Run the Hash N-Degree Quads algorithm, passing\n // temporary issuer, and append the result to the hash path list.\n const result = await this.hashNDegreeQuads(id, issuer);\n hashPathList.push(result);\n }\n\n // 6.3) For each result in the hash path list,\n // lexicographically-sorted by the hash in result:\n hashPathList.sort(_stringHashCompare);\n for(const result of hashPathList) {\n // 6.3.1) For each blank node identifier, existing identifier,\n // that was issued a temporary identifier by identifier issuer\n // in result, issue a canonical identifier, in the same order,\n // using the Issue Identifier algorithm, passing canonical\n // issuer and existing identifier.\n const oldIds = result.issuer.getOldIds();\n for(const id of oldIds) {\n this.canonicalIssuer.getId(id);\n }\n }\n }\n\n /* Note: At this point all blank nodes in the set of RDF quads have been\n assigned canonical identifiers, which have been stored in the canonical\n issuer. Here each quad is updated by assigning each of its blank nodes\n its new identifier. */\n\n // 7) For each quad, quad, in input dataset:\n const normalized = [];\n for(const quad of this.quads) {\n // 7.1) Create a copy, quad copy, of quad and replace any existing\n // blank node identifiers using the canonical identifiers\n // previously issued by canonical issuer.\n // Note: We optimize away the copy here.\n const nQuad = NQuads.serializeQuadComponents(\n this._componentWithCanonicalId(quad.subject),\n quad.predicate,\n this._componentWithCanonicalId(quad.object),\n this._componentWithCanonicalId(quad.graph)\n );\n // 7.2) Add quad copy to the normalized dataset.\n normalized.push(nQuad);\n }\n\n // sort normalized output\n normalized.sort();\n\n // 8) Return the normalized dataset.\n return normalized.join('');\n }\n\n // 4.6) Hash First Degree Quads\n async hashFirstDegreeQuads(id) {\n // 1) Initialize nquads to an empty list. It will be used to store quads in\n // N-Quads format.\n const nquads = [];\n\n // 2) Get the list of quads `quads` associated with the reference blank node\n // identifier in the blank node to quads map.\n const info = this.blankNodeInfo.get(id);\n const quads = info.quads;\n\n // 3) For each quad `quad` in `quads`:\n for(const quad of quads) {\n // 3.1) Serialize the quad in N-Quads format with the following special\n // rule:\n\n // 3.1.1) If any component in quad is an blank node, then serialize it\n // using a special identifier as follows:\n const copy = {\n subject: null, predicate: quad.predicate, object: null, graph: null\n };\n // 3.1.2) If the blank node's existing blank node identifier matches\n // the reference blank node identifier then use the blank node\n // identifier _:a, otherwise, use the blank node identifier _:z.\n copy.subject = this.modifyFirstDegreeComponent(\n id, quad.subject, 'subject');\n copy.object = this.modifyFirstDegreeComponent(\n id, quad.object, 'object');\n copy.graph = this.modifyFirstDegreeComponent(\n id, quad.graph, 'graph');\n nquads.push(NQuads.serializeQuad(copy));\n }\n\n // 4) Sort nquads in lexicographical order.\n nquads.sort();\n\n // 5) Return the hash that results from passing the sorted, joined nquads\n // through the hash algorithm.\n const md = this.createMessageDigest();\n for(const nquad of nquads) {\n md.update(nquad);\n }\n info.hash = await md.digest();\n return info.hash;\n }\n\n // 4.7) Hash Related Blank Node\n async hashRelatedBlankNode(related, quad, issuer, position) {\n // 1) Set the identifier to use for related, preferring first the canonical\n // identifier for related if issued, second the identifier issued by issuer\n // if issued, and last, if necessary, the result of the Hash First Degree\n // Quads algorithm, passing related.\n let id;\n if(this.canonicalIssuer.hasId(related)) {\n id = this.canonicalIssuer.getId(related);\n } else if(issuer.hasId(related)) {\n id = issuer.getId(related);\n } else {\n id = this.blankNodeInfo.get(related).hash;\n }\n\n // 2) Initialize a string input to the value of position.\n // Note: We use a hash object instead.\n const md = this.createMessageDigest();\n md.update(position);\n\n // 3) If position is not g, append <, the value of the predicate in quad,\n // and > to input.\n if(position !== 'g') {\n md.update(this.getRelatedPredicate(quad));\n }\n\n // 4) Append identifier to input.\n md.update(id);\n\n // 5) Return the hash that results from passing input through the hash\n // algorithm.\n return md.digest();\n }\n\n // 4.8) Hash N-Degree Quads\n async hashNDegreeQuads(id, issuer) {\n const deepIterations = this.deepIterations.get(id) || 0;\n if(deepIterations > this.maxDeepIterations) {\n throw new Error(\n `Maximum deep iterations (${this.maxDeepIterations}) exceeded.`);\n }\n this.deepIterations.set(id, deepIterations + 1);\n\n // 1) Create a hash to related blank nodes map for storing hashes that\n // identify related blank nodes.\n // Note: 2) and 3) handled within `createHashToRelated`\n const md = this.createMessageDigest();\n const hashToRelated = await this.createHashToRelated(id, issuer);\n\n // 4) Create an empty string, data to hash.\n // Note: We created a hash object `md` above instead.\n\n // 5) For each related hash to blank node list mapping in hash to related\n // blank nodes map, sorted lexicographically by related hash:\n const hashes = [...hashToRelated.keys()].sort();\n for(const hash of hashes) {\n // 5.1) Append the related hash to the data to hash.\n md.update(hash);\n\n // 5.2) Create a string chosen path.\n let chosenPath = '';\n\n // 5.3) Create an unset chosen issuer variable.\n let chosenIssuer;\n\n // 5.4) For each permutation of blank node list:\n const permuter = new Permuter(hashToRelated.get(hash));\n let i = 0;\n while(permuter.hasNext()) {\n const permutation = permuter.next();\n // Note: batch permutations 3 at a time\n if(++i % 3 === 0) {\n await this._yield();\n }\n\n // 5.4.1) Create a copy of issuer, issuer copy.\n let issuerCopy = issuer.clone();\n\n // 5.4.2) Create a string path.\n let path = '';\n\n // 5.4.3) Create a recursion list, to store blank node identifiers\n // that must be recursively processed by this algorithm.\n const recursionList = [];\n\n // 5.4.4) For each related in permutation:\n let nextPermutation = false;\n for(const related of permutation) {\n // 5.4.4.1) If a canonical identifier has been issued for\n // related, append it to path.\n if(this.canonicalIssuer.hasId(related)) {\n path += this.canonicalIssuer.getId(related);\n } else {\n // 5.4.4.2) Otherwise:\n // 5.4.4.2.1) If issuer copy has not issued an identifier for\n // related, append related to recursion list.\n if(!issuerCopy.hasId(related)) {\n recursionList.push(related);\n }\n // 5.4.4.2.2) Use the Issue Identifier algorithm, passing\n // issuer copy and related and append the result to path.\n path += issuerCopy.getId(related);\n }\n\n // 5.4.4.3) If chosen path is not empty and the length of path\n // is greater than or equal to the length of chosen path and\n // path is lexicographically greater than chosen path, then\n // skip to the next permutation.\n // Note: Comparing path length to chosen path length can be optimized\n // away; only compare lexicographically.\n if(chosenPath.length !== 0 && path > chosenPath) {\n nextPermutation = true;\n break;\n }\n }\n\n if(nextPermutation) {\n continue;\n }\n\n // 5.4.5) For each related in recursion list:\n for(const related of recursionList) {\n // 5.4.5.1) Set result to the result of recursively executing\n // the Hash N-Degree Quads algorithm, passing related for\n // identifier and issuer copy for path identifier issuer.\n const result = await this.hashNDegreeQuads(related, issuerCopy);\n\n // 5.4.5.2) Use the Issue Identifier algorithm, passing issuer\n // copy and related and append the result to path.\n path += issuerCopy.getId(related);\n\n // 5.4.5.3) Append <, the hash in result, and > to path.\n path += `<${result.hash}>`;\n\n // 5.4.5.4) Set issuer copy to the identifier issuer in\n // result.\n issuerCopy = result.issuer;\n\n // 5.4.5.5) If chosen path is not empty and the length of path\n // is greater than or equal to the length of chosen path and\n // path is lexicographically greater than chosen path, then\n // skip to the next permutation.\n // Note: Comparing path length to chosen path length can be optimized\n // away; only compare lexicographically.\n if(chosenPath.length !== 0 && path > chosenPath) {\n nextPermutation = true;\n break;\n }\n }\n\n if(nextPermutation) {\n continue;\n }\n\n // 5.4.6) If chosen path is empty or path is lexicographically\n // less than chosen path, set chosen path to path and chosen\n // issuer to issuer copy.\n if(chosenPath.length === 0 || path < chosenPath) {\n chosenPath = path;\n chosenIssuer = issuerCopy;\n }\n }\n\n // 5.5) Append chosen path to data to hash.\n md.update(chosenPath);\n\n // 5.6) Replace issuer, by reference, with chosen issuer.\n issuer = chosenIssuer;\n }\n\n // 6) Return issuer and the hash that results from passing data to hash\n // through the hash algorithm.\n return {hash: await md.digest(), issuer};\n }\n\n // helper for modifying component during Hash First Degree Quads\n modifyFirstDegreeComponent(id, component) {\n if(component.termType !== 'BlankNode') {\n return component;\n }\n /* Note: A mistake in the URDNA2015 spec that made its way into\n implementations (and therefore must stay to avoid interop breakage)\n resulted in an assigned canonical ID, if available for\n `component.value`, not being used in place of `_:a`/`_:z`, so\n we don't use it here. */\n return {\n termType: 'BlankNode',\n value: component.value === id ? '_:a' : '_:z'\n };\n }\n\n // helper for getting a related predicate\n getRelatedPredicate(quad) {\n return `<${quad.predicate.value}>`;\n }\n\n // helper for creating hash to related blank nodes map\n async createHashToRelated(id, issuer) {\n // 1) Create a hash to related blank nodes map for storing hashes that\n // identify related blank nodes.\n const hashToRelated = new Map();\n\n // 2) Get a reference, quads, to the list of quads in the blank node to\n // quads map for the key identifier.\n const quads = this.blankNodeInfo.get(id).quads;\n\n // 3) For each quad in quads:\n let i = 0;\n for(const quad of quads) {\n // Note: batch hashing related blank node quads 100 at a time\n if(++i % 100 === 0) {\n await this._yield();\n }\n // 3.1) For each component in quad, if component is the subject, object,\n // and graph name and it is a blank node that is not identified by\n // identifier:\n // steps 3.1.1 and 3.1.2 occur in helpers:\n await Promise.all([\n this._addRelatedBlankNodeHash({\n quad, component: quad.subject, position: 's',\n id, issuer, hashToRelated\n }),\n this._addRelatedBlankNodeHash({\n quad, component: quad.object, position: 'o',\n id, issuer, hashToRelated\n }),\n this._addRelatedBlankNodeHash({\n quad, component: quad.graph, position: 'g',\n id, issuer, hashToRelated\n })\n ]);\n }\n\n return hashToRelated;\n }\n\n async _hashAndTrackBlankNode({id, hashToBlankNodes}) {\n // 5.3.1) Create a hash, hash, according to the Hash First Degree\n // Quads algorithm.\n const hash = await this.hashFirstDegreeQuads(id);\n\n // 5.3.2) Add hash and identifier to hash to blank nodes map,\n // creating a new entry if necessary.\n const idList = hashToBlankNodes.get(hash);\n if(!idList) {\n hashToBlankNodes.set(hash, [id]);\n } else {\n idList.push(id);\n }\n }\n\n _addBlankNodeQuadInfo({quad, component}) {\n if(component.termType !== 'BlankNode') {\n return;\n }\n const id = component.value;\n const info = this.blankNodeInfo.get(id);\n if(info) {\n info.quads.add(quad);\n } else {\n this.blankNodeInfo.set(id, {quads: new Set([quad]), hash: null});\n }\n }\n\n async _addRelatedBlankNodeHash(\n {quad, component, position, id, issuer, hashToRelated}) {\n if(!(component.termType === 'BlankNode' && component.value !== id)) {\n return;\n }\n // 3.1.1) Set hash to the result of the Hash Related Blank Node\n // algorithm, passing the blank node identifier for component as\n // related, quad, path identifier issuer as issuer, and position as\n // either s, o, or g based on whether component is a subject, object,\n // graph name, respectively.\n const related = component.value;\n const hash = await this.hashRelatedBlankNode(\n related, quad, issuer, position);\n\n // 3.1.2) Add a mapping of hash to the blank node identifier for\n // component to hash to related blank nodes map, adding an entry as\n // necessary.\n const entries = hashToRelated.get(hash);\n if(entries) {\n entries.push(related);\n } else {\n hashToRelated.set(hash, [related]);\n }\n }\n\n // canonical ids for 7.1\n _componentWithCanonicalId(component) {\n if(component.termType === 'BlankNode' &&\n !component.value.startsWith(this.canonicalIssuer.prefix)) {\n // create new BlankNode\n return {\n termType: 'BlankNode',\n value: this.canonicalIssuer.getId(component.value)\n };\n }\n return component;\n }\n\n async _yield() {\n return new Promise(resolve => setImmediate(resolve));\n }\n};\n\nfunction _stringHashCompare(a, b) {\n return a.hash < b.hash ? -1 : a.hash > b.hash ? 1 : 0;\n}\n","/*!\n * Copyright (c) 2016-2022 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst IdentifierIssuer = require('./IdentifierIssuer');\n// FIXME: do not import; convert to requiring a\n// hash factory\nconst MessageDigest = require('./MessageDigest');\nconst Permuter = require('./Permuter');\nconst NQuads = require('./NQuads');\n\nmodule.exports = class URDNA2015Sync {\n constructor({\n createMessageDigest = () => new MessageDigest('sha256'),\n canonicalIdMap = new Map(),\n maxDeepIterations = Infinity\n } = {}) {\n this.name = 'URDNA2015';\n this.blankNodeInfo = new Map();\n this.canonicalIssuer = new IdentifierIssuer('_:c14n', canonicalIdMap);\n this.createMessageDigest = createMessageDigest;\n this.maxDeepIterations = maxDeepIterations;\n this.quads = null;\n this.deepIterations = null;\n }\n\n // 4.4) Normalization Algorithm\n main(dataset) {\n this.deepIterations = new Map();\n this.quads = dataset;\n\n // 1) Create the normalization state.\n // 2) For every quad in input dataset:\n for(const quad of dataset) {\n // 2.1) For each blank node that occurs in the quad, add a reference\n // to the quad using the blank node identifier in the blank node to\n // quads map, creating a new entry if necessary.\n this._addBlankNodeQuadInfo({quad, component: quad.subject});\n this._addBlankNodeQuadInfo({quad, component: quad.object});\n this._addBlankNodeQuadInfo({quad, component: quad.graph});\n }\n\n // 3) Create a list of non-normalized blank node identifiers\n // non-normalized identifiers and populate it using the keys from the\n // blank node to quads map.\n // Note: We use a map here and it was generated during step 2.\n\n // 4) `simple` flag is skipped -- loop is optimized away. This optimization\n // is permitted because there was a typo in the hash first degree quads\n // algorithm in the URDNA2015 spec that was implemented widely making it\n // such that it could not be fixed; the result was that the loop only\n // needs to be run once and the first degree quad hashes will never change.\n // 5.1-5.2 are skipped; first degree quad hashes are generated just once\n // for all non-normalized blank nodes.\n\n // 5.3) For each blank node identifier identifier in non-normalized\n // identifiers:\n const hashToBlankNodes = new Map();\n const nonNormalized = [...this.blankNodeInfo.keys()];\n for(const id of nonNormalized) {\n // steps 5.3.1 and 5.3.2:\n this._hashAndTrackBlankNode({id, hashToBlankNodes});\n }\n\n // 5.4) For each hash to identifier list mapping in hash to blank\n // nodes map, lexicographically-sorted by hash:\n const hashes = [...hashToBlankNodes.keys()].sort();\n // optimize away second sort, gather non-unique hashes in order as we go\n const nonUnique = [];\n for(const hash of hashes) {\n // 5.4.1) If the length of identifier list is greater than 1,\n // continue to the next mapping.\n const idList = hashToBlankNodes.get(hash);\n if(idList.length > 1) {\n nonUnique.push(idList);\n continue;\n }\n\n // 5.4.2) Use the Issue Identifier algorithm, passing canonical\n // issuer and the single blank node identifier in identifier\n // list, identifier, to issue a canonical replacement identifier\n // for identifier.\n const id = idList[0];\n this.canonicalIssuer.getId(id);\n\n // Note: These steps are skipped, optimized away since the loop\n // only needs to be run once.\n // 5.4.3) Remove identifier from non-normalized identifiers.\n // 5.4.4) Remove hash from the hash to blank nodes map.\n // 5.4.5) Set simple to true.\n }\n\n // 6) For each hash to identifier list mapping in hash to blank nodes map,\n // lexicographically-sorted by hash:\n // Note: sort optimized away, use `nonUnique`.\n for(const idList of nonUnique) {\n // 6.1) Create hash path list where each item will be a result of\n // running the Hash N-Degree Quads algorithm.\n const hashPathList = [];\n\n // 6.2) For each blank node identifier identifier in identifier list:\n for(const id of idList) {\n // 6.2.1) If a canonical identifier has already been issued for\n // identifier, continue to the next identifier.\n if(this.canonicalIssuer.hasId(id)) {\n continue;\n }\n\n // 6.2.2) Create temporary issuer, an identifier issuer\n // initialized with the prefix _:b.\n const issuer = new IdentifierIssuer('_:b');\n\n // 6.2.3) Use the Issue Identifier algorithm, passing temporary\n // issuer and identifier, to issue a new temporary blank node\n // identifier for identifier.\n issuer.getId(id);\n\n // 6.2.4) Run the Hash N-Degree Quads algorithm, passing\n // temporary issuer, and append the result to the hash path list.\n const result = this.hashNDegreeQuads(id, issuer);\n hashPathList.push(result);\n }\n\n // 6.3) For each result in the hash path list,\n // lexicographically-sorted by the hash in result:\n hashPathList.sort(_stringHashCompare);\n for(const result of hashPathList) {\n // 6.3.1) For each blank node identifier, existing identifier,\n // that was issued a temporary identifier by identifier issuer\n // in result, issue a canonical identifier, in the same order,\n // using the Issue Identifier algorithm, passing canonical\n // issuer and existing identifier.\n const oldIds = result.issuer.getOldIds();\n for(const id of oldIds) {\n this.canonicalIssuer.getId(id);\n }\n }\n }\n\n /* Note: At this point all blank nodes in the set of RDF quads have been\n assigned canonical identifiers, which have been stored in the canonical\n issuer. Here each quad is updated by assigning each of its blank nodes\n its new identifier. */\n\n // 7) For each quad, quad, in input dataset:\n const normalized = [];\n for(const quad of this.quads) {\n // 7.1) Create a copy, quad copy, of quad and replace any existing\n // blank node identifiers using the canonical identifiers\n // previously issued by canonical issuer.\n // Note: We optimize away the copy here.\n const nQuad = NQuads.serializeQuadComponents(\n this._componentWithCanonicalId({component: quad.subject}),\n quad.predicate,\n this._componentWithCanonicalId({component: quad.object}),\n this._componentWithCanonicalId({component: quad.graph})\n );\n // 7.2) Add quad copy to the normalized dataset.\n normalized.push(nQuad);\n }\n\n // sort normalized output\n normalized.sort();\n\n // 8) Return the normalized dataset.\n return normalized.join('');\n }\n\n // 4.6) Hash First Degree Quads\n hashFirstDegreeQuads(id) {\n // 1) Initialize nquads to an empty list. It will be used to store quads in\n // N-Quads format.\n const nquads = [];\n\n // 2) Get the list of quads `quads` associated with the reference blank node\n // identifier in the blank node to quads map.\n const info = this.blankNodeInfo.get(id);\n const quads = info.quads;\n\n // 3) For each quad `quad` in `quads`:\n for(const quad of quads) {\n // 3.1) Serialize the quad in N-Quads format with the following special\n // rule:\n\n // 3.1.1) If any component in quad is an blank node, then serialize it\n // using a special identifier as follows:\n const copy = {\n subject: null, predicate: quad.predicate, object: null, graph: null\n };\n // 3.1.2) If the blank node's existing blank node identifier matches\n // the reference blank node identifier then use the blank node\n // identifier _:a, otherwise, use the blank node identifier _:z.\n copy.subject = this.modifyFirstDegreeComponent(\n id, quad.subject, 'subject');\n copy.object = this.modifyFirstDegreeComponent(\n id, quad.object, 'object');\n copy.graph = this.modifyFirstDegreeComponent(\n id, quad.graph, 'graph');\n nquads.push(NQuads.serializeQuad(copy));\n }\n\n // 4) Sort nquads in lexicographical order.\n nquads.sort();\n\n // 5) Return the hash that results from passing the sorted, joined nquads\n // through the hash algorithm.\n const md = this.createMessageDigest();\n for(const nquad of nquads) {\n md.update(nquad);\n }\n info.hash = md.digest();\n return info.hash;\n }\n\n // 4.7) Hash Related Blank Node\n hashRelatedBlankNode(related, quad, issuer, position) {\n // 1) Set the identifier to use for related, preferring first the canonical\n // identifier for related if issued, second the identifier issued by issuer\n // if issued, and last, if necessary, the result of the Hash First Degree\n // Quads algorithm, passing related.\n let id;\n if(this.canonicalIssuer.hasId(related)) {\n id = this.canonicalIssuer.getId(related);\n } else if(issuer.hasId(related)) {\n id = issuer.getId(related);\n } else {\n id = this.blankNodeInfo.get(related).hash;\n }\n\n // 2) Initialize a string input to the value of position.\n // Note: We use a hash object instead.\n const md = this.createMessageDigest();\n md.update(position);\n\n // 3) If position is not g, append <, the value of the predicate in quad,\n // and > to input.\n if(position !== 'g') {\n md.update(this.getRelatedPredicate(quad));\n }\n\n // 4) Append identifier to input.\n md.update(id);\n\n // 5) Return the hash that results from passing input through the hash\n // algorithm.\n return md.digest();\n }\n\n // 4.8) Hash N-Degree Quads\n hashNDegreeQuads(id, issuer) {\n const deepIterations = this.deepIterations.get(id) || 0;\n if(deepIterations > this.maxDeepIterations) {\n throw new Error(\n `Maximum deep iterations (${this.maxDeepIterations}) exceeded.`);\n }\n this.deepIterations.set(id, deepIterations + 1);\n\n // 1) Create a hash to related blank nodes map for storing hashes that\n // identify related blank nodes.\n // Note: 2) and 3) handled within `createHashToRelated`\n const md = this.createMessageDigest();\n const hashToRelated = this.createHashToRelated(id, issuer);\n\n // 4) Create an empty string, data to hash.\n // Note: We created a hash object `md` above instead.\n\n // 5) For each related hash to blank node list mapping in hash to related\n // blank nodes map, sorted lexicographically by related hash:\n const hashes = [...hashToRelated.keys()].sort();\n for(const hash of hashes) {\n // 5.1) Append the related hash to the data to hash.\n md.update(hash);\n\n // 5.2) Create a string chosen path.\n let chosenPath = '';\n\n // 5.3) Create an unset chosen issuer variable.\n let chosenIssuer;\n\n // 5.4) For each permutation of blank node list:\n const permuter = new Permuter(hashToRelated.get(hash));\n while(permuter.hasNext()) {\n const permutation = permuter.next();\n\n // 5.4.1) Create a copy of issuer, issuer copy.\n let issuerCopy = issuer.clone();\n\n // 5.4.2) Create a string path.\n let path = '';\n\n // 5.4.3) Create a recursion list, to store blank node identifiers\n // that must be recursively processed by this algorithm.\n const recursionList = [];\n\n // 5.4.4) For each related in permutation:\n let nextPermutation = false;\n for(const related of permutation) {\n // 5.4.4.1) If a canonical identifier has been issued for\n // related, append it to path.\n if(this.canonicalIssuer.hasId(related)) {\n path += this.canonicalIssuer.getId(related);\n } else {\n // 5.4.4.2) Otherwise:\n // 5.4.4.2.1) If issuer copy has not issued an identifier for\n // related, append related to recursion list.\n if(!issuerCopy.hasId(related)) {\n recursionList.push(related);\n }\n // 5.4.4.2.2) Use the Issue Identifier algorithm, passing\n // issuer copy and related and append the result to path.\n path += issuerCopy.getId(related);\n }\n\n // 5.4.4.3) If chosen path is not empty and the length of path\n // is greater than or equal to the length of chosen path and\n // path is lexicographically greater than chosen path, then\n // skip to the next permutation.\n // Note: Comparing path length to chosen path length can be optimized\n // away; only compare lexicographically.\n if(chosenPath.length !== 0 && path > chosenPath) {\n nextPermutation = true;\n break;\n }\n }\n\n if(nextPermutation) {\n continue;\n }\n\n // 5.4.5) For each related in recursion list:\n for(const related of recursionList) {\n // 5.4.5.1) Set result to the result of recursively executing\n // the Hash N-Degree Quads algorithm, passing related for\n // identifier and issuer copy for path identifier issuer.\n const result = this.hashNDegreeQuads(related, issuerCopy);\n\n // 5.4.5.2) Use the Issue Identifier algorithm, passing issuer\n // copy and related and append the result to path.\n path += issuerCopy.getId(related);\n\n // 5.4.5.3) Append <, the hash in result, and > to path.\n path += `<${result.hash}>`;\n\n // 5.4.5.4) Set issuer copy to the identifier issuer in\n // result.\n issuerCopy = result.issuer;\n\n // 5.4.5.5) If chosen path is not empty and the length of path\n // is greater than or equal to the length of chosen path and\n // path is lexicographically greater than chosen path, then\n // skip to the next permutation.\n // Note: Comparing path length to chosen path length can be optimized\n // away; only compare lexicographically.\n if(chosenPath.length !== 0 && path > chosenPath) {\n nextPermutation = true;\n break;\n }\n }\n\n if(nextPermutation) {\n continue;\n }\n\n // 5.4.6) If chosen path is empty or path is lexicographically\n // less than chosen path, set chosen path to path and chosen\n // issuer to issuer copy.\n if(chosenPath.length === 0 || path < chosenPath) {\n chosenPath = path;\n chosenIssuer = issuerCopy;\n }\n }\n\n // 5.5) Append chosen path to data to hash.\n md.update(chosenPath);\n\n // 5.6) Replace issuer, by reference, with chosen issuer.\n issuer = chosenIssuer;\n }\n\n // 6) Return issuer and the hash that results from passing data to hash\n // through the hash algorithm.\n return {hash: md.digest(), issuer};\n }\n\n // helper for modifying component during Hash First Degree Quads\n modifyFirstDegreeComponent(id, component) {\n if(component.termType !== 'BlankNode') {\n return component;\n }\n /* Note: A mistake in the URDNA2015 spec that made its way into\n implementations (and therefore must stay to avoid interop breakage)\n resulted in an assigned canonical ID, if available for\n `component.value`, not being used in place of `_:a`/`_:z`, so\n we don't use it here. */\n return {\n termType: 'BlankNode',\n value: component.value === id ? '_:a' : '_:z'\n };\n }\n\n // helper for getting a related predicate\n getRelatedPredicate(quad) {\n return `<${quad.predicate.value}>`;\n }\n\n // helper for creating hash to related blank nodes map\n createHashToRelated(id, issuer) {\n // 1) Create a hash to related blank nodes map for storing hashes that\n // identify related blank nodes.\n const hashToRelated = new Map();\n\n // 2) Get a reference, quads, to the list of quads in the blank node to\n // quads map for the key identifier.\n const quads = this.blankNodeInfo.get(id).quads;\n\n // 3) For each quad in quads:\n for(const quad of quads) {\n // 3.1) For each component in quad, if component is the subject, object,\n // or graph name and it is a blank node that is not identified by\n // identifier:\n // steps 3.1.1 and 3.1.2 occur in helpers:\n this._addRelatedBlankNodeHash({\n quad, component: quad.subject, position: 's',\n id, issuer, hashToRelated\n });\n this._addRelatedBlankNodeHash({\n quad, component: quad.object, position: 'o',\n id, issuer, hashToRelated\n });\n this._addRelatedBlankNodeHash({\n quad, component: quad.graph, position: 'g',\n id, issuer, hashToRelated\n });\n }\n\n return hashToRelated;\n }\n\n _hashAndTrackBlankNode({id, hashToBlankNodes}) {\n // 5.3.1) Create a hash, hash, according to the Hash First Degree\n // Quads algorithm.\n const hash = this.hashFirstDegreeQuads(id);\n\n // 5.3.2) Add hash and identifier to hash to blank nodes map,\n // creating a new entry if necessary.\n const idList = hashToBlankNodes.get(hash);\n if(!idList) {\n hashToBlankNodes.set(hash, [id]);\n } else {\n idList.push(id);\n }\n }\n\n _addBlankNodeQuadInfo({quad, component}) {\n if(component.termType !== 'BlankNode') {\n return;\n }\n const id = component.value;\n const info = this.blankNodeInfo.get(id);\n if(info) {\n info.quads.add(quad);\n } else {\n this.blankNodeInfo.set(id, {quads: new Set([quad]), hash: null});\n }\n }\n\n _addRelatedBlankNodeHash(\n {quad, component, position, id, issuer, hashToRelated}) {\n if(!(component.termType === 'BlankNode' && component.value !== id)) {\n return;\n }\n // 3.1.1) Set hash to the result of the Hash Related Blank Node\n // algorithm, passing the blank node identifier for component as\n // related, quad, path identifier issuer as issuer, and position as\n // either s, o, or g based on whether component is a subject, object,\n // graph name, respectively.\n const related = component.value;\n const hash = this.hashRelatedBlankNode(related, quad, issuer, position);\n\n // 3.1.2) Add a mapping of hash to the blank node identifier for\n // component to hash to related blank nodes map, adding an entry as\n // necessary.\n const entries = hashToRelated.get(hash);\n if(entries) {\n entries.push(related);\n } else {\n hashToRelated.set(hash, [related]);\n }\n }\n\n // canonical ids for 7.1\n _componentWithCanonicalId({component}) {\n if(component.termType === 'BlankNode' &&\n !component.value.startsWith(this.canonicalIssuer.prefix)) {\n // create new BlankNode\n return {\n termType: 'BlankNode',\n value: this.canonicalIssuer.getId(component.value)\n };\n }\n return component;\n }\n};\n\nfunction _stringHashCompare(a, b) {\n return a.hash < b.hash ? -1 : a.hash > b.hash ? 1 : 0;\n}\n","/*!\n * Copyright (c) 2016-2022 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst MessageDigest = require('./MessageDigest');\nconst URDNA2015 = require('./URDNA2015');\n\nmodule.exports = class URDNA2012 extends URDNA2015 {\n constructor() {\n super();\n this.name = 'URGNA2012';\n this.createMessageDigest = () => new MessageDigest('sha1');\n }\n\n // helper for modifying component during Hash First Degree Quads\n modifyFirstDegreeComponent(id, component, key) {\n if(component.termType !== 'BlankNode') {\n return component;\n }\n if(key === 'graph') {\n return {\n termType: 'BlankNode',\n value: '_:g'\n };\n }\n return {\n termType: 'BlankNode',\n value: (component.value === id ? '_:a' : '_:z')\n };\n }\n\n // helper for getting a related predicate\n getRelatedPredicate(quad) {\n return quad.predicate.value;\n }\n\n // helper for creating hash to related blank nodes map\n async createHashToRelated(id, issuer) {\n // 1) Create a hash to related blank nodes map for storing hashes that\n // identify related blank nodes.\n const hashToRelated = new Map();\n\n // 2) Get a reference, quads, to the list of quads in the blank node to\n // quads map for the key identifier.\n const quads = this.blankNodeInfo.get(id).quads;\n\n // 3) For each quad in quads:\n let i = 0;\n for(const quad of quads) {\n // 3.1) If the quad's subject is a blank node that does not match\n // identifier, set hash to the result of the Hash Related Blank Node\n // algorithm, passing the blank node identifier for subject as related,\n // quad, path identifier issuer as issuer, and p as position.\n let position;\n let related;\n if(quad.subject.termType === 'BlankNode' && quad.subject.value !== id) {\n related = quad.subject.value;\n position = 'p';\n } else if(\n quad.object.termType === 'BlankNode' && quad.object.value !== id) {\n // 3.2) Otherwise, if quad's object is a blank node that does not match\n // identifier, to the result of the Hash Related Blank Node algorithm,\n // passing the blank node identifier for object as related, quad, path\n // identifier issuer as issuer, and r as position.\n related = quad.object.value;\n position = 'r';\n } else {\n // 3.3) Otherwise, continue to the next quad.\n continue;\n }\n // Note: batch hashing related blank nodes 100 at a time\n if(++i % 100 === 0) {\n await this._yield();\n }\n // 3.4) Add a mapping of hash to the blank node identifier for the\n // component that matched (subject or object) to hash to related blank\n // nodes map, adding an entry as necessary.\n const hash = await this.hashRelatedBlankNode(\n related, quad, issuer, position);\n const entries = hashToRelated.get(hash);\n if(entries) {\n entries.push(related);\n } else {\n hashToRelated.set(hash, [related]);\n }\n }\n\n return hashToRelated;\n }\n};\n","/*!\n * Copyright (c) 2016-2021 Digital Bazaar, Inc. All rights reserved.\n */\n'use strict';\n\nconst MessageDigest = require('./MessageDigest');\nconst URDNA2015Sync = require('./URDNA2015Sync');\n\nmodule.exports = class URDNA2012Sync extends URDNA2015Sync {\n constructor() {\n super();\n this.name = 'URGNA2012';\n this.createMessageDigest = () => new MessageDigest('sha1');\n }\n\n // helper for modifying component during Hash First Degree Quads\n modifyFirstDegreeComponent(id, component, key) {\n if(component.termType !== 'BlankNode') {\n return component;\n }\n if(key === 'graph') {\n return {\n termType: 'BlankNode',\n value: '_:g'\n };\n }\n return {\n termType: 'BlankNode',\n value: (component.value === id ? '_:a' : '_:z')\n };\n }\n\n // helper for getting a related predicate\n getRelatedPredicate(quad) {\n return quad.predicate.value;\n }\n\n // helper for creating hash to related blank nodes map\n createHashToRelated(id, issuer) {\n // 1) Create a hash to related blank nodes map for storing hashes that\n // identify related blank nodes.\n const hashToRelated = new Map();\n\n // 2) Get a reference, quads, to the list of quads in the blank node to\n // quads map for the key identifier.\n const quads = this.blankNodeInfo.get(id).quads;\n\n // 3) For each quad in quads:\n for(const quad of quads) {\n // 3.1) If the quad's subject is a blank node that does not match\n // identifier, set hash to the result of the Hash Related Blank Node\n // algorithm, passing the blank node identifier for subject as related,\n // quad, path identifier issuer as issuer, and p as position.\n let position;\n let related;\n if(quad.subject.termType === 'BlankNode' && quad.subject.value !== id) {\n related = quad.subject.value;\n position = 'p';\n } else if(\n quad.object.termType === 'BlankNode' && quad.object.value !== id) {\n // 3.2) Otherwise, if quad's object is a blank node that does not match\n // identifier, to the result of the Hash Related Blank Node algorithm,\n // passing the blank node identifier for object as related, quad, path\n // identifier issuer as issuer, and r as position.\n related = quad.object.value;\n position = 'r';\n } else {\n // 3.3) Otherwise, continue to the next quad.\n continue;\n }\n // 3.4) Add a mapping of hash to the blank node identifier for the\n // component that matched (subject or object) to hash to related blank\n // nodes map, adding an entry as necessary.\n const hash = this.hashRelatedBlankNode(related, quad, issuer, position);\n const entries = hashToRelated.get(hash);\n if(entries) {\n entries.push(related);\n } else {\n hashToRelated.set(hash, [related]);\n }\n }\n\n return hashToRelated;\n }\n};\n","/**\n * An implementation of the RDF Dataset Normalization specification.\n * This library works in the browser and node.js.\n *\n * BSD 3-Clause License\n * Copyright (c) 2016-2023 Digital Bazaar, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * Neither the name of the Digital Bazaar, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n'use strict';\n\nconst URDNA2015 = require('./URDNA2015');\nconst URGNA2012 = require('./URGNA2012');\nconst URDNA2015Sync = require('./URDNA2015Sync');\nconst URGNA2012Sync = require('./URGNA2012Sync');\n\n// optional native support\nlet rdfCanonizeNative;\ntry {\n rdfCanonizeNative = require('rdf-canonize-native');\n} catch(e) {}\n\n// return a dataset from input dataset or legacy dataset\nfunction _inputToDataset(input/*, options*/) {\n // back-compat with legacy dataset\n if(!Array.isArray(input)) {\n return exports.NQuads.legacyDatasetToQuads(input);\n }\n return input;\n}\n\n// expose helpers\nexports.NQuads = require('./NQuads');\nexports.IdentifierIssuer = require('./IdentifierIssuer');\n\n/**\n * Get or set native API.\n *\n * @param api the native API.\n *\n * @return the currently set native API.\n */\nexports._rdfCanonizeNative = function(api) {\n if(api) {\n rdfCanonizeNative = api;\n }\n return rdfCanonizeNative;\n};\n\n/**\n * Asynchronously canonizes an RDF dataset.\n *\n * @param {Array|object|string} input - The input to canonize given as a\n * dataset or legacy dataset.\n * @param {object} options - The options to use:\n * {string} algorithm - The canonicalization algorithm to use, `URDNA2015` or\n * `URGNA2012`.\n * {Function} [createMessageDigest] - A factory function for creating a\n * `MessageDigest` interface that overrides the built-in message digest\n * implementation used by the canonize algorithm; note that using a hash\n * algorithm (or HMAC algorithm) that differs from the one specified by\n * the canonize algorithm will result in different output.\n * {Map} [canonicalIdMap] - An optional Map to be populated by the canonical\n * identifier issuer with the bnode identifier mapping generated by the\n * canonicalization algorithm.\n * {boolean} [useNative=false] - Use native implementation.\n * {number} [maxDeepIterations=Infinity] - The maximum number of times to run\n * deep comparison algorithms (such as the N-Degree Hash Quads algorithm\n * used in URDNA2015) before bailing out and throwing an error; this is a\n * useful setting for preventing wasted CPU cycles or DoS when canonizing\n * meaningless or potentially malicious datasets, a recommended value is\n * `1`.\n *\n * @return a Promise that resolves to the canonicalized RDF Dataset.\n */\nexports.canonize = async function(input, options) {\n const dataset = _inputToDataset(input, options);\n\n if(options.useNative) {\n if(!rdfCanonizeNative) {\n throw new Error('rdf-canonize-native not available');\n }\n if(options.createMessageDigest) {\n throw new Error(\n '\"createMessageDigest\" cannot be used with \"useNative\".');\n }\n return new Promise((resolve, reject) =>\n rdfCanonizeNative.canonize(dataset, options, (err, canonical) =>\n err ? reject(err) : resolve(canonical)));\n }\n\n if(options.algorithm === 'URDNA2015') {\n return new URDNA2015(options).main(dataset);\n }\n if(options.algorithm === 'URGNA2012') {\n if(options.createMessageDigest) {\n throw new Error(\n '\"createMessageDigest\" cannot be used with \"URGNA2012\".');\n }\n return new URGNA2012(options).main(dataset);\n }\n if(!('algorithm' in options)) {\n throw new Error('No RDF Dataset Canonicalization algorithm specified.');\n }\n throw new Error(\n 'Invalid RDF Dataset Canonicalization algorithm: ' + options.algorithm);\n};\n\n/**\n * This method is no longer available in the public API, it is for testing\n * only. It synchronously canonizes an RDF dataset and does not work in the\n * browser.\n *\n * @param {Array|object|string} input - The input to canonize given as a\n * dataset or legacy dataset.\n * @param {object} options - The options to use:\n * {string} algorithm - The canonicalization algorithm to use, `URDNA2015` or\n * `URGNA2012`.\n * {Function} [createMessageDigest] - A factory function for creating a\n * `MessageDigest` interface that overrides the built-in message digest\n * implementation used by the canonize algorithm; note that using a hash\n * algorithm (or HMAC algorithm) that differs from the one specified by\n * the canonize algorithm will result in different output.\n * {boolean} [useNative=false] - Use native implementation.\n * {number} [maxDeepIterations=Infinity] - The maximum number of times to run\n * deep comparison algorithms (such as the N-Degree Hash Quads algorithm\n * used in URDNA2015) before bailing out and throwing an error; this is a\n * useful setting for preventing wasted CPU cycles or DoS when canonizing\n * meaningless or potentially malicious datasets, a recommended value is\n * `1`.\n *\n * @return the RDF dataset in canonical form.\n */\nexports._canonizeSync = function(input, options) {\n const dataset = _inputToDataset(input, options);\n\n if(options.useNative) {\n if(!rdfCanonizeNative) {\n throw new Error('rdf-canonize-native not available');\n }\n if(options.createMessageDigest) {\n throw new Error(\n '\"createMessageDigest\" cannot be used with \"useNative\".');\n }\n return rdfCanonizeNative.canonizeSync(dataset, options);\n }\n if(options.algorithm === 'URDNA2015') {\n return new URDNA2015Sync(options).main(dataset);\n }\n if(options.algorithm === 'URGNA2012') {\n if(options.createMessageDigest) {\n throw new Error(\n '\"createMessageDigest\" cannot be used with \"URGNA2012\".');\n }\n return new URGNA2012Sync(options).main(dataset);\n }\n if(!('algorithm' in options)) {\n throw new Error('No RDF Dataset Canonicalization algorithm specified.');\n }\n throw new Error(\n 'Invalid RDF Dataset Canonicalization algorithm: ' + options.algorithm);\n};\n","(function (global, undefined) {\n \"use strict\";\n\n if (global.setImmediate) {\n return;\n }\n\n var nextHandle = 1; // Spec says greater than zero\n var tasksByHandle = {};\n var currentlyRunningATask = false;\n var doc = global.document;\n var registerImmediate;\n\n function setImmediate(callback) {\n // Callback can either be a function or a string\n if (typeof callback !== \"function\") {\n callback = new Function(\"\" + callback);\n }\n // Copy function arguments\n var args = new Array(arguments.length - 1);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i + 1];\n }\n // Store and register the task\n var task = { callback: callback, args: args };\n tasksByHandle[nextHandle] = task;\n registerImmediate(nextHandle);\n return nextHandle++;\n }\n\n function clearImmediate(handle) {\n delete tasksByHandle[handle];\n }\n\n function run(task) {\n var callback = task.callback;\n var args = task.args;\n switch (args.length) {\n case 0:\n callback();\n break;\n case 1:\n callback(args[0]);\n break;\n case 2:\n callback(args[0], args[1]);\n break;\n case 3:\n callback(args[0], args[1], args[2]);\n break;\n default:\n callback.apply(undefined, args);\n break;\n }\n }\n\n function runIfPresent(handle) {\n // From the spec: \"Wait until any invocations of this algorithm started before this one have completed.\"\n // So if we're currently running a task, we'll need to delay this invocation.\n if (currentlyRunningATask) {\n // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a\n // \"too much recursion\" error.\n setTimeout(runIfPresent, 0, handle);\n } else {\n var task = tasksByHandle[handle];\n if (task) {\n currentlyRunningATask = true;\n try {\n run(task);\n } finally {\n clearImmediate(handle);\n currentlyRunningATask = false;\n }\n }\n }\n }\n\n function installNextTickImplementation() {\n registerImmediate = function(handle) {\n process.nextTick(function () { runIfPresent(handle); });\n };\n }\n\n function canUsePostMessage() {\n // The test against `importScripts` prevents this implementation from being installed inside a web worker,\n // where `global.postMessage` means something completely different and can't be used for this purpose.\n if (global.postMessage && !global.importScripts) {\n var postMessageIsAsynchronous = true;\n var oldOnMessage = global.onmessage;\n global.onmessage = function() {\n postMessageIsAsynchronous = false;\n };\n global.postMessage(\"\", \"*\");\n global.onmessage = oldOnMessage;\n return postMessageIsAsynchronous;\n }\n }\n\n function installPostMessageImplementation() {\n // Installs an event handler on `global` for the `message` event: see\n // * https://developer.mozilla.org/en/DOM/window.postMessage\n // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages\n\n var messagePrefix = \"setImmediate$\" + Math.random() + \"$\";\n var onGlobalMessage = function(event) {\n if (event.source === global &&\n typeof event.data === \"string\" &&\n event.data.indexOf(messagePrefix) === 0) {\n runIfPresent(+event.data.slice(messagePrefix.length));\n }\n };\n\n if (global.addEventListener) {\n global.addEventListener(\"message\", onGlobalMessage, false);\n } else {\n global.attachEvent(\"onmessage\", onGlobalMessage);\n }\n\n registerImmediate = function(handle) {\n global.postMessage(messagePrefix + handle, \"*\");\n };\n }\n\n function installMessageChannelImplementation() {\n var channel = new MessageChannel();\n channel.port1.onmessage = function(event) {\n var handle = event.data;\n runIfPresent(handle);\n };\n\n registerImmediate = function(handle) {\n channel.port2.postMessage(handle);\n };\n }\n\n function installReadyStateChangeImplementation() {\n var html = doc.documentElement;\n registerImmediate = function(handle) {\n // Create a \\n \\n\\n \\n
\\n
\\n\\n
\\n
\\n \\n\\n\";\n//# sourceMappingURL=new.js.map","\"use strict\";\n\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.formPane = void 0;\nvar UI = _interopRequireWildcard(require(\"solid-ui\"));\nvar _solidLogic = require(\"solid-logic\");\nvar $rdf = _interopRequireWildcard(require(\"rdflib\"));\nfunction _getRequireWildcardCache(e) { if (\"function\" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }\nfunction _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || \"object\" != _typeof(e) && \"function\" != typeof e) return { \"default\": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if (\"default\" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n[\"default\"] = e, t && t.set(e, n), n; }\n/*\n ** Pane for running existing forms for any object\n **\n */\n\nvar ns = UI.ns;\nvar formPane = exports.formPane = {\n icon: UI.icons.iconBase + 'noun_122196.svg',\n name: 'form',\n audience: [ns.solid('PowerUser')],\n // Does the subject deserve this pane?\n label: function label(subject) {\n var n = UI.widgets.formsFor(subject).length;\n UI.log.debug('Form pane: forms for ' + subject + ': ' + n);\n if (!n) return null;\n return '' + n + ' forms';\n },\n render: function render(subject, context) {\n var kb = context.session.store;\n var dom = context.dom;\n var mention = function complain(message, style) {\n var pre = dom.createElement('p');\n pre.setAttribute('style', style || 'color: grey; background-color: white');\n box.appendChild(pre).textContent = message;\n return pre;\n };\n var complain = function complain(message, style) {\n mention(message, 'style', style || 'color: grey; background-color: #fdd;');\n };\n var complainIfBad = function complainIfBad(ok, body) {\n if (ok) {\n // setModifiedDate(store, kb, store);\n // rerender(box); // Deleted forms at the moment\n } else complain('Sorry, failed to save your change:\\n' + body);\n };\n\n // The question of where to store this data about subject\n // This in general needs a whole lot more thought\n // and it connects to the discoverbility through links\n\n // const t = kb.findTypeURIs(subject)\n\n var me = _solidLogic.authn.currentUser();\n var box = dom.createElement('div');\n box.setAttribute('class', 'formPane');\n if (!me) {\n mention('You are not logged in. If you log in and have ' + 'workspaces then you would be able to select workspace in which ' + 'to put this new information');\n } else {\n var ws = kb.each(me, ns.ui('workspace'));\n if (ws.length === 0) {\n mention(\"You don't seem to have any workspaces defined. \" + 'A workspace is a place on the web (http://..) or in ' + 'the file system (file:///) to store application data.\\n');\n } else {\n // @@\n }\n }\n\n // Render forms using a given store\n\n var renderFormsFor = function renderFormsFor(store, subject) {\n kb.fetcher.nowOrWhenFetched(store.uri, subject, function (ok, body) {\n if (!ok) return complain('Cannot load store ' + store.uri + ': ' + body);\n\n // Render the forms\n\n var forms = UI.widgets.formsFor(subject);\n\n // complain('Form for editing this form:');\n for (var i = 0; i < forms.length; i++) {\n var form = forms[i];\n var heading = dom.createElement('h4');\n box.appendChild(heading);\n if (form.uri) {\n var formStore = $rdf.Util.uri.document(form.uri);\n if (formStore.uri !== form.uri) {\n // The form is a hash-type URI\n var e = box.appendChild(UI.widgets.editFormButton(dom, box, form, formStore, complainIfBad));\n e.setAttribute('style', 'float: right;');\n }\n }\n var anchor = dom.createElement('a');\n anchor.setAttribute('href', form.uri);\n heading.appendChild(anchor);\n anchor.textContent = UI.utils.label(form, true);\n\n /* Keep tis as a reminder to let a New one have its URI given by user\n mention(\"Where will this information be stored?\")\n const ele = dom.createElement('input');\n box.appendChild(ele);\n ele.setAttribute('type', 'text');\n ele.setAttribute('size', '72');\n ele.setAttribute('maxlength', '1024');\n ele.setAttribute('style', 'font-size: 80%; color:#222;');\n ele.value = store.uri\n */\n\n UI.widgets.appendForm(dom, box, {}, subject, form, store, complainIfBad);\n }\n }); // end: when store loded\n }; // renderFormsFor\n\n // Figure out what store\n\n // Which places are editable and have stuff about the subject?\n\n var store = null;\n\n // 1. The document URI of the subject itself\n var docuri = $rdf.Util.uri.docpart(subject.uri);\n if (subject.uri !== docuri && kb.updater.editable(docuri, kb)) {\n store = subject.doc();\n } // an editable data file with hash\n\n store = store || kb.any(kb.sym(docuri), ns.link('annotationStore'));\n\n // 2. where stuff is already stored\n if (!store) {\n var docs = {};\n var docList = [];\n store.statementsMatching(subject).forEach(function (st) {\n docs[st.why.uri] = 1;\n });\n store.statementsMatching(undefined, undefined, subject).forEach(function (st) {\n docs[st.why.uri] = 2;\n });\n for (var d in docs) docList.push(docs[d], d);\n docList.sort();\n for (var i = 0; i < docList.length; i++) {\n var uri = docList[i][1];\n if (uri && store.updater.editable(uri)) {\n store = store.sym(uri);\n break;\n }\n }\n }\n\n // 3. In a workspace store\n // @@ TODO: Can probably remove _followeach (not done this time because the commit is a very safe refactor)\n var _followeach = function _followeach(kb, subject, path) {\n if (path.length === 0) return [subject];\n var oo = kb.each(subject, path[0]);\n var res = [];\n for (var _i = 0; _i < oo.length; _i++) {\n res = res.concat(_followeach(kb, oo[_i], path.slice(1)));\n }\n return res;\n };\n var date = '2014'; // @@@@@@@@@@@@ pass as parameter\n\n if (store) {\n // mention(\"@@ Ok, we have a store <\" + store.uri + \">.\");\n renderFormsFor(store, subject);\n } else {\n complain('No suitable store is known, to edit <' + subject.uri + '>.');\n var foobarbaz = UI.login.selectWorkspace(dom, function (ws) {\n mention('Workspace selected OK: ' + ws);\n var activities = store.each(undefined, ns.space('workspace'), ws);\n for (var j = 0; j < activities.length; j++) {\n var act = activities[j];\n var subjectDoc2 = store.any(ws, ns.space('store'));\n var start = store.any(ws, ns.cal('dtstart')).value();\n var end = store.any(ws, ns.cal('dtend')).value();\n if (subjectDoc2 && start && end && start <= date && end > date) {\n renderFormsFor(subjectDoc2, subject);\n break;\n } else {\n complain('Note no suitable annotation store in activity: ' + act);\n }\n }\n });\n box.appendChild(foobarbaz);\n }\n return box;\n }\n};\n//# sourceMappingURL=pane.js.map","\"use strict\";\n\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = void 0;\nvar _solidLogic = require(\"solid-logic\");\nvar _solidUi = require(\"solid-ui\");\nfunction _regeneratorRuntime() { \"use strict\"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = \"function\" == typeof Symbol ? Symbol : {}, a = i.iterator || \"@@iterator\", c = i.asyncIterator || \"@@asyncIterator\", u = i.toStringTag || \"@@toStringTag\"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, \"\"); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, \"_invoke\", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: \"normal\", arg: t.call(e, r) }; } catch (t) { return { type: \"throw\", arg: t }; } } e.wrap = wrap; var h = \"suspendedStart\", l = \"suspendedYield\", f = \"executing\", s = \"completed\", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { [\"next\", \"throw\", \"return\"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if (\"throw\" !== c.type) { var u = c.arg, h = u.value; return h && \"object\" == _typeof(h) && n.call(h, \"__await\") ? e.resolve(h.__await).then(function (t) { invoke(\"next\", t, i, a); }, function (t) { invoke(\"throw\", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke(\"throw\", t, i, a); }); } a(c.arg); } var r; o(this, \"_invoke\", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error(\"Generator is already running\"); if (o === s) { if (\"throw\" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if (\"next\" === n.method) n.sent = n._sent = n.arg;else if (\"throw\" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else \"return\" === n.method && n.abrupt(\"return\", n.arg); o = f; var p = tryCatch(e, r, n); if (\"normal\" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } \"throw\" === p.type && (o = s, n.method = \"throw\", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, \"throw\" === n && e.iterator[\"return\"] && (r.method = \"return\", r.arg = t, maybeInvokeDelegate(e, r), \"throw\" === r.method) || \"return\" !== n && (r.method = \"throw\", r.arg = new TypeError(\"The iterator does not provide a '\" + n + \"' method\")), y; var i = tryCatch(o, e.iterator, r.arg); if (\"throw\" === i.type) return r.method = \"throw\", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, \"return\" !== r.method && (r.method = \"next\", r.arg = t), r.delegate = null, y) : a : (r.method = \"throw\", r.arg = new TypeError(\"iterator result is not an object\"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = \"normal\", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: \"root\" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || \"\" === e) { var r = e[a]; if (r) return r.call(e); if (\"function\" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + \" is not iterable\"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, \"constructor\", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, \"constructor\", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, \"GeneratorFunction\"), e.isGeneratorFunction = function (t) { var e = \"function\" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || \"GeneratorFunction\" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, \"GeneratorFunction\")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, \"Generator\"), define(g, a, function () { return this; }), define(g, \"toString\", function () { return \"[object Generator]\"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = \"next\", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) \"t\" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if (\"throw\" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = \"throw\", a.arg = e, r.next = n, o && (r.method = \"next\", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if (\"root\" === i.tryLoc) return handle(\"end\"); if (i.tryLoc <= this.prev) { var c = n.call(i, \"catchLoc\"), u = n.call(i, \"finallyLoc\"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error(\"try statement without catch or finally\"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, \"finallyLoc\") && this.prev < o.finallyLoc) { var i = o; break; } } i && (\"break\" === t || \"continue\" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = \"next\", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if (\"throw\" === t.type) throw t.arg; return \"break\" === t.type || \"continue\" === t.type ? this.next = t.arg : \"return\" === t.type ? (this.rval = this.arg = t.arg, this.method = \"return\", this.next = \"end\") : \"normal\" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, \"catch\": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if (\"throw\" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error(\"illegal catch attempt\"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, \"next\" === this.method && (this.arg = t), y; } }, e; }\nfunction asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }\nfunction _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err); } _next(undefined); }); }; } /* Home Pane\n **\n ** The home pane is avaiable everywhere and allows a user\n ** to\n ** - keep track of their stuff\n ** - make new things, and possibly\n ** - keep track of accounts and workspaces etc\n **\n */\nvar HomePaneSource = {\n icon: _solidUi.icons.iconBase + 'noun_547570.svg',\n // noun_25830\n\n global: true,\n name: 'home',\n // Does the subject deserve an home pane?\n //\n // yes, always!\n //\n label: function label() {\n return 'home';\n },\n render: function render(subject, context) {\n var dom = context.dom;\n var showContent = /*#__PURE__*/function () {\n var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {\n var homePaneContext, creationDiv, creationContext, relevantPanes;\n return _regeneratorRuntime().wrap(function _callee$(_context) {\n while (1) switch (_context.prev = _context.next) {\n case 0:\n homePaneContext = {\n div: div,\n dom: dom,\n statusArea: div,\n me: me\n };\n /*\n div.appendChild(dom.createElement('h4')).textContent = 'Login status'\n var loginStatusDiv = div.appendChild(context.dom.createElement('div'))\n // TODO: Find out what the actual type is:\n type UriType = unknown;\n loginStatusDiv.appendChild(UI.login.loginStatusBox(context.dom, () => {\n // Here we know new log in status\n }))\n */\n div.appendChild(dom.createElement('h4')).textContent = 'Create new thing somewhere';\n creationDiv = div.appendChild(dom.createElement('div'));\n creationContext = {\n div: creationDiv,\n dom: dom,\n statusArea: div,\n me: me\n };\n _context.next = 6;\n return _solidUi.login.filterAvailablePanes(context.session.paneRegistry.list);\n case 6:\n relevantPanes = _context.sent;\n _solidUi.create.newThingUI(creationContext, context, relevantPanes); // newUI Have to pass panes down\n\n _solidUi.login.registrationList(homePaneContext, {}).then(function () {});\n case 9:\n case \"end\":\n return _context.stop();\n }\n }, _callee);\n }));\n return function showContent() {\n return _ref.apply(this, arguments);\n };\n }();\n var div = dom.createElement('div');\n var me = _solidLogic.authn.currentUser(); // this will be incorrect if not logged in\n\n showContent();\n return div;\n }\n}; // pane object\n\n// ends\nvar _default = exports[\"default\"] = HomePaneSource;\n//# sourceMappingURL=homePane.js.map","\"use strict\";\n\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = void 0;\nvar _solidUi = require(\"solid-ui\");\nvar _rdflib = require(\"rdflib\");\nvar _marked = require(\"marked\");\nvar DOMPurify = _interopRequireWildcard(require(\"dompurify\"));\nfunction _getRequireWildcardCache(e) { if (\"function\" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }\nfunction _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || \"object\" != _typeof(e) && \"function\" != typeof e) return { \"default\": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if (\"default\" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n[\"default\"] = e, t && t.set(e, n), n; }\n/* Human-readable Pane\n **\n ** This outline pane contains the document contents for an HTML document\n ** This is for peeking at a page, because the user might not want to leave the data browser.\n */\n\nvar humanReadablePane = {\n icon: _solidUi.icons.originalIconBase + 'tango/22-text-x-generic.png',\n name: 'humanReadable',\n label: function label(subject, context) {\n var kb = context.session.store;\n\n // See also the source pane, which has lower precedence.\n\n var allowed = ['text/plain', 'text/html', 'text/markdown', 'application/xhtml+xml', 'image/png', 'image/jpeg', 'application/pdf', 'video/mp4'];\n var hasContentTypeIn = function hasContentTypeIn(kb, x, displayables) {\n var cts = kb.fetcher.getHeader(x, 'content-type');\n if (cts) {\n for (var j = 0; j < cts.length; j++) {\n for (var k = 0; k < displayables.length; k++) {\n if (cts[j].indexOf(displayables[k]) >= 0) {\n return true;\n }\n }\n }\n }\n return false;\n };\n\n // This data could come from a fetch OR from ldp container\n var hasContentTypeIn2 = function hasContentTypeIn2(kb, x, displayables) {\n var t = kb.findTypeURIs(subject);\n for (var k = 0; k < displayables.length; k++) {\n if (_rdflib.Util.mediaTypeClass(displayables[k]).uri in t) {\n return true;\n }\n }\n return false;\n };\n if (!subject.uri) return null; // no bnodes\n\n var t = kb.findTypeURIs(subject);\n if (t[_solidUi.ns.link('WebPage').uri]) return 'view';\n if (hasContentTypeIn(kb, subject, allowed) || hasContentTypeIn2(kb, subject, allowed)) {\n return 'View';\n }\n return null;\n },\n render: function render(subject, context) {\n var myDocument = context.dom;\n var div = myDocument.createElement('div');\n var kb = context.session.store;\n var cts = kb.fetcher.getHeader(subject.doc(), 'content-type');\n var ct = cts ? cts[0] : null;\n if (ct) {\n // console.log('humanReadablePane: c-t:' + ct)\n } else {\n console.log('humanReadablePane: unknown content-type?');\n }\n\n // @@ When we can, use CSP to turn off scripts within the iframe\n div.setAttribute('class', 'docView');\n var element = ct === 'text/markdown' ? 'DIV' : 'IFRAME';\n var frame = myDocument.createElement(element);\n\n // render markdown to html\n var markdownHtml = function markdownHtml() {\n kb.fetcher.webOperation('GET', subject.uri).then(function (response) {\n var markdownText = response.responseText;\n var lines = Math.min(30, markdownText.split(/\\n/).length + 5);\n var res = _marked.marked.parse(markdownText);\n var clean = DOMPurify.sanitize(res);\n frame.innerHTML = clean;\n frame.setAttribute('class', 'doc');\n frame.setAttribute('style', \"border: 1px solid; padding: 1em; height: \".concat(lines, \"em; width: 800px; resize: both; overflow: auto;\"));\n });\n };\n if (ct === 'text/markdown') {\n markdownHtml();\n } else if (ct !== 'text/html') {\n // get with authenticated fetch\n kb.fetcher._fetch(subject.uri).then(function (response) {\n return response.blob();\n }).then(function (blob) {\n var objectURL = URL.createObjectURL(blob);\n frame.setAttribute('src', objectURL); // w640 h480 //\n frame.setAttribute('class', 'doc');\n frame.setAttribute('style', \"border: 1px solid; padding: 1em; height:120em; width:80em; resize: both; overflow: auto;\");\n });\n } else {\n frame.setAttribute('src', subject.uri); // allow-same-origin\n frame.setAttribute('class', 'doc');\n frame.setAttribute('style', 'resize = both; height:120em; width:80em;');\n }\n // @@ Note below - if we set ANY sandbox, then Chrome and Safari won't display it if it is PDF.\n // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe\n // You can't have any sandbox and allow plugins.\n // We could sandbox only HTML files I suppose.\n // HTML5 bug: https://lists.w3.org/Archives/Public/public-html/2011Jun/0330.html\n\n // iframe.setAttribute('sandbox', 'allow-same-origin allow-forms'); // allow-scripts ?? no documents should be static\n\n // iframe.setAttribute('height', '480')\n // iframe.setAttribute('width', '640')\n var tr = myDocument.createElement('TR');\n tr.appendChild(frame);\n div.appendChild(tr);\n return div;\n }\n};\nvar _default = exports[\"default\"] = humanReadablePane; // ends\n//# sourceMappingURL=humanReadablePane.js.map","\"use strict\";\n\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.imagePane = void 0;\nvar UI = _interopRequireWildcard(require(\"solid-ui\"));\nfunction _getRequireWildcardCache(e) { if (\"function\" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }\nfunction _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || \"object\" != _typeof(e) && \"function\" != typeof e) return { \"default\": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if (\"default\" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n[\"default\"] = e, t && t.set(e, n), n; }\n/* Image Pane\n **\n ** This outline pane contains the document contents for an Image document\n */\n\nvar imagePane = exports.imagePane = {\n icon: UI.icons.originalIconBase + 'tango/22-image-x-generic.png',\n name: 'image',\n label: function label(subject, context) {\n var store = context.session.store;\n if (!store.anyStatementMatching(subject, UI.ns.rdf('type'), store.sym('http://purl.org/dc/terms/Image'))) {\n // NB: Not dc: namespace!\n return null;\n }\n\n // See also the source pane, which has lower precedence.\n\n var contentTypeMatch = function contentTypeMatch(store, x, contentTypes) {\n var cts = store.fetcher.getHeader(x, 'content-type');\n if (cts) {\n for (var j = 0; j < cts.length; j++) {\n for (var k = 0; k < contentTypes.length; k++) {\n if (cts[j].indexOf(contentTypes[k]) >= 0) {\n return true;\n }\n }\n }\n }\n return false;\n };\n var suppressed = ['application/pdf'];\n if (contentTypeMatch(store, subject, suppressed)) {\n return null;\n }\n return 'view';\n },\n render: function render(subject, context) {\n var myDocument = context.dom;\n var store = context.session.store;\n var div = myDocument.createElement('div');\n div.setAttribute('class', 'imageView');\n var img = myDocument.createElement('IMG');\n\n // get image with authenticated fetch\n store.fetcher._fetch(subject.uri).then(function (response) {\n return response.blob();\n }).then(function (myBlob) {\n var objectURL = URL.createObjectURL(myBlob);\n img.setAttribute('src', objectURL); // w640 h480 //\n });\n img.setAttribute('style', 'max-width: 100%; max-height: 100%;');\n // div.style['max-width'] = '640'\n // div.style['max-height'] = '480'\n var tr = myDocument.createElement('TR'); // why need tr?\n tr.appendChild(img);\n div.appendChild(tr);\n return div;\n }\n};\n\n// ends\n//# sourceMappingURL=imagePane.js.map","\"use strict\";\n\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"OutlineManager\", {\n enumerable: true,\n get: function get() {\n return _manager[\"default\"];\n }\n});\nexports.UI = void 0;\nObject.defineProperty(exports, \"byName\", {\n enumerable: true,\n get: function get() {\n return _paneRegistry.byName;\n }\n});\nexports.getOutliner = getOutliner;\nObject.defineProperty(exports, \"initMainPage\", {\n enumerable: true,\n get: function get() {\n return _mainPage[\"default\"];\n }\n});\nObject.defineProperty(exports, \"list\", {\n enumerable: true,\n get: function get() {\n return _paneRegistry.list;\n }\n});\nObject.defineProperty(exports, \"paneForIcon\", {\n enumerable: true,\n get: function get() {\n return _paneRegistry.paneForIcon;\n }\n});\nObject.defineProperty(exports, \"paneForPredicate\", {\n enumerable: true,\n get: function get() {\n return _paneRegistry.paneForPredicate;\n }\n});\nObject.defineProperty(exports, \"register\", {\n enumerable: true,\n get: function get() {\n return _paneRegistry.register;\n }\n});\nObject.defineProperty(exports, \"versionInfo\", {\n enumerable: true,\n get: function get() {\n return _versionInfo[\"default\"];\n }\n});\nvar _versionInfo = _interopRequireDefault(require(\"./versionInfo\"));\nvar UI = _interopRequireWildcard(require(\"solid-ui\"));\nexports.UI = UI;\nvar _solidLogic = require(\"solid-logic\");\nvar _manager = _interopRequireDefault(require(\"./outline/manager.js\"));\nvar _registerPanes = require(\"./registerPanes.js\");\nvar _paneRegistry = require(\"pane-registry\");\nvar _context = require(\"./outline/context\");\nvar _mainPage = _interopRequireDefault(require(\"./mainPage\"));\nfunction _getRequireWildcardCache(e) { if (\"function\" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }\nfunction _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || \"object\" != _typeof(e) && \"function\" != typeof e) return { \"default\": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if (\"default\" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n[\"default\"] = e, t && t.set(e, n), n; }\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { \"default\": obj }; }\n/* SOLID PANES\n **\n ** Panes are regions of the outline view in which a particular subject is\n ** displayed in a particular way.\n ** Different panes about the same subject are typically stacked vertically.\n ** Panes may be used naked or with a pane selection header.\n **\n ** The label() method has two functions: it determines whether the pane is\n ** relevant to a given subject, returning null if not.\n ** If it is relevant, then it returns a suitable tooltip for a control which selects the pane\n */\n\nfunction getOutliner(dom) {\n if (!dom.outlineManager) {\n var context = (0, _context.createContext)(dom, {\n list: _paneRegistry.list,\n paneForIcon: _paneRegistry.paneForIcon,\n paneForPredicate: _paneRegistry.paneForPredicate,\n register: _paneRegistry.register,\n byName: _paneRegistry.byName\n }, _solidLogic.store, _solidLogic.solidLogicSingleton);\n dom.outlineManager = new _manager[\"default\"](context);\n }\n return dom.outlineManager;\n}\nif (typeof window !== 'undefined') {\n getOutliner(window.document);\n}\n(0, _registerPanes.registerPanes)(function (cjsOrEsModule) {\n return (0, _paneRegistry.register)(cjsOrEsModule[\"default\"] || cjsOrEsModule);\n});\n\n// This has common outline mode functionality for the default and other other panes\n// A separate outline manager is required per DOM in cases like a browser extension\n// where there are many occurrences of window and of window.document\n// But each DOM should have just one outline manager.\n\n// export for simpler access by non-node scripts\nif (typeof window !== 'undefined') {\n ;\n window.panes = {\n getOutliner: getOutliner\n };\n}\n//# sourceMappingURL=index.js.map","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = void 0;\nvar _solidUi = require(\"solid-ui\");\nvar _rdflib = require(\"rdflib\");\n/* Internal Pane\n **\n ** This outline pane contains the properties which are\n ** internal to the user's interaction with the web, and are not normally displayed\n */\n/* global alert confirm */\n\nvar pane = {\n icon: _solidUi.icons.originalIconBase + 'tango/22-emblem-system.png',\n name: 'internal',\n label: function label() {\n return 'under the hood'; // There is often a URI even of no statements\n },\n render: function render(subject, context) {\n var dom = context.dom;\n var store = context.session.store;\n var canonizedSubject = store.canon(subject);\n var types = store.findTypeURIs(canonizedSubject);\n function filter(pred) {\n if (types['http://www.w3.org/2007/ont/link#ProtocolEvent']) return true; // display everything for them\n var view = context.session.paneRegistry.byName('internal');\n return view && view.predicates && !!(typeof view.predicates[pred.uri] !== 'undefined');\n }\n var div = dom.createElement('div');\n div.setAttribute('class', 'internalPane');\n div.setAttribute('style', 'background-color: #ddddff; padding: 0.5em; border-radius: 1em;');\n function deleteRecursive(kb, folder) {\n var fetcher = kb.fetcher;\n if (!fetcher) {\n console.error('No fetcher available');\n return;\n }\n return new Promise(function (resolve, reject) {\n fetcher.load(folder).then(function () {\n var promises = kb.each(folder, _solidUi.ns.ldp('contains')).map(function (file) {\n if (kb.holds(file, _solidUi.ns.rdf('type'), _solidUi.ns.ldp('BasicContainer'))) {\n return deleteRecursive(kb, file);\n } else {\n console.log('deleteRecursive leaf file: ' + file);\n return fetcher.webOperation('DELETE', file.uri);\n }\n });\n Promise.all(promises).then(function () {\n console.log('deleteRecursive empty folder: ' + folder);\n fetcher.webOperation('DELETE', folder.uri).then(function () {\n console.log('Deleted Ok: ' + folder);\n resolve(undefined);\n })[\"catch\"](function (err) {\n var str = 'Unable to delete ' + folder + ': ' + err;\n console.log(str);\n reject(new Error(str));\n });\n resolve(undefined);\n }, function (err) {\n alert(err);\n reject(err);\n });\n });\n });\n }\n var isDocument = subject.uri && !subject.uri.includes('#');\n if (isDocument) {\n var controls = div.appendChild(dom.createElement('table'));\n controls.style.width = '100%';\n controls.style.margin = '1em';\n var controlRow = controls.appendChild(dom.createElement('tr'));\n var deleteCell = controlRow.appendChild(dom.createElement('td'));\n var isFolder = subject.uri && subject.uri.endsWith('/') || store.holds(subject, _solidUi.ns.rdf('type'), _solidUi.ns.ldp('Container'));\n var noun = isFolder ? 'folder' : 'file';\n if (!isProtectedUri(subject)) {\n console.log(subject);\n var deleteButton = _solidUi.widgets.deleteButtonWithCheck(dom, deleteCell, noun, function () {\n if (!confirm(\"Are you sure you want to delete \".concat(subject, \"? This cannot be undone.\"))) {\n return;\n }\n // @@ TODO Remove casing of store.fetcher\n if (!store.fetcher) {\n throw new Error('Store has no fetcher');\n }\n var promise = isFolder ? deleteRecursive(store, subject) || Promise.resolve() : store.fetcher.webOperation('DELETE', subject.uri) || Promise.resolve();\n promise.then(function () {\n var str = 'Deleted: ' + subject;\n console.log(str);\n })[\"catch\"](function (err) {\n var str = 'Unable to delete ' + subject + ': ' + err;\n console.log(str);\n alert(str);\n });\n });\n deleteButton.style = 'height: 2em;';\n deleteButton[\"class\"] = ''; // Remove hover hide\n deleteCell.appendChild(deleteButton);\n }\n var refreshCell = controlRow.appendChild(dom.createElement('td'));\n var refreshButton = _solidUi.widgets.button(dom, _solidUi.icons.iconBase + 'noun_479395.svg', 'refresh');\n refreshCell.appendChild(refreshButton);\n refreshButton.addEventListener('click', function () {\n if (!store.fetcher) {\n throw new Error('Store has no fetcher');\n }\n store.fetcher.refresh(subject, function (ok, errm) {\n var str;\n if (ok) {\n str = 'Refreshed OK: ' + subject;\n } else {\n str = 'Error refreshing: ' + subject + ': ' + errm;\n }\n console.log(str);\n alert(str);\n });\n });\n }\n var plist = store.statementsMatching(subject);\n var docURI = '';\n if (!store.fetcher) {\n throw new Error('Store has no fetcher');\n }\n if (subject.uri) {\n plist.push((0, _rdflib.st)(subject, (0, _rdflib.sym)('http://www.w3.org/2007/ont/link#uri'), subject.uri,\n // @@ TODO Remove casting\n store.fetcher.appNode));\n if (subject.uri.indexOf('#') >= 0) {\n docURI = subject.uri.split('#')[0];\n plist.push((0, _rdflib.st)(subject, (0, _rdflib.sym)('http://www.w3.org/2007/ont/link#documentURI'), subject.uri.split('#')[0],\n // @@ TODO Remove casting\n store.fetcher.appNode));\n plist.push((0, _rdflib.st)(subject, (0, _rdflib.sym)('http://www.w3.org/2007/ont/link#document'), (0, _rdflib.sym)(subject.uri.split('#')[0]), store.fetcher.appNode));\n } else {\n docURI = subject.uri;\n }\n }\n if (docURI) {\n if (!store.updater) {\n throw new Error('Store has no updater');\n }\n var ed = store.updater.editable(docURI);\n if (ed) {\n plist.push((0, _rdflib.st)(subject, (0, _rdflib.sym)('http://www.w3.org/ns/rww#editable'), (0, _rdflib.literal)(ed.toString()), store.fetcher.appNode));\n }\n }\n // @@ TODO get a proper type\n var outliner = context.getOutliner(dom);\n outliner.appendPropertyTRs(div, plist, false, filter);\n plist = store.statementsMatching(undefined, undefined, subject);\n outliner.appendPropertyTRs(div, plist, true, filter);\n return div;\n },\n predicates: {\n // Predicates used for inner workings. Under the hood\n 'http://www.w3.org/2007/ont/link#request': 1,\n 'http://www.w3.org/2007/ont/link#requestedBy': 1,\n 'http://www.w3.org/2007/ont/link#source': 1,\n 'http://www.w3.org/2007/ont/link#session': 2,\n // 2= test neg but display\n 'http://www.w3.org/2007/ont/link#uri': 1,\n 'http://www.w3.org/2007/ont/link#documentURI': 1,\n 'http://www.w3.org/2007/ont/link#document': 1,\n 'http://www.w3.org/2007/ont/link#all': 1,\n // From userinput.js\n 'http://www.w3.org/2007/ont/link#Document': 1,\n 'http://www.w3.org/ns/rww#editable': 1,\n 'http://www.w3.org/2000/01/rdf-schema#seeAlso': 1,\n 'http://www.w3.org/2002/07/owl#': 1\n },\n classes: {\n // Things which are inherently already undercover\n 'http://www.w3.org/2007/ont/link#ProtocolEvent': 1\n }\n};\nfunction isProtectedUri(subject) {\n // TODO: Could make the code below smarter by removing some of the redundancy by creating a recursive function, but did not bother now\n var siteUri = subject.site().uri;\n return subject.uri === siteUri || subject.uri === siteUri + 'profile/' || subject.uri === siteUri + 'profile/card' || subject.uri === siteUri + 'settings/' || subject.uri === siteUri + 'settings/prefs.ttl' || subject.uri === siteUri + 'settings/privateTypeIndex.ttl' || subject.uri === siteUri + 'settings/publicTypeIndex.ttl' || subject.uri === siteUri + 'settings/serverSide.ttl';\n}\nvar _default = exports[\"default\"] = pane; // ends\n//# sourceMappingURL=internalPane.js.map","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.createFooter = createFooter;\nvar _solidUi = require(\"solid-ui\");\n/**\n * links in the footer\n*/\nvar SOLID_PROJECT_URL = 'https://solidproject.org';\nvar SOLID_PROJECT_NAME = 'solidproject.org';\nfunction createFooter(store) {\n (0, _solidUi.initFooter)(store, setFooterOptions());\n}\nfunction setFooterOptions() {\n return {\n solidProjectUrl: SOLID_PROJECT_URL,\n solidProjectName: SOLID_PROJECT_NAME\n };\n}\n//# sourceMappingURL=footer.js.map","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.createHeader = createHeader;\nvar _solidLogic = require(\"solid-logic\");\nvar _solidUi = require(\"solid-ui\");\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _regeneratorRuntime() { \"use strict\"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = \"function\" == typeof Symbol ? Symbol : {}, a = i.iterator || \"@@iterator\", c = i.asyncIterator || \"@@asyncIterator\", u = i.toStringTag || \"@@toStringTag\"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, \"\"); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, \"_invoke\", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: \"normal\", arg: t.call(e, r) }; } catch (t) { return { type: \"throw\", arg: t }; } } e.wrap = wrap; var h = \"suspendedStart\", l = \"suspendedYield\", f = \"executing\", s = \"completed\", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { [\"next\", \"throw\", \"return\"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if (\"throw\" !== c.type) { var u = c.arg, h = u.value; return h && \"object\" == _typeof(h) && n.call(h, \"__await\") ? e.resolve(h.__await).then(function (t) { invoke(\"next\", t, i, a); }, function (t) { invoke(\"throw\", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke(\"throw\", t, i, a); }); } a(c.arg); } var r; o(this, \"_invoke\", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error(\"Generator is already running\"); if (o === s) { if (\"throw\" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if (\"next\" === n.method) n.sent = n._sent = n.arg;else if (\"throw\" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else \"return\" === n.method && n.abrupt(\"return\", n.arg); o = f; var p = tryCatch(e, r, n); if (\"normal\" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } \"throw\" === p.type && (o = s, n.method = \"throw\", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, \"throw\" === n && e.iterator[\"return\"] && (r.method = \"return\", r.arg = t, maybeInvokeDelegate(e, r), \"throw\" === r.method) || \"return\" !== n && (r.method = \"throw\", r.arg = new TypeError(\"The iterator does not provide a '\" + n + \"' method\")), y; var i = tryCatch(o, e.iterator, r.arg); if (\"throw\" === i.type) return r.method = \"throw\", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, \"return\" !== r.method && (r.method = \"next\", r.arg = t), r.delegate = null, y) : a : (r.method = \"throw\", r.arg = new TypeError(\"iterator result is not an object\"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = \"normal\", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: \"root\" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || \"\" === e) { var r = e[a]; if (r) return r.call(e); if (\"function\" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + \" is not iterable\"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, \"constructor\", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, \"constructor\", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, \"GeneratorFunction\"), e.isGeneratorFunction = function (t) { var e = \"function\" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || \"GeneratorFunction\" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, \"GeneratorFunction\")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, \"Generator\"), define(g, a, function () { return this; }), define(g, \"toString\", function () { return \"[object Generator]\"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = \"next\", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) \"t\" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if (\"throw\" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = \"throw\", a.arg = e, r.next = n, o && (r.method = \"next\", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if (\"root\" === i.tryLoc) return handle(\"end\"); if (i.tryLoc <= this.prev) { var c = n.call(i, \"catchLoc\"), u = n.call(i, \"finallyLoc\"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error(\"try statement without catch or finally\"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, \"finallyLoc\") && this.prev < o.finallyLoc) { var i = o; break; } } i && (\"break\" === t || \"continue\" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = \"next\", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if (\"throw\" === t.type) throw t.arg; return \"break\" === t.type || \"continue\" === t.type ? this.next = t.arg : \"return\" === t.type ? (this.rval = this.arg = t.arg, this.method = \"return\", this.next = \"end\") : \"normal\" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, \"catch\": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if (\"throw\" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error(\"illegal catch attempt\"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, \"next\" === this.method && (this.arg = t), y; } }, e; }\nfunction asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }\nfunction _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err); } _next(undefined); }); }; }\n/**\n * menu icons\n*/\nvar HELP_MENU_ICON = _solidUi.icons.iconBase + 'noun_help.svg';\nvar SOLID_ICON_URL = 'https://solidproject.org/assets/img/solid-emblem.svg';\n\n/**\n * menu elements\n*/\nvar USER_GUIDE_MENU_ITEM = 'User guide';\nvar REPORT_A_PROBLEM_MENU_ITEM = 'Report a problem';\nvar SHOW_YOUR_PROFILE_MENU_ITEM = 'Show your profile';\nvar LOG_OUT_MENU_ITEM = 'Log out';\n/**\n * URLS\n */\nvar USER_GUIDE_MENU_URL = 'https://solidos.github.io/userguide/';\nvar REPORT_A_PROBLEM_MENU_URL = 'https://github.com/solidos/solidos/issues';\nfunction createHeader(_x, _x2) {\n return _createHeader.apply(this, arguments);\n}\nfunction _createHeader() {\n _createHeader = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(store, outliner) {\n return _regeneratorRuntime().wrap(function _callee$(_context) {\n while (1) switch (_context.prev = _context.next) {\n case 0:\n _context.t0 = _solidUi.initHeader;\n _context.t1 = store;\n _context.next = 4;\n return setUserMenu(outliner);\n case 4:\n _context.t2 = _context.sent;\n _context.t3 = setHeaderOptions();\n (0, _context.t0)(_context.t1, _context.t2, _context.t3);\n case 7:\n case \"end\":\n return _context.stop();\n }\n }, _callee);\n }));\n return _createHeader.apply(this, arguments);\n}\nfunction setHeaderOptions() {\n var helpMenuList = [{\n label: USER_GUIDE_MENU_ITEM,\n url: USER_GUIDE_MENU_URL,\n target: '_blank'\n }, {\n label: REPORT_A_PROBLEM_MENU_ITEM,\n url: REPORT_A_PROBLEM_MENU_URL,\n target: '_blank'\n }];\n var headerOptions = {\n logo: SOLID_ICON_URL,\n helpIcon: HELP_MENU_ICON,\n helpMenuList: helpMenuList\n };\n return headerOptions;\n}\nfunction setUserMenu(_x3) {\n return _setUserMenu.apply(this, arguments);\n}\nfunction _setUserMenu() {\n _setUserMenu = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(outliner) {\n var showProfile, logOut, userMenuList;\n return _regeneratorRuntime().wrap(function _callee2$(_context2) {\n while (1) switch (_context2.prev = _context2.next) {\n case 0:\n showProfile = {\n label: SHOW_YOUR_PROFILE_MENU_ITEM,\n onclick: function onclick() {\n return openUserProfile(outliner);\n }\n };\n logOut = {\n label: LOG_OUT_MENU_ITEM,\n onclick: function onclick() {\n _solidLogic.authSession.logout();\n }\n }; // the order of the menu is important here, show profile first and logout last\n userMenuList = [showProfile];\n _context2.t0 = userMenuList;\n _context2.next = 6;\n return getMenuItems(outliner);\n case 6:\n _context2.t1 = _context2.sent;\n userMenuList = _context2.t0.concat.call(_context2.t0, _context2.t1);\n userMenuList.push(logOut);\n return _context2.abrupt(\"return\", userMenuList);\n case 10:\n case \"end\":\n return _context2.stop();\n }\n }, _callee2);\n }));\n return _setUserMenu.apply(this, arguments);\n}\nfunction openUserProfile(outliner) {\n outliner.GotoSubject(_solidLogic.authn.currentUser(), true, undefined, true, undefined);\n location.reload();\n}\nfunction getMenuItems(_x4) {\n return _getMenuItems.apply(this, arguments);\n}\nfunction _getMenuItems() {\n _getMenuItems = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(outliner) {\n var items;\n return _regeneratorRuntime().wrap(function _callee3$(_context3) {\n while (1) switch (_context3.prev = _context3.next) {\n case 0:\n _context3.next = 2;\n return outliner.getDashboardItems();\n case 2:\n items = _context3.sent;\n return _context3.abrupt(\"return\", items.map(function (element) {\n return {\n label: element.label,\n onclick: function onclick() {\n return openDashboardPane(outliner, element.tabName || element.paneName);\n }\n };\n }));\n case 4:\n case \"end\":\n return _context3.stop();\n }\n }, _callee3);\n }));\n return _getMenuItems.apply(this, arguments);\n}\nfunction openDashboardPane(_x5, _x6) {\n return _openDashboardPane.apply(this, arguments);\n}\nfunction _openDashboardPane() {\n _openDashboardPane = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(outliner, pane) {\n return _regeneratorRuntime().wrap(function _callee4$(_context4) {\n while (1) switch (_context4.prev = _context4.next) {\n case 0:\n outliner.showDashboard({\n pane: pane\n });\n case 1:\n case \"end\":\n return _context4.stop();\n }\n }, _callee4);\n }));\n return _openDashboardPane.apply(this, arguments);\n}\n//# sourceMappingURL=header.js.map","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = initMainPage;\nvar _index = require(\"../index\");\nvar _header = require(\"./header\");\nvar _footer = require(\"./footer\");\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _regeneratorRuntime() { \"use strict\"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = \"function\" == typeof Symbol ? Symbol : {}, a = i.iterator || \"@@iterator\", c = i.asyncIterator || \"@@asyncIterator\", u = i.toStringTag || \"@@toStringTag\"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, \"\"); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, \"_invoke\", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: \"normal\", arg: t.call(e, r) }; } catch (t) { return { type: \"throw\", arg: t }; } } e.wrap = wrap; var h = \"suspendedStart\", l = \"suspendedYield\", f = \"executing\", s = \"completed\", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { [\"next\", \"throw\", \"return\"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if (\"throw\" !== c.type) { var u = c.arg, h = u.value; return h && \"object\" == _typeof(h) && n.call(h, \"__await\") ? e.resolve(h.__await).then(function (t) { invoke(\"next\", t, i, a); }, function (t) { invoke(\"throw\", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke(\"throw\", t, i, a); }); } a(c.arg); } var r; o(this, \"_invoke\", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error(\"Generator is already running\"); if (o === s) { if (\"throw\" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if (\"next\" === n.method) n.sent = n._sent = n.arg;else if (\"throw\" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else \"return\" === n.method && n.abrupt(\"return\", n.arg); o = f; var p = tryCatch(e, r, n); if (\"normal\" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } \"throw\" === p.type && (o = s, n.method = \"throw\", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, \"throw\" === n && e.iterator[\"return\"] && (r.method = \"return\", r.arg = t, maybeInvokeDelegate(e, r), \"throw\" === r.method) || \"return\" !== n && (r.method = \"throw\", r.arg = new TypeError(\"The iterator does not provide a '\" + n + \"' method\")), y; var i = tryCatch(o, e.iterator, r.arg); if (\"throw\" === i.type) return r.method = \"throw\", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, \"return\" !== r.method && (r.method = \"next\", r.arg = t), r.delegate = null, y) : a : (r.method = \"throw\", r.arg = new TypeError(\"iterator result is not an object\"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = \"normal\", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: \"root\" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || \"\" === e) { var r = e[a]; if (r) return r.call(e); if (\"function\" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + \" is not iterable\"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, \"constructor\", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, \"constructor\", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, \"GeneratorFunction\"), e.isGeneratorFunction = function (t) { var e = \"function\" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || \"GeneratorFunction\" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, \"GeneratorFunction\")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, \"Generator\"), define(g, a, function () { return this; }), define(g, \"toString\", function () { return \"[object Generator]\"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = \"next\", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) \"t\" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if (\"throw\" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = \"throw\", a.arg = e, r.next = n, o && (r.method = \"next\", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if (\"root\" === i.tryLoc) return handle(\"end\"); if (i.tryLoc <= this.prev) { var c = n.call(i, \"catchLoc\"), u = n.call(i, \"finallyLoc\"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error(\"try statement without catch or finally\"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, \"finallyLoc\") && this.prev < o.finallyLoc) { var i = o; break; } } i && (\"break\" === t || \"continue\" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = \"next\", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if (\"throw\" === t.type) throw t.arg; return \"break\" === t.type || \"continue\" === t.type ? this.next = t.arg : \"return\" === t.type ? (this.rval = this.arg = t.arg, this.method = \"return\", this.next = \"end\") : \"normal\" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, \"catch\": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if (\"throw\" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error(\"illegal catch attempt\"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, \"next\" === this.method && (this.arg = t), y; } }, e; }\nfunction asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }\nfunction _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err); } _next(undefined); }); }; } /* Main Page\n **\n ** This code is called in mashlib and renders the header and footer of the Databrowser.\n */\nfunction initMainPage(_x, _x2) {\n return _initMainPage.apply(this, arguments);\n}\nfunction _initMainPage() {\n _initMainPage = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(store, uri) {\n var outliner, subject, header, footer;\n return _regeneratorRuntime().wrap(function _callee$(_context) {\n while (1) switch (_context.prev = _context.next) {\n case 0:\n outliner = (0, _index.getOutliner)(document);\n uri = uri || window.location.href;\n subject = uri;\n if (typeof uri === 'string') subject = store.sym(uri);\n outliner.GotoSubject(subject, true, undefined, true, undefined);\n _context.next = 7;\n return (0, _header.createHeader)(store, outliner);\n case 7:\n header = _context.sent;\n footer = (0, _footer.createFooter)(store);\n return _context.abrupt(\"return\", Promise.all([header, footer]));\n case 10:\n case \"end\":\n return _context.stop();\n }\n }, _callee);\n }));\n return _initMainPage.apply(this, arguments);\n}\n//# sourceMappingURL=index.js.map","\"use strict\";\n\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.n3Pane = void 0;\nvar UI = _interopRequireWildcard(require(\"solid-ui\"));\nfunction _getRequireWildcardCache(e) { if (\"function\" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }\nfunction _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || \"object\" != _typeof(e) && \"function\" != typeof e) return { \"default\": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if (\"default\" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n[\"default\"] = e, t && t.set(e, n), n; }\n/* Notation3 content Pane\n **\n ** This pane shows the content of a particular RDF resource\n ** or at least the RDF semantics we attribute to that resource,\n ** in generated N3 syntax.\n */\n\nvar ns = UI.ns;\nvar n3Pane = exports.n3Pane = {\n icon: UI.icons.originalIconBase + 'w3c/n3_smaller.png',\n name: 'n3',\n audience: [ns.solid('Developer')],\n label: function label(subject, context) {\n var store = context.session.store;\n if ('http://www.w3.org/2007/ont/link#ProtocolEvent' in store.findTypeURIs(subject)) {\n return null;\n }\n var n = store.statementsMatching(undefined, undefined, undefined, subject).length;\n if (n === 0) return null;\n return 'Data (' + n + ') as N3';\n },\n render: function render(subject, context) {\n var myDocument = context.dom;\n var kb = context.session.store;\n var div = myDocument.createElement('div');\n div.setAttribute('class', 'n3Pane');\n // Because of smushing etc, this will not be a copy of the original source\n // We could instead either fetch and re-parse the source,\n // or we could keep all the pre-smushed triples.\n var sts = kb.statementsMatching(undefined, undefined, undefined, subject); // @@ slow with current store!\n /*\n var kludge = kb.formula([]) // No features\n for (var i=0; i< sts.length; i++) {\n s = sts[i]\n kludge.add(s.subject, s.predicate, s.object)\n }\n */\n var sz = UI.rdf.Serializer(kb);\n sz.suggestNamespaces(kb.namespaces);\n sz.setBase(subject.uri);\n var str = sz.statementsToN3(sts);\n var pre = myDocument.createElement('PRE');\n pre.appendChild(myDocument.createTextNode(str));\n div.appendChild(pre);\n return div;\n }\n};\n//# sourceMappingURL=n3Pane.js.map","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.createContext = createContext;\nvar _index = require(\"../index\");\nfunction createContext(dom, paneRegistry, store, logic) {\n return {\n dom: dom,\n getOutliner: _index.getOutliner,\n session: {\n paneRegistry: paneRegistry,\n store: store,\n logic: logic\n }\n };\n}\n//# sourceMappingURL=context.js.map","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.licenseOptions = licenseOptions;\nexports.licenseURI = void 0;\nvar _solidLogic = require(\"solid-logic\");\n// This was a student project to\n// allow the user to chose favoite CC license terms and have them highlighted\n\n// tabulator.options becaome UI.licenseOptions\n// Possible future alternative directoons: Store license preferences in a solid preferences file\n\nvar licenseURI = exports.licenseURI = ['http://creativecommons.org/licenses/by-nc-nd/3.0/', 'http://creativecommons.org/licenses/by-nc-sa/3.0/', 'http://creativecommons.org/licenses/by-nc/3.0/', 'http://creativecommons.org/licenses/by-nd/3.0/', 'http://creativecommons.org/licenses/by-sa/3.0/', 'http://creativecommons.org/licenses/by/3.0/'];\nvar names = ['BY-NC-ND', 'BY-NC-SA', 'BY-NC', 'BY-ND', 'BY-SA', 'BY'];\nfunction licenseOptions() {\n this.options = {};\n this.references = [];\n this.checkedLicenses = [];\n this.openCheckBoxWindow = function () {\n this[\"this\"].display = window.open(' ', 'NewWin', 'menubar=0,location=no,status=no,directories=no,toolbar=no,scrollbars=yes,height=200,width=200');\n };\n var message = \"
\";\n var lics = this.checkedLicenses;\n for (var kk = 0; kk < lics.length; kk++) {\n message += \"CC: ' + names[kk] + '
';\n }\n message += \"
[Select All] \"; // @@ FIXME\n message += \" [Deselect All]\"; // @@ FIXME\n message += '
';\n this.display.document.write(message);\n this.display.document.close();\n var i;\n for (i = 0; i < 6; i++) {\n this.references[i] = this[\"this\"].display.document.checkboxes.elements[i];\n }\n this.selectAll = function () {\n var i;\n for (i = 0; i < 6; i++) {\n this.display.document.checkboxes.elements[i].checked = true;\n this.references[i].checked = true;\n this.checkedLicenses[i] = true;\n }\n };\n this.deselectAll = function () {\n var i;\n for (i = 0; i < 6; i++) {\n this.display.document.checkboxes.elements[i].checked = false;\n this.references[i].checked = false;\n this.checkedLicenses[i] = false;\n }\n };\n this.submit = function () {\n // alert('this.submit: checked=' + this.references[0].checked)\n for (var _i = 0; _i < 6; _i++) {\n this.checkedLicenses[_i] = !!this.references[_i].checked;\n }\n };\n this.checkLicense = function checkLicense(statement) {\n var licenses = _solidLogic.store.each(statement.why, _solidLogic.store.sym('http://creativecommons.org/ns#license'), null, statement.why);\n // UI.log.info('licenses:' + statement.why + ': ' + licenses)\n for (var _i2 = 0; _i2 < licenses.length; _i2++) {\n for (var j = 0; j < this.checkedLicenses.length; j++) {\n if (this.checkedLicenses[j] && licenses[_i2].uri === licenseURI[j]) {\n return true;\n // theClass += ' licOkay' // icon_expand\n // break\n }\n }\n }\n return false;\n };\n return this;\n}\n\n// ends\n//# sourceMappingURL=licenseOptions.js.map","\"use strict\";\n\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = _default;\nvar paneRegistry = _interopRequireWildcard(require(\"pane-registry\"));\nvar $rdf = _interopRequireWildcard(require(\"rdflib\"));\nvar UI = _interopRequireWildcard(require(\"solid-ui\"));\nvar _solidLogic = require(\"solid-logic\");\nvar _propertyViews = require(\"./propertyViews\");\nvar _licenseOptions = require(\"./licenseOptions\");\nvar _outlineIcons = require(\"./outlineIcons.js\");\nvar _userInput = require(\"./userInput.js\");\nvar queryByExample = _interopRequireWildcard(require(\"./queryByExample.js\"));\nfunction _getRequireWildcardCache(e) { if (\"function\" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }\nfunction _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || \"object\" != _typeof(e) && \"function\" != typeof e) return { \"default\": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if (\"default\" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n[\"default\"] = e, t && t.set(e, n), n; }\nfunction _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }\nfunction _iterableToArrayLimit(r, l) { var t = null == r ? null : \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t[\"return\"] && (u = t[\"return\"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\nfunction _regeneratorRuntime() { \"use strict\"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = \"function\" == typeof Symbol ? Symbol : {}, a = i.iterator || \"@@iterator\", c = i.asyncIterator || \"@@asyncIterator\", u = i.toStringTag || \"@@toStringTag\"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, \"\"); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, \"_invoke\", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: \"normal\", arg: t.call(e, r) }; } catch (t) { return { type: \"throw\", arg: t }; } } e.wrap = wrap; var h = \"suspendedStart\", l = \"suspendedYield\", f = \"executing\", s = \"completed\", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { [\"next\", \"throw\", \"return\"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if (\"throw\" !== c.type) { var u = c.arg, h = u.value; return h && \"object\" == _typeof(h) && n.call(h, \"__await\") ? e.resolve(h.__await).then(function (t) { invoke(\"next\", t, i, a); }, function (t) { invoke(\"throw\", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke(\"throw\", t, i, a); }); } a(c.arg); } var r; o(this, \"_invoke\", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error(\"Generator is already running\"); if (o === s) { if (\"throw\" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if (\"next\" === n.method) n.sent = n._sent = n.arg;else if (\"throw\" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else \"return\" === n.method && n.abrupt(\"return\", n.arg); o = f; var p = tryCatch(e, r, n); if (\"normal\" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } \"throw\" === p.type && (o = s, n.method = \"throw\", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, \"throw\" === n && e.iterator[\"return\"] && (r.method = \"return\", r.arg = t, maybeInvokeDelegate(e, r), \"throw\" === r.method) || \"return\" !== n && (r.method = \"throw\", r.arg = new TypeError(\"The iterator does not provide a '\" + n + \"' method\")), y; var i = tryCatch(o, e.iterator, r.arg); if (\"throw\" === i.type) return r.method = \"throw\", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, \"return\" !== r.method && (r.method = \"next\", r.arg = t), r.delegate = null, y) : a : (r.method = \"throw\", r.arg = new TypeError(\"iterator result is not an object\"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = \"normal\", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: \"root\" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || \"\" === e) { var r = e[a]; if (r) return r.call(e); if (\"function\" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + \" is not iterable\"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, \"constructor\", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, \"constructor\", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, \"GeneratorFunction\"), e.isGeneratorFunction = function (t) { var e = \"function\" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || \"GeneratorFunction\" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, \"GeneratorFunction\")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, \"Generator\"), define(g, a, function () { return this; }), define(g, \"toString\", function () { return \"[object Generator]\"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = \"next\", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) \"t\" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if (\"throw\" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = \"throw\", a.arg = e, r.next = n, o && (r.method = \"next\", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if (\"root\" === i.tryLoc) return handle(\"end\"); if (i.tryLoc <= this.prev) { var c = n.call(i, \"catchLoc\"), u = n.call(i, \"finallyLoc\"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error(\"try statement without catch or finally\"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, \"finallyLoc\") && this.prev < o.finallyLoc) { var i = o; break; } } i && (\"break\" === t || \"continue\" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = \"next\", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if (\"throw\" === t.type) throw t.arg; return \"break\" === t.type || \"continue\" === t.type ? this.next = t.arg : \"return\" === t.type ? (this.rval = this.arg = t.arg, this.method = \"return\", this.next = \"end\") : \"normal\" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, \"catch\": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if (\"throw\" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error(\"illegal catch attempt\"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, \"next\" === this.method && (this.arg = t), y; } }, e; }\nfunction asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }\nfunction _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err); } _next(undefined); }); }; } /* istanbul ignore file */ /* -*- coding: utf-8-dos -*-\n Outline Mode Manager\n*/ // @@ chec\n/* global alert XPathResult sourceWidget */\n// XPathResult?\n\n// const iconHeight = '24px'\n\nfunction _default(context) {\n var dom = context.dom;\n this.document = context.dom;\n this.outlineIcons = _outlineIcons.outlineIcons;\n this.labeller = this.labeller || {};\n this.labeller.LanguagePreference = ''; // for now\n var outline = this; // Kenny: do we need this?\n var thisOutline = this;\n var selection = [];\n this.selection = selection;\n this.ancestor = UI.utils.ancestor; // make available as outline.ancestor in callbacks\n this.sparql = UI.rdf.UpdateManager;\n this.kb = _solidLogic.store;\n var kb = _solidLogic.store;\n var sf = _solidLogic.store.fetcher;\n dom.outline = this;\n this.qs = new queryByExample.QuerySource(); // Track queries in queryByExample\n\n // var selection = [] // Array of statements which have been selected\n // this.focusTd // the that is being observed\n this.UserInput = new _userInput.UserInput(this);\n this.clipboardAddress = 'tabulator:clipboard'; // Weird\n this.UserInput.clipboardInit(this.clipboardAddress);\n var outlineElement = this.outlineElement;\n this.init = function () {\n var table = getOutlineContainer();\n table.outline = this;\n };\n\n /** benchmark a function **/\n benchmark.lastkbsize = 0;\n function benchmark(f) {\n var args = [];\n for (var i = arguments.length - 1; i > 0; i--) args[i - 1] = arguments[i];\n // UI.log.debug('BENCHMARK: args=' + args.join());\n var begin = new Date().getTime();\n var returnValue = f.apply(f, args);\n var end = new Date().getTime();\n UI.log.info('BENCHMARK: kb delta: ' + (kb.statements.length - benchmark.lastkbsize) + ', time elapsed for ' + f + ' was ' + (end - begin) + 'ms');\n benchmark.lastkbsize = kb.statements.length;\n return returnValue;\n } // benchmark\n\n // / ////////////////////// Representing data\n\n // Represent an object in summary form as a table cell\n\n function appendRemoveIcon(node, subject, removeNode) {\n var image = UI.utils.AJARImage(_outlineIcons.outlineIcons.src.icon_remove_node, 'remove', undefined, dom);\n image.addEventListener('click', removeNodeIconMouseDownListener);\n // image.setAttribute('align', 'right') Causes icon to be moved down\n image.node = removeNode;\n image.setAttribute('about', subject.toNT());\n image.style.marginLeft = '5px';\n image.style.marginRight = '10px';\n // image.style.border='solid #777 1px';\n node.appendChild(image);\n return image;\n }\n this.appendAccessIcons = function (kb, node, obj) {\n if (obj.termType !== 'NamedNode') return;\n var uris = kb.uris(obj);\n uris.sort();\n var last = null;\n for (var i = 0; i < uris.length; i++) {\n if (uris[i] === last) continue;\n last = uris[i];\n thisOutline.appendAccessIcon(node, last);\n }\n };\n this.appendAccessIcon = function (node, uri) {\n if (!uri) return '';\n var docuri = UI.rdf.uri.docpart(uri);\n if (docuri.slice(0, 5) !== 'http:') return '';\n var state = sf.getState(docuri);\n var icon, alt, listener;\n switch (state) {\n case 'unrequested':\n icon = _outlineIcons.outlineIcons.src.icon_unrequested;\n alt = 'fetch';\n listener = unrequestedIconMouseDownListener;\n break;\n case 'requested':\n icon = _outlineIcons.outlineIcons.src.icon_requested;\n alt = 'fetching';\n listener = failedIconMouseDownListener; // new: can retry yello blob\n break;\n case 'fetched':\n icon = _outlineIcons.outlineIcons.src.icon_fetched;\n listener = fetchedIconMouseDownListener;\n alt = 'loaded';\n break;\n case 'failed':\n icon = _outlineIcons.outlineIcons.src.icon_failed;\n alt = 'failed';\n listener = failedIconMouseDownListener;\n break;\n case 'unpermitted':\n icon = _outlineIcons.outlineIcons.src.icon_failed;\n listener = failedIconMouseDownListener;\n alt = 'no perm';\n break;\n case 'unfetchable':\n icon = _outlineIcons.outlineIcons.src.icon_failed;\n listener = failedIconMouseDownListener;\n alt = 'cannot fetch';\n break;\n default:\n UI.log.error('?? state = ' + state);\n break;\n } // switch\n var img = UI.utils.AJARImage(icon, alt, _outlineIcons.outlineIcons.tooltips[icon].replace(/[Tt]his resource/, docuri), dom);\n img.setAttribute('uri', uri);\n img.addEventListener('click', listener); // @@ seemed to be missing 2017-08\n addButtonCallbacks(img, docuri);\n node.appendChild(img);\n return img;\n }; // appendAccessIcon\n\n /** make the td for an object (grammatical object)\n * @param obj - an RDF term\n * @param view - a VIEW function (rather than a bool asImage)\n **/\n\n this.outlineObjectTD = function outlineObjectTD(obj, view, deleteNode, statement) {\n var td = dom.createElement('td');\n td.setAttribute('style', 'margin: 0.2em; border: none; padding: 0; vertical-align: top;');\n td.setAttribute('notSelectable', 'false');\n var theClass = 'obj';\n\n // check the IPR on the data. Ok if there is any checked license which is one the document has.\n if (statement && statement.why) {\n if (_licenseOptions.licenseOptions && _licenseOptions.licenseOptions.checklicense && _licenseOptions.licenseOptions.checklicense()) {\n theClass += ' licOkay'; // flag as light green etc .licOkay {background-color: #dfd}\n }\n }\n\n // set about and put 'expand' icon\n if (obj.termType === 'NamedNode' || obj.termType === 'BlankNode' || obj.termType === 'Literal' && obj.value.slice && (obj.value.slice(0, 6) === 'ftp://' || obj.value.slice(0, 8) === 'https://' || obj.value.slice(0, 7) === 'http://')) {\n td.setAttribute('about', obj.toNT());\n td.appendChild(UI.utils.AJARImage(UI.icons.originalIconBase + 'tbl-expand-trans.png', 'expand', undefined, dom)).addEventListener('click', expandMouseDownListener);\n }\n td.setAttribute('class', theClass); // this is how you find an object\n // @@ TAKE CSS OUT OF STYLE SHEET\n if (kb.whether(obj, UI.ns.rdf('type'), UI.ns.link('Request'))) {\n td.className = 'undetermined';\n } // @@? why-timbl\n\n if (!view) {\n // view should be a function pointer\n view = viewAsBoringDefault;\n }\n td.appendChild(view(obj));\n if (deleteNode) {\n appendRemoveIcon(td, obj, deleteNode);\n }\n\n // set DOM methods\n td.tabulatorSelect = function () {\n setSelected(this, true);\n };\n td.tabulatorDeselect = function () {\n setSelected(this, false);\n };\n td.addEventListener('click', selectableTDClickListener);\n return td;\n }; // outlineObjectTD\n\n this.outlinePredicateTD = function outlinePredicateTD(predicate, newTr, inverse, internal) {\n var predicateTD = dom.createElement('TD');\n predicateTD.setAttribute('about', predicate.toNT());\n predicateTD.setAttribute('class', internal ? 'pred internal' : 'pred');\n var lab;\n switch (predicate.termType) {\n case 'BlankNode':\n // TBD\n predicateTD.className = 'undetermined';\n break;\n case 'NamedNode':\n lab = UI.utils.predicateLabelForXML(predicate, inverse);\n break;\n case 'Collection':\n // some choices of predicate\n lab = UI.utils.predicateLabelForXML(predicate.elements[0], inverse);\n }\n lab = lab.slice(0, 1).toUpperCase() + lab.slice(1);\n // if (kb.statementsMatching(predicate,rdf('type'), UI.ns.link('Request')).length) predicateTD.className='undetermined';\n\n var labelTD = dom.createElement('TD');\n labelTD.setAttribute('style', 'margin: 0.2em; border: none; padding: 0; vertical-align: top;');\n labelTD.setAttribute('notSelectable', 'true');\n labelTD.appendChild(dom.createTextNode(lab));\n predicateTD.appendChild(labelTD);\n labelTD.style.width = '100%';\n predicateTD.appendChild(termWidget.construct(dom)); // termWidget is global???\n for (var w in _outlineIcons.outlineIcons.termWidgets) {\n if (!newTr || !newTr.AJAR_statement) break; // case for TBD as predicate\n // alert(Icon.termWidgets[w]+' '+Icon.termWidgets[w].filter)\n if (_outlineIcons.outlineIcons.termWidgets[w].filter && _outlineIcons.outlineIcons.termWidgets[w].filter(newTr.AJAR_statement, 'pred', inverse)) {\n termWidget.addIcon(predicateTD, _outlineIcons.outlineIcons.termWidgets[w]);\n }\n }\n\n // set DOM methods\n predicateTD.tabulatorSelect = function () {\n setSelected(this, true);\n };\n predicateTD.tabulatorDeselect = function () {\n setSelected(this, false);\n };\n predicateTD.addEventListener('click', selectableTDClickListener);\n return predicateTD;\n }; // outlinePredicateTD\n\n /**\n * Render Tabbed set of home app panes\n *\n * @param {Object} [options] A set of options you can provide\n * @param {string} [options.selectedTab] To open a specific dashboard pane\n * @param {Function} [options.onClose] If given, will present an X for the dashboard, and call this method when clicked\n * @returns Promise<{Element}> - the div that holds the dashboard\n */\n function globalAppTabs() {\n return _globalAppTabs.apply(this, arguments);\n }\n function _globalAppTabs() {\n _globalAppTabs = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {\n var options,\n div,\n me,\n items,\n renderTab,\n renderMain,\n _args = arguments;\n return _regeneratorRuntime().wrap(function _callee$(_context) {\n while (1) switch (_context.prev = _context.next) {\n case 0:\n renderMain = function _renderMain(containerDiv, item) {\n // Items are pane names\n var pane = paneRegistry.byName(item.paneName); // 20190701\n containerDiv.innerHTML = '';\n var table = containerDiv.appendChild(dom.createElement('table'));\n var me = _solidLogic.authn.currentUser();\n thisOutline.GotoSubject(item.subject || me, true, pane, false, undefined, table);\n };\n renderTab = function _renderTab(div, item) {\n div.dataset.globalPaneName = item.tabName || item.paneName;\n div.textContent = item.label;\n };\n options = _args.length > 0 && _args[0] !== undefined ? _args[0] : {};\n console.log('globalAppTabs @@');\n div = dom.createElement('div');\n me = _solidLogic.authn.currentUser();\n if (me) {\n _context.next = 9;\n break;\n }\n alert('Must be logged in for this');\n throw new Error('Not logged in');\n case 9:\n _context.next = 11;\n return getDashboardItems();\n case 11:\n items = _context.sent;\n div.appendChild(UI.tabs.tabWidget({\n dom: dom,\n subject: me,\n items: items,\n renderMain: renderMain,\n renderTab: renderTab,\n ordered: true,\n orientation: 0,\n backgroundColor: '#eeeeee',\n // black?\n selectedTab: options.selectedTab,\n onClose: options.onClose\n }));\n return _context.abrupt(\"return\", div);\n case 14:\n case \"end\":\n return _context.stop();\n }\n }, _callee);\n }));\n return _globalAppTabs.apply(this, arguments);\n }\n this.getDashboard = globalAppTabs;\n function getDashboardItems() {\n return _getDashboardItems.apply(this, arguments);\n }\n function _getDashboardItems() {\n _getDashboardItems = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7() {\n var me, div, _yield$Promise$all, _yield$Promise$all2, books, pods, getPods, _getPods, getAddressBooks, _getAddressBooks;\n return _regeneratorRuntime().wrap(function _callee7$(_context8) {\n while (1) switch (_context8.prev = _context8.next) {\n case 0:\n _getAddressBooks = function _getAddressBooks3() {\n _getAddressBooks = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6() {\n var _context6;\n return _regeneratorRuntime().wrap(function _callee6$(_context7) {\n while (1) switch (_context7.prev = _context7.next) {\n case 0:\n _context7.prev = 0;\n _context7.next = 3;\n return UI.login.findAppInstances({\n me: me,\n div: div,\n dom: dom\n }, ns.vcard('AddressBook'));\n case 3:\n _context6 = _context7.sent;\n return _context7.abrupt(\"return\", (_context6.instances || []).map(function (book, index) {\n return {\n paneName: 'contact',\n tabName: \"contact-\".concat(index),\n label: 'Contacts',\n subject: book,\n icon: UI.icons.iconBase + 'noun_15695.svg'\n };\n }));\n case 7:\n _context7.prev = 7;\n _context7.t0 = _context7[\"catch\"](0);\n console.error('oops in globalAppTabs AddressBook');\n case 10:\n return _context7.abrupt(\"return\", []);\n case 11:\n case \"end\":\n return _context7.stop();\n }\n }, _callee6, null, [[0, 7]]);\n }));\n return _getAddressBooks.apply(this, arguments);\n };\n getAddressBooks = function _getAddressBooks2() {\n return _getAddressBooks.apply(this, arguments);\n };\n _getPods = function _getPods3() {\n _getPods = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {\n var addPodStorage, _addPodStorage, addPodStorageFromUrl, _addPodStorageFromUrl, pods, uri, podUrl, uniques;\n return _regeneratorRuntime().wrap(function _callee5$(_context5) {\n while (1) switch (_context5.prev = _context5.next) {\n case 0:\n uniques = function _uniques(nodes) {\n var uniqueNodes = [];\n nodes.forEach(function (node) {\n if (!uniqueNodes.find(function (uniqueNode) {\n return uniqueNode.equals(node);\n })) uniqueNodes.push(node);\n });\n return uniqueNodes;\n };\n _addPodStorageFromUrl = function _addPodStorageFromUrl3() {\n _addPodStorageFromUrl = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(url) {\n var podStorage, pathStorage;\n return _regeneratorRuntime().wrap(function _callee4$(_context4) {\n while (1) switch (_context4.prev = _context4.next) {\n case 0:\n podStorage = new URL(url); // check for predicate pim:Storage in containers up the path tree\n pathStorage = podStorage.pathname;\n case 2:\n if (!pathStorage.length) {\n _context4.next = 10;\n break;\n }\n pathStorage = pathStorage.substring(0, pathStorage.lastIndexOf('/'));\n _context4.next = 6;\n return addPodStorage(kb.sym(\"\".concat(podStorage.origin).concat(pathStorage, \"/\")));\n case 6:\n if (!_context4.sent) {\n _context4.next = 8;\n break;\n }\n return _context4.abrupt(\"return\");\n case 8:\n _context4.next = 2;\n break;\n case 10:\n case \"end\":\n return _context4.stop();\n }\n }, _callee4);\n }));\n return _addPodStorageFromUrl.apply(this, arguments);\n };\n addPodStorageFromUrl = function _addPodStorageFromUrl2(_x8) {\n return _addPodStorageFromUrl.apply(this, arguments);\n };\n _addPodStorage = function _addPodStorage3() {\n _addPodStorage = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(pod) {\n return _regeneratorRuntime().wrap(function _callee3$(_context3) {\n while (1) switch (_context3.prev = _context3.next) {\n case 0:\n _context3.next = 2;\n return loadContainerRepresentation(pod);\n case 2:\n if (!kb.holds(pod, ns.rdf('type'), ns.space('Storage'), pod.doc())) {\n _context3.next = 5;\n break;\n }\n pods.push(pod);\n return _context3.abrupt(\"return\", true);\n case 5:\n return _context3.abrupt(\"return\", false);\n case 6:\n case \"end\":\n return _context3.stop();\n }\n }, _callee3);\n }));\n return _addPodStorage.apply(this, arguments);\n };\n addPodStorage = function _addPodStorage2(_x7) {\n return _addPodStorage.apply(this, arguments);\n };\n _context5.prev = 5;\n _context5.next = 8;\n return kb.fetcher.load(me.doc());\n case 8:\n _context5.next = 14;\n break;\n case 10:\n _context5.prev = 10;\n _context5.t0 = _context5[\"catch\"](5);\n console.error('Unable to load profile', _context5.t0);\n return _context5.abrupt(\"return\", []);\n case 14:\n // load pod's storages from profile\n pods = kb.each(me, ns.space('storage'), null, me.doc());\n pods.map( /*#__PURE__*/function () {\n var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(pod) {\n return _regeneratorRuntime().wrap(function _callee2$(_context2) {\n while (1) switch (_context2.prev = _context2.next) {\n case 0:\n _context2.next = 2;\n return loadContainerRepresentation(pod);\n case 2:\n case \"end\":\n return _context2.stop();\n }\n }, _callee2);\n }));\n return function (_x9) {\n return _ref.apply(this, arguments);\n };\n }());\n _context5.prev = 16;\n // if uri then SolidOS is a browse.html web app\n uri = new URL(window.location.href).searchParams.get('uri');\n podUrl = uri || window.location.href;\n _context5.next = 21;\n return addPodStorageFromUrl(podUrl);\n case 21:\n _context5.next = 26;\n break;\n case 23:\n _context5.prev = 23;\n _context5.t1 = _context5[\"catch\"](16);\n console.error('cannot load container', _context5.t1);\n case 26:\n pods = uniques(pods);\n if (pods.length) {\n _context5.next = 29;\n break;\n }\n return _context5.abrupt(\"return\", []);\n case 29:\n return _context5.abrupt(\"return\", pods.map(function (pod, index) {\n function split(item) {\n return item.uri.split('//')[1].slice(0, -1);\n }\n var label = split(me).startsWith(split(pod)) ? 'Your storage' : split(pod);\n return {\n paneName: 'folder',\n tabName: \"folder-\".concat(index),\n label: label,\n subject: pod,\n icon: UI.icons.iconBase + 'noun_Cabinet_251723.svg'\n };\n }));\n case 30:\n case \"end\":\n return _context5.stop();\n }\n }, _callee5, null, [[5, 10], [16, 23]]);\n }));\n return _getPods.apply(this, arguments);\n };\n getPods = function _getPods2() {\n return _getPods.apply(this, arguments);\n };\n me = _solidLogic.authn.currentUser();\n if (me) {\n _context8.next = 7;\n break;\n }\n return _context8.abrupt(\"return\", []);\n case 7:\n div = dom.createElement('div');\n _context8.next = 10;\n return Promise.all([getAddressBooks(), getPods()]);\n case 10:\n _yield$Promise$all = _context8.sent;\n _yield$Promise$all2 = _slicedToArray(_yield$Promise$all, 2);\n books = _yield$Promise$all2[0];\n pods = _yield$Promise$all2[1];\n return _context8.abrupt(\"return\", [{\n paneName: 'home',\n label: 'Your stuff',\n icon: UI.icons.iconBase + 'noun_547570.svg'\n }, {\n paneName: 'basicPreferences',\n label: 'Preferences',\n icon: UI.icons.iconBase + 'noun_Sliders_341315_00000.svg'\n }, {\n paneName: 'editProfile',\n label: 'Edit your profile',\n icon: UI.icons.iconBase + 'noun_492246.svg'\n }].concat(books).concat(pods));\n case 15:\n case \"end\":\n return _context8.stop();\n }\n }, _callee7);\n }));\n return _getDashboardItems.apply(this, arguments);\n }\n this.getDashboardItems = getDashboardItems;\n\n /**\n * Call this method to show the global dashboard.\n *\n * @param {Object} [options] A set of options that can be passed\n * @param {string} [options.pane] To open a specific dashboard pane\n * @returns {Promise}\n */\n function showDashboard() {\n return _showDashboard.apply(this, arguments);\n }\n function _showDashboard() {\n _showDashboard = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8() {\n var options,\n dashboardContainer,\n outlineContainer,\n _tab,\n dashboard,\n tab,\n closeDashboard,\n _args8 = arguments;\n return _regeneratorRuntime().wrap(function _callee8$(_context9) {\n while (1) switch (_context9.prev = _context9.next) {\n case 0:\n closeDashboard = function _closeDashboard() {\n dashboardContainer.style.display = 'none';\n outlineContainer.style.display = 'inherit';\n };\n options = _args8.length > 0 && _args8[0] !== undefined ? _args8[0] : {};\n dashboardContainer = getDashboardContainer();\n outlineContainer = getOutlineContainer(); // reuse dashboard if already children already is inserted\n if (!(dashboardContainer.childNodes.length > 0 && options.pane)) {\n _context9.next = 12;\n break;\n }\n outlineContainer.style.display = 'none';\n dashboardContainer.style.display = 'inherit';\n _tab = dashboardContainer.querySelector(\"[data-global-pane-name=\\\"\".concat(options.pane, \"\\\"]\"));\n if (!_tab) {\n _context9.next = 11;\n break;\n }\n _tab.click();\n return _context9.abrupt(\"return\");\n case 11:\n console.warn('Did not find the referred tab in global dashboard, will open first one');\n case 12:\n _context9.next = 14;\n return globalAppTabs({\n selectedTab: options.pane,\n onClose: closeDashboard\n });\n case 14:\n dashboard = _context9.sent;\n // close the dashboard if user log out\n _solidLogic.authSession.onLogout(closeDashboard);\n\n // finally - switch to showing dashboard\n outlineContainer.style.display = 'none';\n dashboardContainer.appendChild(dashboard);\n tab = dashboardContainer.querySelector(\"[data-global-pane-name=\\\"\".concat(options.pane, \"\\\"]\"));\n if (tab) {\n tab.click();\n }\n case 20:\n case \"end\":\n return _context9.stop();\n }\n }, _callee8);\n }));\n return _showDashboard.apply(this, arguments);\n }\n this.showDashboard = showDashboard;\n function getDashboardContainer() {\n return getOrCreateContainer('GlobalDashboard');\n }\n function getOutlineContainer() {\n return getOrCreateContainer('outline');\n }\n\n /**\n * Get element with id or create a new on the fly with that id\n *\n * @param {string} id The ID of the element you want to get or create\n * @returns {HTMLElement}\n */\n function getOrCreateContainer(id) {\n return document.getElementById(id) || function () {\n var dashboardContainer = document.createElement('div');\n dashboardContainer.id = id;\n var mainContainer = document.querySelector('[role=\"main\"]') || document.body;\n return mainContainer.appendChild(dashboardContainer);\n }();\n }\n function loadContainerRepresentation(_x) {\n return _loadContainerRepresentation.apply(this, arguments);\n }\n function _loadContainerRepresentation() {\n _loadContainerRepresentation = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9(subject) {\n var response, containerTurtle;\n return _regeneratorRuntime().wrap(function _callee9$(_context10) {\n while (1) switch (_context10.prev = _context10.next) {\n case 0:\n if (kb.any(subject, ns.ldp('contains'), undefined, subject.doc())) {\n _context10.next = 6;\n break;\n }\n _context10.next = 3;\n return kb.fetcher.webOperation('GET', subject.uri, kb.fetcher.initFetchOptions(subject.uri, {\n headers: {\n accept: 'text/turtle'\n }\n }));\n case 3:\n response = _context10.sent;\n containerTurtle = response.responseText;\n $rdf.parse(containerTurtle, kb, subject.uri, 'text/turtle');\n case 6:\n case \"end\":\n return _context10.stop();\n }\n }, _callee9);\n }));\n return _loadContainerRepresentation.apply(this, arguments);\n }\n function getRelevantPanes(_x2, _x3) {\n return _getRelevantPanes.apply(this, arguments);\n }\n function _getRelevantPanes() {\n _getRelevantPanes = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10(subject, context) {\n var panes, relevantPanes, filteredPanes, firstRelevantPaneIndex, firstFilteredPaneIndex;\n return _regeneratorRuntime().wrap(function _callee10$(_context11) {\n while (1) switch (_context11.prev = _context11.next) {\n case 0:\n if (!subject.uri.endsWith('/')) {\n _context11.next = 3;\n break;\n }\n _context11.next = 3;\n return loadContainerRepresentation(subject);\n case 3:\n panes = context.session.paneRegistry;\n relevantPanes = panes.list.filter(function (pane) {\n return pane.label(subject, context) && !pane.global;\n });\n if (!(relevantPanes.length === 0)) {\n _context11.next = 7;\n break;\n }\n return _context11.abrupt(\"return\", [panes.byName('internal')]);\n case 7:\n _context11.next = 9;\n return UI.login.filterAvailablePanes(relevantPanes);\n case 9:\n filteredPanes = _context11.sent;\n if (!(filteredPanes.length === 0)) {\n _context11.next = 12;\n break;\n }\n return _context11.abrupt(\"return\", [relevantPanes[0]]);\n case 12:\n firstRelevantPaneIndex = panes.list.indexOf(relevantPanes[0]);\n firstFilteredPaneIndex = panes.list.indexOf(filteredPanes[0]); // if the first relevant pane is loaded before the panes available wrt role, we still want to offer the most relevant pane\n return _context11.abrupt(\"return\", firstRelevantPaneIndex < firstFilteredPaneIndex ? [relevantPanes[0]].concat(filteredPanes) : filteredPanes);\n case 15:\n case \"end\":\n return _context11.stop();\n }\n }, _callee10);\n }));\n return _getRelevantPanes.apply(this, arguments);\n }\n function getPane(relevantPanes, subject) {\n return relevantPanes.find(function (pane) {\n return pane.shouldGetFocus && pane.shouldGetFocus(subject);\n }) || relevantPanes[0];\n }\n function expandedHeaderTR(_x4, _x5, _x6) {\n return _expandedHeaderTR.apply(this, arguments);\n } // expandedHeaderTR\n // / //////////////////////////////////////////////////////////////////////////\n /* PANES\n **\n ** Panes are regions of the outline view in which a particular subject is\n ** displayed in a particular way. They are like views but views are for query results.\n ** subject panes are currently stacked vertically.\n */\n // / //////////////////// Specific panes are in panes/*.js\n //\n // The defaultPane is the first one registered for which the label method exists\n // Those registered first take priority as a default pane.\n // That is, those earlier in this file\n /**\n * Pane registration\n */\n // the second argument indicates whether the query button is required\n // / ///////////////////////////////////////////////////////////////////////////\n // Remove a node from the DOM so that Firefox refreshes the screen OK\n // Just deleting it cause whitespace to accumulate.\n function _expandedHeaderTR() {\n _expandedHeaderTR = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12(subject, requiredPane, options) {\n var renderPaneIconTray, _renderPaneIconTray, tr, td, header, showHeader, icon, strong;\n return _regeneratorRuntime().wrap(function _callee12$(_context13) {\n while (1) switch (_context13.prev = _context13.next) {\n case 0:\n _renderPaneIconTray = function _renderPaneIconTray3() {\n _renderPaneIconTray = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11(td) {\n var options,\n paneShownStyle,\n paneHiddenStyle,\n paneIconTray,\n relevantPanes,\n paneNumber,\n _args11 = arguments;\n return _regeneratorRuntime().wrap(function _callee11$(_context12) {\n while (1) switch (_context12.prev = _context12.next) {\n case 0:\n options = _args11.length > 1 && _args11[1] !== undefined ? _args11[1] : {};\n paneShownStyle = 'width: 24px; border-radius: 0.5em; border-top: solid #222 1px; border-left: solid #222 0.1em; border-bottom: solid #eee 0.1em; border-right: solid #eee 0.1em; margin-left: 1em; padding: 3px; background-color: #ffd;';\n paneHiddenStyle = 'width: 24px; border-radius: 0.5em; margin-left: 1em; padding: 3px';\n paneIconTray = td.appendChild(dom.createElement('nav'));\n paneIconTray.style = 'display:flex; justify-content: flex-start; align-items: center;';\n if (!options.hideList) {\n _context12.next = 9;\n break;\n }\n _context12.t0 = [];\n _context12.next = 12;\n break;\n case 9:\n _context12.next = 11;\n return getRelevantPanes(subject, context);\n case 11:\n _context12.t0 = _context12.sent;\n case 12:\n relevantPanes = _context12.t0;\n tr.firstPane = requiredPane || getPane(relevantPanes, subject);\n paneNumber = relevantPanes.indexOf(tr.firstPane);\n if (relevantPanes.length !== 1) {\n // if only one, simplify interface\n relevantPanes.forEach(function (pane, index) {\n var label = pane.label(subject, context);\n var ico = UI.utils.AJARImage(pane.icon, label, label, dom);\n ico.style = pane === tr.firstPane ? paneShownStyle : paneHiddenStyle; // init to something at least\n // ico.setAttribute('align','right'); @@ Should be better, but ffox bug pushes them down\n // ico.style.width = iconHeight\n // ico.style.height = iconHeight\n var listen = function listen(ico, pane) {\n // Freeze scope for event time\n ico.addEventListener('click', function (event) {\n var containingTable;\n // Find the containing table for this subject\n for (containingTable = td; containingTable.parentNode; containingTable = containingTable.parentNode) {\n if (containingTable.nodeName === 'TABLE') break;\n }\n if (containingTable.nodeName !== 'TABLE') {\n throw new Error('outline: internal error.');\n }\n var removePanes = function removePanes(specific) {\n for (var d = containingTable.firstChild; d; d = d.nextSibling) {\n if (typeof d.pane !== 'undefined') {\n if (!specific || d.pane === specific) {\n if (d.paneButton) {\n d.paneButton.setAttribute('class', 'paneHidden');\n d.paneButton.style = paneHiddenStyle;\n }\n removeAndRefresh(d);\n // If we just delete the node d, ffox doesn't refresh the display properly.\n // state = 'paneHidden';\n if (d.pane.requireQueryButton && containingTable.parentNode.className /* outer table */ && numberOfPanesRequiringQueryButton === 1 && dom.getElementById('queryButton')) {\n dom.getElementById('queryButton').setAttribute('style', 'display:none;');\n }\n }\n }\n }\n };\n var renderPane = function renderPane(pane) {\n var paneDiv;\n UI.log.info('outline: Rendering pane (2): ' + pane.name);\n try {\n paneDiv = pane.render(subject, context, options);\n } catch (e) {\n // Easier debugging for pane developers\n paneDiv = dom.createElement('div');\n paneDiv.setAttribute('class', 'exceptionPane');\n var pre = dom.createElement('pre');\n paneDiv.appendChild(pre);\n pre.appendChild(dom.createTextNode(UI.utils.stackString(e)));\n }\n if (pane.requireQueryButton && dom.getElementById('queryButton')) {\n dom.getElementById('queryButton').removeAttribute('style');\n }\n var second = containingTable.firstChild.nextSibling;\n var row = dom.createElement('tr');\n var cell = row.appendChild(dom.createElement('td'));\n cell.appendChild(paneDiv);\n if (second) containingTable.insertBefore(row, second);else containingTable.appendChild(row);\n row.pane = pane;\n row.paneButton = ico;\n };\n var state = ico.getAttribute('class');\n if (state === 'paneHidden') {\n if (!event.shiftKey) {\n // shift means multiple select\n removePanes();\n }\n renderPane(pane);\n ico.setAttribute('class', 'paneShown');\n ico.style = paneShownStyle;\n } else {\n removePanes(pane);\n ico.setAttribute('class', 'paneHidden');\n ico.style = paneHiddenStyle;\n }\n var numberOfPanesRequiringQueryButton = 0;\n for (var d = containingTable.firstChild; d; d = d.nextSibling) {\n if (d.pane && d.pane.requireQueryButton) {\n numberOfPanesRequiringQueryButton++;\n }\n }\n }, false);\n }; // listen\n\n listen(ico, pane);\n ico.setAttribute('class', index !== paneNumber ? 'paneHidden' : 'paneShown');\n if (index === paneNumber) tr.paneButton = ico;\n paneIconTray.appendChild(ico);\n });\n }\n return _context12.abrupt(\"return\", paneIconTray);\n case 17:\n case \"end\":\n return _context12.stop();\n }\n }, _callee11);\n }));\n return _renderPaneIconTray.apply(this, arguments);\n };\n renderPaneIconTray = function _renderPaneIconTray2(_x10) {\n return _renderPaneIconTray.apply(this, arguments);\n }; // renderPaneIconTray\n // Body of expandedHeaderTR\n tr = dom.createElement('tr');\n if (options.hover) {\n // By default no hide till hover as community deems it confusing\n tr.setAttribute('class', 'hoverControl');\n }\n td = tr.appendChild(dom.createElement('td'));\n td.setAttribute('style', 'margin: 0.2em; border: none; padding: 0; vertical-align: top;' + 'display:flex; justify-content: space-between; flex-direction: row;');\n td.setAttribute('notSelectable', 'true');\n td.setAttribute('about', subject.toNT());\n td.setAttribute('colspan', '2');\n\n // Stuff at the right about the subject\n header = td.appendChild(dom.createElement('div'));\n header.style = 'display:flex; justify-content: flex-start; align-items: center; flex-wrap: wrap;';\n showHeader = !!requiredPane;\n if (!options.solo && !showHeader) {\n icon = header.appendChild(UI.utils.AJARImage(UI.icons.originalIconBase + 'tbl-collapse.png', 'collapse', undefined, dom));\n icon.addEventListener('click', collapseMouseDownListener);\n strong = header.appendChild(dom.createElement('h1'));\n strong.appendChild(dom.createTextNode(UI.utils.label(subject)));\n strong.style = 'font-size: 150%; margin: 0 0.6em 0 0; padding: 0.1em 0.4em;';\n UI.widgets.makeDraggable(strong, subject);\n }\n _context13.t0 = header;\n _context13.next = 16;\n return renderPaneIconTray(td, {\n hideList: showHeader\n });\n case 16:\n _context13.t1 = _context13.sent;\n _context13.t0.appendChild.call(_context13.t0, _context13.t1);\n // set DOM methods\n tr.firstChild.tabulatorSelect = function () {\n setSelected(this, true);\n };\n tr.firstChild.tabulatorDeselect = function () {\n setSelected(this, false);\n };\n return _context13.abrupt(\"return\", tr);\n case 21:\n case \"end\":\n return _context13.stop();\n }\n }, _callee12);\n }));\n return _expandedHeaderTR.apply(this, arguments);\n }\n function removeAndRefresh(d) {\n var table = d.parentNode;\n var par = table.parentNode;\n var placeholder = dom.createElement('table');\n placeholder.setAttribute('style', 'width: 100%;');\n par.replaceChild(placeholder, table);\n table.removeChild(d);\n par.replaceChild(table, placeholder); // Attempt to\n }\n var propertyTable = this.propertyTable = function propertyTable(subject, table, pane, options) {\n UI.log.debug('Property table for: ' + subject);\n subject = kb.canon(subject);\n // if (!pane) pane = panes.defaultPane;\n\n if (!table) {\n // Create a new property table\n table = dom.createElement('table');\n table.setAttribute('style', 'width: 100%;');\n expandedHeaderTR(subject, pane, options).then(function (tr1) {\n table.appendChild(tr1);\n if (tr1.firstPane) {\n var paneDiv;\n try {\n UI.log.info('outline: Rendering pane (1): ' + tr1.firstPane.name);\n paneDiv = tr1.firstPane.render(subject, context, options);\n } catch (e) {\n // Easier debugging for pane developers\n paneDiv = dom.createElement('div');\n paneDiv.setAttribute('class', 'exceptionPane');\n var pre = dom.createElement('pre');\n paneDiv.appendChild(pre);\n pre.appendChild(dom.createTextNode(UI.utils.stackString(e)));\n }\n var row = dom.createElement('tr');\n var cell = row.appendChild(dom.createElement('td'));\n cell.appendChild(paneDiv);\n if (tr1.firstPane.requireQueryButton && dom.getElementById('queryButton')) {\n dom.getElementById('queryButton').removeAttribute('style');\n }\n table.appendChild(row);\n row.pane = tr1.firstPane;\n row.paneButton = tr1.paneButton;\n }\n });\n return table;\n } else {\n // New display of existing table, keeping expanded bits\n UI.log.info('Re-expand: ' + table);\n // do some other stuff here\n return table;\n }\n }; /* propertyTable */\n\n function propertyTR(doc, st, inverse) {\n var tr = doc.createElement('TR');\n tr.AJAR_statement = st;\n tr.AJAR_inverse = inverse;\n // tr.AJAR_variable = null; // @@ ?? was just 'tr.AJAR_variable'\n tr.setAttribute('predTR', 'true');\n var predicateTD = thisOutline.outlinePredicateTD(st.predicate, tr, inverse);\n tr.appendChild(predicateTD); // @@ add 'internal' to predicateTD's class for style? mno\n return tr;\n }\n this.propertyTR = propertyTR;\n\n // / ////////// Property list\n function appendPropertyTRs(parent, plist, inverse, predicateFilter) {\n // UI.log.info('@appendPropertyTRs, 'this' is %s, dom is %s, '+ // Gives 'can't access dead object'\n // 'thisOutline.document is %s', this, dom.location, thisOutline.document.location);\n // UI.log.info('@appendPropertyTRs, dom is now ' + this.document.location);\n // UI.log.info('@appendPropertyTRs, dom is now ' + thisOutline.document.location);\n UI.log.debug('Property list length = ' + plist.length);\n if (plist.length === 0) return '';\n var sel, j, k;\n if (inverse) {\n sel = function sel(x) {\n return x.subject;\n };\n plist = plist.sort(UI.utils.RDFComparePredicateSubject);\n } else {\n sel = function sel(x) {\n return x.object;\n };\n plist = plist.sort(UI.utils.RDFComparePredicateObject);\n }\n var max = plist.length;\n var _loop = function _loop() {\n // squishing together equivalent properties I think\n var s = plist[j];\n // if (s.object == parentSubject) continue; // that we knew\n\n // Avoid predicates from other panes\n if (predicateFilter && !predicateFilter(s.predicate, inverse)) return 0; // continue\n var tr = propertyTR(dom, s, inverse);\n parent.appendChild(tr);\n var predicateTD = tr.firstChild; // we need to kludge the rowspan later\n\n var defaultpropview = views.defaults[s.predicate.uri];\n\n // LANGUAGE PREFERENCES WAS AVAILABLE WITH FF EXTENSION - get from elsewhere?\n\n var dups = 0; // How many rows have the same predicate, -1?\n var langTagged = 0; // how many objects have language tags?\n var myLang = 0; // Is there one I like?\n\n for (k = 0; k + j < max && plist[j + k].predicate.sameTerm(s.predicate); k++) {\n if (k > 0 && sel(plist[j + k]).sameTerm(sel(plist[j + k - 1]))) dups++;\n if (sel(plist[j + k]).lang && outline.labeller.LanguagePreference) {\n langTagged += 1;\n if (sel(plist[j + k]).lang.indexOf(outline.labeller.LanguagePreference) >= 0) {\n myLang++;\n }\n }\n }\n\n /* Display only the one in the preferred language\n ONLY in the case (currently) when all the values are tagged.\n Then we treat them as alternatives. */\n\n if (myLang > 0 && langTagged === dups + 1) {\n for (var _k = j; _k <= j + dups; _k++) {\n if (outline.labeller.LanguagePreference && sel(plist[_k]).lang.indexOf(outline.labeller.LanguagePreference) >= 0) {\n tr.appendChild(thisOutline.outlineObjectTD(sel(plist[_k]), defaultpropview, undefined, s));\n break;\n }\n }\n j += dups; // extra push\n return 0; // continue\n }\n tr.appendChild(thisOutline.outlineObjectTD(sel(s), defaultpropview, undefined, s));\n\n /* Note: showNobj shows between n to 2n objects.\n * This is to prevent the case where you have a long list of objects\n * shown, and dangling at the end is '1 more' (which is easily ignored)\n * Therefore more objects are shown than hidden.\n */\n\n tr.showNobj = function (n) {\n var predDups = k - dups;\n var show = 2 * n < predDups ? n : predDups;\n var showLaterArray = [];\n if (predDups !== 1) {\n predicateTD.setAttribute('rowspan', show === predDups ? predDups : n + 1);\n var l;\n if (show < predDups && show === 1) {\n // what case is this...\n predicateTD.setAttribute('rowspan', 2);\n }\n var displayed = 0; // The number of cells generated-1,\n // all duplicate thing removed\n for (l = 1; l < k; l++) {\n // This detects the same things\n if (!kb.canon(sel(plist[j + l])).sameTerm(kb.canon(sel(plist[j + l - 1])))) {\n displayed++;\n s = plist[j + l];\n defaultpropview = views.defaults[s.predicate.uri];\n var trObj = dom.createElement('tr');\n trObj.style.colspan = '1';\n trObj.appendChild(thisOutline.outlineObjectTD(sel(plist[j + l]), defaultpropview, undefined, s));\n trObj.AJAR_statement = s;\n trObj.AJAR_inverse = inverse;\n parent.appendChild(trObj);\n if (displayed >= show) {\n trObj.style.display = 'none';\n showLaterArray.push(trObj);\n }\n } else {\n // ToDo: show all the data sources of this statement\n UI.log.info('there are duplicates here: %s', plist[j + l - 1]);\n }\n }\n // @@a quick fix on the messing problem.\n if (show === predDups) {\n predicateTD.setAttribute('rowspan', displayed + 1);\n }\n } // end of if (predDups!==1)\n\n if (show < predDups) {\n // Add the x more here\n var moreTR = dom.createElement('tr');\n var moreTD = moreTR.appendChild(dom.createElement('td'));\n moreTD.setAttribute('style', 'margin: 0.2em; border: none; padding: 0; vertical-align: top;');\n moreTD.setAttribute('notSelectable', 'false');\n if (predDups > n) {\n // what is this for??\n var small = dom.createElement('a');\n moreTD.appendChild(small);\n var predToggle = function (f) {\n return f(predicateTD, k, dups, n);\n }(function (predicateTD, k, dups, n) {\n return function (display) {\n small.innerHTML = '';\n if (display === 'none') {\n small.appendChild(UI.utils.AJARImage(UI.icons.originalIconBase + 'tbl-more-trans.png', 'more', 'See all', dom));\n small.appendChild(dom.createTextNode(predDups - n + ' more...'));\n predicateTD.setAttribute('rowspan', n + 1);\n } else {\n small.appendChild(UI.utils.AJARImage(UI.icons.originalIconBase + 'tbl-shrink.png', '(less)', undefined, dom));\n predicateTD.setAttribute('rowspan', predDups + 1);\n }\n for (var i = 0; i < showLaterArray.length; i++) {\n var _trObj = showLaterArray[i];\n _trObj.style.display = display;\n }\n };\n }); // ???\n var current = 'none';\n var toggleObj = function toggleObj(event) {\n predToggle(current);\n current = current === 'none' ? '' : 'none';\n if (event) event.stopPropagation();\n return false; // what is this for?\n };\n toggleObj();\n small.addEventListener('click', toggleObj, false);\n } // if(predDups>n)\n parent.appendChild(moreTR);\n } // if\n }; // tr.showNobj\n\n tr.showAllobj = function () {\n tr.showNobj(k - dups);\n };\n tr.showNobj(10);\n j += k - 1; // extra push\n },\n _ret;\n for (j = 0; j < max; j++) {\n _ret = _loop();\n if (_ret === 0) continue;\n }\n } // appendPropertyTRs\n\n this.appendPropertyTRs = appendPropertyTRs;\n\n /* termWidget\n **\n */\n var termWidget = {}; // @@@@@@ global\n global.termWidget = termWidget;\n termWidget.construct = function (dom) {\n dom = dom || document;\n var td = dom.createElement('TD');\n td.setAttribute('style', 'margin: 0.2em; border: none; padding: 0; vertical-align: top;');\n td.setAttribute('class', 'iconTD');\n td.setAttribute('notSelectable', 'true');\n td.style.width = '0px';\n return td;\n };\n termWidget.addIcon = function (td, icon, listener) {\n var iconTD = td.childNodes[1];\n if (!iconTD) return;\n var width = iconTD.style.width;\n var img = UI.utils.AJARImage(icon.src, icon.alt, icon.tooltip, dom);\n width = parseInt(width);\n width = width + icon.width;\n iconTD.style.width = width + 'px';\n iconTD.appendChild(img);\n if (listener) {\n img.addEventListener('click', listener);\n }\n };\n termWidget.removeIcon = function (td, icon) {\n var iconTD = td.childNodes[1];\n var baseURI;\n if (!iconTD) return;\n var width = iconTD.style.width;\n width = parseInt(width);\n width = width - icon.width;\n iconTD.style.width = width + 'px';\n for (var x = 0; x < iconTD.childNodes.length; x++) {\n var elt = iconTD.childNodes[x];\n var eltSrc = elt.src;\n\n // ignore first '?' and everything after it //Kenny doesn't know what this is for\n try {\n baseURI = dom.location.href.split('?')[0];\n } catch (e) {\n console.log(e);\n baseURI = '';\n }\n var relativeIconSrc = UI.rdf.uri.join(icon.src, baseURI);\n if (eltSrc === relativeIconSrc) {\n iconTD.removeChild(elt);\n }\n }\n };\n termWidget.replaceIcon = function (td, oldIcon, newIcon, listener) {\n termWidget.removeIcon(td, oldIcon);\n termWidget.addIcon(td, newIcon, listener);\n };\n\n // / /////////////////////////////////////////////////// VALUE BROWSER VIEW\n\n // / /////////////////////////////////////////////////////// TABLE VIEW\n\n // Summarize a thing as a table cell\n\n /**********************\n query global vars\n ***********************/\n\n // const doesn't work in Opera\n // const BLANK_QUERY = { pat: kb.formula(), vars: [], orderBy: [] };\n // @ pat: the query pattern in an RDFIndexedFormula. Statements are in pat.statements\n // @ vars: the free variables in the query\n // @ orderBy: the variables to order the table\n\n function QueryObj() {\n this.pat = kb.formula();\n this.vars = [];\n // this.orderBy = []\n }\n var queries = [];\n queries[0] = new QueryObj();\n /*\n function querySave () {\n queries.push(queries[0])\n var choices = dom.getElementById('queryChoices')\n var next = dom.createElement('option')\n var box = dom.createElement('input')\n var index = queries.length - 1\n box.setAttribute('type', 'checkBox')\n box.setAttribute('value', index)\n choices.appendChild(box)\n choices.appendChild(dom.createTextNode('Saved query #' + index))\n choices.appendChild(dom.createElement('br'))\n next.setAttribute('value', index)\n next.appendChild(dom.createTextNode('Saved query #' + index))\n dom.getElementById('queryJump').appendChild(next)\n }\n */\n /*\n function resetQuery () {\n function resetOutliner (pat) {\n var n = pat.statements.length\n var pattern, tr\n for (let i = 0; i < n; i++) {\n pattern = pat.statements[i]\n tr = pattern.tr\n // UI.log.debug('tr: ' + tr.AJAR_statement);\n if (typeof tr !== 'undefined') {\n delete tr.AJAR_pattern\n delete tr.AJAR_variable\n }\n }\n for (let x in pat.optional) { resetOutliner(pat.optional[x]) }\n }\n resetOutliner(myQuery.pat)\n UI.utils.clearVariableNames()\n queries[0] = myQuery = new QueryObj()\n }\n */\n function addButtonCallbacks(target, fireOn) {\n UI.log.debug('Button callbacks for ' + fireOn + ' added');\n var makeIconCallback = function makeIconCallback(icon) {\n return function IconCallback(req) {\n if (req.indexOf('#') >= 0) {\n console.log('@@ makeIconCallback: Not expecting # in URI whose state changed: ' + req);\n // alert('Should have no hash in '+req)\n }\n if (!target) {\n return false;\n }\n if (!outline.ancestor(target, 'DIV')) return false;\n // if (term.termType != 'symbol') { return true } // should always ve\n if (req === fireOn) {\n target.src = icon;\n target.title = _outlineIcons.outlineIcons.tooltips[icon];\n }\n return true;\n };\n };\n sf.addCallback('request', makeIconCallback(_outlineIcons.outlineIcons.src.icon_requested));\n sf.addCallback('done', makeIconCallback(_outlineIcons.outlineIcons.src.icon_fetched));\n sf.addCallback('fail', makeIconCallback(_outlineIcons.outlineIcons.src.icon_failed));\n }\n\n // Selection support\n\n function selected(node) {\n var a = node.getAttribute('class');\n if (a && a.indexOf('selected') >= 0) return true;\n return false;\n }\n\n // These woulkd be simpler using closer variables below\n function optOnIconMouseDownListener(e) {\n // outlineIcons.src.icon_opton needed?\n var target = thisOutline.targetOf(e);\n var p = target.parentNode;\n termWidget.replaceIcon(p.parentNode, _outlineIcons.outlineIcons.termWidgets.optOn, _outlineIcons.outlineIcons.termWidgets.optOff, optOffIconMouseDownListener);\n p.parentNode.parentNode.removeAttribute('optional');\n }\n function optOffIconMouseDownListener(e) {\n // outlineIcons.src.icon_optoff needed?\n var target = thisOutline.targetOf(e);\n var p = target.parentNode;\n termWidget.replaceIcon(p.parentNode, _outlineIcons.outlineIcons.termWidgets.optOff, _outlineIcons.outlineIcons.termWidgets.optOn, optOnIconMouseDownListener);\n p.parentNode.parentNode.setAttribute('optional', 'true');\n }\n function setSelectedParent(node, inc) {\n var onIcon = _outlineIcons.outlineIcons.termWidgets.optOn;\n var offIcon = _outlineIcons.outlineIcons.termWidgets.optOff;\n for (var n = node; n.parentNode; n = n.parentNode) {\n while (true) {\n if (n.getAttribute('predTR')) {\n var num = n.getAttribute('parentOfSelected');\n if (!num) num = 0;else num = parseInt(num);\n if (num === 0 && inc > 0) {\n termWidget.addIcon(n.childNodes[0], n.getAttribute('optional') ? onIcon : offIcon, n.getAttribute('optional') ? optOnIconMouseDownListener : optOffIconMouseDownListener);\n }\n num = num + inc;\n n.setAttribute('parentOfSelected', num);\n if (num === 0) {\n n.removeAttribute('parentOfSelected');\n termWidget.removeIcon(n.childNodes[0], n.getAttribute('optional') ? onIcon : offIcon);\n }\n break;\n } else if (n.previousSibling && n.previousSibling.nodeName === 'TR') {\n n = n.previousSibling;\n } else break;\n }\n }\n }\n this.statusBarClick = function (event) {\n var target = UI.utils.getTarget(event);\n if (target.label) {\n window.content.location = target.label;\n // The following alternative does not work in the extension.\n // var s = store.sym(target.label);\n // outline.GotoSubject(s, true);\n }\n };\n this.showURI = function showURI(about) {\n if (about && dom.getElementById('UserURI')) {\n dom.getElementById('UserURI').value = about.termType === 'NamedNode' ? about.uri : ''; // blank if no URI\n }\n };\n this.showSource = function showSource() {\n if (typeof sourceWidget === 'undefined') return;\n // deselect all before going on, this is necessary because you would switch tab,\n // close tab or so on...\n for (var uri in sourceWidget.sources) {\n sourceWidget.sources[uri].setAttribute('class', '');\n } // .class doesn't work. Be careful!\n for (var i = 0; i < selection.length; i++) {\n if (!selection[i].parentNode) {\n console.log('showSource: EH? no parentNode? ' + selection[i] + '\\n');\n continue;\n }\n var st = selection[i].parentNode.AJAR_statement;\n if (!st) continue; // for root TD\n var source = st.why;\n if (source && source.uri) {\n sourceWidget.highlight(source, true);\n }\n }\n };\n this.getSelection = function getSelection() {\n return selection;\n };\n function setSelected(node, newValue) {\n // UI.log.info('selection has ' +selection.map(function(item){return item.textContent;}).join(', '));\n // UI.log.debug('@outline setSelected, intended to '+(newValue?'select ':'deselect ')+node+node.textContent);\n // if (newValue === selected(node)) return; //we might not need this anymore...\n if (node.nodeName !== 'TD') {\n UI.log.debug('down' + node.nodeName);\n throw new Error('Expected TD in setSelected: ' + node.nodeName + ' : ' + node.textContent);\n }\n UI.log.debug('pass');\n var cla = node.getAttribute('class');\n if (!cla) cla = '';\n if (newValue) {\n cla += ' selected';\n if (cla.indexOf('pred') >= 0 || cla.indexOf('obj') >= 0) {\n setSelectedParent(node, 1);\n }\n selection.push(node);\n // UI.log.info('Selecting '+node.textContent)\n\n var about = UI.utils.getTerm(node); // show uri for a newly selectedTd\n thisOutline.showURI(about);\n var st = node.AJAR_statement; // show blue cross when the why of that triple is editable\n if (typeof st === 'undefined' && node.parentNode) st = node.parentNode.AJAR_statement;\n // if (typeof st === 'undefined') return; // @@ Kludge? Click in the middle of nowhere\n if (st) {\n // don't do these for headers or base nodes\n var source = st.why;\n // var target = st.why\n var editable = _solidLogic.store.updater.editable(source.uri, kb);\n if (!editable) {\n // let target = node.parentNode.AJAR_inverse ? st.object : st.subject\n } // left hand side\n // think about this later. Because we update to the why for now.\n // alert('Target='+target+', editable='+editable+'\\nselected statement:' + st)\n if (editable && cla.indexOf('pred') >= 0) {\n termWidget.addIcon(node, _outlineIcons.outlineIcons.termWidgets.addTri);\n } // Add blue plus\n }\n } else {\n UI.log.debug('cla=$' + cla + '$');\n if (cla === 'selected') cla = ''; // for header \n cla = cla.replace(' selected', '');\n if (cla.indexOf('pred') >= 0 || cla.indexOf('obj') >= 0) {\n setSelectedParent(node, -1);\n }\n if (cla.indexOf('pred') >= 0) {\n termWidget.removeIcon(node, _outlineIcons.outlineIcons.termWidgets.addTri);\n }\n selection = selection.filter(function (x) {\n return x === node;\n });\n UI.log.info('Deselecting ' + node.textContent);\n }\n if (typeof sourceWidget !== 'undefined') thisOutline.showSource(); // Update the data sources display\n // UI.log.info('selection becomes [' +selection.map(function(item){return item.textContent;}).join(', ')+']');\n // UI.log.info('Setting className ' + cla);\n node.setAttribute('class', cla);\n }\n function deselectAll() {\n var n = selection.length;\n for (var i = n - 1; i >= 0; i--) setSelected(selection[i], false);\n selection = [];\n }\n\n /** Get the target of an event **/\n this.targetOf = function (e) {\n var target;\n if (!e) e = window.event;\n if (e.target) {\n target = e.target;\n } else if (e.srcElement) {\n target = e.srcElement;\n } else {\n UI.log.error(\"can't get target for event \" + e);\n return false;\n } // fail\n if (target.nodeType === 3) {\n // defeat Safari bug [sic]\n target = target.parentNode;\n }\n return target;\n }; // targetOf\n\n this.walk = function walk(directionCode, inputTd) {\n var selectedTd = inputTd || selection[0];\n var newSelTd;\n switch (directionCode) {\n case 'down':\n try {\n newSelTd = selectedTd.parentNode.nextSibling.lastChild;\n } catch (e) {\n this.walk('up');\n return;\n } // end\n deselectAll();\n setSelected(newSelTd, true);\n break;\n case 'up':\n try {\n newSelTd = selectedTd.parentNode.previousSibling.lastChild;\n } catch (e) {\n return;\n } // top\n deselectAll();\n setSelected(newSelTd, true);\n break;\n case 'right':\n deselectAll();\n if (selectedTd.nextSibling || selectedTd.lastChild.tagName === 'strong') {\n setSelected(selectedTd.nextSibling, true);\n } else {\n var newSelected = dom.evaluate('table/div/tr/td[2]', selectedTd, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;\n setSelected(newSelected, true);\n }\n break;\n case 'left':\n deselectAll();\n if (selectedTd.previousSibling && selectedTd.previousSibling.className === 'undetermined') {\n setSelected(selectedTd.previousSibling, true);\n return true; // do not shrink signal\n } else {\n setSelected(UI.utils.ancestor(selectedTd.parentNode, 'TD'), true);\n } // supplied by thieOutline.focusTd\n break;\n case 'moveTo':\n // UI.log.info(selection[0].textContent+'->'+inputTd.textContent);\n deselectAll();\n setSelected(inputTd, true);\n break;\n }\n if (directionCode === 'down' || directionCode === 'up') {\n if (!newSelTd.tabulatorSelect) this.walk(directionCode);\n }\n // return newSelTd;\n };\n\n // Keyboard Input: we can consider this as...\n // 1. a fast way to modify data - enter will go to next predicate\n // 2. an alternative way to input - enter at the end of a predicate will create a new statement\n this.OutlinerKeypressPanel = function OutlinerKeypressPanel(e) {\n UI.log.info('Key ' + e.keyCode + ' pressed');\n function showURI(about) {\n if (about && dom.getElementById('UserURI')) {\n dom.getElementById('UserURI').value = about.termType === 'NamedNode' ? about.uri : ''; // blank if no URI\n }\n }\n function setSelectedAfterward(_uri) {\n if (arguments[3]) return true;\n walk('right', selectedTd);\n showURI(UI.utils.getAbout(kb, selection[0]));\n return true;\n }\n var target, editable;\n if (UI.utils.getTarget(e).tagName === 'TEXTAREA') return;\n if (UI.utils.getTarget(e).id === 'UserURI') return;\n if (selection.length > 1) return;\n if (selection.length === 0) {\n if (e.keyCode === 13 || e.keyCode === 38 || e.keyCode === 40 || e.keyCode === 37 || e.keyCode === 39) {\n this.walk('right', thisOutline.focusTd);\n showURI(UI.utils.getAbout(kb, selection[0]));\n }\n return;\n }\n var selectedTd = selection[0];\n // if not done, Have to deal with redraw...\n sf.removeCallback('done', 'setSelectedAfterward');\n sf.removeCallback('fail', 'setSelectedAfterward');\n switch (e.keyCode) {\n case 13:\n // enter\n if (UI.utils.getTarget(e).tagName === 'HTML') {\n // I don't know why 'HTML'\n var object = UI.utils.getAbout(kb, selectedTd);\n target = selectedTd.parentNode.AJAR_statement.why;\n editable = _solidLogic.store.updater.editable(target.uri, kb);\n if (object) {\n // \n outline.GotoSubject(object, true);\n /* //deal with this later\n deselectAll();\n var newTr=dom.getElementById('outline').lastChild;\n setSelected(newTr.firstChild.firstChild.childNodes[1].lastChild,true);\n function setSelectedAfterward(uri){\n deselectAll();\n setSelected(newTr.firstChild.firstChild.childNodes[1].lastChild,true);\n showURI(getAbout(kb,selection[0]));\n return true;\n }\n sf.insertCallback('done',setSelectedAfterward);\n sf.insertCallback('fail',setSelectedAfterward);\n */\n // \n } else if (editable) {\n // this is a text node and editable\n thisOutline.UserInput.Enter(selectedTd);\n }\n } else {\n // var newSelTd=thisOutline.UserInput.lastModified.parentNode.parentNode.nextSibling.lastChild;\n this.UserInput.Keypress(e);\n this.walk('down'); // bug with input at the end\n // dom.getElementById('docHTML').focus(); //have to set this or focus blurs\n e.stopPropagation();\n }\n return;\n case 38:\n // up\n // thisOutline.UserInput.clearInputAndSave();\n // ^^^ does not work because up and down not captured...\n this.walk('up');\n e.stopPropagation();\n e.preventDefault();\n break;\n case 40:\n // down\n // thisOutline.UserInput.clearInputAndSave();\n this.walk('down');\n e.stopPropagation();\n e.preventDefault();\n } // switch\n\n if (UI.utils.getTarget(e).tagName === 'INPUT') return;\n var walk;\n switch (e.keyCode) {\n case 46: // delete\n case 8:\n // backspace\n target = selectedTd.parentNode.AJAR_statement.why;\n editable = _solidLogic.store.updater.editable(target.uri, kb);\n if (editable) {\n e.preventDefault(); // prevent from going back\n this.UserInput.Delete(selectedTd);\n }\n break;\n case 37:\n {\n // left\n if (this.walk('left')) return;\n var titleTd = UI.utils.ancestor(selectedTd.parentNode, 'TD');\n outlineCollapse(selectedTd, UI.utils.getAbout(kb, titleTd));\n break;\n }\n case 39:\n // right\n // @@ TODO: Write away the need for exception on next line\n // eslint-disable-next-line no-case-declarations\n var obj = UI.utils.getAbout(kb, selectedTd);\n if (obj) {\n walk = this.walk;\n if (selectedTd.nextSibling) {\n // when selectedTd is a predicate\n this.walk('right');\n return;\n }\n if (selectedTd.firstChild.tagName !== 'TABLE') {\n // not expanded\n sf.addCallback('done', setSelectedAfterward);\n sf.addCallback('fail', setSelectedAfterward);\n outlineExpand(selectedTd, obj, {\n pane: paneRegistry.byName('defaultPane')\n });\n }\n setSelectedAfterward();\n }\n break;\n case 38: // up\n case 40:\n // down\n break;\n default:\n switch (e.charCode) {\n case 99:\n // c for Copy\n if (e.ctrlKey) {\n thisOutline.UserInput.copyToClipboard(thisOutline.clipboardAddress, selectedTd);\n break;\n }\n break;\n case 118: // v\n case 112:\n // p for Paste\n if (e.ctrlKey) {\n thisOutline.UserInput.pasteFromClipboard(thisOutline.clipboardAddress, selectedTd);\n // dom.getElementById('docHTML').focus(); //have to set this or focus blurs\n // window.focus();\n // e.stopPropagation();\n break;\n }\n break;\n default:\n if (UI.utils.getTarget(e).tagName === 'HTML') {\n /*\n //\n thisOutline.UserInput.Click(e,selectedTd);\n thisOutline.UserInput.lastModified.value=String.fromCharCode(e.charCode);\n if (selectedTd.className==='undetermined selected') thisOutline.UserInput.AutoComplete(e.charCode)\n //\n */\n // Events are not reliable...\n // var e2=document.createEvent('KeyboardEvent');\n // e2.initKeyEvent('keypress',true,true,null,false,false,false,false,e.keyCode,0);\n // UserInput.lastModified.dispatchEvent(e2);\n }\n }\n } // end of switch\n\n showURI(UI.utils.getAbout(kb, selection[0]));\n // alert(window);alert(doc);\n /*\n var wm = Components.classes['@mozilla.org/appshell/window-mediator;1']\n .getService(Components.interfaces.nsIWindowMediator);\n var gBrowser = wm.getMostRecentWindow('navigator:browser') */\n // gBrowser.addTab('http://www.w3.org/');\n // alert(gBrowser.addTab);alert(gBrowser.scroll);alert(gBrowser.scrollBy)\n // gBrowser.scrollBy(0,100);\n\n // var thisHtml=selection[0].owner\n if (selection[0]) {\n var PosY = UI.utils.findPos(selection[0])[1];\n if (PosY + selection[0].clientHeight > window.scrollY + window.innerHeight) {\n UI.utils.getEyeFocus(selection[0], true, true, window);\n }\n if (PosY < window.scrollY + 54) {\n UI.utils.getEyeFocus(selection[0], true, undefined, window);\n }\n }\n };\n this.OutlinerMouseclickPanel = function (e) {\n switch (thisOutline.UserInput._tabulatorMode) {\n case 0:\n TabulatorMousedown(e);\n break;\n case 1:\n thisOutline.UserInput.Click(e);\n break;\n default:\n }\n };\n\n /** things to do onmousedown in outline view **/\n /*\n ** To Do: This big event handler needs to be replaced by lots\n ** of little ones individually connected to each icon. This horrible\n ** switch below isn't modular. (Sorry!) - Tim\n */\n // expand\n // collapse\n // refocus\n // select\n // visit/open a page\n\n function expandMouseDownListener(e) {\n // For icon (UI.icons.originalIconBase + 'tbl-expand-trans.png')\n var target = thisOutline.targetOf(e);\n var p = target.parentNode;\n var subject = UI.utils.getAbout(kb, target);\n var pane = e.altKey ? paneRegistry.byName('internal') : undefined; // set later: was panes.defaultPane\n\n if (e.shiftKey) {\n // Shift forces a refocus - bring this to the top\n outlineRefocus(p, subject, pane);\n } else {\n if (e.altKey) {\n // To investigate screw ups, dont wait show internals\n outlineExpand(p, subject, {\n pane: paneRegistry.byName('internal'),\n immediate: true\n });\n } else {\n outlineExpand(p, subject);\n }\n }\n }\n function collapseMouseDownListener(e) {\n // for icon UI.icons.originalIconBase + 'tbl-collapse.png'\n var target = thisOutline.targetOf(e);\n var subject = UI.utils.getAbout(kb, target);\n var pane = e.altKey ? paneRegistry.byName('internal') : undefined;\n var p = target.parentNode.parentNode;\n outlineCollapse(p, subject, pane);\n }\n function failedIconMouseDownListener(e) {\n // outlineIcons.src.icon_failed\n var target = thisOutline.targetOf(e);\n var uri = target.getAttribute('uri'); // Put on access buttons\n if (e.altKey) {\n sf.fetch(UI.rdf.uri.docpart(uri), {\n force: true\n }); // Add 'force' bit?\n } else {\n sf.refresh(kb.sym(UI.rdf.uri.docpart(uri))); // just one\n }\n }\n function fetchedIconMouseDownListener(e) {\n // outlineIcons.src.icon_fetched\n var target = thisOutline.targetOf(e);\n var uri = target.getAttribute('uri'); // Put on access buttons\n if (e.altKey) {\n sf.fetch(UI.rdf.uri.docpart(uri), {\n force: true\n });\n } else {\n sf.refresh(kb.sym(UI.rdf.uri.docpart(uri))); // just one\n }\n }\n function unrequestedIconMouseDownListener(e) {\n var target = thisOutline.targetOf(e);\n var uri = target.getAttribute('uri'); // Put on access buttons\n sf.fetch(UI.rdf.uri.docpart(uri));\n }\n function removeNodeIconMouseDownListener(e) {\n // icon_remove_node\n var target = thisOutline.targetOf(e);\n var node = target.node;\n if (node.childNodes.length > 1) node = target.parentNode; // parallel outline view @@ Hack\n removeAndRefresh(node); // @@ update icons for pane?\n }\n function selectableTDClickListener(e) {\n // Is we are in editing mode already\n if (thisOutline.UserInput._tabulatorMode) {\n return thisOutline.UserInput.Click(e);\n }\n var target = thisOutline.targetOf(e);\n // Originally this was set on the whole tree and could happen anywhere\n // var p = target.parentNode\n var node;\n for (node = UI.utils.ancestor(target, 'TD'); node && !(node.getAttribute('notSelectable') === 'false');\n // Default now is not selectable\n node = UI.utils.ancestor(node.parentNode, 'TD')) {\n // ...\n }\n if (!node) return;\n\n // var node = target;\n\n var sel = selected(node);\n // var cla = node.getAttribute('class')\n UI.log.debug('Was node selected before: ' + sel);\n if (e.altKey) {\n setSelected(node, !selected(node));\n } else if (e.shiftKey) {\n setSelected(node, true);\n } else {\n // setSelected(node, !selected(node))\n deselectAll();\n thisOutline.UserInput.clearInputAndSave(e);\n setSelected(node, true);\n if (e.detail === 2) {\n // double click -> quit TabulatorMousedown()\n e.stopPropagation();\n return;\n }\n // if the node is already selected and the corresponding statement is editable,\n // go to UserInput\n var st;\n if (node.parentNode) st = node.parentNode.AJAR_statement;\n if (!st) return; // For example in the title TD of an expanded pane\n var _target = st.why;\n var editable = _solidLogic.store.updater.editable(_target.uri, kb);\n if (sel && editable) thisOutline.UserInput.Click(e, selection[0]); // was next 2 lines\n // var text='TabulatorMouseDown@Outline()';\n // HCIoptions['able to edit in Discovery Mode by mouse'].setupHere([sel,e,thisOutline,selection[0]],text);\n }\n UI.log.debug('Was node selected after: ' + selected(node) + ', count=' + selection.length);\n // var tr = node.parentNode\n /*\n if (tr.AJAR_statement) {\n // var why = tr.AJAR_statement.why\n // UI.log.info('Information from '+why);\n }\n */\n e.stopPropagation();\n // this is important or conflict between deselect and user input happens\n }\n function TabulatorMousedown(e) {\n UI.log.info('@TabulatorMousedown, dom.location is now ' + dom.location);\n var target = thisOutline.targetOf(e);\n if (!target) return;\n var tname = target.tagName;\n // UI.log.debug('TabulatorMousedown: ' + tname + ' shift='+e.shiftKey+' alt='+e.altKey+' ctrl='+e.ctrlKey);\n // var p = target.parentNode\n // var about = UI.utils.getAbout(kb, target)\n // var source = null\n if (tname === 'INPUT' || tname === 'TEXTAREA') {\n return;\n }\n\n // not input then clear\n thisOutline.UserInput.clearMenu();\n\n // ToDo:remove this and recover X\n if (thisOutline.UserInput.lastModified && thisOutline.UserInput.lastModified.parentNode.nextSibling) {\n thisOutline.UserInput.backOut();\n }\n\n // if (typeof rav=='undefined') //uncomment this for javascript2rdf\n // have to put this here or this conflicts with deselectAll()\n\n if (!target.src || target.src.slice(target.src.indexOf('/icons/') + 1) !== _outlineIcons.outlineIcons.src.icon_show_choices && target.src.slice(target.src.indexOf('/icons/') + 1) !== _outlineIcons.outlineIcons.src.icon_add_triple) {\n thisOutline.UserInput.clearInputAndSave(e);\n }\n if (!target.src || target.src.slice(target.src.indexOf('/icons/') + 1) !== _outlineIcons.outlineIcons.src.icon_show_choices) {\n thisOutline.UserInput.clearMenu();\n }\n if (e) e.stopPropagation();\n } // function TabulatorMousedown\n\n function setUrlBarAndTitle(subject) {\n dom.title = UI.utils.label(subject);\n if (dom.location.href.startsWith(subject.site().uri)) {\n // dom.location = subject.uri // No causes reload\n }\n }\n\n /** Expand an outline view\n * @param p {Element} - container\n */\n function outlineExpand(p, subject1, options) {\n options = options || {};\n var pane = options.pane;\n var already = !!options.already;\n var immediate = options.immediate;\n UI.log.info('@outlineExpand, dom is now ' + dom.location);\n // remove callback to prevent unexpected repaint\n sf.removeCallback('done', 'expand');\n sf.removeCallback('fail', 'expand');\n var subject = kb.canon(subject1);\n // var requTerm = subject.uri ? kb.sym(UI.rdf.uri.docpart(subject.uri)) : subject\n\n function render() {\n subject = kb.canon(subject);\n if (!p || !p.parentNode || !p.parentNode.parentNode) return false;\n var newTable;\n UI.log.info('@@ REPAINTING ');\n if (!already) {\n // first expand\n newTable = propertyTable(subject, undefined, pane, options);\n } else {\n UI.log.info(' ... p is ' + p);\n for (newTable = p.firstChild; newTable.nextSibling; newTable = newTable.nextSibling) {\n UI.log.info(' ... checking node ' + newTable);\n if (newTable.nodeName === 'table') break;\n }\n newTable = propertyTable(subject, newTable, pane, options);\n }\n already = true;\n if (UI.utils.ancestor(p, 'TABLE') && UI.utils.ancestor(p, 'TABLE').style.backgroundColor === 'white') {\n newTable.style.backgroundColor = '#eee';\n } else {\n newTable.style.backgroundColor = 'white';\n }\n UI.utils.emptyNode(p).appendChild(newTable);\n thisOutline.focusTd = p; // I don't know why I couldn't use 'this'...because not defined in callbacks\n UI.log.debug('expand: Node for ' + subject + ' expanded');\n // fetch seeAlso when render()\n // var seeAlsoStats = sf.store.statementsMatching(subject, UI.ns.rdfs('seeAlso'))\n // seeAlsoStats.map(function (x) {sf.lookUpThing(x.object, subject,false);})\n var seeAlsoWhat = kb.each(subject, UI.ns.rdfs('seeAlso'));\n for (var i = 0; i < seeAlsoWhat.length; i++) {\n if (i === 25) {\n UI.log.warn('expand: Warning: many (' + seeAlsoWhat.length + ') seeAlso links for ' + subject);\n // break; Not sure what limits the AJAX system has here\n }\n sf.lookUpThing(seeAlsoWhat[i], subject);\n }\n }\n function expand(uri) {\n if (arguments[3]) return true; // already fetched indicator\n var cursubj = kb.canon(subject); // canonical identifier may have changed\n UI.log.info('@@ expand: relevant subject=' + cursubj + ', uri=' + uri + ', already=' + already);\n // var term = kb.sym(uri)\n var docTerm = kb.sym(UI.rdf.uri.docpart(uri));\n if (uri.indexOf('#') >= 0) {\n throw new Error('Internal error: hash in ' + uri);\n }\n var relevant = function relevant() {\n // Is the loading of this URI relevam to the display of subject?\n if (!cursubj.uri) return true; // bnode should expand()\n var as = kb.uris(cursubj);\n if (!as) return false;\n for (var i = 0; i < as.length; i++) {\n // canon'l uri or any alias\n for (var rd = UI.rdf.uri.docpart(as[i]); rd; rd = kb.HTTPRedirects[rd]) {\n if (uri === rd) return true;\n }\n }\n if (kb.anyStatementMatching(cursubj, undefined, undefined, docTerm)) {\n return true;\n } // Kenny: inverse?\n return false;\n };\n if (relevant()) {\n UI.log.success('@@ expand OK: relevant subject=' + cursubj + ', uri=' + uri + ', source=' + already);\n render();\n return false; // @@@@@@@@@@@ Will this allow just the first\n }\n return true;\n }\n // Body of outlineExpand\n\n if (options.solo) {\n setUrlBarAndTitle(subject);\n }\n UI.log.debug('outlineExpand: dereferencing ' + subject);\n var status = dom.createElement('span');\n p.appendChild(status);\n sf.addCallback('done', expand); // @@@@@@@ This can really mess up existing work\n sf.addCallback('fail', expand); // Need to do if there s one a gentle resync of page with store\n\n var returnConditions = []; // this is quite a general way to do cut and paste programming\n // I might make a class for this\n if (subject.uri && subject.uri.split(':')[0] === 'rdf') {\n // what is this? -tim\n render();\n return;\n }\n for (var i = 0; i < returnConditions.length; i++) {\n var returnCode = void 0;\n if (returnCode === returnConditions[i](subject)) {\n render();\n UI.log.debug('outline 1815');\n if (returnCode[1]) outlineElement.removeChild(outlineElement.lastChild);\n return;\n }\n }\n if (subject.uri && !immediate && !UI.widgets.isAudio(subject) && !UI.widgets.isVideo(subject)) {\n // Wait till at least the main URI is loaded before expanding:\n sf.nowOrWhenFetched(subject.doc(), undefined, function (ok, body) {\n if (ok) {\n sf.lookUpThing(subject);\n render(); // inital open, or else full if re-open\n if (options.solo) {\n // Update window title with new information\n // dom.title = UI.utils.label(subject)\n setUrlBarAndTitle(subject);\n }\n } else {\n var message = dom.createElement('pre');\n message.textContent = body;\n message.setAttribute('style', 'background-color: #fee;');\n message.textContent = 'Outline.expand: Unable to fetch ' + subject.doc() + ': ' + body;\n p.appendChild(message);\n }\n });\n } else {\n render();\n }\n } // outlineExpand\n\n function outlineCollapse(p, subject) {\n var row = UI.utils.ancestor(p, 'TR');\n row = UI.utils.ancestor(row.parentNode, 'TR'); // two levels up\n var statement;\n if (row) statement = row.AJAR_statement;\n var level; // find level (the enclosing TD)\n for (level = p.parentNode; level.tagName !== 'TD'; level = level.parentNode) {\n if (typeof level === 'undefined') {\n alert('Not enclosed in TD!');\n return;\n }\n }\n UI.log.debug('Collapsing subject ' + subject);\n var myview;\n if (statement) {\n UI.log.debug('looking up pred ' + statement.predicate.uri + 'in defaults');\n myview = views.defaults[statement.predicate.uri];\n }\n UI.log.debug('view= ' + myview);\n var deleteNode;\n if (level.parentNode.parentNode.id === 'outline') {\n deleteNode = level.parentNode;\n }\n thisOutline.replaceTD(thisOutline.outlineObjectTD(subject, myview, deleteNode, statement), level);\n } // outlineCollapse\n\n this.replaceTD = function replaceTD(newTd, replacedTd) {\n var reselect;\n if (selected(replacedTd)) reselect = true;\n\n // deselects everything being collapsed. This goes backwards because\n // deselecting an element decreases selection.length\n for (var x = selection.length - 1; x > -1; x--) {\n for (var elt = selection[x]; elt.parentNode; elt = elt.parentNode) {\n if (elt === replacedTd) {\n setSelected(selection[x], false);\n }\n }\n }\n replacedTd.parentNode.replaceChild(newTd, replacedTd);\n if (reselect) setSelected(newTd, true);\n };\n function outlineRefocus(p, subject) {\n // Shift-expand or shift-collapse: Maximize\n var outer = null;\n for (var level = p.parentNode; level; level = level.parentNode) {\n UI.log.debug('level ' + level.tagName);\n if (level.tagName === 'TD') outer = level;\n } // find outermost td\n UI.utils.emptyNode(outer).appendChild(propertyTable(subject));\n setUrlBarAndTitle(subject);\n // dom.title = UI.utils.label(subject)\n outer.setAttribute('about', subject.toNT());\n } // outlineRefocus\n\n outline.outlineRefocus = outlineRefocus;\n\n // Inversion is turning the outline view inside-out\n // It may be called eversion\n /*\n function outlineInversion (p, subject) { // re-root at subject\n function move_root (rootTR, childTR) { // swap root with child\n // @@\n }\n }\n */\n this.GotoFormURI_enterKey = function (e) {\n if (e.keyCode === 13) outline.GotoFormURI(e);\n };\n this.GotoFormURI = function (_e) {\n GotoURI(dom.getElementById('UserURI').value);\n };\n function GotoURI(uri) {\n var subject = kb.sym(uri);\n this.GotoSubject(subject, true);\n }\n this.GotoURIinit = function (uri) {\n var subject = kb.sym(uri);\n this.GotoSubject(subject);\n };\n\n /** Display the subject in an outline view\n @param subject -- RDF term for teh thing to be presented\n @param expand -- flag -- open the subject rather than keep folded closed\n @param pane -- optional -- pane to be used for expanded display\n @param solo -- optional -- the window will be cleared out and only the subject displayed\n @param referer -- optional -- where did we hear about this from anyway?\n @param table -- option -- a table element in which to put the outline.\n */\n this.GotoSubject = function (subject, expand, pane, solo, referrer, table) {\n table = table || dom.getElementById('outline'); // if does not exist just add one? nowhere to out it\n if (solo) {\n UI.utils.emptyNode(table);\n table.style.width = '100%';\n }\n function GotoSubjectDefault() {\n var tr = dom.createElement('TR');\n tr.style.verticalAlign = 'top';\n table.appendChild(tr);\n var td = thisOutline.outlineObjectTD(subject, undefined, tr);\n tr.appendChild(td);\n return td;\n }\n var td = GotoSubjectDefault();\n if (solo) setUrlBarAndTitle(subject); // dom.title = UI.utils.label(subject) // 'Tabulator: '+ No need to advertize\n\n if (expand) {\n outlineExpand(td, subject, {\n pane: pane,\n solo: solo\n });\n var tr = td.parentNode;\n UI.utils.getEyeFocus(tr, false, undefined, window); // instantly: false\n }\n if (solo && dom && dom.defaultView && dom.defaultView.history &&\n // Don't add the new location to the history if we arrived here through a direct link\n // (i.e. when static/databrowser.html in node-solid-server called this method):\n document.location.href !== subject.uri) {\n var stateObj = pane ? {\n paneName: pane.name\n } : {};\n try {\n // can fail if different origin\n dom.defaultView.history.pushState(stateObj, subject.uri, subject.uri);\n } catch (e) {\n console.log(e);\n }\n }\n return subject;\n };\n\n // / /////////////////////////////////////////////////////\n //\n //\n // VIEWS\n //\n //\n // / /////////////////////////////////////////////////////\n\n var ns = UI.ns;\n var views = (0, _propertyViews.propertyViews)(dom);\n\n // var thisOutline = this dup\n /** some builtin simple views **/\n\n function viewAsBoringDefault(obj) {\n // UI.log.debug('entered viewAsBoringDefault...');\n var rep; // representation in html\n\n if (obj.termType === 'Literal') {\n var styles = {\n integer: 'text-align: right;',\n decimal: \"text-align: '.';\",\n \"double\": \"text-align: '.';\"\n };\n rep = dom.createElement('span');\n rep.textContent = obj.value;\n // Newlines have effect and overlong lines wrapped automatically\n var style = '';\n if (obj.datatype && obj.datatype.uri) {\n var xsd = UI.ns.xsd('').uri;\n if (obj.datatype.uri.slice(0, xsd.length) === xsd) {\n style = styles[obj.datatype.uri.slice(xsd.length)];\n }\n }\n rep.setAttribute('style', style || 'white-space: pre-wrap;');\n } else if (obj.termType === 'NamedNode' || obj.termType === 'BlankNode') {\n rep = dom.createElement('span');\n rep.setAttribute('about', obj.toNT());\n thisOutline.appendAccessIcons(kb, rep, obj);\n if (obj.termType === 'NamedNode') {\n if (obj.uri.slice(0, 4) === 'tel:') {\n var num = obj.uri.slice(4);\n var anchor = dom.createElement('a');\n rep.appendChild(dom.createTextNode(num));\n anchor.setAttribute('href', obj.uri);\n anchor.appendChild(UI.utils.AJARImage(_outlineIcons.outlineIcons.src.icon_telephone, 'phone', 'phone ' + num, dom));\n rep.appendChild(anchor);\n anchor.firstChild.setAttribute('class', 'phoneIcon');\n } else {\n // not tel:\n rep.appendChild(dom.createTextNode(UI.utils.label(obj)));\n var _anchor = UI.widgets.linkIcon(dom, obj);\n rep.appendChild(_anchor);\n UI.widgets.makeDraggable(rep, obj); // 2017\n }\n } else {\n // bnode\n rep.appendChild(dom.createTextNode(UI.utils.label(obj)));\n }\n } else if (obj.termType === 'Collection') {\n // obj.elements is an array of the elements in the collection\n rep = dom.createElement('table');\n rep.setAttribute('style', 'width: 100%;');\n rep.setAttribute('about', obj.toNT());\n /* Not sure which looks best -- with or without. I think without\n var tr = rep.appendChild(document.createElement('tr'));\n tr.appendChild(document.createTextNode(\n obj.elements.length ? '(' + obj.elements.length+')' : '(none)'));\n */\n for (var i = 0; i < obj.elements.length; i++) {\n var elt = obj.elements[i];\n var row = rep.appendChild(dom.createElement('tr'));\n var numcell = row.appendChild(dom.createElement('td'));\n numcell.setAttribute('style', 'margin: 0.2em; border: none; padding: 0; vertical-align: top;');\n numcell.setAttribute('notSelectable', 'false');\n numcell.setAttribute('about', obj.toNT());\n numcell.innerHTML = i + 1 + ')';\n row.appendChild(thisOutline.outlineObjectTD(elt));\n }\n } else if (obj.termType === 'Graph') {\n rep = paneRegistry.byName('dataContentPane').statementsAsTables(obj.statements, context);\n rep.setAttribute('class', 'nestedFormula');\n } else {\n UI.log.error('Object ' + obj + ' has unknown term type: ' + obj.termType);\n rep = dom.createTextNode('[unknownTermType:' + obj.termType + ']');\n } // boring defaults.\n UI.log.debug('contents: ' + rep.innerHTML);\n return rep;\n } // boring_default\n\n this.createTabURI = function () {\n dom.getElementById('UserURI').value = dom.URL + '?uri=' + dom.getElementById('UserURI').value;\n };\n\n // a way to expose variables to UserInput without making them propeties/methods\n this.UserInput.setSelected = setSelected;\n this.UserInput.deselectAll = deselectAll;\n this.UserInput.views = views;\n this.outlineExpand = outlineExpand;\n\n // this.panes = panes; // Allow external panes to register\n\n return this;\n} // END OF OUTLINE\n//# sourceMappingURL=manager.js.map","\"use strict\";\n\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.outlineIcons = void 0;\nvar UI = _interopRequireWildcard(require(\"solid-ui\"));\nfunction _getRequireWildcardCache(e) { if (\"function\" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }\nfunction _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || \"object\" != _typeof(e) && \"function\" != typeof e) return { \"default\": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if (\"default\" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n[\"default\"] = e, t && t.set(e, n), n; }\n// This is a system of tracking tooltip phrases used by the tabulator outliner\n\nvar outlineIcons = exports.outlineIcons = {};\noutlineIcons.src = []; // collect the URIs of the icon filterColumns\noutlineIcons.tooltips = []; // look up tool tips from URL\n\n/// /////////////////////// Common icons\n\noutlineIcons.src.icon_expand = UI.icons.originalIconBase + 'tbl-expand-trans.png';\noutlineIcons.src.icon_more = UI.icons.originalIconBase + 'tbl-more-trans.png'; // looks just like expand, diff semantics\n// Icon.src.icon_expand = UI.icons.originalIconBase + 'clean/Icon.src.Icon.src.icon_expand.png';\noutlineIcons.src.icon_collapse = UI.icons.originalIconBase + 'tbl-collapse.png';\noutlineIcons.src.icon_internals = UI.icons.originalIconBase + 'tango/22-emblem-system.png';\noutlineIcons.src.icon_instances = UI.icons.originalIconBase + 'tango/22-folder-open.png';\noutlineIcons.src.icon_foaf = UI.icons.originalIconBase + 'foaf/foafTiny.gif';\noutlineIcons.src.icon_social = UI.icons.originalIconBase + 'social/social.gif';\noutlineIcons.src.icon_mb = UI.icons.originalIconBase + 'microblog/microblog.png';\noutlineIcons.src.icon_shrink = UI.icons.originalIconBase + 'tbl-shrink.png'; // shrink list back up\noutlineIcons.src.icon_rows = UI.icons.originalIconBase + 'tbl-rows.png';\n// Icon.src.Icon.src.icon_columns = 'icons/tbl-columns.png';\n\n// Status balls:\n\noutlineIcons.src.icon_unrequested = UI.icons.originalIconBase + '16dot-blue.gif';\n// outlineIcons.src.Icon.src.icon_parse = UI.icons.originalIconBase + '18x18-white.gif';\noutlineIcons.src.icon_fetched = UI.icons.originalIconBase + '16dot-green.gif';\noutlineIcons.src.icon_failed = UI.icons.originalIconBase + '16dot-red.gif';\noutlineIcons.src.icon_requested = UI.icons.originalIconBase + '16dot-yellow.gif';\n// Icon.src.icon_maximize = UI.icons.originalIconBase + 'clean/Icon.src.Icon.src.icon_con_max.png';\n\n// Panes:\noutlineIcons.src.icon_CVPane = UI.icons.originalIconBase + 'CV.png';\noutlineIcons.src.icon_defaultPane = UI.icons.originalIconBase + 'about.png';\noutlineIcons.src.icon_visit = UI.icons.originalIconBase + 'tango/22-text-x-generic.png';\noutlineIcons.src.icon_dataContents = UI.icons.originalIconBase + 'rdf_flyer.24.gif'; // @@ Bad .. find better\noutlineIcons.src.icon_n3Pane = UI.icons.originalIconBase + 'w3c/n3_smaller.png'; // @@ Bad .. find better\noutlineIcons.src.icon_RDFXMLPane = UI.icons.originalIconBase + '22-text-xml4.png'; // @@ Bad .. find better\noutlineIcons.src.icon_imageContents = UI.icons.originalIconBase + 'tango/22-image-x-generic.png';\noutlineIcons.src.icon_airPane = UI.icons.originalIconBase + '1pt5a.gif';\noutlineIcons.src.icon_LawPane = UI.icons.originalIconBase + 'law.jpg';\noutlineIcons.src.icon_pushbackPane = UI.icons.originalIconBase + 'pb-logo.png';\n\n// For photo albums (By albert08@csail.mit.edu)\noutlineIcons.src.icon_photoPane = UI.icons.originalIconBase + 'photo_small.png';\noutlineIcons.src.icon_tagPane = UI.icons.originalIconBase + 'tag_small.png';\noutlineIcons.src.icon_TinyTag = UI.icons.originalIconBase + 'tag_tiny.png';\noutlineIcons.src.icon_photoBegin = UI.icons.originalIconBase + 'photo_begin.png';\noutlineIcons.src.icon_photoNext = UI.icons.originalIconBase + 'photo_next.png';\noutlineIcons.src.icon_photoBack = UI.icons.originalIconBase + 'photo_back.png';\noutlineIcons.src.icon_photoEnd = UI.icons.originalIconBase + 'photo_end.png';\noutlineIcons.src.icon_photoImportPane = UI.icons.originalIconBase + 'flickr_small.png';\n// Icon.src.icon_CloseButton = UI.icons.originalIconBase + 'close_tiny.png';\n// Icon.src.icon_AddButton = UI.icons.originalIconBase + 'addphoto_tiny.png';\n\n// For that one we need a document with grid lines. Make data-x-generix maybe\n\n// actions for sources;\noutlineIcons.src.icon_retract = UI.icons.originalIconBase + 'retract.gif';\noutlineIcons.src.icon_refresh = UI.icons.originalIconBase + 'refresh.gif';\noutlineIcons.src.icon_optoff = UI.icons.originalIconBase + 'optional_off.PNG';\noutlineIcons.src.icon_opton = UI.icons.originalIconBase + 'optional_on.PNG';\noutlineIcons.src.icon_map = UI.icons.originalIconBase + 'compassrose.png';\noutlineIcons.src.icon_retracted = outlineIcons.src.icon_unrequested;\noutlineIcons.src.icon_retracted = outlineIcons.src.icon_unrequested;\noutlineIcons.src.icon_time = UI.icons.originalIconBase + 'icons/Wclocksmall.png';\n\n// Within outline mode:\n\noutlineIcons.src.icon_telephone = UI.icons.originalIconBase + 'silk/telephone.png';\noutlineIcons.src.icon_time = UI.icons.originalIconBase + 'Wclocksmall.png';\noutlineIcons.src.icon_remove_node = UI.icons.originalIconBase + 'tbl-x-small.png';\noutlineIcons.src.icon_add_triple = UI.icons.originalIconBase + 'tango/22-list-add.png';\noutlineIcons.src.icon_add_new_triple = UI.icons.originalIconBase + 'tango/22-list-add-new.png';\noutlineIcons.src.icon_show_choices = UI.icons.originalIconBase + 'userinput_show_choices_temp.png'; // looks just like collapse, diff smmantics\n\n// Inline Justification\noutlineIcons.src.icon_display_reasons = UI.icons.originalIconBase + 'tango/22-help-browser.png';\noutlineIcons.tooltips[outlineIcons.src.icon_display_reasons] = 'Display explanations';\n\n// Other tooltips\noutlineIcons.tooltips[outlineIcons.src.icon_add_triple] = 'Add more';\noutlineIcons.tooltips[outlineIcons.src.icon_add_new_triple] = 'Add one';\noutlineIcons.tooltips[outlineIcons.src.icon_remove_node] = 'Remove';\noutlineIcons.tooltips[outlineIcons.src.icon_expand] = 'View details.';\noutlineIcons.tooltips[outlineIcons.src.icon_collapse] = 'Hide details.';\noutlineIcons.tooltips[outlineIcons.src.icon_shrink] = 'Shrink list.';\noutlineIcons.tooltips[outlineIcons.src.icon_internals] = 'Under the hood';\noutlineIcons.tooltips[outlineIcons.src.icon_instances] = 'List';\noutlineIcons.tooltips[outlineIcons.src.icon_foaf] = 'Friends';\noutlineIcons.tooltips[outlineIcons.src.icon_rows] = 'Make a table of data like this';\n// Note the string '[Tt]his resource' can be replaced with an actual URI by the code\noutlineIcons.tooltips[outlineIcons.src.icon_unrequested] = 'Fetch this.';\noutlineIcons.tooltips[outlineIcons.src.icon_fetched] = 'Fetched successfully.';\noutlineIcons.tooltips[outlineIcons.src.icon_failed] = 'Failed to load. Click to retry.';\noutlineIcons.tooltips[outlineIcons.src.icon_requested] = 'This is being fetched. Please wait...';\noutlineIcons.tooltips[outlineIcons.src.icon_visit] = 'View document';\noutlineIcons.tooltips[outlineIcons.src.icon_retract] = 'Remove this source and all its data from tabulator.';\noutlineIcons.tooltips[outlineIcons.src.icon_refresh] = 'Refresh this source and reload its triples.';\n\n/// ////////////////////////////// End comon area\n\noutlineIcons.OutlinerIcon = function (src, width, alt, tooltip, filter) {\n this.src = src;\n this.alt = alt;\n this.width = width;\n this.tooltip = tooltip;\n this.filter = filter;\n // filter: RDFStatement,('subj'|'pred'|'obj')->boolean, inverse->boolean (whether the statement is an inverse).\n // Filter on whether to show this icon for a term; optional property.\n // If filter is not passed, this icon will never AUTOMATICALLY be shown.\n // You can show it with termWidget.addIcon\n return this;\n};\noutlineIcons.termWidgets = {};\noutlineIcons.termWidgets.optOn = new outlineIcons.OutlinerIcon(outlineIcons.src.icon_opton, 20, 'opt on', 'Make this branch of your query mandatory.');\noutlineIcons.termWidgets.optOff = new outlineIcons.OutlinerIcon(outlineIcons.src.icon_optoff, 20, 'opt off', 'Make this branch of your query optional.');\noutlineIcons.termWidgets.addTri = new outlineIcons.OutlinerIcon(outlineIcons.src.icon_add_triple, 18, 'add tri', 'Add one');\n// Ideally: \"New \"+label(subject)\n//# sourceMappingURL=outlineIcons.js.map","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.propertyViews = propertyViews;\nexports.viewsAddPropertyView = viewsAddPropertyView;\nvar _solidUi = require(\"solid-ui\");\nvar _viewAsImage = _interopRequireDefault(require(\"./viewAsImage\"));\nvar _viewAsMbox = _interopRequireDefault(require(\"./viewAsMbox\"));\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { \"default\": obj }; }\n/** some builtin simple views **/\n\nfunction propertyViews(dom) {\n // view that applies to items that are objects of certain properties.\n var views = {\n properties: [],\n defaults: [],\n classes: []\n }; // views\n\n var asImage = (0, _viewAsImage[\"default\"])(dom);\n var asMbox = (0, _viewAsMbox[\"default\"])(dom);\n viewsAddPropertyView(views, _solidUi.ns.foaf('depiction').uri, asImage, true);\n viewsAddPropertyView(views, _solidUi.ns.foaf('img').uri, asImage, true);\n viewsAddPropertyView(views, _solidUi.ns.foaf('thumbnail').uri, asImage, true);\n viewsAddPropertyView(views, _solidUi.ns.foaf('logo').uri, asImage, true);\n viewsAddPropertyView(views, _solidUi.ns.schema('image').uri, asImage, true);\n viewsAddPropertyView(views, _solidUi.ns.foaf('mbox').uri, asMbox, true);\n return views;\n}\n\n/** add a property view function **/\nfunction viewsAddPropertyView(views, property, pviewfunc, isDefault) {\n if (!views.properties[property]) {\n views.properties[property] = [];\n }\n views.properties[property].push(pviewfunc);\n if (isDefault) {\n // will override an existing default!\n views.defaults[property] = pviewfunc;\n }\n} // viewsAddPropertyView\n//# sourceMappingURL=propertyViews.js.map","\"use strict\";\n\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.QuerySource = QuerySource;\nexports.makeQueryRow = makeQueryRow;\nexports.viewAndSaveQuery = viewAndSaveQuery;\nvar _solidLogic = require(\"solid-logic\");\nvar UI = _interopRequireWildcard(require(\"solid-ui\"));\nfunction _getRequireWildcardCache(e) { if (\"function\" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }\nfunction _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || \"object\" != _typeof(e) && \"function\" != typeof e) return { \"default\": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if (\"default\" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n[\"default\"] = e, t && t.set(e, n), n; }\n/* istanbul ignore file */\n// The query-by-example functionality in the tabulator\n// was the ability to expore a bit of the web in outline mode,\n// select a ceratain set of fields in the tree,\n// then pres \"find all\" which would then generte a SPARQL query\n// to find all other places which had the same pattern.\n// Fields could be optional by pressing th ewhite optoional button\n\nvar optionalSubqueriesIndex = [];\nfunction predParentOf(node) {\n var n = node;\n while (true) {\n if (n.getAttribute('predTR')) {\n return n;\n } else if (n.previousSibling && n.previousSibling.nodeName === 'TR') {\n n = n.previousSibling;\n } else {\n console.log('Could not find predParent');\n return node;\n }\n }\n}\nfunction makeQueryRow(q, tr, constraint) {\n // predtr = predParentOf(tr)\n // var nodes = tr.childNodes\n // var n = tr.childNodes.length\n var inverse = tr.AJAR_inverse;\n // var hasVar = 0\n var parentVar, level, pat;\n function makeRDFStatement(freeVar, parent) {\n if (inverse) {\n return new UI.rdf.Statement(freeVar, st.predicate, parent);\n } else {\n return new UI.rdf.Statement(parent, st.predicate, freeVar);\n }\n }\n var optionalSubqueryIndex = null;\n for (level = tr.parentNode; level; level = level.parentNode) {\n if (typeof level.AJAR_statement !== 'undefined') {\n // level.AJAR_statement\n level.setAttribute('bla', level.AJAR_statement); // @@? -timbl\n // UI.log.debug(\"Parent TR statement=\"+level.AJAR_statement + \", var=\" + level.AJAR_variable)\n /* for(let c=0;c= 0) {\n UI.log.info(' We have a predicate');\n makeQueryRow(q, tr);\n }\n if (sel.getAttribute('class').indexOf('obj') >= 0) {\n UI.log.info(' We have an object');\n makeQueryRow(q, tr, true);\n }\n }\n qs.addQuery(q);\n function resetOutliner(pat) {\n var n = pat.statements.length;\n var pattern, tr;\n for (var _i = 0; _i < n; _i++) {\n pattern = pat.statements[_i];\n tr = pattern.tr;\n // UI.log.debug('tr: ' + tr.AJAR_statement);\n if (typeof tr !== 'undefined') {\n tr.AJAR_pattern = null; // TODO: is this == to whats in current version?\n tr.AJAR_variable = null;\n }\n }\n for (var x in pat.optional) {\n resetOutliner(pat.optional[x]);\n }\n }\n resetOutliner(q.pat);\n // NextVariable=0;\n return q;\n} // saveQuery\n\n// When the user asks for all list of all matching parts of the data\n//\nfunction viewAndSaveQuery(outline, selection) {\n var qs = outline.qs;\n UI.log.info('outline.doucment is now ' + outline.document.location);\n var q = saveQuery(selection, qs);\n /*\n if (tabulator.isExtension) {\n // tabulator.drawInBestView(q)\n } else\n */\n\n for (var i = 0; i < qs.listeners.length; i++) {\n qs.listeners[i].getActiveView().view.drawQuery(q);\n qs.listeners[i].updateQueryControls(qs.listeners[i].getActiveView());\n }\n}\n\n/**\n * The QuerySource object stores a set of listeners and a set of queries.\n * It keeps the listeners aware of those queries that the source currently\n * contains, and it is then up to the listeners to decide what to do with\n * those queries in terms of displays.\n * Not used 2010-08 -- TimBL\n * @class QuerySource\n * @author jambo\n */\n\nfunction QuerySource() {\n /**\n * stores all of the queries currently held by this source,\n * indexed by ID number.\n */\n this.queries = [];\n /**\n * stores the listeners for a query object.\n * @see TabbedContainer\n */\n this.listeners = [];\n\n /**\n * add a Query object to the query source--It will be given an ID number\n * and a name, if it doesn't already have one. This subsequently adds the\n * query to all of the listeners the QuerySource knows about.\n */\n this.addQuery = function (q) {\n var i;\n if (q.name === null || q.name === '') {\n q.name = 'Query #' + (this.queries.length + 1);\n }\n q.id = this.queries.length;\n this.queries.push(q);\n for (i = 0; i < this.listeners.length; i++) {\n if (this.listeners[i] !== null) {\n this.listeners[i].addQuery(q);\n }\n }\n };\n\n /**\n * Remove a Query object from the source. Tells all listeners to also\n * remove the query.\n */\n this.removeQuery = function (q) {\n var i;\n for (i = 0; i < this.listeners.length; i++) {\n if (this.listeners[i] !== null) {\n this.listeners[i].removeQuery(q);\n }\n }\n if (this.queries[q.id] !== null) {\n delete this.queries[q.id];\n }\n };\n\n /**\n * adds a \"Listener\" to this QuerySource - that is, an object\n * which is capable of both adding and removing queries.\n * Currently, only the TabbedContainer class is added.\n * also puts all current queries into the listener to be used.\n */\n this.addListener = function (listener) {\n var i;\n this.listeners.push(listener);\n for (i = 0; i < this.queries.length; i++) {\n if (this.queries[i] !== null) {\n listener.addQuery(this.queries[i]);\n }\n }\n };\n /**\n * removes listener from the array of listeners, if it exists! Also takes\n * all of the queries from this source out of the listener.\n */\n this.removeListener = function (listener) {\n var i;\n for (i = 0; i < this.queries.length; i++) {\n if (this.queries[i] !== null) {\n listener.removeQuery(this.queries[i]);\n }\n }\n for (i = 0; i < this.listeners.length; i++) {\n if (this.listeners[i] === listener) {\n delete this.listeners[i];\n }\n }\n };\n}\n//# sourceMappingURL=queryByExample.js.map","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.UserInput = UserInput;\nvar UI = _interopRequireWildcard(require(\"solid-ui\"));\nvar _solidLogic = require(\"solid-logic\");\nvar panes = _interopRequireWildcard(require(\"pane-registry\"));\nfunction _getRequireWildcardCache(e) { if (\"function\" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }\nfunction _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || \"object\" != _typeof(e) && \"function\" != typeof e) return { \"default\": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if (\"default\" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n[\"default\"] = e, t && t.set(e, n), n; }\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); } /* istanbul ignore file */ // Original author: kennyluck\n//\n// Kenny's Notes:\n/* places to generate SPARQL update: clearInputAndSave() pasteFromClipboard()->insertTermTo();\n undetermined statement generated formUndetStat()\n ->fillInRequest()\n ontological issues\n temporarily using the tabont namespace\n clipboard: 'predicates' 'objects' 'all'(internal)\n request: 'from' 'to' 'message' 'Request'\n*/\nvar $rdf = UI.rdf;\nvar UserInputFormula; // Formula to store references of user's work\nvar TempFormula; // Formula to store incomplete triples (Requests),\n// temporarily disjoint with kb to avoid bugs\n\nfunction UserInput(outline) {\n var myDocument = outline.document; // is this ok?\n // UI.log.warn(\"myDocument when it's set is \"+myDocument.location);\n this.menuId = 'predicateMenu1';\n\n /* //namespace information, as a subgraph of the knowledge base, is built in showMenu\n this.namespaces={};\n for (var name in UI.ns) {\n this.namespaces[name] = UI.ns[name]('').uri;\n }\n var NameSpaces=this.namespaces;\n */\n\n // hq, print and trim functions\n var qp = function qp(str) {\n console.log(str + '\\n');\n };\n\n // var tabont = UI.ns.tabont;\n // var foaf = UI.ns.foaf\n var rdf = UI.ns.rdf;\n // var RDFS = UI.ns.rdfs\n // var OWL = UI.ns.owl\n // var dc = UI.ns.dc\n // var rss = UI.ns.rss\n // var contact = UI.ns.contact\n // var mo = UI.ns.mo\n var bibo = UI.rdf.Namespace('http://purl.org/ontology/bibo/'); // hql for pubsPane\n // var dcterms = UI.rdf.Namespace('http://purl.org/dc/terms/')\n var dcelems = UI.rdf.Namespace('http://purl.org/dc/elements/1.1/');\n var movedArrow = false; // hq\n\n // var updateService=new updateCenter(kb);\n\n if (!UserInputFormula) {\n UserInputFormula = new UI.rdf.Formula();\n UserInputFormula.superFormula = _solidLogic.store;\n // UserInputFormula.registerFormula(\"Your Work\");\n }\n if (!TempFormula) TempFormula = new UI.rdf.IndexedFormula();\n // Use RDFIndexedFormula so add returns the statement\n TempFormula.name = 'TempFormula';\n if (!_solidLogic.store.updater) _solidLogic.store.updater = new UI.rdf.UpdateManager(_solidLogic.store);\n return {\n // updateService: updateService,\n\n sparqler: _solidLogic.store.updater,\n lastModified: null,\n // the last being modified, .isNew indicates whether it's a new input\n lastModifiedStat: null,\n // the last statement being modified\n statIsInverse: false,\n // whether the statement is an inverse\n\n /**\n * Triggering Events: event entry points, should be called only from outline.js but not anywhere else\n * in userinput.js, should be as short as possible, function names to be discussed\n */\n\n // Called when the blue cross under the default pane is clicked.\n // Add a new row to a property list ( P and O)\n addNewPredicateObject: function addNewPredicateObject(e) {\n if (UI.utils.getTarget(e).className !== 'bottom-border-active') return;\n var This = outline.UserInput;\n var target = UI.utils.getTarget(e);\n\n // UI.log.warn(ancestor(target,'TABLE').textContent);\n var insertTr = myDocument.createElement('tr');\n UI.utils.ancestor(target, 'DIV').insertBefore(insertTr, UI.utils.ancestor(target, 'TR'));\n var tempTr = myDocument.createElement('tr');\n var reqTerm1 = This.generateRequest('(TBD)', tempTr, true);\n insertTr.appendChild(tempTr.firstChild);\n var reqTerm2 = This.generateRequest('(Enter text or drag an object onto this field)', tempTr, false);\n insertTr.appendChild(tempTr.firstChild);\n // there should be an elegant way of doing this\n\n // Take the why of the last TR and write to it.\n if (UI.utils.ancestor(target, 'TR').previousSibling &&\n // there is a previous predicate/object line\n UI.utils.ancestor(target, 'TR').previousSibling.AJAR_statement) {\n var preStat = UI.utils.ancestor(target, 'TR').previousSibling.AJAR_statement;\n // This should always(?) input a non-inverse statement\n This.formUndetStat(insertTr, preStat.subject, reqTerm1, reqTerm2, preStat.why, false);\n } else {\n // no previous row: write to the document defining the subject\n var subject = UI.utils.getAbout(_solidLogic.store, UI.utils.ancestor(target.parentNode.parentNode, 'TD'));\n var doc = _solidLogic.store.sym(UI.rdf.Util.uri.docpart(subject.uri));\n This.formUndetStat(insertTr, subject, reqTerm1, reqTerm2, doc, false);\n }\n outline.walk('moveTo', insertTr.firstChild);\n UI.log.info('addNewPredicateObject: selection = ' + outline.getSelection().map(function (item) {\n return item.textContent;\n }).join(', '));\n this.startFillInText(outline.getSelection()[0]);\n },\n // Called when a blue cross on a predicate is clicked\n // tr.AJAR_inverse stores whether the clicked predicate is an inverse one\n // tr.AJAR_statement (an incomplete statement in TempFormula) stores the destination(why), now\n // determined by the preceding one (is this good?)\n addNewObject: function addNewObject(e) {\n var predicateTd = UI.utils.getTarget(e).parentNode.parentNode;\n // var predicateTerm = UI.utils.getAbout(kb, predicateTd)\n var isInverse = predicateTd.parentNode.AJAR_inverse;\n // var titleTerm=UI.utils.getAbout(kb,UI.utils.ancestor(predicateTd.parentNode,'TD'));\n // set pseudo lastModifiedStat here\n this.lastModifiedStat = predicateTd.parentNode.AJAR_statement;\n var insertTr = this.appendToPredicate(predicateTd);\n var reqTerm = this.generateRequest(' (Error) ', insertTr, false);\n var preStat = insertTr.previousSibling.AJAR_statement;\n if (!isInverse) {\n this.formUndetStat(insertTr, preStat.subject, preStat.predicate, reqTerm, preStat.why, false);\n } else {\n this.formUndetStat(insertTr, reqTerm, preStat.predicate, preStat.object, preStat.why, true);\n }\n outline.walk('moveTo', insertTr.lastChild);\n this.startFillInText(insertTr.lastChild);\n // this.statIsInverse=false;\n },\n // Called when delete is pressed\n Delete: function Delete(selectedTd) {\n this.deleteTriple(selectedTd, false);\n },\n // Called when enter is pressed\n Enter: function Enter(selectedTd) {\n this.literalModification(selectedTd);\n },\n // Called when a selected cell is clicked again\n Click: function Click(e) {\n var target = UI.utils.getTarget(e);\n if (UI.utils.getTerm(target).termType !== 'Literal') return;\n this.literalModification(target);\n // this prevents the generated inputbox to be clicked again\n e.preventDefault();\n e.stopPropagation();\n },\n // Called when paste is called (Ctrl+v)\n pasteFromClipboard: function pasteFromClipboard(address, selectedTd) {\n function termFrom(fromCode) {\n var term = outline.clipboard[fromCode].shift();\n if (term === null) {\n UI.log.warn('no more element in clipboard!');\n return;\n }\n switch (fromCode) {\n case 'predicates':\n case 'objects':\n {\n var allArray = outline.clipboard.all;\n for (var i = 0; true; i++) {\n if (term.sameTerm(allArray[i])) {\n allArray.splice(i, 1);\n break;\n }\n }\n break;\n }\n case 'all':\n throw new Error('hostorical code not understood - what is theCollection?');\n /*\n var isObject = term.sameTerm(theCollection('objects').elements[0])\n isObject ? outline.clipboard.objecs.shift() : outline.clipboard.predicates.shift() // drop the corresponding term\n return [term, isObject]\n break\n */\n }\n return term;\n }\n var term;\n switch (selectedTd.className) {\n case 'undetermined selected':\n term = selectedTd.nextSibling ? termFrom('predicates') : termFrom('objects');\n if (!term) return;\n break;\n case 'pred selected':\n // paste objects into this predicate\n term = termFrom('objects');\n if (!term) return;\n break;\n case 'selected':\n {\n // header , undetermined generated\n var returnArray = termFrom('all');\n if (!returnArray) return;\n term = returnArray[0];\n this.insertTermTo(selectedTd, term, returnArray[1]);\n return;\n }\n }\n this.insertTermTo(selectedTd, term);\n },\n /**\n * Intermediate Processing:\n */\n\n // a general entry point for any event except Click&Enter(goes to literalModification)\n // do a little inference to pick the right input box\n startFillInText: function startFillInText(selectedTd) {\n switch (this.whatSortOfEditCell(selectedTd)) {\n case 'DatatypeProperty-like':\n // this.clearMenu();\n // selectedTd.className='';\n UI.utils.emptyNode(selectedTd);\n this.lastModified = this.createInputBoxIn(selectedTd, ' (Please Input) ');\n this.lastModified.isNew = false;\n this.lastModified.select();\n break;\n case 'predicate':\n // the goal is to bring back all the menus (with autocomplete functionality\n // this.performAutoCompleteEdit(selectedTd,['PredicateAutoComplete',\n // this.choiceQuery('SuggestPredicateByDomain')]);\n this.performAutoCompleteEdit(selectedTd, 'PredicateAutoComplete');\n break;\n case 'ObjectProperty-like':\n case 'no-idea':\n // menu should be either function that\n this.performAutoCompleteEdit(selectedTd, 'GeneralAutoComplete');\n\n /*\n //\n emptyNode(selectedTd);\n this.lastModified=this.createInputBoxIn(selectedTd,\"\");\n this.lastModified.select();\n this.lastModified.addEventListener('keypress',this.AutoComplete,false);\n //this pops up the autocomplete menu\n this.AutoComplete(1);\n //\n */\n }\n },\n literalModification: function literalModification(selectedTd) {\n UI.log.debug('entering literal Modification with ' + selectedTd + selectedTd.textContent);\n // var This=outline.UserInput;\n if (selectedTd.className.indexOf(' pendingedit') !== -1) {\n UI.log.warn('The node you attempted to edit has a request still pending.\\n' + 'Please wait for the request to finish (the text will turn black)\\n' + 'before editing this node again.');\n return true;\n }\n var target = selectedTd;\n var about = this.getStatementAbout(target); // timbl - to avoid alert from random clicks\n if (!about) return;\n var obj;\n var trNode;\n try {\n obj = UI.utils.getTerm(target);\n trNode = UI.utils.ancestor(target, 'TR');\n } catch (e) {\n UI.log.warn('userinput.js: ' + e + UI.utils.getAbout(_solidLogic.store, selectedTd));\n UI.log.error(target + ' getStatement Error:' + e);\n }\n var tdNode;\n try {\n tdNode = trNode.lastChild;\n } catch (e) {\n UI.log.error(e + '@' + target);\n }\n // seems to be a event handling problem of firefox3\n /*\n if (e.type!='keypress'&&(selectedTd.className=='undetermined selected'||selectedTd.className=='undetermined')){\n this.Refill(e,selectedTd);\n return;\n }\n */\n // ignore clicking trNode.firstChild (be careful for
or )\n // if (e.type!='keypress'&&target!=tdNode && UI.utils.ancestor(target,'TD')!=tdNode) return;\n\n if (obj.termType === 'Literal') {\n tdNode.removeChild(tdNode.firstChild); // remove the text\n\n if (obj.value.match('\\n')) {\n // match a line feed and require