@kitelev/exocortex-cli 13.191.0 → 13.193.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +3 -3
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // @kitelev/exocortex-cli v13.191.0
2
+ // @kitelev/exocortex-cli v13.193.0
3
3
  // CLI tool for Exocortex knowledge management system - SPARQL queries, task management, and more
4
4
  // License: MIT
5
5
 
@@ -146,7 +146,7 @@ ${i})`;case"extend":return`${i}Extend (?${e.variable} = ${this.expressionToStrin
146
146
  ${this.toString(e.input,t+1)}
147
147
  ${i})`;case"subquery":return`${i}Subquery(
148
148
  ${this.toString(e.query,t+1)}
149
- ${i})`;default:return`${i}Unknown(${e.type})`}}tripleToString(e){return`${this.elementToString(e.subject)} ${this.predicateToString(e.predicate)} ${this.elementToString(e.object)}`}predicateToString(e){return this.isPropertyPath(e)?this.propertyPathToString(e):this.elementToString(e)}isPropertyPath(e){return e.type==="path"}propertyPathToString(e){let t=e.items.map(i=>i.type==="path"?`(${this.propertyPathToString(i)})`:`<${i.value}>`);switch(e.pathType){case"/":return t.join("/");case"|":return t.join("|");case"^":return`^${t[0]}`;case"+":return`${t[0]}+`;case"*":return`${t[0]}*`;case"?":return`${t[0]}?`}}elementToString(e){switch(e.type){case"variable":return`?${e.value}`;case"iri":return`<${e.value}>`;case"literal":let t=`"${e.value}"`;return e.language&&(t+=`@${e.language}`),e.datatype&&(t+=`^^<${e.datatype}>`),t;case"blank":return`_:${e.value}`;default:return String(e)}}expressionToString(e){switch(e.type){case"variable":return`?${e.name}`;case"literal":return typeof e.value=="string"?`"${e.value}"`:String(e.value);case"comparison":return`(${this.expressionToString(e.left)} ${e.operator} ${this.expressionToString(e.right)})`;case"logical":return e.operator==="!"?`!(${this.expressionToString(e.operands[0])})`:`(${e.operands.map(t=>this.expressionToString(t)).join(` ${e.operator} `)})`;case"arithmetic":return`(${this.expressionToString(e.left)} ${e.operator} ${this.expressionToString(e.right)})`;case"function":return`${e.function}(${e.args.map(t=>this.expressionToString(t)).join(", ")})`;case"exists":return`${e.negated?"NOT EXISTS":"EXISTS"} { ${this.toString(e.pattern,0)} }`;default:return"unknown"}}toJSON(e){return JSON.stringify(e,null,2)}};pl.AlgebraSerializer=Pm});var cn=y(ml=>{"use strict";Object.defineProperty(ml,"__esModule",{value:!0});ml.SolutionMapping=void 0;var p3=yt(),m3=et(),g3=sr(),Fm=class r{static{o(this,"SolutionMapping")}constructor(e){this.bindings=e?new Map(e):new Map}get(e){return this.bindings.get(e)}set(e,t){this.bindings.set(e,t)}has(e){return this.bindings.has(e)}variables(){return Array.from(this.bindings.keys())}getBindings(){return new Map(this.bindings)}isCompatibleWith(e){for(let[t,i]of this.bindings.entries()){let n=e.get(t);if(n!==void 0&&!this.areEqual(i,n))return!1}return!0}merge(e){if(!this.isCompatibleWith(e))return null;let t=new r(this.bindings);for(let[i,n]of e.getBindings().entries())t.set(i,n);return t}clone(){return new r(this.bindings)}areEqual(e,t){return e instanceof p3.Literal&&t instanceof p3.Literal?e.equals(t):e instanceof m3.IRI&&t instanceof m3.IRI?e.value===t.value:e instanceof g3.BlankNode&&t instanceof g3.BlankNode?e.id===t.id:!1}toJSON(){let e={};for(let[t,i]of this.bindings.entries())e[t]=i.toString();return e}size(){return this.bindings.size}};ml.SolutionMapping=Fm});var v3=y(da=>{"use strict";Object.defineProperty(da,"__esModule",{value:!0});da.PropertyPathExecutor=da.PropertyPathExecutorError=void 0;var dP=cn(),gl=et(),y3=sr(),Do=class extends Error{static{o(this,"PropertyPathExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="PropertyPathExecutorError"}};da.PropertyPathExecutorError=Do;var Im=class{static{o(this,"PropertyPathExecutor")}constructor(e){this.tripleStore=e,this.MAX_DEPTH=100}async*execute(e,t,i){let n=await this.resolveElement(e),s=this.isVariable(i)?null:await this.resolveElement(i);for(let a of n){let c=await this.evaluatePath(a,t,s);for(let u of c){let l=new dP.SolutionMapping;this.isVariable(e)&&l.set(e.value,a),this.isVariable(i)&&l.set(i.value,u),yield l}}}async*executeWithBindings(e,t){if(!this.isPropertyPath(e.predicate))throw new Do("Predicate is not a property path");let i=this.instantiateElement(e.subject,t),n=this.instantiateElement(e.object,t);for await(let s of this.execute(i,e.predicate,n)){let a=t.merge(s);a!==null&&(yield a)}}async evaluatePath(e,t,i){switch(t.pathType){case"/":return this.evaluateSequencePath(e,t.items,i);case"|":return this.evaluateAlternativePath(e,t.items,i);case"^":return this.evaluateInversePath(e,t.items[0],i);case"+":return this.evaluateOneOrMorePath(e,t.items[0],i);case"*":return this.evaluateZeroOrMorePath(e,t.items[0],i);case"?":return this.evaluateZeroOrOnePath(e,t.items[0],i)}}async evaluateSequencePath(e,t,i){let n=new Set([e]);for(let s=0;s<t.length;s++){let a=t[s],c=s===t.length-1,u=new Set;for(let l of n){let f=await this.evaluatePathItem(l,a,c?i:null);for(let h of f)u.add(h)}if(n=u,n.size===0)break}return n}async evaluateAlternativePath(e,t,i){let n=new Set;for(let s of t){let a=await this.evaluatePathItem(e,s,i);for(let c of a)n.add(c)}return n}async evaluateInversePath(e,t,i){if(t.type==="iri"){let n=new gl.IRI(t.value),s=await this.tripleStore.match(void 0,n,e),a=new Set;for(let c of s)(i===null||this.nodeInSet(c.subject,i))&&a.add(c.subject);return a}else return this.evaluatePath(e,this.invertPath(t),i)}async evaluateOneOrMorePath(e,t,i){let n=new Set,s=new Set,a=[{node:e,depth:0}];for(;a.length>0;){let{node:c,depth:u}=a.shift();if(u>=this.MAX_DEPTH)continue;let l=await this.evaluatePathItem(c,t,null);for(let f of l){let h=this.nodeToKey(f);(i===null||this.nodeInSet(f,i))&&s.add(f),n.has(h)||(n.add(h),a.push({node:f,depth:u+1}))}}return s}async evaluateZeroOrMorePath(e,t,i){let n=await this.evaluateOneOrMorePath(e,t,i);return(i===null||this.nodeInSet(e,i))&&n.add(e),n}async evaluateZeroOrOnePath(e,t,i){let n=new Set;(i===null||this.nodeInSet(e,i))&&n.add(e);let s=await this.evaluatePathItem(e,t,i);for(let a of s)n.add(a);return n}async evaluatePathItem(e,t,i){if(t.type==="iri"){let n=new gl.IRI(t.value),s=await this.tripleStore.match(e,n,void 0),a=new Set;for(let c of s)(i===null||this.nodeInSet(c.object,i))&&a.add(c.object);return a}else return this.evaluatePath(e,t,i)}invertPath(e){switch(e.pathType){case"^":return e.items[0];case"/":return{type:"path",pathType:"/",items:[...e.items].reverse().map(i=>i.type==="iri"?{type:"path",pathType:"^",items:[i]}:this.invertPath(i))};case"|":return{type:"path",pathType:"|",items:e.items.map(i=>i.type==="iri"?{type:"path",pathType:"^",items:[i]}:this.invertPath(i))};case"+":case"*":case"?":let t=e.items[0].type==="iri"?{type:"path",pathType:"^",items:[e.items[0]]}:this.invertPath(e.items[0]);return{type:"path",pathType:e.pathType,items:[t]}}}async resolveElement(e){if(this.isVariable(e)){let i=new Set,n=await this.tripleStore.match(void 0,void 0,void 0);for(let s of n)i.add(s.subject),i.add(s.object);return i}let t=new Set;switch(e.type){case"iri":t.add(new gl.IRI(e.value));break;case"blank":t.add(new y3.BlankNode(e.value));break;default:throw new Do(`Unsupported element type in subject/object position: ${e.type}`)}return t}instantiateElement(e,t){if(this.isVariable(e)){let i=t.get(e.value);if(i){if(i instanceof gl.IRI)return{type:"iri",value:i.value};if(i instanceof y3.BlankNode)return{type:"blank",value:i.id}}}return e}isVariable(e){return e.type==="variable"}isPropertyPath(e){return e.type==="path"}nodeToKey(e){return e.toString()}nodeInSet(e,t){let i=this.nodeToKey(e);for(let n of t)if(this.nodeToKey(n)===i)return!0;return!1}};da.PropertyPathExecutor=Im});var Nm=y(pa=>{"use strict";Object.defineProperty(pa,"__esModule",{value:!0});pa.BGPExecutor=pa.BGPExecutorError=void 0;var yl=cn(),In=et(),Rm=yt(),vl=sr(),_l=eu(),pP=v3(),Ht=class extends Error{static{o(this,"BGPExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="BGPExecutorError"}};pa.BGPExecutorError=Ht;var Dm=class{static{o(this,"BGPExecutor")}constructor(e){this.tripleStore=e,this.propertyPathExecutor=new pP.PropertyPathExecutor(e)}async*execute(e){if(e.triples.length===0){yield new yl.SolutionMapping;return}let t=this.matchTriplePattern(e.triples[0]);for(let i=1;i<e.triples.length;i++)t=this.joinWithPattern(t,e.triples[i]);for await(let i of t)yield i}async executeAll(e){let t=[];for await(let i of this.execute(e))t.push(i);return t}async*executeInGraph(e,t){if(e.triples.length===0){yield new yl.SolutionMapping;return}let i=this.matchTriplePatternInGraph(e.triples[0],t);for(let n=1;n<e.triples.length;n++)i=this.joinWithPatternInGraph(i,e.triples[n],t);for await(let n of i)yield n}async*matchTriplePatternInGraph(e,t){if(this.isPropertyPath(e.predicate))throw new Ht("Property paths within named graphs are not yet supported");let i=e.predicate,n=this.isVariable(e.subject)?void 0:this.toRDFTermAsSubject(e.subject),s=this.isVariable(i)?void 0:this.toRDFTermAsPredicate(i),a=this.isVariable(e.object)?void 0:this.toRDFTerm(e.object);if(!this.tripleStore.matchInGraph)throw new Ht("Triple store does not support named graph operations");let c=await this.tripleStore.matchInGraph(n,s,a,t);for(let u of c){let l=new yl.SolutionMapping;this.isVariable(e.subject)&&l.set(e.subject.value,u.subject),this.isVariable(i)&&l.set(i.value,u.predicate),this.isVariable(e.object)&&l.set(e.object.value,u.object),yield l}}async*joinWithPatternInGraph(e,t,i){let n=[];for await(let s of e)n.push(s);for(let s of n){let a=this.instantiatePattern(t,s);for await(let c of this.matchTriplePatternInGraph(a,i)){let u=s.merge(c);u!==null&&(yield u)}}}async*matchTriplePattern(e){if(this.isPropertyPath(e.predicate)){yield*this.propertyPathExecutor.execute(e.subject,e.predicate,e.object);return}let t=e.predicate,i=this.isVariable(e.subject)||this.isQuotedTriple(e.subject)&&this.hasVariablesInQuotedTriple(e.subject)?void 0:this.toRDFTermAsSubject(e.subject),n=this.isVariable(t)?void 0:this.toRDFTermAsPredicate(t),s=this.isVariable(e.object)||this.isQuotedTriple(e.object)&&this.hasVariablesInQuotedTriple(e.object)?void 0:this.toRDFTerm(e.object),a=await this.tripleStore.match(i,n,s);for(let c of a){let u=new yl.SolutionMapping;if(this.isVariable(e.subject))u.set(e.subject.value,c.subject);else if(this.isQuotedTriple(e.subject)){let l=this.matchQuotedTriplePattern(e.subject,c.subject);if(l===null)continue;for(let[f,h]of l.entries())u.set(f,h)}if(this.isVariable(t)&&u.set(t.value,c.predicate),this.isVariable(e.object))u.set(e.object.value,c.object);else if(this.isQuotedTriple(e.object)){let l=this.matchQuotedTriplePattern(e.object,c.object);if(l===null)continue;for(let[f,h]of l.entries())u.set(f,h)}yield u}}hasVariablesInQuotedTriple(e){return!!(this.isVariable(e.subject)||e.predicate.type==="variable"||this.isVariable(e.object)||this.isQuotedTriple(e.subject)&&this.hasVariablesInQuotedTriple(e.subject)||this.isQuotedTriple(e.object)&&this.hasVariablesInQuotedTriple(e.object))}matchQuotedTriplePattern(e,t){if(!(t instanceof _l.QuotedTriple))return null;let i=new Map;if(this.isVariable(e.subject))i.set(e.subject.value,t.subject);else if(this.isQuotedTriple(e.subject)){let n=this.matchQuotedTriplePattern(e.subject,t.subject);if(n===null)return null;for(let[s,a]of n)i.set(s,a)}else if(!this.elementsMatch(e.subject,t.subject))return null;if(e.predicate.type==="variable")i.set(e.predicate.value,t.predicate);else if(e.predicate.value!==t.predicate.value)return null;if(this.isVariable(e.object))i.set(e.object.value,t.object);else if(this.isQuotedTriple(e.object)){let n=this.matchQuotedTriplePattern(e.object,t.object);if(n===null)return null;for(let[s,a]of n)i.set(s,a)}else if(!this.elementsMatch(e.object,t.object))return null;return i}elementsMatch(e,t){switch(e.type){case"iri":return t instanceof In.IRI&&e.value===t.value;case"literal":return!(!(t instanceof Rm.Literal)||e.value!==t.value||e.datatype!==t.datatype?.value||e.language!==t.language);case"blank":return t instanceof vl.BlankNode&&e.value===t.id;case"quoted":return t instanceof _l.QuotedTriple?this.toRDFQuotedTriple(e).equals(t):!1;default:return!1}}isPropertyPath(e){return e.type==="path"}async*joinWithPattern(e,t){let i=[];for await(let n of e)i.push(n);for(let n of i){let s=this.instantiatePattern(t,n);for await(let a of this.matchTriplePattern(s)){let c=n.merge(a);c!==null&&(yield c)}}}instantiatePattern(e,t){let i=this.isPropertyPath(e.predicate)?e.predicate:this.instantiateElement(e.predicate,t);return{subject:this.instantiateElement(e.subject,t),predicate:i,object:this.instantiateElement(e.object,t)}}instantiateElement(e,t){if(this.isVariable(e)){let i=t.get(e.value);if(i)return this.toAlgebraElement(i)}return this.isQuotedTriple(e)?this.instantiateQuotedTriple(e,t):e}instantiateQuotedTriple(e,t){let i=this.instantiateElement(e.subject,t),n=e.predicate.type==="variable"?this.instantiatePredicateVariable(e.predicate,t):e.predicate,s=this.instantiateElement(e.object,t);return{type:"quoted",subject:i,predicate:n,object:s}}instantiatePredicateVariable(e,t){let i=t.get(e.value);return i&&i instanceof In.IRI?{type:"iri",value:i.value}:e}isVariable(e){return e.type==="variable"}isQuotedTriple(e){return e.type==="quoted"}toRDFTermAsSubject(e){switch(e.type){case"iri":return new In.IRI(e.value);case"blank":return new vl.BlankNode(e.value);case"literal":throw new Ht("Literals cannot appear in subject position");case"variable":throw new Ht(`Cannot convert variable to RDF term: ${e.value}`);case"quoted":return this.toRDFQuotedTriple(e);default:throw new Ht(`Unknown element type: ${e.type}`)}}toRDFQuotedTriple(e){let t=this.toRDFTermAsSubject(e.subject),i=e.predicate.type==="iri"?new In.IRI(e.predicate.value):(()=>{throw new Ht("Quoted triple predicate must be IRI")})(),n=this.toRDFTerm(e.object);return new _l.QuotedTriple(t,i,n)}toRDFTermAsPredicate(e){switch(e.type){case"iri":return new In.IRI(e.value);case"literal":throw new Ht("Literals cannot appear in predicate position");case"blank":throw new Ht("Blank nodes cannot appear in predicate position");case"variable":throw new Ht(`Cannot convert variable to RDF term: ${e.value}`);default:throw new Ht(`Unknown element type: ${e.type}`)}}toRDFTerm(e){switch(e.type){case"iri":return new In.IRI(e.value);case"literal":return new Rm.Literal(e.value,e.datatype?new In.IRI(e.datatype):void 0,e.language);case"blank":return new vl.BlankNode(e.value);case"variable":throw new Ht(`Cannot convert variable to RDF term: ${e.value}`);case"quoted":return this.toRDFQuotedTriple(e);default:throw new Ht(`Unknown element type: ${e.type}`)}}toAlgebraElement(e){if(e instanceof In.IRI)return{type:"iri",value:e.value};if(e instanceof Rm.Literal)return{type:"literal",value:e.value,datatype:e.datatype?.value,language:e.language};if(e instanceof vl.BlankNode)return{type:"blank",value:e.id};if(e instanceof _l.QuotedTriple)return this.toAlgebraQuotedTriple(e);throw new Ht(`Unknown RDF term type: ${e.constructor?.name||"unknown"}`)}toAlgebraQuotedTriple(e){return{type:"quoted",subject:this.toAlgebraElement(e.subject),predicate:{type:"iri",value:e.predicate.value},object:this.toAlgebraElement(e.object)}}};pa.BGPExecutor=Dm});var jm=y(wl=>{"use strict";Object.defineProperty(wl,"__esModule",{value:!0});wl.BuiltInFunctions=void 0;var Be=et(),q=yt(),hi=sr(),km=Cr(),No=class{static{o(this,"BuiltInFunctions")}static str(e){if(e===void 0)throw new Error("STR: argument is undefined");return e instanceof Be.IRI||e instanceof q.Literal?e.value:e instanceof hi.BlankNode?e.id:String(e)}static lang(e){if(e===void 0)throw new Error("LANG: argument is undefined");return e instanceof q.Literal&&e.language?e.language:""}static langdir(e){if(e===void 0)throw new Error("LANGDIR: argument is undefined");return!(e instanceof q.Literal)||!e.language?"":e.direction?`${e.language}--${e.direction}`:e.language}static langMatches(e,t){let i=e.toLowerCase(),n=t.toLowerCase();return n==="*"?i!=="":i===""?n==="":i===n?!0:i.startsWith(n+"-")}static datatype(e){if(e===void 0)throw new Error("DATATYPE: argument is undefined");if(e instanceof q.Literal)return e.datatype?e.datatype:e.language?new Be.IRI("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"):new Be.IRI("http://www.w3.org/2001/XMLSchema#string");throw new Error("DATATYPE: argument must be a literal")}static bound(e){return e!==void 0}static isIRI(e){return e===void 0?!1:e instanceof Be.IRI}static isBlank(e){return e===void 0?!1:e instanceof hi.BlankNode}static isLiteral(e){return e===void 0?!1:e instanceof q.Literal}static hasLangdir(e){return e===void 0||!(e instanceof q.Literal)?!1:!!e.language&&!!e.direction}static isNumeric(e){if(e===void 0||!(e instanceof q.Literal))return!1;let t=e.datatype?.value;return t?["http://www.w3.org/2001/XMLSchema#integer","http://www.w3.org/2001/XMLSchema#decimal","http://www.w3.org/2001/XMLSchema#float","http://www.w3.org/2001/XMLSchema#double","http://www.w3.org/2001/XMLSchema#nonPositiveInteger","http://www.w3.org/2001/XMLSchema#negativeInteger","http://www.w3.org/2001/XMLSchema#long","http://www.w3.org/2001/XMLSchema#int","http://www.w3.org/2001/XMLSchema#short","http://www.w3.org/2001/XMLSchema#byte","http://www.w3.org/2001/XMLSchema#nonNegativeInteger","http://www.w3.org/2001/XMLSchema#unsignedLong","http://www.w3.org/2001/XMLSchema#unsignedInt","http://www.w3.org/2001/XMLSchema#unsignedShort","http://www.w3.org/2001/XMLSchema#unsignedByte","http://www.w3.org/2001/XMLSchema#positiveInteger"].includes(t):!1}static regex(e,t,i){try{return new RegExp(t,i).test(e)}catch(n){throw new Error(`REGEX: invalid pattern '${t}': ${n.message}`)}}static compare(e,t,i){if(this.isDayTimeDurationValue(e)&&this.isDayTimeDurationValue(t))return this.compareDurations(e instanceof q.Literal?e:String(e),t instanceof q.Literal?t:String(t),i);let n=this.toComparableValue(e),s=this.toComparableValue(t);switch(i){case"=":return n===s;case"!=":return n!==s;case"<":return n<s;case">":return n>s;case"<=":return n<=s;case">=":return n>=s;default:throw new Error(`Unknown comparison operator: ${i}`)}}static isDayTimeDurationValue(e){return e instanceof q.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#dayTimeDuration":!1}static toComparableValue(e){if(typeof e=="string"||typeof e=="number")return e;if(e instanceof q.Literal){let t=e.datatype?.value;if(t?.includes("#integer")||t?.includes("#decimal")||t?.includes("#double")){let i=parseFloat(e.value);if(!isNaN(i))return i}if(t==="http://www.w3.org/2001/XMLSchema#dayTimeDuration")try{return this.parseDayTimeDuration(e.value)}catch{return e.value}return e.value}return e instanceof Be.IRI?e.value:e instanceof hi.BlankNode?e.id:String(e)}static contains(e,t){return e.includes(t)}static strStarts(e,t){return e.startsWith(t)}static strEnds(e,t){return e.endsWith(t)}static strlen(e){return e.length}static ucase(e){return e.toUpperCase()}static lcase(e){return e.toLowerCase()}static substr(e,t,i){let n=t-1;if(n<0){if(i!==void 0){let s=i+n;return s<=0?"":e.substring(0,s)}return e}return i!==void 0?e.substring(n,n+i):e.substring(n)}static strBefore(e,t){if(t==="")return"";let i=e.indexOf(t);return i===-1?"":e.substring(0,i)}static strAfter(e,t){if(t==="")return e;let i=e.indexOf(t);return i===-1?"":e.substring(i+t.length)}static concat(...e){return e.join("")}static replace(e,t,i,n){try{let s=new RegExp(t,n||"g");return e.replace(s,i)}catch(s){throw new Error(`REPLACE: invalid pattern '${t}': ${s.message}`)}}static parseDate(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`PARSEDATE: invalid date string '${e}'`);return t.getTime()}static dateBefore(e,t){let i=this.parseDate(e),n=this.parseDate(t);return i<n}static dateAfter(e,t){let i=this.parseDate(e),n=this.parseDate(t);return i>n}static dateInRange(e,t,i){let n=this.parseDate(e),s=this.parseDate(t),a=this.parseDate(i);return n>=s&&n<=a}static dateDiffMinutes(e,t){let i=this.parseDate(e),n=this.parseDate(t),s=Math.abs(n-i);return Math.round(s/(1e3*60))}static dateDiffHours(e,t){let i=this.parseDate(e),n=this.parseDate(t),s=Math.abs(n-i);return Math.round(s/(1e3*60*60)*100)/100}static logicalAnd(e){return e.every(t=>t===!0)}static logicalOr(e){return e.some(t=>t===!0)}static logicalNot(e){return!e}static year(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`YEAR: invalid date string '${e}'`);return t.getFullYear()}static month(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`MONTH: invalid date string '${e}'`);return t.getMonth()+1}static day(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`DAY: invalid date string '${e}'`);return t.getDate()}static hours(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`HOURS: invalid date string '${e}'`);return t.getHours()}static minutes(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`MINUTES: invalid date string '${e}'`);return t.getMinutes()}static seconds(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`SECONDS: invalid date string '${e}'`);return t.getSeconds()+t.getMilliseconds()/1e3}static timezone(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`TIMEZONE: invalid date string '${e}'`);let i;if(e.endsWith("Z"))i="PT0S";else{let n=e.match(/([+-]\d{2}):?(\d{2})$/);if(n){let s=parseInt(n[1],10),a=parseInt(n[2],10),c=s>=0?"":"-",u=Math.abs(s);a===0?i=`${c}PT${u}H`:i=`${c}PT${u}H${a}M`}else{let s=-t.getTimezoneOffset(),a=Math.floor(Math.abs(s)/60),c=Math.abs(s)%60,u=s>=0?"":"-";c===0?i=`${u}PT${a}H`:i=`${u}PT${a}H${c}M`}}return new q.Literal(i,new Be.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static tz(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`TZ: invalid date string '${e}'`);if(e.endsWith("Z"))return"Z";let i=e.match(/([+-]\d{2}:\d{2})$/);if(i)return i[1];let n=e.match(/([+-])(\d{2})(\d{2})$/);return n?`${n[1]}${n[2]}:${n[3]}`:""}static now(){return new Date().toISOString()}static msToMinutes(e){return Math.round(e/(1e3*60))}static msToHours(e){return Math.round(e/(1e3*60*60)*100)/100}static msToSeconds(e){return Math.round(e/1e3)}static abs(e){return Math.abs(e)}static round(e){return Math.round(e)}static ceil(e){return Math.ceil(e)}static floor(e){return Math.floor(e)}static rand(){return Math.random()}static coalesce(e){for(let t of e)if(t!=null)return t}static if(e,t,i){return e?t:i}static xsdDateTime(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`xsd:dateTime: invalid date string '${e}'`);return new q.Literal(t.toISOString(),new Be.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}static xsdInteger(e){let t=parseInt(e,10);if(isNaN(t))throw new Error(`xsd:integer: cannot convert '${e}' to integer`);return new q.Literal(String(t),new Be.IRI("http://www.w3.org/2001/XMLSchema#integer"))}static xsdDecimal(e){let t=parseFloat(e);if(isNaN(t))throw new Error(`xsd:decimal: cannot convert '${e}' to decimal`);return new q.Literal(String(t),new Be.IRI("http://www.w3.org/2001/XMLSchema#decimal"))}static encodeForUri(e){return encodeURIComponent(e)}static md5(e){return require("crypto").createHash("md5").update(e).digest("hex")}static sha1(e){return require("crypto").createHash("sha1").update(e).digest("hex")}static sha256(e){return require("crypto").createHash("sha256").update(e).digest("hex")}static sha384(e){return require("crypto").createHash("sha384").update(e).digest("hex")}static sha512(e){return require("crypto").createHash("sha512").update(e).digest("hex")}static sameTerm(e,t){if(e===void 0&&t===void 0)return!0;if(e===void 0||t===void 0||e.constructor!==t.constructor)return!1;if(e instanceof Be.IRI&&t instanceof Be.IRI)return e.value===t.value;if(e instanceof hi.BlankNode&&t instanceof hi.BlankNode)return e.id===t.id;if(e instanceof q.Literal&&t instanceof q.Literal){if(e.value!==t.value||e.language!==t.language)return!1;let i=e.datatype?.value,n=t.datatype?.value;return i===n}return!1}static iri(e){if(e===void 0)throw new Error("IRI: argument is undefined");if(e instanceof Be.IRI)return e;if(e instanceof q.Literal)return new Be.IRI(e.value);throw e instanceof hi.BlankNode?new Error("IRI: cannot convert blank node to IRI"):new Error("IRI: unsupported term type")}static uri(e){return this.iri(e)}static bnode(e){if(e===void 0){let t=`b${(0,km.v4)().replace(/-/g,"").substring(0,12)}`;return new hi.BlankNode(t)}if(e instanceof q.Literal)return new hi.BlankNode(e.value);if(e instanceof hi.BlankNode)return e;throw new Error("BNODE: argument must be a string literal or omitted")}static strdt(e,t){if(e===void 0)throw new Error("STRDT: lexical form is undefined");if(t===void 0)throw new Error("STRDT: datatype IRI is undefined");let i;if(e instanceof q.Literal){if(e.language)throw new Error("STRDT: lexical form must not have a language tag");i=e.value}else if(typeof e=="string")i=e;else throw new Error("STRDT: lexical form must be a string literal");let n;if(t instanceof Be.IRI)n=t;else if(t instanceof q.Literal)n=new Be.IRI(t.value);else throw new Error("STRDT: datatype must be an IRI");return new q.Literal(i,n)}static strlang(e,t){if(e===void 0)throw new Error("STRLANG: lexical form is undefined");if(t===void 0)throw new Error("STRLANG: language tag is undefined");let i;if(e instanceof q.Literal){if(e.language)throw new Error("STRLANG: lexical form must not already have a language tag");i=e.value}else if(typeof e=="string")i=e;else throw new Error("STRLANG: lexical form must be a string literal");let n;if(t instanceof q.Literal)n=t.value;else if(typeof t=="string")n=t;else throw new Error("STRLANG: language tag must be a string literal");if(n==="")throw new Error("STRLANG: language tag cannot be empty");return new q.Literal(i,void 0,n)}static strlangdir(e,t,i){if(e===void 0)throw new Error("STRLANGDIR: lexical form is undefined");if(t===void 0)throw new Error("STRLANGDIR: language tag is undefined");if(i===void 0)throw new Error("STRLANGDIR: direction is undefined");let n;if(e instanceof q.Literal){if(e.language)throw new Error("STRLANGDIR: lexical form must not already have a language tag");n=e.value}else if(typeof e=="string")n=e;else throw new Error("STRLANGDIR: lexical form must be a string literal");let s;if(t instanceof q.Literal)s=t.value;else if(typeof t=="string")s=t;else throw new Error("STRLANGDIR: language tag must be a string literal");if(s==="")throw new Error("STRLANGDIR: language tag cannot be empty");let a;if(i instanceof q.Literal)a=i.value.toLowerCase();else throw new Error("STRLANGDIR: direction must be a string literal");if(a!=="ltr"&&a!=="rtl")throw new Error(`STRLANGDIR: invalid direction '${a}'. Must be 'ltr' or 'rtl'`);return new q.Literal(n,void 0,s,a)}static uuid(){let e=(0,km.v4)();return new Be.IRI(`urn:uuid:${e}`)}static struuid(){let e=(0,km.v4)();return new q.Literal(e)}static parseDayTimeDuration(e){if(!e)throw new Error("parseDayTimeDuration: duration string is empty");let t=!1,i=e.trim();if(i.startsWith("-")&&(t=!0,i=i.substring(1)),!i.startsWith("P"))throw new Error(`parseDayTimeDuration: invalid format, must start with 'P': '${e}'`);i=i.substring(1);let n=0,s=i.indexOf("T"),a="",c="";if(s===-1?a=i:(a=i.substring(0,s),c=i.substring(s+1)),a){let u=a.match(/^(\d+(?:\.\d+)?)D$/);if(u){let l=parseFloat(u[1]);n+=l*24*60*60*1e3}else if(a!=="")throw new Error(`parseDayTimeDuration: invalid day component: '${a}' in '${e}'`)}if(c){let u=c,l=u.match(/^(\d+(?:\.\d+)?)H/);if(l){let d=parseFloat(l[1]);n+=d*60*60*1e3,u=u.substring(l[0].length)}let f=u.match(/^(\d+(?:\.\d+)?)M/);if(f){let d=parseFloat(f[1]);n+=d*60*1e3,u=u.substring(f[0].length)}let h=u.match(/^(\d+(?:\.\d+)?)S$/);if(h){let d=parseFloat(h[1]);n+=d*1e3,u=u.substring(h[0].length)}if(u!=="")throw new Error(`parseDayTimeDuration: invalid time component: '${u}' in '${e}'`)}return t?-n:n}static formatDayTimeDuration(e){let t=e<0,i=Math.abs(e),n=Math.floor(i/(1440*60*1e3));i=i%(1440*60*1e3);let s=Math.floor(i/(3600*1e3));i=i%(3600*1e3);let a=Math.floor(i/(60*1e3));i=i%(60*1e3);let c=i/1e3,u=t?"-P":"P";return n>0&&(u+=`${n}D`),(s>0||a>0||c>0||n===0)&&(u+="T",s>0&&(u+=`${s}H`),a>0&&(u+=`${a}M`),(c>0||s===0&&a===0)&&(Number.isInteger(c)?u+=`${c}S`:u+=`${parseFloat(c.toFixed(3))}S`)),u}static xsdDayTimeDuration(e){return this.parseDayTimeDuration(e),new q.Literal(e,new Be.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static compareDurations(e,t,i){let n=e instanceof q.Literal?e.value:e,s=t instanceof q.Literal?t.value:t,a=this.parseDayTimeDuration(n),c=this.parseDayTimeDuration(s);switch(i){case"=":return a===c;case"!=":return a!==c;case"<":return a<c;case">":return a>c;case"<=":return a<=c;case">=":return a>=c;default:throw new Error(`compareDurations: unknown operator: ${i}`)}}static isDayTimeDuration(e){return e instanceof q.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#dayTimeDuration":!1}static dateTimeDiff(e,t){let i=e instanceof q.Literal?e.value:e,n=t instanceof q.Literal?t.value:t,s=new Date(i),a=new Date(n);if(isNaN(s.getTime()))throw new Error(`dateTimeDiff: invalid first dateTime: '${i}'`);if(isNaN(a.getTime()))throw new Error(`dateTimeDiff: invalid second dateTime: '${n}'`);let c=s.getTime()-a.getTime(),u=this.formatDayTimeDuration(c);return new q.Literal(u,new Be.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static dateTimeAdd(e,t){let i=e instanceof q.Literal?e.value:e,n=t instanceof q.Literal?t.value:t,s=new Date(i);if(isNaN(s.getTime()))throw new Error(`dateTimeAdd: invalid dateTime: '${i}'`);let a=this.parseDayTimeDuration(n),c=s.getTime()+a,u=new Date(c);return new q.Literal(u.toISOString(),new Be.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}static dateTimeSubtract(e,t){let i=e instanceof q.Literal?e.value:e,n=t instanceof q.Literal?t.value:t,s=new Date(i);if(isNaN(s.getTime()))throw new Error(`dateTimeSubtract: invalid dateTime: '${i}'`);let a=this.parseDayTimeDuration(n),c=s.getTime()-a,u=new Date(c);return new q.Literal(u.toISOString(),new Be.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}static durationAdd(e,t){let i=e instanceof q.Literal?e.value:e,n=t instanceof q.Literal?t.value:t,s=this.parseDayTimeDuration(i),a=this.parseDayTimeDuration(n),c=this.formatDayTimeDuration(s+a);return new q.Literal(c,new Be.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static durationSubtract(e,t){let i=e instanceof q.Literal?e.value:e,n=t instanceof q.Literal?t.value:t,s=this.parseDayTimeDuration(i),a=this.parseDayTimeDuration(n),c=this.formatDayTimeDuration(s-a);return new q.Literal(c,new Be.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static durationMultiply(e,t){let i=e instanceof q.Literal?e.value:e,n=this.parseDayTimeDuration(i),s=this.formatDayTimeDuration(n*t);return new q.Literal(s,new Be.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static durationDivide(e,t){if(t===0)throw new Error("durationDivide: division by zero");let i=e instanceof q.Literal?e.value:e,n=this.parseDayTimeDuration(i),s=this.formatDayTimeDuration(n/t);return new q.Literal(s,new Be.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static durationToDays(e){let t=e instanceof q.Literal?e.value:e;return this.parseDayTimeDuration(t)/(1440*60*1e3)}static durationToHours(e){let t=e instanceof q.Literal?e.value:e;return this.parseDayTimeDuration(t)/(3600*1e3)}static durationToMinutes(e){let t=e instanceof q.Literal?e.value:e;return this.parseDayTimeDuration(t)/(60*1e3)}static durationToSeconds(e){let t=e instanceof q.Literal?e.value:e;return this.parseDayTimeDuration(t)/1e3}static parseDurationComponents(e){if(!e)throw new Error("parseDurationComponents: duration string is empty");let t=!1,i=e.trim();if(i.startsWith("-")&&(t=!0,i=i.substring(1)),!i.startsWith("P"))throw new Error(`parseDurationComponents: invalid format, must start with 'P': '${e}'`);i=i.substring(1);let n=0,s=0,a=0,c=0,u=i.indexOf("T"),l="",f="";if(u===-1?l=i:(l=i.substring(0,u),f=i.substring(u+1)),l){let h=l.match(/^(\d+(?:\.\d+)?)D$/);if(h)n=parseFloat(h[1]);else if(l!=="")throw new Error(`parseDurationComponents: invalid day component: '${l}' in '${e}'`)}if(f){let h=f,d=h.match(/^(\d+(?:\.\d+)?)H/);d&&(s=parseFloat(d[1]),h=h.substring(d[0].length));let g=h.match(/^(\d+(?:\.\d+)?)M/);g&&(a=parseFloat(g[1]),h=h.substring(g[0].length));let _=h.match(/^(\d+(?:\.\d+)?)S$/);if(_&&(c=parseFloat(_[1]),h=h.substring(_[0].length)),h!=="")throw new Error(`parseDurationComponents: invalid time component: '${h}' in '${e}'`)}return{negative:t,days:n,hours:s,minutes:a,seconds:c}}static durationDays(e){let t=e instanceof q.Literal?e.value:e,i=this.parseDurationComponents(t),n=Math.floor(i.days);return i.negative?-n:n}static durationHours(e){let t=e instanceof q.Literal?e.value:e,i=this.parseDurationComponents(t),n=Math.floor(i.hours);return i.negative?-n:n}static durationMinutes(e){let t=e instanceof q.Literal?e.value:e,i=this.parseDurationComponents(t),n=Math.floor(i.minutes);return i.negative?-n:n}static durationSeconds(e){let t=e instanceof q.Literal?e.value:e,i=this.parseDurationComponents(t);return i.negative?-i.seconds:i.seconds}static adjust(e,t){let i=e instanceof q.Literal?e.value:e,n=new Date(i);if(isNaN(n.getTime()))throw new Error(`ADJUST: invalid dateTime: '${i}'`);if(t==null){let Ie=n.getUTCFullYear(),Je=String(n.getUTCMonth()+1).padStart(2,"0"),ot=String(n.getUTCDate()).padStart(2,"0"),B=String(n.getUTCHours()).padStart(2,"0"),ue=String(n.getUTCMinutes()).padStart(2,"0"),we=String(n.getUTCSeconds()).padStart(2,"0"),He=n.getUTCMilliseconds(),Ue=`${Ie}-${Je}-${ot}T${B}:${ue}:${we}`;return He>0&&(Ue+=`.${String(He).padStart(3,"0")}`),new q.Literal(Ue,new Be.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}let s=t instanceof q.Literal?t.value:t,a=this.parseDayTimeDuration(s),c=840*60*1e3;if(Math.abs(a)>c)throw new Error(`ADJUST: timezone offset out of range: '${s}'`);let u=n.getTime(),l=new Date(u+a),f=l.getUTCFullYear(),h=String(l.getUTCMonth()+1).padStart(2,"0"),d=String(l.getUTCDate()).padStart(2,"0"),g=String(l.getUTCHours()).padStart(2,"0"),_=String(l.getUTCMinutes()).padStart(2,"0"),w=String(l.getUTCSeconds()).padStart(2,"0"),C=l.getUTCMilliseconds(),O=a>=0?"+":"-",F=Math.floor(Math.abs(a)/(3600*1e3)),j=Math.floor(Math.abs(a)%(3600*1e3)/(60*1e3)),G=`${O}${String(F).padStart(2,"0")}:${String(j).padStart(2,"0")}`,W=`${f}-${h}-${d}T${g}:${_}:${w}`;return C>0&&(W+=`.${String(C).padStart(3,"0")}`),W+=G,new q.Literal(W,new Be.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}static normalize(e,t){if(e===void 0)throw new Error("NORMALIZE: string argument is undefined");let i;if(e instanceof q.Literal)i=e.value;else if(e instanceof Be.IRI)i=e.value;else if(e instanceof hi.BlankNode)i=e.id;else if(typeof e=="string")i=e;else throw new Error("NORMALIZE: first argument must be a string or literal");let n="NFC";if(t!==void 0)if(t instanceof q.Literal)n=t.value.toUpperCase();else if(typeof t=="string")n=t.toUpperCase();else if(t instanceof Be.IRI)n=t.value.toUpperCase();else throw new Error("NORMALIZE: second argument must be a string literal");if(!this.VALID_NORMALIZATION_FORMS.includes(n))throw new Error(`NORMALIZE: invalid normalization form '${n}'. Valid forms are: NFC, NFD, NFKC, NFKD`);let s=i.normalize(n);return new q.Literal(s,new Be.IRI("http://www.w3.org/2001/XMLSchema#string"))}static fold(e){if(e===void 0)throw new Error("FOLD: string argument is undefined");let t;if(e instanceof q.Literal)t=e.value;else if(e instanceof Be.IRI)t=e.value;else if(e instanceof hi.BlankNode)t=e.id;else if(typeof e=="string")t=e;else throw new Error("FOLD: argument must be a string or literal");let i=this.unicodeCaseFold(t);return new q.Literal(i,new Be.IRI("http://www.w3.org/2001/XMLSchema#string"))}static unicodeCaseFold(e){let t="";for(let i of e){let n=this.CASE_FOLDING_MAP.get(i);n!==void 0?t+=n:t+=i.toLowerCase()}return t}};wl.BuiltInFunctions=No;No.VALID_NORMALIZATION_FORMS=["NFC","NFD","NFKC","NFKD"];No.CASE_FOLDING_MAP=new Map([["\xDF","ss"],["\u1E9E","ss"],["\u03A3","\u03C3"],["\u03C2","\u03C3"],["\u0130","i\u0307"],["I","i"],["\u0587","\u0565\u0582"],["\uFB00","ff"],["\uFB01","fi"],["\uFB02","fl"],["\uFB03","ffi"],["\uFB04","ffl"],["\uFB05","st"],["\uFB06","st"],["\u0390","\u03B9\u0308\u0301"],["\u03B0","\u03C5\u0308\u0301"],["\u017F","s"],["\u1E9B","\u1E61"],["\u212A","k"],["\u212B","\xE5"]])});var Sl=y(ma=>{"use strict";Object.defineProperty(ma,"__esModule",{value:!0});ma.FilterExecutor=ma.FilterExecutorError=void 0;var D=jm(),bl=yt(),Mt=class extends Error{static{o(this,"FilterExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="FilterExecutorError"}};ma.FilterExecutorError=Mt;var Lm=class{static{o(this,"FilterExecutor")}constructor(){this.existsEvaluator=null,this.tripleStore=null,this.uuidCache=new Map}setExistsEvaluator(e){this.existsEvaluator=e}setTripleStore(e){this.tripleStore=e,this.uuidCache.clear()}async*execute(e,t){let i=this.expressionContainsExists(e.expression);for await(let n of t)try{let s;i?s=await this.evaluateExpressionAsync(e.expression,n):s=this.evaluateExpression(e.expression,n),s===!0&&(yield n)}catch{continue}}expressionContainsExists(e){if(e.type==="exists")return!0;if(e.type==="logical")return e.operands.some(t=>this.expressionContainsExists(t));if(e.type==="comparison")return this.expressionContainsExists(e.left)||this.expressionContainsExists(e.right);if(e.type==="in"){let t=e;return this.expressionContainsExists(t.expression)||t.list.some(i=>this.expressionContainsExists(i))}return!1}async executeAll(e,t){let i=[];async function*n(){for(let s of t)yield s}o(n,"generator");for await(let s of this.execute(e,n()))i.push(s);return i}evaluateExpression(e,t){let i=e;if(i.termType)switch(i.termType){case"Variable":return t.get(i.value);case"Literal":return i.value;case"NamedNode":return i.value;default:throw new Mt(`Unsupported termType: ${i.termType}`)}switch(e.type){case"comparison":return this.evaluateComparison(e,t);case"logical":return this.evaluateLogical(e,t);case"arithmetic":return this.evaluateArithmetic(e,t);case"function":case"functionCall":return this.evaluateFunction(e,t);case"variable":return t.get(e.name);case"literal":return e.value;case"in":return this.evaluateIn(e,t);case"exists":throw new Mt("EXISTS expressions require async evaluation. Use evaluateExpressionAsync instead.");default:throw new Mt(`Unsupported expression type: ${e.type}, expr.termType=${i.termType}`)}}async evaluateExpressionAsync(e,t){return e.type==="exists"?this.evaluateExists(e,t):e.type==="logical"?this.evaluateLogicalAsync(e,t):this.evaluateExpression(e,t)}async evaluateExists(e,t){if(!this.existsEvaluator)throw new Mt("EXISTS evaluator not set. Call setExistsEvaluator before evaluating EXISTS expressions.");let i=await this.existsEvaluator(e.pattern,t);return e.negated?!i:i}async evaluateLogicalAsync(e,t){if(e.operator==="!"){let n=await this.evaluateExpressionAsync(e.operands[0],t);return D.BuiltInFunctions.logicalNot(n)}let i=[];for(let n of e.operands){let s=await this.evaluateExpressionAsync(n,t);i.push(s)}if(e.operator==="&&")return D.BuiltInFunctions.logicalAnd(i);if(e.operator==="||")return D.BuiltInFunctions.logicalOr(i);throw new Mt(`Unknown logical operator: ${e.operator}`)}evaluateComparison(e,t){let i=this.evaluateExpression(e.left,t),n=this.evaluateExpression(e.right,t);return D.BuiltInFunctions.compare(i,n,e.operator)}evaluateLogical(e,t){if(e.operator==="!"){let n=this.evaluateExpression(e.operands[0],t);return D.BuiltInFunctions.logicalNot(n)}let i=e.operands.map(n=>this.evaluateExpression(n,t));if(e.operator==="&&")return D.BuiltInFunctions.logicalAnd(i);if(e.operator==="||")return D.BuiltInFunctions.logicalOr(i);throw new Mt(`Unknown logical operator: ${e.operator}`)}evaluateIn(e,t){let i=this.evaluateExpression(e.expression,t),n=e.list.some(s=>{let a=this.evaluateExpression(s,t);return D.BuiltInFunctions.compare(i,a,"=")});return e.negated?!n:n}evaluateArithmetic(e,t){let i=this.evaluateExpression(e.left,t),n=this.evaluateExpression(e.right,t);if(e.operator==="-"&&this.isDateTimeValue(i)&&this.isDateTimeValue(n))return D.BuiltInFunctions.dateTimeDiff(i,n);if(e.operator==="+"&&this.isDateTimeValue(i)&&this.isDayTimeDurationValue(n))return D.BuiltInFunctions.dateTimeAdd(i,n);if(e.operator==="-"&&this.isDateTimeValue(i)&&this.isDayTimeDurationValue(n))return D.BuiltInFunctions.dateTimeSubtract(i,n);if(e.operator==="+"&&this.isDayTimeDurationValue(i)&&this.isDayTimeDurationValue(n))return D.BuiltInFunctions.durationAdd(i,n);if(e.operator==="-"&&this.isDayTimeDurationValue(i)&&this.isDayTimeDurationValue(n))return D.BuiltInFunctions.durationSubtract(i,n);if(e.operator==="*"&&this.isDayTimeDurationValue(i)&&!this.isDayTimeDurationValue(n)){let c=this.toNumericValue(n);return D.BuiltInFunctions.durationMultiply(i,c)}if(e.operator==="*"&&!this.isDayTimeDurationValue(i)&&this.isDayTimeDurationValue(n)){let c=this.toNumericValue(i);return D.BuiltInFunctions.durationMultiply(n,c)}if(e.operator==="/"&&this.isDayTimeDurationValue(i)&&!this.isDayTimeDurationValue(n)){let c=this.toNumericValue(n);if(c===0)throw new Mt("Division by zero");return D.BuiltInFunctions.durationDivide(i,c)}let s=this.toNumericValue(i),a=this.toNumericValue(n);switch(e.operator){case"+":return s+a;case"-":return s-a;case"*":return s*a;case"/":if(a===0)throw new Mt("Division by zero");return s/a;default:throw new Mt(`Unknown arithmetic operator: ${e.operator}`)}}isDayTimeDurationValue(e){return e instanceof bl.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#dayTimeDuration":!1}toNumericValue(e){if(typeof e=="number")return e;if(e instanceof bl.Literal){let t=e.datatype?.value||"";if(t.includes("#integer")||t.includes("#decimal")||t.includes("#double")||t.includes("#float")){let n=parseFloat(e.value);if(!isNaN(n))return n}let i=parseFloat(e.value);if(!isNaN(i))return i}if(typeof e=="string"){let t=parseFloat(e);if(!isNaN(t))return t}if(e&&typeof e=="object"&&"value"in e){let t=parseFloat(String(e.value));if(!isNaN(t))return t}throw new Mt(`Cannot convert to number: ${e}`)}isDateTimeValue(e){if(e instanceof bl.Literal){let t=e.datatype?.value||"";return t.includes("#dateTime")||t.includes("#date")?!0:/^\d{4}-\d{2}-\d{2}(T|\s)/.test(e.value)}return typeof e=="string"?/^\d{4}-\d{2}-\d{2}(T|\s)/.test(e):!1}evaluateFunction(e,t){let i;if(typeof e.function=="string")i=e.function.toLowerCase();else if(e.function&&typeof e.function=="object"&&"value"in e.function){let n=e.function.value;i=((n.includes("#")?n.split("#").pop():n.split("/").pop())||n).toLowerCase()}else throw new Mt(`Unknown function format: ${e.function}`);switch(i){case"str":let n=this.getTermFromExpression(e.args[0],t);return D.BuiltInFunctions.str(n);case"lang":let s=this.getTermFromExpression(e.args[0],t);return D.BuiltInFunctions.lang(s);case"datatype":let a=this.getTermFromExpression(e.args[0],t);return D.BuiltInFunctions.datatype(a).value;case"bound":if(e.args[0].type==="variable"){let E=t.get(e.args[0].name);return D.BuiltInFunctions.bound(E)}return!0;case"isiri":case"isuri":let c=this.getTermFromExpression(e.args[0],t);return D.BuiltInFunctions.isIRI(c);case"isblank":let u=this.getTermFromExpression(e.args[0],t);return D.BuiltInFunctions.isBlank(u);case"isliteral":let l=this.getTermFromExpression(e.args[0],t);return D.BuiltInFunctions.isLiteral(l);case"regex":let f=this.getStringValue(this.evaluateExpression(e.args[0],t)),h=this.getStringValue(this.evaluateExpression(e.args[1],t)),d=e.args[2]?this.getStringValue(this.evaluateExpression(e.args[2],t)):void 0;return D.BuiltInFunctions.regex(f,h,d);case"langmatches":let g=this.getStringValue(this.evaluateExpression(e.args[0],t)),_=this.getStringValue(this.evaluateExpression(e.args[1],t));return D.BuiltInFunctions.langMatches(g,_);case"contains":let w=this.getStringValue(this.evaluateExpression(e.args[0],t)),C=this.getStringValue(this.evaluateExpression(e.args[1],t));return D.BuiltInFunctions.contains(w,C);case"strstarts":let O=this.getStringValue(this.evaluateExpression(e.args[0],t)),F=this.getStringValue(this.evaluateExpression(e.args[1],t));return D.BuiltInFunctions.strStarts(O,F);case"strends":let j=this.getStringValue(this.evaluateExpression(e.args[0],t)),G=this.getStringValue(this.evaluateExpression(e.args[1],t));return D.BuiltInFunctions.strEnds(j,G);case"strlen":let W=this.getStringValue(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.strlen(W);case"ucase":let Ie=this.getStringValue(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.ucase(Ie);case"lcase":let Je=this.getStringValue(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.lcase(Je);case"substr":let ot=this.getStringValue(this.evaluateExpression(e.args[0],t)),B=Number(this.evaluateExpression(e.args[1],t));if(e.args[2]){let E=Number(this.evaluateExpression(e.args[2],t));return D.BuiltInFunctions.substr(ot,B,E)}return D.BuiltInFunctions.substr(ot,B);case"strbefore":let ue=this.getStringValue(this.evaluateExpression(e.args[0],t)),we=this.getStringValue(this.evaluateExpression(e.args[1],t));return D.BuiltInFunctions.strBefore(ue,we);case"strafter":let He=this.getStringValue(this.evaluateExpression(e.args[0],t)),Ue=this.getStringValue(this.evaluateExpression(e.args[1],t));return D.BuiltInFunctions.strAfter(He,Ue);case"concat":let Ze=e.args.map(E=>this.getStringValue(this.evaluateExpression(E,t)));return D.BuiltInFunctions.concat(...Ze);case"replace":let ke=this.getStringValue(this.evaluateExpression(e.args[0],t)),je=this.getStringValue(this.evaluateExpression(e.args[1],t)),Re=this.getStringValue(this.evaluateExpression(e.args[2],t)),H=e.args[3]?this.getStringValue(this.evaluateExpression(e.args[3],t)):void 0;return D.BuiltInFunctions.replace(ke,je,Re,H);case"parsedate":let N=this.getStringValue(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.parseDate(N);case"datebefore":let Le=this.getStringValue(this.evaluateExpression(e.args[0],t)),Ge=this.getStringValue(this.evaluateExpression(e.args[1],t));return D.BuiltInFunctions.dateBefore(Le,Ge);case"dateafter":let V=this.getStringValue(this.evaluateExpression(e.args[0],t)),he=this.getStringValue(this.evaluateExpression(e.args[1],t));return D.BuiltInFunctions.dateAfter(V,he);case"dateinrange":let Ae=this.getStringValue(this.evaluateExpression(e.args[0],t)),z=this.getStringValue(this.evaluateExpression(e.args[1],t)),xe=this.getStringValue(this.evaluateExpression(e.args[2],t));return D.BuiltInFunctions.dateInRange(Ae,z,xe);case"datediffminutes":let Ce=this.getStringValue(this.evaluateExpression(e.args[0],t)),be=this.getStringValue(this.evaluateExpression(e.args[1],t));return D.BuiltInFunctions.dateDiffMinutes(Ce,be);case"datediffhours":let Oe=this.getStringValue(this.evaluateExpression(e.args[0],t)),le=this.getStringValue(this.evaluateExpression(e.args[1],t));return D.BuiltInFunctions.dateDiffHours(Oe,le);case"year":let Se=this.getStringValue(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.year(Se);case"month":let de=this.getStringValue(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.month(de);case"day":case"days":{let E=this.evaluateExpression(e.args[0],t);return this.isDayTimeDurationValue(E)?D.BuiltInFunctions.durationDays(E):D.BuiltInFunctions.day(this.getStringValue(E))}case"hours":{let E=this.evaluateExpression(e.args[0],t);return this.isDayTimeDurationValue(E)?D.BuiltInFunctions.durationHours(E):D.BuiltInFunctions.hours(this.getStringValue(E))}case"minutes":{let E=this.evaluateExpression(e.args[0],t);return this.isDayTimeDurationValue(E)?D.BuiltInFunctions.durationMinutes(E):D.BuiltInFunctions.minutes(this.getStringValue(E))}case"seconds":{let E=this.evaluateExpression(e.args[0],t);return this.isDayTimeDurationValue(E)?D.BuiltInFunctions.durationSeconds(E):D.BuiltInFunctions.seconds(this.getStringValue(E))}case"timezone":let Ee=this.getStringValue(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.timezone(Ee);case"tz":let Pe=this.getStringValue(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.tz(Pe);case"adjust":{let E=this.evaluateExpression(e.args[0],t),k=e.args.length>1?this.evaluateExpression(e.args[1],t):void 0;return D.BuiltInFunctions.adjust(E,k)}case"now":return D.BuiltInFunctions.now();case"datetime":case"xsd:datetime":{let E=this.evaluateExpression(e.args[0],t);return D.BuiltInFunctions.xsdDateTime(this.getStringValue(E))}case"integer":case"xsd:integer":{let E=this.evaluateExpression(e.args[0],t);return D.BuiltInFunctions.xsdInteger(this.getStringValue(E))}case"decimal":case"xsd:decimal":{let E=this.evaluateExpression(e.args[0],t);return D.BuiltInFunctions.xsdDecimal(this.getStringValue(E))}case"daytimeduration":case"xsd:daytimeduration":{let E=this.evaluateExpression(e.args[0],t);return D.BuiltInFunctions.xsdDayTimeDuration(this.getStringValue(E))}case"durationtodays":{let E=this.evaluateExpression(e.args[0],t);return D.BuiltInFunctions.durationToDays(E)}case"durationtohours":{let E=this.evaluateExpression(e.args[0],t);return D.BuiltInFunctions.durationToHours(E)}case"durationtominutes":{let E=this.evaluateExpression(e.args[0],t);return D.BuiltInFunctions.durationToMinutes(E)}case"durationtoseconds":{let E=this.evaluateExpression(e.args[0],t);return D.BuiltInFunctions.durationToSeconds(E)}case"durationdays":{let E=this.evaluateExpression(e.args[0],t);return D.BuiltInFunctions.durationDays(E)}case"durationhours":{let E=this.evaluateExpression(e.args[0],t);return D.BuiltInFunctions.durationHours(E)}case"durationminutes":{let E=this.evaluateExpression(e.args[0],t);return D.BuiltInFunctions.durationMinutes(E)}case"durationseconds":{let E=this.evaluateExpression(e.args[0],t);return D.BuiltInFunctions.durationSeconds(E)}case"datetimediff":{let E=this.evaluateExpression(e.args[0],t),k=this.evaluateExpression(e.args[1],t);return D.BuiltInFunctions.dateTimeDiff(E,k)}case"datetimeadd":{let E=this.evaluateExpression(e.args[0],t),k=this.evaluateExpression(e.args[1],t);return D.BuiltInFunctions.dateTimeAdd(E,k)}case"datetimesubtract":{let E=this.evaluateExpression(e.args[0],t),k=this.evaluateExpression(e.args[1],t);return D.BuiltInFunctions.dateTimeSubtract(E,k)}case"mstominutes":let J=Number(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.msToMinutes(J);case"mstohours":let re=Number(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.msToHours(re);case"mstoseconds":let ie=Number(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.msToSeconds(ie);case"abs":let Z=Number(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.abs(Z);case"round":let ee=Number(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.round(ee);case"ceil":let te=Number(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.ceil(te);case"floor":let X=Number(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.floor(X);case"rand":return D.BuiltInFunctions.rand();case"coalesce":for(let E of e.args)try{let k=this.evaluateExpression(E,t);if(k!=null)return k}catch{continue}return;case"if":if(!e.args||e.args.length!==3)throw new Mt("IF requires exactly 3 arguments");let ne=this.evaluateExpression(e.args[0],t);return this.toBoolean(ne)?this.evaluateExpression(e.args[1],t):this.evaluateExpression(e.args[2],t);case"encode_for_uri":let se=this.getStringValue(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.encodeForUri(se);case"isnumeric":let ae=this.getTermFromExpression(e.args[0],t);return D.BuiltInFunctions.isNumeric(ae);case"haslangdir":let Q=this.getTermFromExpression(e.args[0],t);return D.BuiltInFunctions.hasLangdir(Q);case"sameterm":let oe=this.getTermFromExpression(e.args[0],t),De=this.getTermFromExpression(e.args[1],t);return D.BuiltInFunctions.sameTerm(oe,De);case"md5":let Fe=this.getStringValue(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.md5(Fe);case"sha1":let ve=this.getStringValue(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.sha1(ve);case"sha256":let v=this.getStringValue(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.sha256(v);case"sha384":let S=this.getStringValue(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.sha384(S);case"sha512":let T=this.getStringValue(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.sha512(T);case"byuuid":return this.evaluateByUUID(e,t);default:throw new Mt(`Unknown function: ${i}`)}}getTermFromExpression(e,t){if(e.type==="variable")return t.get(e.name)}getStringValue(e){return e==null?"":typeof e=="object"&&"value"in e?String(e.value):String(e)}toBoolean(e){if(typeof e=="boolean")return e;if(typeof e=="number")return!isNaN(e)&&e!==0;if(typeof e=="string")return e.length>0;if(e instanceof bl.Literal){let t=e.datatype?.value||"";if(t.includes("#boolean"))return e.value==="true"||e.value==="1";if(t.includes("#integer")||t.includes("#decimal")||t.includes("#double")||t.includes("#float")){let i=parseFloat(e.value);return!isNaN(i)&&i!==0}return e.value.length>0}return!!e}evaluateByUUID(e,t){if(!e.args||e.args.length!==1)throw new Mt("exo:byUUID requires exactly 1 argument (UUID string)");let i=this.evaluateExpression(e.args[0],t),n=this.getStringValue(i);if(!n)return;let s=n.toLowerCase();if(this.uuidCache.has(s))return this.uuidCache.get(s)??void 0;if(!this.tripleStore){this.uuidCache.set(s,null);return}if(this.tripleStore.findSubjectsByUUIDSync){let a=this.tripleStore.findSubjectsByUUIDSync(s);if(a.length===0){this.uuidCache.set(s,null);return}let c=a[0];return this.uuidCache.set(s,c),c}this.uuidCache.set(s,null)}cacheUUIDResult(e,t){let i=e.toLowerCase();this.uuidCache.set(i,t)}getCachedUUID(e){let t=e.toLowerCase();if(this.uuidCache.has(t))return this.uuidCache.get(t)}};ma.FilterExecutor=Lm});var Vm=y(El=>{"use strict";Object.defineProperty(El,"__esModule",{value:!0});El.OptionalExecutor=void 0;var Mm=class{static{o(this,"OptionalExecutor")}async*execute(e,t){let i=[];for await(let s of e)i.push(s);let n=[];for await(let s of t)n.push(s);for(let s of i){let a=!1;for(let c of n){let u=s.merge(c);u!==null&&(yield u,a=!0)}a||(yield s)}}async executeAll(e,t){let i=[];async function*n(){for(let a of e)yield a}o(n,"generateLeft");async function*s(){for(let a of t)yield a}o(s,"generateRight");for await(let a of this.execute(n(),s()))i.push(a);return i}};El.OptionalExecutor=Mm});var qm=y(Tl=>{"use strict";Object.defineProperty(Tl,"__esModule",{value:!0});Tl.UnionExecutor=void 0;var $m=class{static{o(this,"UnionExecutor")}async*execute(e,t){let i=new Set;for await(let n of e){let s=this.getSolutionKey(n);i.has(s)||(i.add(s),yield n)}for await(let n of t){let s=this.getSolutionKey(n);i.has(s)||(i.add(s),yield n)}}async executeAll(e,t){let i=[];async function*n(){for(let a of e)yield a}o(n,"generateLeft");async function*s(){for(let a of t)yield a}o(s,"generateRight");for await(let a of this.execute(n(),s()))i.push(a);return i}getSolutionKey(e){let t=e.toJSON();return Object.keys(t).sort().map(n=>`${n}=${t[n]}`).join("|")}};Tl.UnionExecutor=$m});var Wm=y(Al=>{"use strict";Object.defineProperty(Al,"__esModule",{value:!0});Al.ConstructExecutor=void 0;var mP=_n(),Es=et(),Bm=yt(),Um=sr(),gP=eu(),Gm=class{static{o(this,"ConstructExecutor")}async execute(e,t){let i=[],n=new Set;for(let s of t)for(let a of e)try{let c=this.instantiateTriple(a,s),u=`${c.subject.toString()}|${c.predicate.toString()}|${c.object.toString()}`;n.has(u)||(n.add(u),i.push(c))}catch{continue}return i}instantiateTriple(e,t){if(this.isPropertyPath(e.predicate))throw new Error("Property paths are not supported in CONSTRUCT templates");let i=this.instantiateElement(e.subject,t),n=this.instantiateElement(e.predicate,t),s=this.instantiateElement(e.object,t);return new mP.Triple(i,n,s)}isPropertyPath(e){return e.type==="path"}instantiateElement(e,t){if(e.type==="variable"){let i=t.get(e.value);if(!i)throw new Error(`Unbound variable: ${e.value}`);return i}if(e.type==="iri")return new Es.IRI(e.value);if(e.type==="literal")return new Bm.Literal(e.value,e.datatype?new Es.IRI(e.datatype):void 0,e.language);if(e.type==="blank")return new Um.BlankNode(e.value);if(e.type==="quoted")return this.instantiateQuotedTriple(e,t);throw new Error(`Unknown element type: ${e.type}`)}instantiateQuotedTriple(e,t){let i=this.instantiateQuotedSubject(e.subject,t),n=this.instantiateQuotedPredicate(e.predicate,t),s=this.instantiateQuotedObject(e.object,t);return new gP.QuotedTriple(i,n,s)}instantiateQuotedSubject(e,t){if(e.type==="variable"){let i=t.get(e.value);if(!i)throw new Error(`Unbound variable in quoted triple subject: ${e.value}`);if(i instanceof Bm.Literal)throw new Error("Literals cannot appear in quoted triple subject position");return i}if(e.type==="iri")return new Es.IRI(e.value);if(e.type==="blank")return new Um.BlankNode(e.value);if(e.type==="quoted")return this.instantiateQuotedTriple(e,t);throw new Error(`Invalid element type for quoted triple subject: ${e.type}`)}instantiateQuotedPredicate(e,t){if(e.type==="variable"){let i=t.get(e.value);if(!i)throw new Error(`Unbound variable in quoted triple predicate: ${e.value}`);if(!(i instanceof Es.IRI))throw new Error("Quoted triple predicate must be an IRI");return i}return new Es.IRI(e.value)}instantiateQuotedObject(e,t){if(e.type==="variable"){let n=t.get(e.value);if(!n)throw new Error(`Unbound variable in quoted triple object: ${e.value}`);return n}if(e.type==="iri")return new Es.IRI(e.value);if(e.type==="blank")return new Um.BlankNode(e.value);if(e.type==="literal")return new Bm.Literal(e.value,e.datatype?new Es.IRI(e.datatype):void 0,e.language);if(e.type==="quoted")return this.instantiateQuotedTriple(e,t);let i=e;throw new Error(`Invalid element type for quoted triple object: ${i.type}`)}};Al.ConstructExecutor=Gm});var w3=y(xl=>{"use strict";Object.defineProperty(xl,"__esModule",{value:!0});xl.DescribeExecutor=void 0;var _3=et(),zm=class{static{o(this,"DescribeExecutor")}constructor(e){this.tripleStore=e}async execute(e,t){let i=[],n=new Set,s=new Set,a=t?.depth;for(let c of e)await this.describeResourceWithDepth(c,a,1,t?.symmetric??!0,i,n,s);return i}async describeResourceWithDepth(e,t,i,n,s,a,c){let u=e.toString();if(c.has(u)||(c.add(u),t!==void 0&&i>t))return;let l=[],f=await this.tripleStore.match(e,void 0,void 0);if(l.push(...f),n){let d=await this.tripleStore.match(void 0,void 0,e);l.push(...d)}let h=[];for(let d of l){let g=`${d.subject.toString()}|${d.predicate.toString()}|${d.object.toString()}`;a.has(g)||(a.add(g),s.push(d),(t===void 0||i<t)&&(this.isIRI(d.subject)&&d.subject.toString()!==u&&h.push(d.subject),this.isIRI(d.object)&&d.object.toString()!==u&&h.push(d.object)))}for(let d of h)await this.describeResourceWithDepth(d,t,i+1,n,s,a,c)}isIRI(e){return e?e instanceof _3.IRI||e.termType==="NamedNode"||typeof e.value=="string"&&e.value.startsWith("http"):!1}async describeByIRI(e,t){let i=new _3.IRI(e);return this.execute([i],t)}};xl.DescribeExecutor=zm});var b3=y(Cl=>{"use strict";Object.defineProperty(Cl,"__esModule",{value:!0});Cl.MinusExecutor=void 0;var Hm=class{static{o(this,"MinusExecutor")}async*execute(e,t){let i=[];for await(let s of e)i.push(s);let n=[];for await(let s of t)n.push(s);for(let s of i){let a=!1;for(let c of n)if(this.areCompatible(s,c)){a=!0;break}a||(yield s)}}async executeAll(e,t){let i=[];async function*n(){for(let a of e)yield a}o(n,"generateLeft");async function*s(){for(let a of t)yield a}o(s,"generateRight");for await(let a of this.execute(n(),s()))i.push(a);return i}areCompatible(e,t){let i=e.variables(),n=new Set(t.variables()),s=i.filter(a=>n.has(a));if(s.length===0)return!1;for(let a of s){let c=e.get(a),u=t.get(a);if(c===void 0||u===void 0||c.toString()!==u.toString())return!1}return!0}};Cl.MinusExecutor=Hm});var E3=y(ga=>{"use strict";Object.defineProperty(ga,"__esModule",{value:!0});ga.ValuesExecutor=ga.ValuesExecutorError=void 0;var yP=cn(),S3=et(),vP=yt(),Ol=class extends Error{static{o(this,"ValuesExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="ValuesExecutorError"}};ga.ValuesExecutorError=Ol;var Km=class{static{o(this,"ValuesExecutor")}async*execute(e){if(e.bindings.length!==0)for(let t of e.bindings)yield this.createSolutionMapping(t)}async executeAll(e){let t=[];for await(let i of this.execute(e))t.push(i);return t}createSolutionMapping(e){let t=new yP.SolutionMapping;for(let[i,n]of Object.entries(e)){let s=this.toRDFTerm(n);t.set(i,s)}return t}toRDFTerm(e){if(e.type==="iri")return new S3.IRI(e.value);if(e.type==="literal")return new vP.Literal(e.value,e.datatype?new S3.IRI(e.datatype):void 0,e.language);throw new Ol(`Unknown term type: ${e.type}`)}};ga.ValuesExecutor=Km});var Qm=y(va=>{"use strict";Object.defineProperty(va,"__esModule",{value:!0});va.CustomAggregateRegistry=va.CustomAggregateError=void 0;var ya=class extends Error{static{o(this,"CustomAggregateError")}constructor(e,t){super(e),this.iri=t,this.name="CustomAggregateError"}};va.CustomAggregateError=ya;var Pl=class r{static{o(this,"CustomAggregateRegistry")}constructor(){this.aggregates=new Map}static getInstance(){return r.instance||(r.instance=new r),r.instance}static resetInstance(){r.instance&&r.instance.clear(),r.instance=null}register(e,t){if(!e||typeof e!="string")throw new ya("Aggregate IRI must be a non-empty string");if(!t||typeof t.init!="function"||typeof t.step!="function"||typeof t.finalize!="function")throw new ya("Aggregate must implement init(), step(), and finalize() methods",e);if(this.aggregates.has(e))throw new ya(`Aggregate with IRI "${e}" is already registered`,e);this.aggregates.set(e,t)}unregister(e){return this.aggregates.delete(e)}get(e){return this.aggregates.get(e)}has(e){return this.aggregates.has(e)}getRegisteredIris(){return Array.from(this.aggregates.keys())}clear(){this.aggregates.clear()}get size(){return this.aggregates.size}};va.CustomAggregateRegistry=Pl;Pl.instance=null});var Ym=y(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.BUILT_IN_AGGREGATES=Ne.modeAggregate=Ne.stddevAggregate=Ne.varianceAggregate=Ne.medianAggregate=Ne.EXO_AGGREGATE_NS=void 0;Ne.getNumericValue=Fl;Ne.createDecimalLiteral=di;Ne.createDoubleLiteral=bP;Ne.createPercentileAggregate=Ts;var As=yt(),_a=et(),_P=new _a.IRI("http://www.w3.org/2001/XMLSchema#decimal"),wP=new _a.IRI("http://www.w3.org/2001/XMLSchema#double");Ne.EXO_AGGREGATE_NS="https://exocortex.my/ontology/agg#";function Fl(r){return r==null?NaN:typeof r=="number"?r:typeof r=="string"?parseFloat(r):r instanceof As.Literal?parseFloat(r.value):r instanceof _a.IRI?NaN:typeof r=="boolean"?r?1:0:NaN}o(Fl,"getNumericValue");function di(r){return new As.Literal(String(r),_P)}o(di,"createDecimalLiteral");function bP(r){return new As.Literal(String(r),wP)}o(bP,"createDoubleLiteral");Ne.medianAggregate={init(){return{values:[]}},step(r,e){let t=r,i=Fl(e);isNaN(i)||t.values.push(i)},finalize(r){let e=r,{values:t}=e;if(t.length===0)return di(0);let i=[...t].sort((a,c)=>a-c),n=Math.floor(i.length/2),s=i.length%2!==0?i[n]:(i[n-1]+i[n])/2;return di(s)}};Ne.varianceAggregate={init(){return{values:[]}},step(r,e){let t=r,i=Fl(e);isNaN(i)||t.values.push(i)},finalize(r){let e=r,{values:t}=e;if(t.length===0)return di(0);let i=t.reduce((s,a)=>s+a,0)/t.length,n=t.reduce((s,a)=>s+Math.pow(a-i,2),0)/t.length;return di(n)}};Ne.stddevAggregate={init(){return{values:[]}},step(r,e){Ne.varianceAggregate.step(r,e)},finalize(r){let e=r,{values:t}=e;if(t.length===0)return di(0);let i=t.reduce((s,a)=>s+a,0)/t.length,n=t.reduce((s,a)=>s+Math.pow(a-i,2),0)/t.length;return di(Math.sqrt(n))}};Ne.modeAggregate={init(){return{counts:new Map,values:new Map}},step(r,e){if(e==null)return;let t=r,i=String(e instanceof As.Literal||e instanceof _a.IRI?e.value:e),n=t.counts.get(i)||0;t.counts.set(i,n+1),t.values.set(i,e)},finalize(r){let e=r;if(e.counts.size===0)return new As.Literal(" ",new _a.IRI("http://www.w3.org/2001/XMLSchema#string"));let t="",i=0;for(let[a,c]of e.counts)c>i&&(i=c,t=a);let n=e.values.get(t);if(n instanceof As.Literal)return n;let s=parseFloat(t);return isNaN(s)?new As.Literal(t,new _a.IRI("http://www.w3.org/2001/XMLSchema#string")):di(s)}};function Ts(r){let e=Math.max(0,Math.min(100,r))/100;return{init(){return{values:[],percentile:e}},step(t,i){let n=t,s=Fl(i);isNaN(s)||n.values.push(s)},finalize(t){let i=t,{values:n}=i;if(n.length===0)return di(0);let s=[...n].sort((h,d)=>h-d),a=i.percentile*(s.length-1),c=Math.floor(a),u=Math.ceil(a);if(c===u)return di(s[c]);let l=a-c,f=s[c]*(1-l)+s[u]*l;return di(f)}}}o(Ts,"createPercentileAggregate");Ne.BUILT_IN_AGGREGATES={[`${Ne.EXO_AGGREGATE_NS}median`]:Ne.medianAggregate,[`${Ne.EXO_AGGREGATE_NS}variance`]:Ne.varianceAggregate,[`${Ne.EXO_AGGREGATE_NS}stddev`]:Ne.stddevAggregate,[`${Ne.EXO_AGGREGATE_NS}mode`]:Ne.modeAggregate,[`${Ne.EXO_AGGREGATE_NS}percentile25`]:Ts(25),[`${Ne.EXO_AGGREGATE_NS}percentile50`]:Ts(50),[`${Ne.EXO_AGGREGATE_NS}percentile75`]:Ts(75),[`${Ne.EXO_AGGREGATE_NS}percentile90`]:Ts(90),[`${Ne.EXO_AGGREGATE_NS}percentile95`]:Ts(95),[`${Ne.EXO_AGGREGATE_NS}percentile99`]:Ts(99)}});var x3=y(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.AggregateExecutor=wa.AggregateExecutorError=void 0;var bt=yt(),Jm=et(),SP=Sl(),EP=Qm(),TP=Ym(),T3=new Jm.IRI("http://www.w3.org/2001/XMLSchema#integer"),xs=new Jm.IRI("http://www.w3.org/2001/XMLSchema#decimal"),Di=new Jm.IRI("http://www.w3.org/2001/XMLSchema#string");function A3(r){return typeof r=="object"&&r.type==="custom"}o(A3,"isCustomAggregation");var ko=class extends Error{static{o(this,"AggregateExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="AggregateExecutorError"}};wa.AggregateExecutorError=ko;var Xm=class{static{o(this,"AggregateExecutor")}constructor(){this.filterExecutor=new SP.FilterExecutor}execute(e,t){let i=this.groupSolutions(t,e.variables),n=[];for(let[s,a]of i.entries()){let c=new Map;for(let f of e.variables)if(a.length>0){let h=a[0].get(f);h&&c.set(f,h)}for(let f of e.aggregates){let h=this.computeAggregate(f.expression,a);c.set(f.variable,h)}let{SolutionMapping:u}=cn(),l=new u;for(let[f,h]of c.entries())l.set(f,h);n.push(l)}if(n.length===0&&e.aggregates.length>0){let s=this.createEmptyAggregateResult(e);s&&n.push(s)}return n}groupSolutions(e,t){let i=new Map;if(t.length===0)return i.set("",e),i;for(let n of e){let s=this.computeGroupKey(n,t),a=i.get(s);a?a.push(n):i.set(s,[n])}return i}computeGroupKey(e,t){return t.map(i=>{let n=e.get(i);return n?this.termToString(n):""}).join("|")}termToString(e){if(e&&typeof e=="object"){if("value"in e)return String(e.value);if("id"in e)return String(e.id)}return String(e)}computeAggregate(e,t){if(A3(e.aggregation))return this.computeCustomAggregate(e,t);let i=this.extractValues(e,t),n=e.aggregation;switch(n){case"count":{let s=this.computeCount(i,e.distinct);return new bt.Literal(String(s),T3)}case"sum":{let s=this.computeSum(i);return new bt.Literal(String(s),xs)}case"avg":{let s=this.computeAvg(i);return new bt.Literal(String(s),xs)}case"min":{let s=this.computeMin(i);return s===void 0?new bt.Literal("",Di):typeof s=="number"?new bt.Literal(String(s),xs):new bt.Literal(String(s),Di)}case"max":{let s=this.computeMax(i);return s===void 0?new bt.Literal("",Di):typeof s=="number"?new bt.Literal(String(s),xs):new bt.Literal(String(s),Di)}case"group_concat":{let s=this.computeGroupConcat(i,e.separator||" ",e.distinct);return new bt.Literal(s||" ",Di)}case"sample":{let s=this.computeSample(i,e.distinct);return s===void 0?new bt.Literal(" ",Di):typeof s=="number"?new bt.Literal(String(s),xs):new bt.Literal(String(s),Di)}default:{let s=n;throw new ko(`Unknown aggregation function: ${s}`)}}}computeCustomAggregate(e,t){let n=e.aggregation.iri,a=EP.CustomAggregateRegistry.getInstance().get(n);if(a||(a=TP.BUILT_IN_AGGREGATES[n]),!a)throw new ko(`Unknown custom aggregate function: ${n}. Register it with CustomAggregateRegistry.getInstance().register() or use a built-in aggregate.`);let c=a.init();for(let u of t){let l=null;if(e.expression){let f=this.evaluateExpression(e.expression,u);f!==void 0&&(l=f)}else l=1;a.step(c,l)}return a.finalize(c)}extractValues(e,t){if(!e.expression)return t.map(()=>1);let i=[];for(let n of t){let s=this.evaluateExpression(e.expression,n);s!=null&&i.push(s)}return i}evaluateExpression(e,t){if(e.type==="variable"){let i=t.get(e.name);return i==null?void 0:typeof i=="number"||typeof i=="string"||typeof i=="boolean"?i:typeof i=="object"&&"value"in i?i.value:i}if(e.type==="literal")return e.value;try{return this.filterExecutor.evaluateExpression(e,t)}catch{return}}computeCount(e,t){return t?new Set(e.map(i=>String(i))).size:e.length}computeSum(e){return e.map(i=>parseFloat(String(i))).filter(i=>!isNaN(i)).reduce((i,n)=>i+n,0)}computeAvg(e){let t=e.map(i=>parseFloat(String(i))).filter(i=>!isNaN(i));return t.length===0?0:t.reduce((i,n)=>i+n,0)/t.length}computeMin(e){if(e.length===0)return;let t=e.map(n=>parseFloat(String(n))).filter(n=>!isNaN(n));if(t.length>0)return Math.min(...t);let i=e.map(n=>String(n));return i.reduce((n,s)=>s<n?s:n,i[0])}computeMax(e){if(e.length===0)return;let t=e.map(n=>parseFloat(String(n))).filter(n=>!isNaN(n));if(t.length>0)return Math.max(...t);let i=e.map(n=>String(n));return i.reduce((n,s)=>s>n?s:n,i[0])}computeGroupConcat(e,t,i){let n=e.map(s=>String(s));return i&&(n=[...new Set(n)]),n.join(t)}computeSample(e,t){if(e.length===0)return;if(t){let s=[...new Set(e.map(u=>String(u)))];if(s.length===0)return;let a=s[0],c=parseFloat(a);return isNaN(c)?a:c}let i=e[0];if(typeof i=="number")return i;let n=parseFloat(String(i));return isNaN(n)?String(i):n}createEmptyAggregateResult(e){let{SolutionMapping:t}=cn(),i=new t;for(let n of e.aggregates){let s=n.expression.aggregation;if(A3(s)){i.set(n.variable,new bt.Literal("0",xs));continue}switch(s){case"count":i.set(n.variable,new bt.Literal("0",T3));break;case"sum":case"avg":i.set(n.variable,new bt.Literal("0",xs));break;case"group_concat":i.set(n.variable,new bt.Literal(" ",Di));break;case"min":case"max":case"sample":i.set(n.variable,new bt.Literal("",Di));break;default:i.set(n.variable,new bt.Literal("",Di))}}return i}};wa.AggregateExecutor=Xm});var O3=y(ba=>{"use strict";Object.defineProperty(ba,"__esModule",{value:!0});ba.ServiceExecutor=ba.ServiceExecutorError=void 0;var AP=cn(),C3=et(),xP=yt(),CP=sr(),Cs=class extends Error{static{o(this,"ServiceExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="ServiceExecutorError"}};ba.ServiceExecutorError=Cs;var Zm=class{static{o(this,"ServiceExecutor")}constructor(e={}){this.timeout=e.timeout??3e4,this.httpClient=e.httpClient??((t,i)=>fetch(t,i)),this.maxRetries=e.maxRetries??2,this.retryDelay=e.retryDelay??1e3}async*execute(e,t){try{let i=t(e.pattern),n=await this.executeRemoteQuery(e.endpoint,i);for(let s of n)yield s}catch(i){if(e.silent)return;throw i}}async executeRemoteQuery(e,t){let i;for(let n=0;n<=this.maxRetries;n++)try{let s=new AbortController,a=setTimeout(()=>s.abort(),this.timeout);try{let c=await this.httpClient(e,{method:"POST",headers:{"Content-Type":"application/sparql-query",Accept:"application/sparql-results+json"},body:t,signal:s.signal});if(!c.ok)throw new Cs(`Remote SPARQL endpoint returned ${c.status}: ${c.statusText}`);let u=await c.json();return this.parseJsonResults(u)}finally{clearTimeout(a)}}catch(s){if(i=s instanceof Error?s:new Error(String(s)),this.isRetryableError(i)&&n<this.maxRetries){await this.delay(this.retryDelay);continue}throw new Cs(`Failed to query remote SPARQL endpoint ${e}: ${i.message}`,i)}throw new Cs(`Failed to query remote SPARQL endpoint ${e} after ${this.maxRetries+1} attempts`,i)}parseJsonResults(e){return!e.results||!Array.isArray(e.results.bindings)?[]:e.results.bindings.map(t=>this.parseBinding(t))}parseBinding(e){let t=new AP.SolutionMapping;for(let[i,n]of Object.entries(e)){let s=this.parseRDFTerm(n);t.set(i,s)}return t}parseRDFTerm(e){switch(e.type){case"uri":return new C3.IRI(e.value);case"literal":{let t=e.datatype?new C3.IRI(e.datatype):void 0;return new xP.Literal(e.value,t,e["xml:lang"])}case"bnode":return new CP.BlankNode(e.value);default:throw new Cs(`Unknown RDF term type: ${e.type}`)}}isRetryableError(e){let t=e.message.toLowerCase();return!!(e.name==="AbortError"||t.includes("network")||t.includes("econnreset")||t.includes("econnrefused")||t.includes("etimedout")||t.includes("returned 5"))}delay(e){return new Promise(t=>setTimeout(t,e))}};ba.ServiceExecutor=Zm});var F3=y(Sa=>{"use strict";Object.defineProperty(Sa,"__esModule",{value:!0});Sa.GraphExecutor=Sa.GraphExecutorError=void 0;var P3=et(),Il=class extends Error{static{o(this,"GraphExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="GraphExecutorError"}};Sa.GraphExecutorError=Il;var eg=class{static{o(this,"GraphExecutor")}constructor(e){this.tripleStore=e}async*execute(e,t,i){let n=e.name;if(n.type==="iri")yield*this.executeWithGraph(e.pattern,n,t);else if(n.type==="variable")yield*this.executeWithGraphVariable(e,n,t,i);else throw new Il(`Invalid graph name type: ${n.type}`)}async*executeWithGraph(e,t,i){let n=new P3.IRI(t.value);this.tripleStore.hasGraph&&!await this.tripleStore.hasGraph(n)||(yield*i(e,n))}async*executeWithGraphVariable(e,t,i,n){if(n){let a=n.get(t.value);if(a&&a instanceof P3.IRI){yield*this.executeWithGraph(e.pattern,{type:"iri",value:a.value},i);return}}if(!this.tripleStore.getNamedGraphs)return;let s=await this.tripleStore.getNamedGraphs();for(let a of s)for await(let c of i(e.pattern,a)){let u=c.clone();u.set(t.value,a),yield u}}};Sa.GraphExecutor=eg});var I3=y(Ta=>{"use strict";Object.defineProperty(Ta,"__esModule",{value:!0});Ta.SPARQLGenerator=Ta.SPARQLGeneratorError=void 0;var Ea=class extends Error{static{o(this,"SPARQLGeneratorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="SPARQLGeneratorError"}};Ta.SPARQLGeneratorError=Ea;var tg=class{static{o(this,"SPARQLGenerator")}collectVariables(e){let t=new Set;return this.collectVariablesFromOperation(e,t),t}generateSelect(e){let t=this.collectVariables(e),i=t.size>0?Array.from(t).map(s=>`?${s}`).join(" "):"*",n=this.generateWhereClause(e);return`SELECT ${i} WHERE {
149
+ ${i})`;default:return`${i}Unknown(${e.type})`}}tripleToString(e){return`${this.elementToString(e.subject)} ${this.predicateToString(e.predicate)} ${this.elementToString(e.object)}`}predicateToString(e){return this.isPropertyPath(e)?this.propertyPathToString(e):this.elementToString(e)}isPropertyPath(e){return e.type==="path"}propertyPathToString(e){let t=e.items.map(i=>i.type==="path"?`(${this.propertyPathToString(i)})`:`<${i.value}>`);switch(e.pathType){case"/":return t.join("/");case"|":return t.join("|");case"^":return`^${t[0]}`;case"+":return`${t[0]}+`;case"*":return`${t[0]}*`;case"?":return`${t[0]}?`}}elementToString(e){switch(e.type){case"variable":return`?${e.value}`;case"iri":return`<${e.value}>`;case"literal":let t=`"${e.value}"`;return e.language&&(t+=`@${e.language}`),e.datatype&&(t+=`^^<${e.datatype}>`),t;case"blank":return`_:${e.value}`;default:return String(e)}}expressionToString(e){switch(e.type){case"variable":return`?${e.name}`;case"literal":return typeof e.value=="string"?`"${e.value}"`:String(e.value);case"comparison":return`(${this.expressionToString(e.left)} ${e.operator} ${this.expressionToString(e.right)})`;case"logical":return e.operator==="!"?`!(${this.expressionToString(e.operands[0])})`:`(${e.operands.map(t=>this.expressionToString(t)).join(` ${e.operator} `)})`;case"arithmetic":return`(${this.expressionToString(e.left)} ${e.operator} ${this.expressionToString(e.right)})`;case"function":return`${e.function}(${e.args.map(t=>this.expressionToString(t)).join(", ")})`;case"exists":return`${e.negated?"NOT EXISTS":"EXISTS"} { ${this.toString(e.pattern,0)} }`;default:return"unknown"}}toJSON(e){return JSON.stringify(e,null,2)}};pl.AlgebraSerializer=Pm});var cn=y(ml=>{"use strict";Object.defineProperty(ml,"__esModule",{value:!0});ml.SolutionMapping=void 0;var p3=yt(),m3=et(),g3=sr(),Fm=class r{static{o(this,"SolutionMapping")}constructor(e){this.bindings=e?new Map(e):new Map}get(e){return this.bindings.get(e)}set(e,t){this.bindings.set(e,t)}has(e){return this.bindings.has(e)}variables(){return Array.from(this.bindings.keys())}getBindings(){return new Map(this.bindings)}isCompatibleWith(e){for(let[t,i]of this.bindings.entries()){let n=e.get(t);if(n!==void 0&&!this.areEqual(i,n))return!1}return!0}merge(e){if(!this.isCompatibleWith(e))return null;let t=new r(this.bindings);for(let[i,n]of e.getBindings().entries())t.set(i,n);return t}clone(){return new r(this.bindings)}areEqual(e,t){return e instanceof p3.Literal&&t instanceof p3.Literal?e.equals(t):e instanceof m3.IRI&&t instanceof m3.IRI?e.value===t.value:e instanceof g3.BlankNode&&t instanceof g3.BlankNode?e.id===t.id:!1}toJSON(){let e={};for(let[t,i]of this.bindings.entries())e[t]=i.toString();return e}size(){return this.bindings.size}};ml.SolutionMapping=Fm});var v3=y(da=>{"use strict";Object.defineProperty(da,"__esModule",{value:!0});da.PropertyPathExecutor=da.PropertyPathExecutorError=void 0;var dP=cn(),gl=et(),y3=sr(),Do=class extends Error{static{o(this,"PropertyPathExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="PropertyPathExecutorError"}};da.PropertyPathExecutorError=Do;var Im=class{static{o(this,"PropertyPathExecutor")}constructor(e){this.tripleStore=e,this.MAX_DEPTH=100}async*execute(e,t,i){let n=await this.resolveElement(e),s=this.isVariable(i)?null:await this.resolveElement(i);for(let a of n){let c=await this.evaluatePath(a,t,s);for(let u of c){let l=new dP.SolutionMapping;this.isVariable(e)&&l.set(e.value,a),this.isVariable(i)&&l.set(i.value,u),yield l}}}async*executeWithBindings(e,t){if(!this.isPropertyPath(e.predicate))throw new Do("Predicate is not a property path");let i=this.instantiateElement(e.subject,t),n=this.instantiateElement(e.object,t);for await(let s of this.execute(i,e.predicate,n)){let a=t.merge(s);a!==null&&(yield a)}}async evaluatePath(e,t,i){switch(t.pathType){case"/":return this.evaluateSequencePath(e,t.items,i);case"|":return this.evaluateAlternativePath(e,t.items,i);case"^":return this.evaluateInversePath(e,t.items[0],i);case"+":return this.evaluateOneOrMorePath(e,t.items[0],i);case"*":return this.evaluateZeroOrMorePath(e,t.items[0],i);case"?":return this.evaluateZeroOrOnePath(e,t.items[0],i)}}async evaluateSequencePath(e,t,i){let n=new Set([e]);for(let s=0;s<t.length;s++){let a=t[s],c=s===t.length-1,u=new Set;for(let l of n){let f=await this.evaluatePathItem(l,a,c?i:null);for(let h of f)u.add(h)}if(n=u,n.size===0)break}return n}async evaluateAlternativePath(e,t,i){let n=new Set;for(let s of t){let a=await this.evaluatePathItem(e,s,i);for(let c of a)n.add(c)}return n}async evaluateInversePath(e,t,i){if(t.type==="iri"){let n=new gl.IRI(t.value),s=await this.tripleStore.match(void 0,n,e),a=new Set;for(let c of s)(i===null||this.nodeInSet(c.subject,i))&&a.add(c.subject);return a}else return this.evaluatePath(e,this.invertPath(t),i)}async evaluateOneOrMorePath(e,t,i){let n=new Set,s=new Set,a=[{node:e,depth:0}];for(;a.length>0;){let{node:c,depth:u}=a.shift();if(u>=this.MAX_DEPTH)continue;let l=await this.evaluatePathItem(c,t,null);for(let f of l){let h=this.nodeToKey(f);(i===null||this.nodeInSet(f,i))&&s.add(f),n.has(h)||(n.add(h),a.push({node:f,depth:u+1}))}}return s}async evaluateZeroOrMorePath(e,t,i){let n=await this.evaluateOneOrMorePath(e,t,i);return(i===null||this.nodeInSet(e,i))&&n.add(e),n}async evaluateZeroOrOnePath(e,t,i){let n=new Set;(i===null||this.nodeInSet(e,i))&&n.add(e);let s=await this.evaluatePathItem(e,t,i);for(let a of s)n.add(a);return n}async evaluatePathItem(e,t,i){if(t.type==="iri"){let n=new gl.IRI(t.value),s=await this.tripleStore.match(e,n,void 0),a=new Set;for(let c of s)(i===null||this.nodeInSet(c.object,i))&&a.add(c.object);return a}else return this.evaluatePath(e,t,i)}invertPath(e){switch(e.pathType){case"^":return e.items[0];case"/":return{type:"path",pathType:"/",items:[...e.items].reverse().map(i=>i.type==="iri"?{type:"path",pathType:"^",items:[i]}:this.invertPath(i))};case"|":return{type:"path",pathType:"|",items:e.items.map(i=>i.type==="iri"?{type:"path",pathType:"^",items:[i]}:this.invertPath(i))};case"+":case"*":case"?":let t=e.items[0].type==="iri"?{type:"path",pathType:"^",items:[e.items[0]]}:this.invertPath(e.items[0]);return{type:"path",pathType:e.pathType,items:[t]}}}async resolveElement(e){if(this.isVariable(e)){let i=new Set,n=await this.tripleStore.match(void 0,void 0,void 0);for(let s of n)i.add(s.subject),i.add(s.object);return i}let t=new Set;switch(e.type){case"iri":t.add(new gl.IRI(e.value));break;case"blank":t.add(new y3.BlankNode(e.value));break;default:throw new Do(`Unsupported element type in subject/object position: ${e.type}`)}return t}instantiateElement(e,t){if(this.isVariable(e)){let i=t.get(e.value);if(i){if(i instanceof gl.IRI)return{type:"iri",value:i.value};if(i instanceof y3.BlankNode)return{type:"blank",value:i.id}}}return e}isVariable(e){return e.type==="variable"}isPropertyPath(e){return e.type==="path"}nodeToKey(e){return e.toString()}nodeInSet(e,t){let i=this.nodeToKey(e);for(let n of t)if(this.nodeToKey(n)===i)return!0;return!1}};da.PropertyPathExecutor=Im});var Nm=y(pa=>{"use strict";Object.defineProperty(pa,"__esModule",{value:!0});pa.BGPExecutor=pa.BGPExecutorError=void 0;var yl=cn(),In=et(),Rm=yt(),vl=sr(),_l=eu(),pP=v3(),Ht=class extends Error{static{o(this,"BGPExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="BGPExecutorError"}};pa.BGPExecutorError=Ht;var Dm=class{static{o(this,"BGPExecutor")}constructor(e){this.tripleStore=e,this.propertyPathExecutor=new pP.PropertyPathExecutor(e)}async*execute(e){if(e.triples.length===0){yield new yl.SolutionMapping;return}let t=this.matchTriplePattern(e.triples[0]);for(let i=1;i<e.triples.length;i++)t=this.joinWithPattern(t,e.triples[i]);for await(let i of t)yield i}async executeAll(e){let t=[];for await(let i of this.execute(e))t.push(i);return t}async*executeInGraph(e,t){if(e.triples.length===0){yield new yl.SolutionMapping;return}let i=this.matchTriplePatternInGraph(e.triples[0],t);for(let n=1;n<e.triples.length;n++)i=this.joinWithPatternInGraph(i,e.triples[n],t);for await(let n of i)yield n}async*matchTriplePatternInGraph(e,t){if(this.isPropertyPath(e.predicate))throw new Ht("Property paths within named graphs are not yet supported");let i=e.predicate,n=this.isVariable(e.subject)?void 0:this.toRDFTermAsSubject(e.subject),s=this.isVariable(i)?void 0:this.toRDFTermAsPredicate(i),a=this.isVariable(e.object)?void 0:this.toRDFTerm(e.object);if(!this.tripleStore.matchInGraph)throw new Ht("Triple store does not support named graph operations");let c=await this.tripleStore.matchInGraph(n,s,a,t);for(let u of c){let l=new yl.SolutionMapping;this.isVariable(e.subject)&&l.set(e.subject.value,u.subject),this.isVariable(i)&&l.set(i.value,u.predicate),this.isVariable(e.object)&&l.set(e.object.value,u.object),yield l}}async*joinWithPatternInGraph(e,t,i){let n=[];for await(let s of e)n.push(s);for(let s of n){let a=this.instantiatePattern(t,s);for await(let c of this.matchTriplePatternInGraph(a,i)){let u=s.merge(c);u!==null&&(yield u)}}}async*matchTriplePattern(e){if(this.isPropertyPath(e.predicate)){yield*this.propertyPathExecutor.execute(e.subject,e.predicate,e.object);return}let t=e.predicate,i=this.isVariable(e.subject)||this.isQuotedTriple(e.subject)&&this.hasVariablesInQuotedTriple(e.subject)?void 0:this.toRDFTermAsSubject(e.subject),n=this.isVariable(t)?void 0:this.toRDFTermAsPredicate(t),s=this.isVariable(e.object)||this.isQuotedTriple(e.object)&&this.hasVariablesInQuotedTriple(e.object)?void 0:this.toRDFTerm(e.object),a=await this.tripleStore.match(i,n,s);for(let c of a){let u=new yl.SolutionMapping;if(this.isVariable(e.subject))u.set(e.subject.value,c.subject);else if(this.isQuotedTriple(e.subject)){let l=this.matchQuotedTriplePattern(e.subject,c.subject);if(l===null)continue;for(let[f,h]of l.entries())u.set(f,h)}if(this.isVariable(t)&&u.set(t.value,c.predicate),this.isVariable(e.object))u.set(e.object.value,c.object);else if(this.isQuotedTriple(e.object)){let l=this.matchQuotedTriplePattern(e.object,c.object);if(l===null)continue;for(let[f,h]of l.entries())u.set(f,h)}yield u}}hasVariablesInQuotedTriple(e){return!!(this.isVariable(e.subject)||e.predicate.type==="variable"||this.isVariable(e.object)||this.isQuotedTriple(e.subject)&&this.hasVariablesInQuotedTriple(e.subject)||this.isQuotedTriple(e.object)&&this.hasVariablesInQuotedTriple(e.object))}matchQuotedTriplePattern(e,t){if(!(t instanceof _l.QuotedTriple))return null;let i=new Map;if(this.isVariable(e.subject))i.set(e.subject.value,t.subject);else if(this.isQuotedTriple(e.subject)){let n=this.matchQuotedTriplePattern(e.subject,t.subject);if(n===null)return null;for(let[s,a]of n)i.set(s,a)}else if(!this.elementsMatch(e.subject,t.subject))return null;if(e.predicate.type==="variable")i.set(e.predicate.value,t.predicate);else if(e.predicate.value!==t.predicate.value)return null;if(this.isVariable(e.object))i.set(e.object.value,t.object);else if(this.isQuotedTriple(e.object)){let n=this.matchQuotedTriplePattern(e.object,t.object);if(n===null)return null;for(let[s,a]of n)i.set(s,a)}else if(!this.elementsMatch(e.object,t.object))return null;return i}elementsMatch(e,t){switch(e.type){case"iri":return t instanceof In.IRI&&e.value===t.value;case"literal":return!(!(t instanceof Rm.Literal)||e.value!==t.value||e.datatype!==t.datatype?.value||e.language!==t.language);case"blank":return t instanceof vl.BlankNode&&e.value===t.id;case"quoted":return t instanceof _l.QuotedTriple?this.toRDFQuotedTriple(e).equals(t):!1;default:return!1}}isPropertyPath(e){return e.type==="path"}async*joinWithPattern(e,t){let i=[];for await(let n of e)i.push(n);for(let n of i){let s=this.instantiatePattern(t,n);for await(let a of this.matchTriplePattern(s)){let c=n.merge(a);c!==null&&(yield c)}}}instantiatePattern(e,t){let i=this.isPropertyPath(e.predicate)?e.predicate:this.instantiateElement(e.predicate,t);return{subject:this.instantiateElement(e.subject,t),predicate:i,object:this.instantiateElement(e.object,t)}}instantiateElement(e,t){if(this.isVariable(e)){let i=t.get(e.value);if(i)return this.toAlgebraElement(i)}return this.isQuotedTriple(e)?this.instantiateQuotedTriple(e,t):e}instantiateQuotedTriple(e,t){let i=this.instantiateElement(e.subject,t),n=e.predicate.type==="variable"?this.instantiatePredicateVariable(e.predicate,t):e.predicate,s=this.instantiateElement(e.object,t);return{type:"quoted",subject:i,predicate:n,object:s}}instantiatePredicateVariable(e,t){let i=t.get(e.value);return i&&i instanceof In.IRI?{type:"iri",value:i.value}:e}isVariable(e){return e.type==="variable"}isQuotedTriple(e){return e.type==="quoted"}toRDFTermAsSubject(e){switch(e.type){case"iri":return new In.IRI(e.value);case"blank":return new vl.BlankNode(e.value);case"literal":throw new Ht("Literals cannot appear in subject position");case"variable":throw new Ht(`Cannot convert variable to RDF term: ${e.value}`);case"quoted":return this.toRDFQuotedTriple(e);default:throw new Ht(`Unknown element type: ${e.type}`)}}toRDFQuotedTriple(e){let t=this.toRDFTermAsSubject(e.subject),i=e.predicate.type==="iri"?new In.IRI(e.predicate.value):(()=>{throw new Ht("Quoted triple predicate must be IRI")})(),n=this.toRDFTerm(e.object);return new _l.QuotedTriple(t,i,n)}toRDFTermAsPredicate(e){switch(e.type){case"iri":return new In.IRI(e.value);case"literal":throw new Ht("Literals cannot appear in predicate position");case"blank":throw new Ht("Blank nodes cannot appear in predicate position");case"variable":throw new Ht(`Cannot convert variable to RDF term: ${e.value}`);default:throw new Ht(`Unknown element type: ${e.type}`)}}toRDFTerm(e){switch(e.type){case"iri":return new In.IRI(e.value);case"literal":return new Rm.Literal(e.value,e.datatype?new In.IRI(e.datatype):void 0,e.language);case"blank":return new vl.BlankNode(e.value);case"variable":throw new Ht(`Cannot convert variable to RDF term: ${e.value}`);case"quoted":return this.toRDFQuotedTriple(e);default:throw new Ht(`Unknown element type: ${e.type}`)}}toAlgebraElement(e){if(e instanceof In.IRI)return{type:"iri",value:e.value};if(e instanceof Rm.Literal)return{type:"literal",value:e.value,datatype:e.datatype?.value,language:e.language};if(e instanceof vl.BlankNode)return{type:"blank",value:e.id};if(e instanceof _l.QuotedTriple)return this.toAlgebraQuotedTriple(e);throw new Ht(`Unknown RDF term type: ${e.constructor?.name||"unknown"}`)}toAlgebraQuotedTriple(e){return{type:"quoted",subject:this.toAlgebraElement(e.subject),predicate:{type:"iri",value:e.predicate.value},object:this.toAlgebraElement(e.object)}}};pa.BGPExecutor=Dm});var jm=y(wl=>{"use strict";Object.defineProperty(wl,"__esModule",{value:!0});wl.BuiltInFunctions=void 0;var Be=et(),q=yt(),hi=sr(),km=Cr(),No=class{static{o(this,"BuiltInFunctions")}static str(e){if(e===void 0)throw new Error("STR: argument is undefined");return e instanceof Be.IRI||e instanceof q.Literal?e.value:e instanceof hi.BlankNode?e.id:String(e)}static lang(e){if(e===void 0)throw new Error("LANG: argument is undefined");return e instanceof q.Literal&&e.language?e.language:""}static langdir(e){if(e===void 0)throw new Error("LANGDIR: argument is undefined");return!(e instanceof q.Literal)||!e.language?"":e.direction?`${e.language}--${e.direction}`:e.language}static langMatches(e,t){let[i,n]=this.parseDirectionalLangTag(e),[s,a]=this.parseDirectionalLangTag(t),c=i.toLowerCase(),u=s.toLowerCase();return u==="*"?c!=="":c===""?u==="":a&&n!==a?!1:c===u?!0:c.startsWith(u+"-")}static parseDirectionalLangTag(e){let t=e.indexOf("--");if(t===-1)return[e,void 0];let i=e.substring(0,t),n=e.substring(t+2).toLowerCase();return[i,n]}static datatype(e){if(e===void 0)throw new Error("DATATYPE: argument is undefined");if(e instanceof q.Literal)return e.datatype?e.datatype:e.language?new Be.IRI("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"):new Be.IRI("http://www.w3.org/2001/XMLSchema#string");throw new Error("DATATYPE: argument must be a literal")}static bound(e){return e!==void 0}static isIRI(e){return e===void 0?!1:e instanceof Be.IRI}static isBlank(e){return e===void 0?!1:e instanceof hi.BlankNode}static isLiteral(e){return e===void 0?!1:e instanceof q.Literal}static hasLangdir(e){return e===void 0||!(e instanceof q.Literal)?!1:!!e.language&&!!e.direction}static isNumeric(e){if(e===void 0||!(e instanceof q.Literal))return!1;let t=e.datatype?.value;return t?["http://www.w3.org/2001/XMLSchema#integer","http://www.w3.org/2001/XMLSchema#decimal","http://www.w3.org/2001/XMLSchema#float","http://www.w3.org/2001/XMLSchema#double","http://www.w3.org/2001/XMLSchema#nonPositiveInteger","http://www.w3.org/2001/XMLSchema#negativeInteger","http://www.w3.org/2001/XMLSchema#long","http://www.w3.org/2001/XMLSchema#int","http://www.w3.org/2001/XMLSchema#short","http://www.w3.org/2001/XMLSchema#byte","http://www.w3.org/2001/XMLSchema#nonNegativeInteger","http://www.w3.org/2001/XMLSchema#unsignedLong","http://www.w3.org/2001/XMLSchema#unsignedInt","http://www.w3.org/2001/XMLSchema#unsignedShort","http://www.w3.org/2001/XMLSchema#unsignedByte","http://www.w3.org/2001/XMLSchema#positiveInteger"].includes(t):!1}static regex(e,t,i){try{return new RegExp(t,i).test(e)}catch(n){throw new Error(`REGEX: invalid pattern '${t}': ${n.message}`)}}static compare(e,t,i){if(this.isDayTimeDurationValue(e)&&this.isDayTimeDurationValue(t))return this.compareDurations(e instanceof q.Literal?e:String(e),t instanceof q.Literal?t:String(t),i);let n=this.toComparableValue(e),s=this.toComparableValue(t);switch(i){case"=":return n===s;case"!=":return n!==s;case"<":return n<s;case">":return n>s;case"<=":return n<=s;case">=":return n>=s;default:throw new Error(`Unknown comparison operator: ${i}`)}}static isDayTimeDurationValue(e){return e instanceof q.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#dayTimeDuration":!1}static toComparableValue(e){if(typeof e=="string"||typeof e=="number")return e;if(e instanceof q.Literal){let t=e.datatype?.value;if(t?.includes("#integer")||t?.includes("#decimal")||t?.includes("#double")){let i=parseFloat(e.value);if(!isNaN(i))return i}if(t==="http://www.w3.org/2001/XMLSchema#dayTimeDuration")try{return this.parseDayTimeDuration(e.value)}catch{return e.value}return e.value}return e instanceof Be.IRI?e.value:e instanceof hi.BlankNode?e.id:String(e)}static contains(e,t){return e.includes(t)}static strStarts(e,t){return e.startsWith(t)}static strEnds(e,t){return e.endsWith(t)}static strlen(e){return e.length}static ucase(e){return e.toUpperCase()}static lcase(e){return e.toLowerCase()}static substr(e,t,i){let n=t-1;if(n<0){if(i!==void 0){let s=i+n;return s<=0?"":e.substring(0,s)}return e}return i!==void 0?e.substring(n,n+i):e.substring(n)}static strBefore(e,t){if(t==="")return"";let i=e.indexOf(t);return i===-1?"":e.substring(0,i)}static strAfter(e,t){if(t==="")return e;let i=e.indexOf(t);return i===-1?"":e.substring(i+t.length)}static concat(...e){return e.join("")}static replace(e,t,i,n){try{let s=new RegExp(t,n||"g");return e.replace(s,i)}catch(s){throw new Error(`REPLACE: invalid pattern '${t}': ${s.message}`)}}static parseDate(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`PARSEDATE: invalid date string '${e}'`);return t.getTime()}static dateBefore(e,t){let i=this.parseDate(e),n=this.parseDate(t);return i<n}static dateAfter(e,t){let i=this.parseDate(e),n=this.parseDate(t);return i>n}static dateInRange(e,t,i){let n=this.parseDate(e),s=this.parseDate(t),a=this.parseDate(i);return n>=s&&n<=a}static dateDiffMinutes(e,t){let i=this.parseDate(e),n=this.parseDate(t),s=Math.abs(n-i);return Math.round(s/(1e3*60))}static dateDiffHours(e,t){let i=this.parseDate(e),n=this.parseDate(t),s=Math.abs(n-i);return Math.round(s/(1e3*60*60)*100)/100}static logicalAnd(e){return e.every(t=>t===!0)}static logicalOr(e){return e.some(t=>t===!0)}static logicalNot(e){return!e}static year(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`YEAR: invalid date string '${e}'`);return t.getFullYear()}static month(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`MONTH: invalid date string '${e}'`);return t.getMonth()+1}static day(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`DAY: invalid date string '${e}'`);return t.getDate()}static hours(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`HOURS: invalid date string '${e}'`);return t.getHours()}static minutes(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`MINUTES: invalid date string '${e}'`);return t.getMinutes()}static seconds(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`SECONDS: invalid date string '${e}'`);return t.getSeconds()+t.getMilliseconds()/1e3}static timezone(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`TIMEZONE: invalid date string '${e}'`);let i;if(e.endsWith("Z"))i="PT0S";else{let n=e.match(/([+-]\d{2}):?(\d{2})$/);if(n){let s=parseInt(n[1],10),a=parseInt(n[2],10),c=s>=0?"":"-",u=Math.abs(s);a===0?i=`${c}PT${u}H`:i=`${c}PT${u}H${a}M`}else{let s=-t.getTimezoneOffset(),a=Math.floor(Math.abs(s)/60),c=Math.abs(s)%60,u=s>=0?"":"-";c===0?i=`${u}PT${a}H`:i=`${u}PT${a}H${c}M`}}return new q.Literal(i,new Be.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static tz(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`TZ: invalid date string '${e}'`);if(e.endsWith("Z"))return"Z";let i=e.match(/([+-]\d{2}:\d{2})$/);if(i)return i[1];let n=e.match(/([+-])(\d{2})(\d{2})$/);return n?`${n[1]}${n[2]}:${n[3]}`:""}static now(){return new Date().toISOString()}static msToMinutes(e){return Math.round(e/(1e3*60))}static msToHours(e){return Math.round(e/(1e3*60*60)*100)/100}static msToSeconds(e){return Math.round(e/1e3)}static abs(e){return Math.abs(e)}static round(e){return Math.round(e)}static ceil(e){return Math.ceil(e)}static floor(e){return Math.floor(e)}static rand(){return Math.random()}static coalesce(e){for(let t of e)if(t!=null)return t}static if(e,t,i){return e?t:i}static xsdDateTime(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`xsd:dateTime: invalid date string '${e}'`);return new q.Literal(t.toISOString(),new Be.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}static xsdInteger(e){let t=parseInt(e,10);if(isNaN(t))throw new Error(`xsd:integer: cannot convert '${e}' to integer`);return new q.Literal(String(t),new Be.IRI("http://www.w3.org/2001/XMLSchema#integer"))}static xsdDecimal(e){let t=parseFloat(e);if(isNaN(t))throw new Error(`xsd:decimal: cannot convert '${e}' to decimal`);return new q.Literal(String(t),new Be.IRI("http://www.w3.org/2001/XMLSchema#decimal"))}static encodeForUri(e){return encodeURIComponent(e)}static md5(e){return require("crypto").createHash("md5").update(e).digest("hex")}static sha1(e){return require("crypto").createHash("sha1").update(e).digest("hex")}static sha256(e){return require("crypto").createHash("sha256").update(e).digest("hex")}static sha384(e){return require("crypto").createHash("sha384").update(e).digest("hex")}static sha512(e){return require("crypto").createHash("sha512").update(e).digest("hex")}static sameTerm(e,t){if(e===void 0&&t===void 0)return!0;if(e===void 0||t===void 0||e.constructor!==t.constructor)return!1;if(e instanceof Be.IRI&&t instanceof Be.IRI)return e.value===t.value;if(e instanceof hi.BlankNode&&t instanceof hi.BlankNode)return e.id===t.id;if(e instanceof q.Literal&&t instanceof q.Literal){if(e.value!==t.value||e.language!==t.language)return!1;let i=e.datatype?.value,n=t.datatype?.value;return i===n}return!1}static iri(e){if(e===void 0)throw new Error("IRI: argument is undefined");if(e instanceof Be.IRI)return e;if(e instanceof q.Literal)return new Be.IRI(e.value);throw e instanceof hi.BlankNode?new Error("IRI: cannot convert blank node to IRI"):new Error("IRI: unsupported term type")}static uri(e){return this.iri(e)}static bnode(e){if(e===void 0){let t=`b${(0,km.v4)().replace(/-/g,"").substring(0,12)}`;return new hi.BlankNode(t)}if(e instanceof q.Literal)return new hi.BlankNode(e.value);if(e instanceof hi.BlankNode)return e;throw new Error("BNODE: argument must be a string literal or omitted")}static strdt(e,t){if(e===void 0)throw new Error("STRDT: lexical form is undefined");if(t===void 0)throw new Error("STRDT: datatype IRI is undefined");let i;if(e instanceof q.Literal){if(e.language)throw new Error("STRDT: lexical form must not have a language tag");i=e.value}else if(typeof e=="string")i=e;else throw new Error("STRDT: lexical form must be a string literal");let n;if(t instanceof Be.IRI)n=t;else if(t instanceof q.Literal)n=new Be.IRI(t.value);else throw new Error("STRDT: datatype must be an IRI");return new q.Literal(i,n)}static strlang(e,t){if(e===void 0)throw new Error("STRLANG: lexical form is undefined");if(t===void 0)throw new Error("STRLANG: language tag is undefined");let i;if(e instanceof q.Literal){if(e.language)throw new Error("STRLANG: lexical form must not already have a language tag");i=e.value}else if(typeof e=="string")i=e;else throw new Error("STRLANG: lexical form must be a string literal");let n;if(t instanceof q.Literal)n=t.value;else if(typeof t=="string")n=t;else throw new Error("STRLANG: language tag must be a string literal");if(n==="")throw new Error("STRLANG: language tag cannot be empty");return new q.Literal(i,void 0,n)}static strlangdir(e,t,i){if(e===void 0)throw new Error("STRLANGDIR: lexical form is undefined");if(t===void 0)throw new Error("STRLANGDIR: language tag is undefined");if(i===void 0)throw new Error("STRLANGDIR: direction is undefined");let n;if(e instanceof q.Literal){if(e.language)throw new Error("STRLANGDIR: lexical form must not already have a language tag");n=e.value}else if(typeof e=="string")n=e;else throw new Error("STRLANGDIR: lexical form must be a string literal");let s;if(t instanceof q.Literal)s=t.value;else if(typeof t=="string")s=t;else throw new Error("STRLANGDIR: language tag must be a string literal");if(s==="")throw new Error("STRLANGDIR: language tag cannot be empty");let a;if(i instanceof q.Literal)a=i.value.toLowerCase();else throw new Error("STRLANGDIR: direction must be a string literal");if(a!=="ltr"&&a!=="rtl")throw new Error(`STRLANGDIR: invalid direction '${a}'. Must be 'ltr' or 'rtl'`);return new q.Literal(n,void 0,s,a)}static uuid(){let e=(0,km.v4)();return new Be.IRI(`urn:uuid:${e}`)}static struuid(){let e=(0,km.v4)();return new q.Literal(e)}static parseDayTimeDuration(e){if(!e)throw new Error("parseDayTimeDuration: duration string is empty");let t=!1,i=e.trim();if(i.startsWith("-")&&(t=!0,i=i.substring(1)),!i.startsWith("P"))throw new Error(`parseDayTimeDuration: invalid format, must start with 'P': '${e}'`);i=i.substring(1);let n=0,s=i.indexOf("T"),a="",c="";if(s===-1?a=i:(a=i.substring(0,s),c=i.substring(s+1)),a){let u=a.match(/^(\d+(?:\.\d+)?)D$/);if(u){let l=parseFloat(u[1]);n+=l*24*60*60*1e3}else if(a!=="")throw new Error(`parseDayTimeDuration: invalid day component: '${a}' in '${e}'`)}if(c){let u=c,l=u.match(/^(\d+(?:\.\d+)?)H/);if(l){let d=parseFloat(l[1]);n+=d*60*60*1e3,u=u.substring(l[0].length)}let f=u.match(/^(\d+(?:\.\d+)?)M/);if(f){let d=parseFloat(f[1]);n+=d*60*1e3,u=u.substring(f[0].length)}let h=u.match(/^(\d+(?:\.\d+)?)S$/);if(h){let d=parseFloat(h[1]);n+=d*1e3,u=u.substring(h[0].length)}if(u!=="")throw new Error(`parseDayTimeDuration: invalid time component: '${u}' in '${e}'`)}return t?-n:n}static formatDayTimeDuration(e){let t=e<0,i=Math.abs(e),n=Math.floor(i/(1440*60*1e3));i=i%(1440*60*1e3);let s=Math.floor(i/(3600*1e3));i=i%(3600*1e3);let a=Math.floor(i/(60*1e3));i=i%(60*1e3);let c=i/1e3,u=t?"-P":"P";return n>0&&(u+=`${n}D`),(s>0||a>0||c>0||n===0)&&(u+="T",s>0&&(u+=`${s}H`),a>0&&(u+=`${a}M`),(c>0||s===0&&a===0)&&(Number.isInteger(c)?u+=`${c}S`:u+=`${parseFloat(c.toFixed(3))}S`)),u}static xsdDayTimeDuration(e){return this.parseDayTimeDuration(e),new q.Literal(e,new Be.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static compareDurations(e,t,i){let n=e instanceof q.Literal?e.value:e,s=t instanceof q.Literal?t.value:t,a=this.parseDayTimeDuration(n),c=this.parseDayTimeDuration(s);switch(i){case"=":return a===c;case"!=":return a!==c;case"<":return a<c;case">":return a>c;case"<=":return a<=c;case">=":return a>=c;default:throw new Error(`compareDurations: unknown operator: ${i}`)}}static isDayTimeDuration(e){return e instanceof q.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#dayTimeDuration":!1}static dateTimeDiff(e,t){let i=e instanceof q.Literal?e.value:e,n=t instanceof q.Literal?t.value:t,s=new Date(i),a=new Date(n);if(isNaN(s.getTime()))throw new Error(`dateTimeDiff: invalid first dateTime: '${i}'`);if(isNaN(a.getTime()))throw new Error(`dateTimeDiff: invalid second dateTime: '${n}'`);let c=s.getTime()-a.getTime(),u=this.formatDayTimeDuration(c);return new q.Literal(u,new Be.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static dateTimeAdd(e,t){let i=e instanceof q.Literal?e.value:e,n=t instanceof q.Literal?t.value:t,s=new Date(i);if(isNaN(s.getTime()))throw new Error(`dateTimeAdd: invalid dateTime: '${i}'`);let a=this.parseDayTimeDuration(n),c=s.getTime()+a,u=new Date(c);return new q.Literal(u.toISOString(),new Be.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}static dateTimeSubtract(e,t){let i=e instanceof q.Literal?e.value:e,n=t instanceof q.Literal?t.value:t,s=new Date(i);if(isNaN(s.getTime()))throw new Error(`dateTimeSubtract: invalid dateTime: '${i}'`);let a=this.parseDayTimeDuration(n),c=s.getTime()-a,u=new Date(c);return new q.Literal(u.toISOString(),new Be.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}static durationAdd(e,t){let i=e instanceof q.Literal?e.value:e,n=t instanceof q.Literal?t.value:t,s=this.parseDayTimeDuration(i),a=this.parseDayTimeDuration(n),c=this.formatDayTimeDuration(s+a);return new q.Literal(c,new Be.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static durationSubtract(e,t){let i=e instanceof q.Literal?e.value:e,n=t instanceof q.Literal?t.value:t,s=this.parseDayTimeDuration(i),a=this.parseDayTimeDuration(n),c=this.formatDayTimeDuration(s-a);return new q.Literal(c,new Be.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static durationMultiply(e,t){let i=e instanceof q.Literal?e.value:e,n=this.parseDayTimeDuration(i),s=this.formatDayTimeDuration(n*t);return new q.Literal(s,new Be.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static durationDivide(e,t){if(t===0)throw new Error("durationDivide: division by zero");let i=e instanceof q.Literal?e.value:e,n=this.parseDayTimeDuration(i),s=this.formatDayTimeDuration(n/t);return new q.Literal(s,new Be.IRI("http://www.w3.org/2001/XMLSchema#dayTimeDuration"))}static durationToDays(e){let t=e instanceof q.Literal?e.value:e;return this.parseDayTimeDuration(t)/(1440*60*1e3)}static durationToHours(e){let t=e instanceof q.Literal?e.value:e;return this.parseDayTimeDuration(t)/(3600*1e3)}static durationToMinutes(e){let t=e instanceof q.Literal?e.value:e;return this.parseDayTimeDuration(t)/(60*1e3)}static durationToSeconds(e){let t=e instanceof q.Literal?e.value:e;return this.parseDayTimeDuration(t)/1e3}static parseDurationComponents(e){if(!e)throw new Error("parseDurationComponents: duration string is empty");let t=!1,i=e.trim();if(i.startsWith("-")&&(t=!0,i=i.substring(1)),!i.startsWith("P"))throw new Error(`parseDurationComponents: invalid format, must start with 'P': '${e}'`);i=i.substring(1);let n=0,s=0,a=0,c=0,u=i.indexOf("T"),l="",f="";if(u===-1?l=i:(l=i.substring(0,u),f=i.substring(u+1)),l){let h=l.match(/^(\d+(?:\.\d+)?)D$/);if(h)n=parseFloat(h[1]);else if(l!=="")throw new Error(`parseDurationComponents: invalid day component: '${l}' in '${e}'`)}if(f){let h=f,d=h.match(/^(\d+(?:\.\d+)?)H/);d&&(s=parseFloat(d[1]),h=h.substring(d[0].length));let g=h.match(/^(\d+(?:\.\d+)?)M/);g&&(a=parseFloat(g[1]),h=h.substring(g[0].length));let _=h.match(/^(\d+(?:\.\d+)?)S$/);if(_&&(c=parseFloat(_[1]),h=h.substring(_[0].length)),h!=="")throw new Error(`parseDurationComponents: invalid time component: '${h}' in '${e}'`)}return{negative:t,days:n,hours:s,minutes:a,seconds:c}}static durationDays(e){let t=e instanceof q.Literal?e.value:e,i=this.parseDurationComponents(t),n=Math.floor(i.days);return i.negative?-n:n}static durationHours(e){let t=e instanceof q.Literal?e.value:e,i=this.parseDurationComponents(t),n=Math.floor(i.hours);return i.negative?-n:n}static durationMinutes(e){let t=e instanceof q.Literal?e.value:e,i=this.parseDurationComponents(t),n=Math.floor(i.minutes);return i.negative?-n:n}static durationSeconds(e){let t=e instanceof q.Literal?e.value:e,i=this.parseDurationComponents(t);return i.negative?-i.seconds:i.seconds}static adjust(e,t){let i=e instanceof q.Literal?e.value:e,n=new Date(i);if(isNaN(n.getTime()))throw new Error(`ADJUST: invalid dateTime: '${i}'`);if(t==null){let Ie=n.getUTCFullYear(),Je=String(n.getUTCMonth()+1).padStart(2,"0"),ot=String(n.getUTCDate()).padStart(2,"0"),B=String(n.getUTCHours()).padStart(2,"0"),ue=String(n.getUTCMinutes()).padStart(2,"0"),we=String(n.getUTCSeconds()).padStart(2,"0"),He=n.getUTCMilliseconds(),Ue=`${Ie}-${Je}-${ot}T${B}:${ue}:${we}`;return He>0&&(Ue+=`.${String(He).padStart(3,"0")}`),new q.Literal(Ue,new Be.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}let s=t instanceof q.Literal?t.value:t,a=this.parseDayTimeDuration(s),c=840*60*1e3;if(Math.abs(a)>c)throw new Error(`ADJUST: timezone offset out of range: '${s}'`);let u=n.getTime(),l=new Date(u+a),f=l.getUTCFullYear(),h=String(l.getUTCMonth()+1).padStart(2,"0"),d=String(l.getUTCDate()).padStart(2,"0"),g=String(l.getUTCHours()).padStart(2,"0"),_=String(l.getUTCMinutes()).padStart(2,"0"),w=String(l.getUTCSeconds()).padStart(2,"0"),C=l.getUTCMilliseconds(),O=a>=0?"+":"-",F=Math.floor(Math.abs(a)/(3600*1e3)),j=Math.floor(Math.abs(a)%(3600*1e3)/(60*1e3)),G=`${O}${String(F).padStart(2,"0")}:${String(j).padStart(2,"0")}`,W=`${f}-${h}-${d}T${g}:${_}:${w}`;return C>0&&(W+=`.${String(C).padStart(3,"0")}`),W+=G,new q.Literal(W,new Be.IRI("http://www.w3.org/2001/XMLSchema#dateTime"))}static normalize(e,t){if(e===void 0)throw new Error("NORMALIZE: string argument is undefined");let i;if(e instanceof q.Literal)i=e.value;else if(e instanceof Be.IRI)i=e.value;else if(e instanceof hi.BlankNode)i=e.id;else if(typeof e=="string")i=e;else throw new Error("NORMALIZE: first argument must be a string or literal");let n="NFC";if(t!==void 0)if(t instanceof q.Literal)n=t.value.toUpperCase();else if(typeof t=="string")n=t.toUpperCase();else if(t instanceof Be.IRI)n=t.value.toUpperCase();else throw new Error("NORMALIZE: second argument must be a string literal");if(!this.VALID_NORMALIZATION_FORMS.includes(n))throw new Error(`NORMALIZE: invalid normalization form '${n}'. Valid forms are: NFC, NFD, NFKC, NFKD`);let s=i.normalize(n);return new q.Literal(s,new Be.IRI("http://www.w3.org/2001/XMLSchema#string"))}static fold(e){if(e===void 0)throw new Error("FOLD: string argument is undefined");let t;if(e instanceof q.Literal)t=e.value;else if(e instanceof Be.IRI)t=e.value;else if(e instanceof hi.BlankNode)t=e.id;else if(typeof e=="string")t=e;else throw new Error("FOLD: argument must be a string or literal");let i=this.unicodeCaseFold(t);return new q.Literal(i,new Be.IRI("http://www.w3.org/2001/XMLSchema#string"))}static unicodeCaseFold(e){let t="";for(let i of e){let n=this.CASE_FOLDING_MAP.get(i);n!==void 0?t+=n:t+=i.toLowerCase()}return t}};wl.BuiltInFunctions=No;No.VALID_NORMALIZATION_FORMS=["NFC","NFD","NFKC","NFKD"];No.CASE_FOLDING_MAP=new Map([["\xDF","ss"],["\u1E9E","ss"],["\u03A3","\u03C3"],["\u03C2","\u03C3"],["\u0130","i\u0307"],["I","i"],["\u0587","\u0565\u0582"],["\uFB00","ff"],["\uFB01","fi"],["\uFB02","fl"],["\uFB03","ffi"],["\uFB04","ffl"],["\uFB05","st"],["\uFB06","st"],["\u0390","\u03B9\u0308\u0301"],["\u03B0","\u03C5\u0308\u0301"],["\u017F","s"],["\u1E9B","\u1E61"],["\u212A","k"],["\u212B","\xE5"]])});var Sl=y(ma=>{"use strict";Object.defineProperty(ma,"__esModule",{value:!0});ma.FilterExecutor=ma.FilterExecutorError=void 0;var D=jm(),bl=yt(),Mt=class extends Error{static{o(this,"FilterExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="FilterExecutorError"}};ma.FilterExecutorError=Mt;var Lm=class{static{o(this,"FilterExecutor")}constructor(){this.existsEvaluator=null,this.tripleStore=null,this.uuidCache=new Map}setExistsEvaluator(e){this.existsEvaluator=e}setTripleStore(e){this.tripleStore=e,this.uuidCache.clear()}async*execute(e,t){let i=this.expressionContainsExists(e.expression);for await(let n of t)try{let s;i?s=await this.evaluateExpressionAsync(e.expression,n):s=this.evaluateExpression(e.expression,n),s===!0&&(yield n)}catch{continue}}expressionContainsExists(e){if(e.type==="exists")return!0;if(e.type==="logical")return e.operands.some(t=>this.expressionContainsExists(t));if(e.type==="comparison")return this.expressionContainsExists(e.left)||this.expressionContainsExists(e.right);if(e.type==="in"){let t=e;return this.expressionContainsExists(t.expression)||t.list.some(i=>this.expressionContainsExists(i))}return!1}async executeAll(e,t){let i=[];async function*n(){for(let s of t)yield s}o(n,"generator");for await(let s of this.execute(e,n()))i.push(s);return i}evaluateExpression(e,t){let i=e;if(i.termType)switch(i.termType){case"Variable":return t.get(i.value);case"Literal":return i.value;case"NamedNode":return i.value;default:throw new Mt(`Unsupported termType: ${i.termType}`)}switch(e.type){case"comparison":return this.evaluateComparison(e,t);case"logical":return this.evaluateLogical(e,t);case"arithmetic":return this.evaluateArithmetic(e,t);case"function":case"functionCall":return this.evaluateFunction(e,t);case"variable":return t.get(e.name);case"literal":return e.value;case"in":return this.evaluateIn(e,t);case"exists":throw new Mt("EXISTS expressions require async evaluation. Use evaluateExpressionAsync instead.");default:throw new Mt(`Unsupported expression type: ${e.type}, expr.termType=${i.termType}`)}}async evaluateExpressionAsync(e,t){return e.type==="exists"?this.evaluateExists(e,t):e.type==="logical"?this.evaluateLogicalAsync(e,t):this.evaluateExpression(e,t)}async evaluateExists(e,t){if(!this.existsEvaluator)throw new Mt("EXISTS evaluator not set. Call setExistsEvaluator before evaluating EXISTS expressions.");let i=await this.existsEvaluator(e.pattern,t);return e.negated?!i:i}async evaluateLogicalAsync(e,t){if(e.operator==="!"){let n=await this.evaluateExpressionAsync(e.operands[0],t);return D.BuiltInFunctions.logicalNot(n)}let i=[];for(let n of e.operands){let s=await this.evaluateExpressionAsync(n,t);i.push(s)}if(e.operator==="&&")return D.BuiltInFunctions.logicalAnd(i);if(e.operator==="||")return D.BuiltInFunctions.logicalOr(i);throw new Mt(`Unknown logical operator: ${e.operator}`)}evaluateComparison(e,t){let i=this.evaluateExpression(e.left,t),n=this.evaluateExpression(e.right,t);return D.BuiltInFunctions.compare(i,n,e.operator)}evaluateLogical(e,t){if(e.operator==="!"){let n=this.evaluateExpression(e.operands[0],t);return D.BuiltInFunctions.logicalNot(n)}let i=e.operands.map(n=>this.evaluateExpression(n,t));if(e.operator==="&&")return D.BuiltInFunctions.logicalAnd(i);if(e.operator==="||")return D.BuiltInFunctions.logicalOr(i);throw new Mt(`Unknown logical operator: ${e.operator}`)}evaluateIn(e,t){let i=this.evaluateExpression(e.expression,t),n=e.list.some(s=>{let a=this.evaluateExpression(s,t);return D.BuiltInFunctions.compare(i,a,"=")});return e.negated?!n:n}evaluateArithmetic(e,t){let i=this.evaluateExpression(e.left,t),n=this.evaluateExpression(e.right,t);if(e.operator==="-"&&this.isDateTimeValue(i)&&this.isDateTimeValue(n))return D.BuiltInFunctions.dateTimeDiff(i,n);if(e.operator==="+"&&this.isDateTimeValue(i)&&this.isDayTimeDurationValue(n))return D.BuiltInFunctions.dateTimeAdd(i,n);if(e.operator==="-"&&this.isDateTimeValue(i)&&this.isDayTimeDurationValue(n))return D.BuiltInFunctions.dateTimeSubtract(i,n);if(e.operator==="+"&&this.isDayTimeDurationValue(i)&&this.isDayTimeDurationValue(n))return D.BuiltInFunctions.durationAdd(i,n);if(e.operator==="-"&&this.isDayTimeDurationValue(i)&&this.isDayTimeDurationValue(n))return D.BuiltInFunctions.durationSubtract(i,n);if(e.operator==="*"&&this.isDayTimeDurationValue(i)&&!this.isDayTimeDurationValue(n)){let c=this.toNumericValue(n);return D.BuiltInFunctions.durationMultiply(i,c)}if(e.operator==="*"&&!this.isDayTimeDurationValue(i)&&this.isDayTimeDurationValue(n)){let c=this.toNumericValue(i);return D.BuiltInFunctions.durationMultiply(n,c)}if(e.operator==="/"&&this.isDayTimeDurationValue(i)&&!this.isDayTimeDurationValue(n)){let c=this.toNumericValue(n);if(c===0)throw new Mt("Division by zero");return D.BuiltInFunctions.durationDivide(i,c)}let s=this.toNumericValue(i),a=this.toNumericValue(n);switch(e.operator){case"+":return s+a;case"-":return s-a;case"*":return s*a;case"/":if(a===0)throw new Mt("Division by zero");return s/a;default:throw new Mt(`Unknown arithmetic operator: ${e.operator}`)}}isDayTimeDurationValue(e){return e instanceof bl.Literal?(e.datatype?.value||"")==="http://www.w3.org/2001/XMLSchema#dayTimeDuration":!1}toNumericValue(e){if(typeof e=="number")return e;if(e instanceof bl.Literal){let t=e.datatype?.value||"";if(t.includes("#integer")||t.includes("#decimal")||t.includes("#double")||t.includes("#float")){let n=parseFloat(e.value);if(!isNaN(n))return n}let i=parseFloat(e.value);if(!isNaN(i))return i}if(typeof e=="string"){let t=parseFloat(e);if(!isNaN(t))return t}if(e&&typeof e=="object"&&"value"in e){let t=parseFloat(String(e.value));if(!isNaN(t))return t}throw new Mt(`Cannot convert to number: ${e}`)}isDateTimeValue(e){if(e instanceof bl.Literal){let t=e.datatype?.value||"";return t.includes("#dateTime")||t.includes("#date")?!0:/^\d{4}-\d{2}-\d{2}(T|\s)/.test(e.value)}return typeof e=="string"?/^\d{4}-\d{2}-\d{2}(T|\s)/.test(e):!1}evaluateFunction(e,t){let i;if(typeof e.function=="string")i=e.function.toLowerCase();else if(e.function&&typeof e.function=="object"&&"value"in e.function){let n=e.function.value;i=((n.includes("#")?n.split("#").pop():n.split("/").pop())||n).toLowerCase()}else throw new Mt(`Unknown function format: ${e.function}`);switch(i){case"str":let n=this.getTermFromExpression(e.args[0],t);return D.BuiltInFunctions.str(n);case"lang":let s=this.getTermFromExpression(e.args[0],t);return D.BuiltInFunctions.lang(s);case"datatype":let a=this.getTermFromExpression(e.args[0],t);return D.BuiltInFunctions.datatype(a).value;case"bound":if(e.args[0].type==="variable"){let E=t.get(e.args[0].name);return D.BuiltInFunctions.bound(E)}return!0;case"isiri":case"isuri":let c=this.getTermFromExpression(e.args[0],t);return D.BuiltInFunctions.isIRI(c);case"isblank":let u=this.getTermFromExpression(e.args[0],t);return D.BuiltInFunctions.isBlank(u);case"isliteral":let l=this.getTermFromExpression(e.args[0],t);return D.BuiltInFunctions.isLiteral(l);case"regex":let f=this.getStringValue(this.evaluateExpression(e.args[0],t)),h=this.getStringValue(this.evaluateExpression(e.args[1],t)),d=e.args[2]?this.getStringValue(this.evaluateExpression(e.args[2],t)):void 0;return D.BuiltInFunctions.regex(f,h,d);case"langmatches":let g=this.getStringValue(this.evaluateExpression(e.args[0],t)),_=this.getStringValue(this.evaluateExpression(e.args[1],t));return D.BuiltInFunctions.langMatches(g,_);case"contains":let w=this.getStringValue(this.evaluateExpression(e.args[0],t)),C=this.getStringValue(this.evaluateExpression(e.args[1],t));return D.BuiltInFunctions.contains(w,C);case"strstarts":let O=this.getStringValue(this.evaluateExpression(e.args[0],t)),F=this.getStringValue(this.evaluateExpression(e.args[1],t));return D.BuiltInFunctions.strStarts(O,F);case"strends":let j=this.getStringValue(this.evaluateExpression(e.args[0],t)),G=this.getStringValue(this.evaluateExpression(e.args[1],t));return D.BuiltInFunctions.strEnds(j,G);case"strlen":let W=this.getStringValue(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.strlen(W);case"ucase":let Ie=this.getStringValue(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.ucase(Ie);case"lcase":let Je=this.getStringValue(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.lcase(Je);case"substr":let ot=this.getStringValue(this.evaluateExpression(e.args[0],t)),B=Number(this.evaluateExpression(e.args[1],t));if(e.args[2]){let E=Number(this.evaluateExpression(e.args[2],t));return D.BuiltInFunctions.substr(ot,B,E)}return D.BuiltInFunctions.substr(ot,B);case"strbefore":let ue=this.getStringValue(this.evaluateExpression(e.args[0],t)),we=this.getStringValue(this.evaluateExpression(e.args[1],t));return D.BuiltInFunctions.strBefore(ue,we);case"strafter":let He=this.getStringValue(this.evaluateExpression(e.args[0],t)),Ue=this.getStringValue(this.evaluateExpression(e.args[1],t));return D.BuiltInFunctions.strAfter(He,Ue);case"concat":let Ze=e.args.map(E=>this.getStringValue(this.evaluateExpression(E,t)));return D.BuiltInFunctions.concat(...Ze);case"replace":let ke=this.getStringValue(this.evaluateExpression(e.args[0],t)),je=this.getStringValue(this.evaluateExpression(e.args[1],t)),Re=this.getStringValue(this.evaluateExpression(e.args[2],t)),H=e.args[3]?this.getStringValue(this.evaluateExpression(e.args[3],t)):void 0;return D.BuiltInFunctions.replace(ke,je,Re,H);case"parsedate":let N=this.getStringValue(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.parseDate(N);case"datebefore":let Le=this.getStringValue(this.evaluateExpression(e.args[0],t)),Ge=this.getStringValue(this.evaluateExpression(e.args[1],t));return D.BuiltInFunctions.dateBefore(Le,Ge);case"dateafter":let V=this.getStringValue(this.evaluateExpression(e.args[0],t)),he=this.getStringValue(this.evaluateExpression(e.args[1],t));return D.BuiltInFunctions.dateAfter(V,he);case"dateinrange":let Ae=this.getStringValue(this.evaluateExpression(e.args[0],t)),z=this.getStringValue(this.evaluateExpression(e.args[1],t)),xe=this.getStringValue(this.evaluateExpression(e.args[2],t));return D.BuiltInFunctions.dateInRange(Ae,z,xe);case"datediffminutes":let Ce=this.getStringValue(this.evaluateExpression(e.args[0],t)),be=this.getStringValue(this.evaluateExpression(e.args[1],t));return D.BuiltInFunctions.dateDiffMinutes(Ce,be);case"datediffhours":let Oe=this.getStringValue(this.evaluateExpression(e.args[0],t)),le=this.getStringValue(this.evaluateExpression(e.args[1],t));return D.BuiltInFunctions.dateDiffHours(Oe,le);case"year":let Se=this.getStringValue(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.year(Se);case"month":let de=this.getStringValue(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.month(de);case"day":case"days":{let E=this.evaluateExpression(e.args[0],t);return this.isDayTimeDurationValue(E)?D.BuiltInFunctions.durationDays(E):D.BuiltInFunctions.day(this.getStringValue(E))}case"hours":{let E=this.evaluateExpression(e.args[0],t);return this.isDayTimeDurationValue(E)?D.BuiltInFunctions.durationHours(E):D.BuiltInFunctions.hours(this.getStringValue(E))}case"minutes":{let E=this.evaluateExpression(e.args[0],t);return this.isDayTimeDurationValue(E)?D.BuiltInFunctions.durationMinutes(E):D.BuiltInFunctions.minutes(this.getStringValue(E))}case"seconds":{let E=this.evaluateExpression(e.args[0],t);return this.isDayTimeDurationValue(E)?D.BuiltInFunctions.durationSeconds(E):D.BuiltInFunctions.seconds(this.getStringValue(E))}case"timezone":let Ee=this.getStringValue(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.timezone(Ee);case"tz":let Pe=this.getStringValue(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.tz(Pe);case"adjust":{let E=this.evaluateExpression(e.args[0],t),k=e.args.length>1?this.evaluateExpression(e.args[1],t):void 0;return D.BuiltInFunctions.adjust(E,k)}case"now":return D.BuiltInFunctions.now();case"datetime":case"xsd:datetime":{let E=this.evaluateExpression(e.args[0],t);return D.BuiltInFunctions.xsdDateTime(this.getStringValue(E))}case"integer":case"xsd:integer":{let E=this.evaluateExpression(e.args[0],t);return D.BuiltInFunctions.xsdInteger(this.getStringValue(E))}case"decimal":case"xsd:decimal":{let E=this.evaluateExpression(e.args[0],t);return D.BuiltInFunctions.xsdDecimal(this.getStringValue(E))}case"daytimeduration":case"xsd:daytimeduration":{let E=this.evaluateExpression(e.args[0],t);return D.BuiltInFunctions.xsdDayTimeDuration(this.getStringValue(E))}case"durationtodays":{let E=this.evaluateExpression(e.args[0],t);return D.BuiltInFunctions.durationToDays(E)}case"durationtohours":{let E=this.evaluateExpression(e.args[0],t);return D.BuiltInFunctions.durationToHours(E)}case"durationtominutes":{let E=this.evaluateExpression(e.args[0],t);return D.BuiltInFunctions.durationToMinutes(E)}case"durationtoseconds":{let E=this.evaluateExpression(e.args[0],t);return D.BuiltInFunctions.durationToSeconds(E)}case"durationdays":{let E=this.evaluateExpression(e.args[0],t);return D.BuiltInFunctions.durationDays(E)}case"durationhours":{let E=this.evaluateExpression(e.args[0],t);return D.BuiltInFunctions.durationHours(E)}case"durationminutes":{let E=this.evaluateExpression(e.args[0],t);return D.BuiltInFunctions.durationMinutes(E)}case"durationseconds":{let E=this.evaluateExpression(e.args[0],t);return D.BuiltInFunctions.durationSeconds(E)}case"datetimediff":{let E=this.evaluateExpression(e.args[0],t),k=this.evaluateExpression(e.args[1],t);return D.BuiltInFunctions.dateTimeDiff(E,k)}case"datetimeadd":{let E=this.evaluateExpression(e.args[0],t),k=this.evaluateExpression(e.args[1],t);return D.BuiltInFunctions.dateTimeAdd(E,k)}case"datetimesubtract":{let E=this.evaluateExpression(e.args[0],t),k=this.evaluateExpression(e.args[1],t);return D.BuiltInFunctions.dateTimeSubtract(E,k)}case"mstominutes":let J=Number(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.msToMinutes(J);case"mstohours":let re=Number(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.msToHours(re);case"mstoseconds":let ie=Number(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.msToSeconds(ie);case"abs":let Z=Number(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.abs(Z);case"round":let ee=Number(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.round(ee);case"ceil":let te=Number(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.ceil(te);case"floor":let X=Number(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.floor(X);case"rand":return D.BuiltInFunctions.rand();case"coalesce":for(let E of e.args)try{let k=this.evaluateExpression(E,t);if(k!=null)return k}catch{continue}return;case"if":if(!e.args||e.args.length!==3)throw new Mt("IF requires exactly 3 arguments");let ne=this.evaluateExpression(e.args[0],t);return this.toBoolean(ne)?this.evaluateExpression(e.args[1],t):this.evaluateExpression(e.args[2],t);case"encode_for_uri":let se=this.getStringValue(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.encodeForUri(se);case"isnumeric":let ae=this.getTermFromExpression(e.args[0],t);return D.BuiltInFunctions.isNumeric(ae);case"haslangdir":let Q=this.getTermFromExpression(e.args[0],t);return D.BuiltInFunctions.hasLangdir(Q);case"sameterm":let oe=this.getTermFromExpression(e.args[0],t),De=this.getTermFromExpression(e.args[1],t);return D.BuiltInFunctions.sameTerm(oe,De);case"md5":let Fe=this.getStringValue(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.md5(Fe);case"sha1":let ve=this.getStringValue(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.sha1(ve);case"sha256":let v=this.getStringValue(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.sha256(v);case"sha384":let S=this.getStringValue(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.sha384(S);case"sha512":let T=this.getStringValue(this.evaluateExpression(e.args[0],t));return D.BuiltInFunctions.sha512(T);case"byuuid":return this.evaluateByUUID(e,t);default:throw new Mt(`Unknown function: ${i}`)}}getTermFromExpression(e,t){if(e.type==="variable")return t.get(e.name)}getStringValue(e){return e==null?"":typeof e=="object"&&"value"in e?String(e.value):String(e)}toBoolean(e){if(typeof e=="boolean")return e;if(typeof e=="number")return!isNaN(e)&&e!==0;if(typeof e=="string")return e.length>0;if(e instanceof bl.Literal){let t=e.datatype?.value||"";if(t.includes("#boolean"))return e.value==="true"||e.value==="1";if(t.includes("#integer")||t.includes("#decimal")||t.includes("#double")||t.includes("#float")){let i=parseFloat(e.value);return!isNaN(i)&&i!==0}return e.value.length>0}return!!e}evaluateByUUID(e,t){if(!e.args||e.args.length!==1)throw new Mt("exo:byUUID requires exactly 1 argument (UUID string)");let i=this.evaluateExpression(e.args[0],t),n=this.getStringValue(i);if(!n)return;let s=n.toLowerCase();if(this.uuidCache.has(s))return this.uuidCache.get(s)??void 0;if(!this.tripleStore){this.uuidCache.set(s,null);return}if(this.tripleStore.findSubjectsByUUIDSync){let a=this.tripleStore.findSubjectsByUUIDSync(s);if(a.length===0){this.uuidCache.set(s,null);return}let c=a[0];return this.uuidCache.set(s,c),c}this.uuidCache.set(s,null)}cacheUUIDResult(e,t){let i=e.toLowerCase();this.uuidCache.set(i,t)}getCachedUUID(e){let t=e.toLowerCase();if(this.uuidCache.has(t))return this.uuidCache.get(t)}};ma.FilterExecutor=Lm});var Vm=y(El=>{"use strict";Object.defineProperty(El,"__esModule",{value:!0});El.OptionalExecutor=void 0;var Mm=class{static{o(this,"OptionalExecutor")}async*execute(e,t){let i=[];for await(let s of e)i.push(s);let n=[];for await(let s of t)n.push(s);for(let s of i){let a=!1;for(let c of n){let u=s.merge(c);u!==null&&(yield u,a=!0)}a||(yield s)}}async executeAll(e,t){let i=[];async function*n(){for(let a of e)yield a}o(n,"generateLeft");async function*s(){for(let a of t)yield a}o(s,"generateRight");for await(let a of this.execute(n(),s()))i.push(a);return i}};El.OptionalExecutor=Mm});var qm=y(Tl=>{"use strict";Object.defineProperty(Tl,"__esModule",{value:!0});Tl.UnionExecutor=void 0;var $m=class{static{o(this,"UnionExecutor")}async*execute(e,t){let i=new Set;for await(let n of e){let s=this.getSolutionKey(n);i.has(s)||(i.add(s),yield n)}for await(let n of t){let s=this.getSolutionKey(n);i.has(s)||(i.add(s),yield n)}}async executeAll(e,t){let i=[];async function*n(){for(let a of e)yield a}o(n,"generateLeft");async function*s(){for(let a of t)yield a}o(s,"generateRight");for await(let a of this.execute(n(),s()))i.push(a);return i}getSolutionKey(e){let t=e.toJSON();return Object.keys(t).sort().map(n=>`${n}=${t[n]}`).join("|")}};Tl.UnionExecutor=$m});var Wm=y(Al=>{"use strict";Object.defineProperty(Al,"__esModule",{value:!0});Al.ConstructExecutor=void 0;var mP=_n(),Es=et(),Bm=yt(),Um=sr(),gP=eu(),Gm=class{static{o(this,"ConstructExecutor")}async execute(e,t){let i=[],n=new Set;for(let s of t)for(let a of e)try{let c=this.instantiateTriple(a,s),u=`${c.subject.toString()}|${c.predicate.toString()}|${c.object.toString()}`;n.has(u)||(n.add(u),i.push(c))}catch{continue}return i}instantiateTriple(e,t){if(this.isPropertyPath(e.predicate))throw new Error("Property paths are not supported in CONSTRUCT templates");let i=this.instantiateElement(e.subject,t),n=this.instantiateElement(e.predicate,t),s=this.instantiateElement(e.object,t);return new mP.Triple(i,n,s)}isPropertyPath(e){return e.type==="path"}instantiateElement(e,t){if(e.type==="variable"){let i=t.get(e.value);if(!i)throw new Error(`Unbound variable: ${e.value}`);return i}if(e.type==="iri")return new Es.IRI(e.value);if(e.type==="literal")return new Bm.Literal(e.value,e.datatype?new Es.IRI(e.datatype):void 0,e.language);if(e.type==="blank")return new Um.BlankNode(e.value);if(e.type==="quoted")return this.instantiateQuotedTriple(e,t);throw new Error(`Unknown element type: ${e.type}`)}instantiateQuotedTriple(e,t){let i=this.instantiateQuotedSubject(e.subject,t),n=this.instantiateQuotedPredicate(e.predicate,t),s=this.instantiateQuotedObject(e.object,t);return new gP.QuotedTriple(i,n,s)}instantiateQuotedSubject(e,t){if(e.type==="variable"){let i=t.get(e.value);if(!i)throw new Error(`Unbound variable in quoted triple subject: ${e.value}`);if(i instanceof Bm.Literal)throw new Error("Literals cannot appear in quoted triple subject position");return i}if(e.type==="iri")return new Es.IRI(e.value);if(e.type==="blank")return new Um.BlankNode(e.value);if(e.type==="quoted")return this.instantiateQuotedTriple(e,t);throw new Error(`Invalid element type for quoted triple subject: ${e.type}`)}instantiateQuotedPredicate(e,t){if(e.type==="variable"){let i=t.get(e.value);if(!i)throw new Error(`Unbound variable in quoted triple predicate: ${e.value}`);if(!(i instanceof Es.IRI))throw new Error("Quoted triple predicate must be an IRI");return i}return new Es.IRI(e.value)}instantiateQuotedObject(e,t){if(e.type==="variable"){let n=t.get(e.value);if(!n)throw new Error(`Unbound variable in quoted triple object: ${e.value}`);return n}if(e.type==="iri")return new Es.IRI(e.value);if(e.type==="blank")return new Um.BlankNode(e.value);if(e.type==="literal")return new Bm.Literal(e.value,e.datatype?new Es.IRI(e.datatype):void 0,e.language);if(e.type==="quoted")return this.instantiateQuotedTriple(e,t);let i=e;throw new Error(`Invalid element type for quoted triple object: ${i.type}`)}};Al.ConstructExecutor=Gm});var w3=y(xl=>{"use strict";Object.defineProperty(xl,"__esModule",{value:!0});xl.DescribeExecutor=void 0;var _3=et(),zm=class{static{o(this,"DescribeExecutor")}constructor(e){this.tripleStore=e}async execute(e,t){let i=[],n=new Set,s=new Set,a=t?.depth;for(let c of e)await this.describeResourceWithDepth(c,a,1,t?.symmetric??!0,i,n,s);return i}async describeResourceWithDepth(e,t,i,n,s,a,c){let u=e.toString();if(c.has(u)||(c.add(u),t!==void 0&&i>t))return;let l=[],f=await this.tripleStore.match(e,void 0,void 0);if(l.push(...f),n){let d=await this.tripleStore.match(void 0,void 0,e);l.push(...d)}let h=[];for(let d of l){let g=`${d.subject.toString()}|${d.predicate.toString()}|${d.object.toString()}`;a.has(g)||(a.add(g),s.push(d),(t===void 0||i<t)&&(this.isIRI(d.subject)&&d.subject.toString()!==u&&h.push(d.subject),this.isIRI(d.object)&&d.object.toString()!==u&&h.push(d.object)))}for(let d of h)await this.describeResourceWithDepth(d,t,i+1,n,s,a,c)}isIRI(e){return e?e instanceof _3.IRI||e.termType==="NamedNode"||typeof e.value=="string"&&e.value.startsWith("http"):!1}async describeByIRI(e,t){let i=new _3.IRI(e);return this.execute([i],t)}};xl.DescribeExecutor=zm});var b3=y(Cl=>{"use strict";Object.defineProperty(Cl,"__esModule",{value:!0});Cl.MinusExecutor=void 0;var Hm=class{static{o(this,"MinusExecutor")}async*execute(e,t){let i=[];for await(let s of e)i.push(s);let n=[];for await(let s of t)n.push(s);for(let s of i){let a=!1;for(let c of n)if(this.areCompatible(s,c)){a=!0;break}a||(yield s)}}async executeAll(e,t){let i=[];async function*n(){for(let a of e)yield a}o(n,"generateLeft");async function*s(){for(let a of t)yield a}o(s,"generateRight");for await(let a of this.execute(n(),s()))i.push(a);return i}areCompatible(e,t){let i=e.variables(),n=new Set(t.variables()),s=i.filter(a=>n.has(a));if(s.length===0)return!1;for(let a of s){let c=e.get(a),u=t.get(a);if(c===void 0||u===void 0||c.toString()!==u.toString())return!1}return!0}};Cl.MinusExecutor=Hm});var E3=y(ga=>{"use strict";Object.defineProperty(ga,"__esModule",{value:!0});ga.ValuesExecutor=ga.ValuesExecutorError=void 0;var yP=cn(),S3=et(),vP=yt(),Ol=class extends Error{static{o(this,"ValuesExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="ValuesExecutorError"}};ga.ValuesExecutorError=Ol;var Km=class{static{o(this,"ValuesExecutor")}async*execute(e){if(e.bindings.length!==0)for(let t of e.bindings)yield this.createSolutionMapping(t)}async executeAll(e){let t=[];for await(let i of this.execute(e))t.push(i);return t}createSolutionMapping(e){let t=new yP.SolutionMapping;for(let[i,n]of Object.entries(e)){let s=this.toRDFTerm(n);t.set(i,s)}return t}toRDFTerm(e){if(e.type==="iri")return new S3.IRI(e.value);if(e.type==="literal")return new vP.Literal(e.value,e.datatype?new S3.IRI(e.datatype):void 0,e.language);throw new Ol(`Unknown term type: ${e.type}`)}};ga.ValuesExecutor=Km});var Qm=y(va=>{"use strict";Object.defineProperty(va,"__esModule",{value:!0});va.CustomAggregateRegistry=va.CustomAggregateError=void 0;var ya=class extends Error{static{o(this,"CustomAggregateError")}constructor(e,t){super(e),this.iri=t,this.name="CustomAggregateError"}};va.CustomAggregateError=ya;var Pl=class r{static{o(this,"CustomAggregateRegistry")}constructor(){this.aggregates=new Map}static getInstance(){return r.instance||(r.instance=new r),r.instance}static resetInstance(){r.instance&&r.instance.clear(),r.instance=null}register(e,t){if(!e||typeof e!="string")throw new ya("Aggregate IRI must be a non-empty string");if(!t||typeof t.init!="function"||typeof t.step!="function"||typeof t.finalize!="function")throw new ya("Aggregate must implement init(), step(), and finalize() methods",e);if(this.aggregates.has(e))throw new ya(`Aggregate with IRI "${e}" is already registered`,e);this.aggregates.set(e,t)}unregister(e){return this.aggregates.delete(e)}get(e){return this.aggregates.get(e)}has(e){return this.aggregates.has(e)}getRegisteredIris(){return Array.from(this.aggregates.keys())}clear(){this.aggregates.clear()}get size(){return this.aggregates.size}};va.CustomAggregateRegistry=Pl;Pl.instance=null});var Ym=y(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.BUILT_IN_AGGREGATES=Ne.modeAggregate=Ne.stddevAggregate=Ne.varianceAggregate=Ne.medianAggregate=Ne.EXO_AGGREGATE_NS=void 0;Ne.getNumericValue=Fl;Ne.createDecimalLiteral=di;Ne.createDoubleLiteral=bP;Ne.createPercentileAggregate=Ts;var As=yt(),_a=et(),_P=new _a.IRI("http://www.w3.org/2001/XMLSchema#decimal"),wP=new _a.IRI("http://www.w3.org/2001/XMLSchema#double");Ne.EXO_AGGREGATE_NS="https://exocortex.my/ontology/agg#";function Fl(r){return r==null?NaN:typeof r=="number"?r:typeof r=="string"?parseFloat(r):r instanceof As.Literal?parseFloat(r.value):r instanceof _a.IRI?NaN:typeof r=="boolean"?r?1:0:NaN}o(Fl,"getNumericValue");function di(r){return new As.Literal(String(r),_P)}o(di,"createDecimalLiteral");function bP(r){return new As.Literal(String(r),wP)}o(bP,"createDoubleLiteral");Ne.medianAggregate={init(){return{values:[]}},step(r,e){let t=r,i=Fl(e);isNaN(i)||t.values.push(i)},finalize(r){let e=r,{values:t}=e;if(t.length===0)return di(0);let i=[...t].sort((a,c)=>a-c),n=Math.floor(i.length/2),s=i.length%2!==0?i[n]:(i[n-1]+i[n])/2;return di(s)}};Ne.varianceAggregate={init(){return{values:[]}},step(r,e){let t=r,i=Fl(e);isNaN(i)||t.values.push(i)},finalize(r){let e=r,{values:t}=e;if(t.length===0)return di(0);let i=t.reduce((s,a)=>s+a,0)/t.length,n=t.reduce((s,a)=>s+Math.pow(a-i,2),0)/t.length;return di(n)}};Ne.stddevAggregate={init(){return{values:[]}},step(r,e){Ne.varianceAggregate.step(r,e)},finalize(r){let e=r,{values:t}=e;if(t.length===0)return di(0);let i=t.reduce((s,a)=>s+a,0)/t.length,n=t.reduce((s,a)=>s+Math.pow(a-i,2),0)/t.length;return di(Math.sqrt(n))}};Ne.modeAggregate={init(){return{counts:new Map,values:new Map}},step(r,e){if(e==null)return;let t=r,i=String(e instanceof As.Literal||e instanceof _a.IRI?e.value:e),n=t.counts.get(i)||0;t.counts.set(i,n+1),t.values.set(i,e)},finalize(r){let e=r;if(e.counts.size===0)return new As.Literal(" ",new _a.IRI("http://www.w3.org/2001/XMLSchema#string"));let t="",i=0;for(let[a,c]of e.counts)c>i&&(i=c,t=a);let n=e.values.get(t);if(n instanceof As.Literal)return n;let s=parseFloat(t);return isNaN(s)?new As.Literal(t,new _a.IRI("http://www.w3.org/2001/XMLSchema#string")):di(s)}};function Ts(r){let e=Math.max(0,Math.min(100,r))/100;return{init(){return{values:[],percentile:e}},step(t,i){let n=t,s=Fl(i);isNaN(s)||n.values.push(s)},finalize(t){let i=t,{values:n}=i;if(n.length===0)return di(0);let s=[...n].sort((h,d)=>h-d),a=i.percentile*(s.length-1),c=Math.floor(a),u=Math.ceil(a);if(c===u)return di(s[c]);let l=a-c,f=s[c]*(1-l)+s[u]*l;return di(f)}}}o(Ts,"createPercentileAggregate");Ne.BUILT_IN_AGGREGATES={[`${Ne.EXO_AGGREGATE_NS}median`]:Ne.medianAggregate,[`${Ne.EXO_AGGREGATE_NS}variance`]:Ne.varianceAggregate,[`${Ne.EXO_AGGREGATE_NS}stddev`]:Ne.stddevAggregate,[`${Ne.EXO_AGGREGATE_NS}mode`]:Ne.modeAggregate,[`${Ne.EXO_AGGREGATE_NS}percentile25`]:Ts(25),[`${Ne.EXO_AGGREGATE_NS}percentile50`]:Ts(50),[`${Ne.EXO_AGGREGATE_NS}percentile75`]:Ts(75),[`${Ne.EXO_AGGREGATE_NS}percentile90`]:Ts(90),[`${Ne.EXO_AGGREGATE_NS}percentile95`]:Ts(95),[`${Ne.EXO_AGGREGATE_NS}percentile99`]:Ts(99)}});var x3=y(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.AggregateExecutor=wa.AggregateExecutorError=void 0;var bt=yt(),Jm=et(),SP=Sl(),EP=Qm(),TP=Ym(),T3=new Jm.IRI("http://www.w3.org/2001/XMLSchema#integer"),xs=new Jm.IRI("http://www.w3.org/2001/XMLSchema#decimal"),Di=new Jm.IRI("http://www.w3.org/2001/XMLSchema#string");function A3(r){return typeof r=="object"&&r.type==="custom"}o(A3,"isCustomAggregation");var ko=class extends Error{static{o(this,"AggregateExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="AggregateExecutorError"}};wa.AggregateExecutorError=ko;var Xm=class{static{o(this,"AggregateExecutor")}constructor(){this.filterExecutor=new SP.FilterExecutor}execute(e,t){let i=this.groupSolutions(t,e.variables),n=[];for(let[s,a]of i.entries()){let c=new Map;for(let f of e.variables)if(a.length>0){let h=a[0].get(f);h&&c.set(f,h)}for(let f of e.aggregates){let h=this.computeAggregate(f.expression,a);c.set(f.variable,h)}let{SolutionMapping:u}=cn(),l=new u;for(let[f,h]of c.entries())l.set(f,h);n.push(l)}if(n.length===0&&e.aggregates.length>0){let s=this.createEmptyAggregateResult(e);s&&n.push(s)}return n}groupSolutions(e,t){let i=new Map;if(t.length===0)return i.set("",e),i;for(let n of e){let s=this.computeGroupKey(n,t),a=i.get(s);a?a.push(n):i.set(s,[n])}return i}computeGroupKey(e,t){return t.map(i=>{let n=e.get(i);return n?this.termToString(n):""}).join("|")}termToString(e){if(e&&typeof e=="object"){if("value"in e)return String(e.value);if("id"in e)return String(e.id)}return String(e)}computeAggregate(e,t){if(A3(e.aggregation))return this.computeCustomAggregate(e,t);let i=this.extractValues(e,t),n=e.aggregation;switch(n){case"count":{let s=this.computeCount(i,e.distinct);return new bt.Literal(String(s),T3)}case"sum":{let s=this.computeSum(i);return new bt.Literal(String(s),xs)}case"avg":{let s=this.computeAvg(i);return new bt.Literal(String(s),xs)}case"min":{let s=this.computeMin(i);return s===void 0?new bt.Literal("",Di):typeof s=="number"?new bt.Literal(String(s),xs):new bt.Literal(String(s),Di)}case"max":{let s=this.computeMax(i);return s===void 0?new bt.Literal("",Di):typeof s=="number"?new bt.Literal(String(s),xs):new bt.Literal(String(s),Di)}case"group_concat":{let s=this.computeGroupConcat(i,e.separator||" ",e.distinct);return new bt.Literal(s||" ",Di)}case"sample":{let s=this.computeSample(i,e.distinct);return s===void 0?new bt.Literal(" ",Di):typeof s=="number"?new bt.Literal(String(s),xs):new bt.Literal(String(s),Di)}default:{let s=n;throw new ko(`Unknown aggregation function: ${s}`)}}}computeCustomAggregate(e,t){let n=e.aggregation.iri,a=EP.CustomAggregateRegistry.getInstance().get(n);if(a||(a=TP.BUILT_IN_AGGREGATES[n]),!a)throw new ko(`Unknown custom aggregate function: ${n}. Register it with CustomAggregateRegistry.getInstance().register() or use a built-in aggregate.`);let c=a.init();for(let u of t){let l=null;if(e.expression){let f=this.evaluateExpression(e.expression,u);f!==void 0&&(l=f)}else l=1;a.step(c,l)}return a.finalize(c)}extractValues(e,t){if(!e.expression)return t.map(()=>1);let i=[];for(let n of t){let s=this.evaluateExpression(e.expression,n);s!=null&&i.push(s)}return i}evaluateExpression(e,t){if(e.type==="variable"){let i=t.get(e.name);return i==null?void 0:typeof i=="number"||typeof i=="string"||typeof i=="boolean"?i:typeof i=="object"&&"value"in i?i.value:i}if(e.type==="literal")return e.value;try{return this.filterExecutor.evaluateExpression(e,t)}catch{return}}computeCount(e,t){return t?new Set(e.map(i=>String(i))).size:e.length}computeSum(e){return e.map(i=>parseFloat(String(i))).filter(i=>!isNaN(i)).reduce((i,n)=>i+n,0)}computeAvg(e){let t=e.map(i=>parseFloat(String(i))).filter(i=>!isNaN(i));return t.length===0?0:t.reduce((i,n)=>i+n,0)/t.length}computeMin(e){if(e.length===0)return;let t=e.map(n=>parseFloat(String(n))).filter(n=>!isNaN(n));if(t.length>0)return Math.min(...t);let i=e.map(n=>String(n));return i.reduce((n,s)=>s<n?s:n,i[0])}computeMax(e){if(e.length===0)return;let t=e.map(n=>parseFloat(String(n))).filter(n=>!isNaN(n));if(t.length>0)return Math.max(...t);let i=e.map(n=>String(n));return i.reduce((n,s)=>s>n?s:n,i[0])}computeGroupConcat(e,t,i){let n=e.map(s=>String(s));return i&&(n=[...new Set(n)]),n.join(t)}computeSample(e,t){if(e.length===0)return;if(t){let s=[...new Set(e.map(u=>String(u)))];if(s.length===0)return;let a=s[0],c=parseFloat(a);return isNaN(c)?a:c}let i=e[0];if(typeof i=="number")return i;let n=parseFloat(String(i));return isNaN(n)?String(i):n}createEmptyAggregateResult(e){let{SolutionMapping:t}=cn(),i=new t;for(let n of e.aggregates){let s=n.expression.aggregation;if(A3(s)){i.set(n.variable,new bt.Literal("0",xs));continue}switch(s){case"count":i.set(n.variable,new bt.Literal("0",T3));break;case"sum":case"avg":i.set(n.variable,new bt.Literal("0",xs));break;case"group_concat":i.set(n.variable,new bt.Literal(" ",Di));break;case"min":case"max":case"sample":i.set(n.variable,new bt.Literal("",Di));break;default:i.set(n.variable,new bt.Literal("",Di))}}return i}};wa.AggregateExecutor=Xm});var O3=y(ba=>{"use strict";Object.defineProperty(ba,"__esModule",{value:!0});ba.ServiceExecutor=ba.ServiceExecutorError=void 0;var AP=cn(),C3=et(),xP=yt(),CP=sr(),Cs=class extends Error{static{o(this,"ServiceExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="ServiceExecutorError"}};ba.ServiceExecutorError=Cs;var Zm=class{static{o(this,"ServiceExecutor")}constructor(e={}){this.timeout=e.timeout??3e4,this.httpClient=e.httpClient??((t,i)=>fetch(t,i)),this.maxRetries=e.maxRetries??2,this.retryDelay=e.retryDelay??1e3}async*execute(e,t){try{let i=t(e.pattern),n=await this.executeRemoteQuery(e.endpoint,i);for(let s of n)yield s}catch(i){if(e.silent)return;throw i}}async executeRemoteQuery(e,t){let i;for(let n=0;n<=this.maxRetries;n++)try{let s=new AbortController,a=setTimeout(()=>s.abort(),this.timeout);try{let c=await this.httpClient(e,{method:"POST",headers:{"Content-Type":"application/sparql-query",Accept:"application/sparql-results+json"},body:t,signal:s.signal});if(!c.ok)throw new Cs(`Remote SPARQL endpoint returned ${c.status}: ${c.statusText}`);let u=await c.json();return this.parseJsonResults(u)}finally{clearTimeout(a)}}catch(s){if(i=s instanceof Error?s:new Error(String(s)),this.isRetryableError(i)&&n<this.maxRetries){await this.delay(this.retryDelay);continue}throw new Cs(`Failed to query remote SPARQL endpoint ${e}: ${i.message}`,i)}throw new Cs(`Failed to query remote SPARQL endpoint ${e} after ${this.maxRetries+1} attempts`,i)}parseJsonResults(e){return!e.results||!Array.isArray(e.results.bindings)?[]:e.results.bindings.map(t=>this.parseBinding(t))}parseBinding(e){let t=new AP.SolutionMapping;for(let[i,n]of Object.entries(e)){let s=this.parseRDFTerm(n);t.set(i,s)}return t}parseRDFTerm(e){switch(e.type){case"uri":return new C3.IRI(e.value);case"literal":{let t=e.datatype?new C3.IRI(e.datatype):void 0;return new xP.Literal(e.value,t,e["xml:lang"])}case"bnode":return new CP.BlankNode(e.value);default:throw new Cs(`Unknown RDF term type: ${e.type}`)}}isRetryableError(e){let t=e.message.toLowerCase();return!!(e.name==="AbortError"||t.includes("network")||t.includes("econnreset")||t.includes("econnrefused")||t.includes("etimedout")||t.includes("returned 5"))}delay(e){return new Promise(t=>setTimeout(t,e))}};ba.ServiceExecutor=Zm});var F3=y(Sa=>{"use strict";Object.defineProperty(Sa,"__esModule",{value:!0});Sa.GraphExecutor=Sa.GraphExecutorError=void 0;var P3=et(),Il=class extends Error{static{o(this,"GraphExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="GraphExecutorError"}};Sa.GraphExecutorError=Il;var eg=class{static{o(this,"GraphExecutor")}constructor(e){this.tripleStore=e}async*execute(e,t,i){let n=e.name;if(n.type==="iri")yield*this.executeWithGraph(e.pattern,n,t);else if(n.type==="variable")yield*this.executeWithGraphVariable(e,n,t,i);else throw new Il(`Invalid graph name type: ${n.type}`)}async*executeWithGraph(e,t,i){let n=new P3.IRI(t.value);this.tripleStore.hasGraph&&!await this.tripleStore.hasGraph(n)||(yield*i(e,n))}async*executeWithGraphVariable(e,t,i,n){if(n){let a=n.get(t.value);if(a&&a instanceof P3.IRI){yield*this.executeWithGraph(e.pattern,{type:"iri",value:a.value},i);return}}if(!this.tripleStore.getNamedGraphs)return;let s=await this.tripleStore.getNamedGraphs();for(let a of s)for await(let c of i(e.pattern,a)){let u=c.clone();u.set(t.value,a),yield u}}};Sa.GraphExecutor=eg});var I3=y(Ta=>{"use strict";Object.defineProperty(Ta,"__esModule",{value:!0});Ta.SPARQLGenerator=Ta.SPARQLGeneratorError=void 0;var Ea=class extends Error{static{o(this,"SPARQLGeneratorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="SPARQLGeneratorError"}};Ta.SPARQLGeneratorError=Ea;var tg=class{static{o(this,"SPARQLGenerator")}collectVariables(e){let t=new Set;return this.collectVariablesFromOperation(e,t),t}generateSelect(e){let t=this.collectVariables(e),i=t.size>0?Array.from(t).map(s=>`?${s}`).join(" "):"*",n=this.generateWhereClause(e);return`SELECT ${i} WHERE {
150
150
  ${n}
151
151
  }`}generateWhereClause(e,t=2){let i=" ".repeat(t);switch(e.type){case"bgp":return this.generateBGP(e,t);case"filter":return`${this.generateWhereClause(e.input,t)}
152
152
  ${i}FILTER(${this.generateExpression(e.expression)})`;case"join":return`${this.generateWhereClause(e.left,t)}
@@ -293,7 +293,7 @@ globstar while`,e,d,t,g,_),this.matchOne(e.slice(d),t.slice(g),i))return this.de
293
293
  \u{1F4CB} Failed Files:`);for(let t of e.results.filter(i=>!i.success))console.log(` \u274C ${t.filepath}: ${t.error}`)}if(e.movedCount>0&&r==="text"){console.log(`
294
294
  \u{1F4CB} Moved Files:`);for(let t of e.results.filter(i=>i.success&&i.changes?.moved))console.log(` \u{1F4C1} ${t.filepath} \u2192 ${t.changes?.newPath}`)}}}o(D7,"outputResult");function gS(){return new _r("batch-repair").description("Batch repair folder locations for all markdown files in a directory").argument("<directory>","Directory to process (relative to vault root)").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--dry-run","Preview changes without modifying files").option("--format <type>","Output format: text|json (default: text)","text").option("--progress","Show progress during processing (default: true)",!0).option("--no-progress","Disable progress output").action(async(r,e)=>{let t=e.format||"text";ge.setFormat(t);try{let i=(0,mS.resolve)(e.vault),n=new Wn(i),s=r;if(!await n.directoryExists(s))throw new rt(`Directory not found: ${s}`,"exocortex batch-repair <existing-directory>");let c=await n.getMarkdownFiles(s);if(c.length===0){if(t==="json"){let O=lt.success({success:!0,total:0,movedCount:0,alreadyCorrectCount:0,errorCount:0,results:[],durationMs:0,atomic:!1});console.log(JSON.stringify(O,null,2))}else console.log(`
295
295
  \u{1F4C2} No markdown files found in ${s}`);process.exit(0)}let u=c.map(O=>({command:"repair-folder",filepath:O})),l=e.progress!==!1&&t==="text",f=0;l&&console.log(`
296
- \u{1F50D} Processing ${c.length} files in ${s}...`);let d=await new Ls(i,e.dryRun).executeBatch(u,!1),g=0,_=0,w=0;for(let O of d.results)if(O.success?O.changes?.moved?g++:_++:w++,l&&!e.dryRun){f++;let F=Math.round(f/c.length*100);process.stdout.write(`\r Processing ${f}/${c.length} (${F}%)...`)}l&&process.stdout.write("\r"+" ".repeat(60)+"\r");let C={...d,movedCount:g,alreadyCorrectCount:_,errorCount:w};D7(t,C),process.exit(C.success?0:5)}catch(i){ge.handle(i)}})}o(gS,"batchRepairCommand");var jf=require("fs"),bi=require("path");function yS(){return new _r("resolve").description("Resolve UUID to file path").argument("<uuid>","Full or partial UUID to resolve").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--format <type>","Output format: uri|path|json (default: uri)","uri").option("--output <type>","Response format: text|json (for MCP tools)","text").option("--partial","Match partial UUIDs (returns all matches)").action(async(r,e)=>{let t=e.output||"text";ge.setFormat(t);try{let i=Date.now();if(!N7(r))throw new rt(`Invalid UUID format: ${r}`,"exocortex resolve <uuid> [--format uri|path|json] [--partial]",{uuid:r});let n=(0,bi.resolve)(e.vault);if(!(0,jf.existsSync)(n))throw new hn(n);let s=k7(n,r,e.partial??!1),a=Date.now()-i;if(s.length===0){if(t==="json"){let c=lt.error("VALIDATION_FILE_NOT_FOUND",`UUID not found: ${r}`,3,{context:{uuid:r}});console.log(JSON.stringify(c,null,2))}else console.error(`UUID not found: ${r}`);process.exit(1)}e.partial||s.length>1?L7(s,n,e.format,t,r,a):j7(s[0],n,e.format,t,r,a)}catch(i){ge.handle(i)}})}o(yS,"resolveCommand");function N7(r){if(r.length<4)return!1;let e=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,t=/^[0-9a-f-]+$/i;return e.test(r)||t.test(r)}o(N7,"isValidUuidFormat");function k7(r,e,t){let i=[],n=e.toLowerCase();function s(a){let c=(0,jf.readdirSync)(a,{withFileTypes:!0});for(let u of c){let l=(0,bi.join)(a,u.name);if(u.isDirectory())!u.name.startsWith(".")&&u.name!=="node_modules"&&s(l);else if(u.isFile()&&u.name.endsWith(".md")){let f=u.name.toLowerCase();t?f.includes(n)&&i.push(l):(f.startsWith(n+".md")||f.startsWith(n+" ")||f.startsWith(n+"-"))&&i.push(l)}}}return o(s,"walk"),s(r),i}o(k7,"findFilesWithUuid");function vS(r){return`obsidian://vault/${encodeURI(r)}`}o(vS,"pathToObsidianUri");function _S(r){let e=r.match(/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i);return e?e[1]:(0,bi.basename)(r,".md")}o(_S,"extractUuidFromFilename");function j7(r,e,t,i,n,s){let a=(0,bi.relative)(e,r),c=vS(a),u=_S((0,bi.basename)(r));if(i==="json"){let l={uuid:u,path:a,absolutePath:r,uri:c},f=lt.success(l,{durationMs:s,searchUuid:n});console.log(JSON.stringify(f,null,2))}else switch(t){case"path":console.log(r);break;case"json":console.log(JSON.stringify({uuid:u,path:a,absolutePath:r,uri:c},null,2));break;case"uri":default:console.log(c);break}}o(j7,"outputSingleResult");function L7(r,e,t,i,n,s){let a=r.map(c=>{let u=(0,bi.relative)(e,c),l=vS(u);return{uuid:_S((0,bi.basename)(c)),path:u,absolutePath:c,uri:l}});if(i==="json"){let c=lt.success({matches:a,count:a.length},{durationMs:s,searchUuid:n,itemCount:a.length});console.log(JSON.stringify(c,null,2))}else switch(t){case"path":for(let c of a)console.log(c.absolutePath);break;case"json":console.log(JSON.stringify(a,null,2));break;case"uri":default:for(let c of a)console.log(c.uri);break}}o(L7,"outputMultipleResults");var Hn=new _r;Hn.name("exocortex").description("CLI tool for Exocortex knowledge management system").version("13.191.0");Hn.command("sparql").description("SPARQL query execution").addCommand(ib());Hn.addCommand(lS());Hn.addCommand(dS());Hn.addCommand(pS());Hn.addCommand(gS());Hn.addCommand(yS());Hn.parse();
296
+ \u{1F50D} Processing ${c.length} files in ${s}...`);let d=await new Ls(i,e.dryRun).executeBatch(u,!1),g=0,_=0,w=0;for(let O of d.results)if(O.success?O.changes?.moved?g++:_++:w++,l&&!e.dryRun){f++;let F=Math.round(f/c.length*100);process.stdout.write(`\r Processing ${f}/${c.length} (${F}%)...`)}l&&process.stdout.write("\r"+" ".repeat(60)+"\r");let C={...d,movedCount:g,alreadyCorrectCount:_,errorCount:w};D7(t,C),process.exit(C.success?0:5)}catch(i){ge.handle(i)}})}o(gS,"batchRepairCommand");var jf=require("fs"),bi=require("path");function yS(){return new _r("resolve").description("Resolve UUID to file path").argument("<uuid>","Full or partial UUID to resolve").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--format <type>","Output format: uri|path|json (default: uri)","uri").option("--output <type>","Response format: text|json (for MCP tools)","text").option("--partial","Match partial UUIDs (returns all matches)").action(async(r,e)=>{let t=e.output||"text";ge.setFormat(t);try{let i=Date.now();if(!N7(r))throw new rt(`Invalid UUID format: ${r}`,"exocortex resolve <uuid> [--format uri|path|json] [--partial]",{uuid:r});let n=(0,bi.resolve)(e.vault);if(!(0,jf.existsSync)(n))throw new hn(n);let s=k7(n,r,e.partial??!1),a=Date.now()-i;if(s.length===0){if(t==="json"){let c=lt.error("VALIDATION_FILE_NOT_FOUND",`UUID not found: ${r}`,3,{context:{uuid:r}});console.log(JSON.stringify(c,null,2))}else console.error(`UUID not found: ${r}`);process.exit(1)}e.partial||s.length>1?L7(s,n,e.format,t,r,a):j7(s[0],n,e.format,t,r,a)}catch(i){ge.handle(i)}})}o(yS,"resolveCommand");function N7(r){if(r.length<4)return!1;let e=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,t=/^[0-9a-f-]+$/i;return e.test(r)||t.test(r)}o(N7,"isValidUuidFormat");function k7(r,e,t){let i=[],n=e.toLowerCase();function s(a){let c=(0,jf.readdirSync)(a,{withFileTypes:!0});for(let u of c){let l=(0,bi.join)(a,u.name);if(u.isDirectory())!u.name.startsWith(".")&&u.name!=="node_modules"&&s(l);else if(u.isFile()&&u.name.endsWith(".md")){let f=u.name.toLowerCase();t?f.includes(n)&&i.push(l):(f.startsWith(n+".md")||f.startsWith(n+" ")||f.startsWith(n+"-"))&&i.push(l)}}}return o(s,"walk"),s(r),i}o(k7,"findFilesWithUuid");function vS(r){return`obsidian://vault/${encodeURI(r)}`}o(vS,"pathToObsidianUri");function _S(r){let e=r.match(/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i);return e?e[1]:(0,bi.basename)(r,".md")}o(_S,"extractUuidFromFilename");function j7(r,e,t,i,n,s){let a=(0,bi.relative)(e,r),c=vS(a),u=_S((0,bi.basename)(r));if(i==="json"){let l={uuid:u,path:a,absolutePath:r,uri:c},f=lt.success(l,{durationMs:s,searchUuid:n});console.log(JSON.stringify(f,null,2))}else switch(t){case"path":console.log(r);break;case"json":console.log(JSON.stringify({uuid:u,path:a,absolutePath:r,uri:c},null,2));break;case"uri":default:console.log(c);break}}o(j7,"outputSingleResult");function L7(r,e,t,i,n,s){let a=r.map(c=>{let u=(0,bi.relative)(e,c),l=vS(u);return{uuid:_S((0,bi.basename)(c)),path:u,absolutePath:c,uri:l}});if(i==="json"){let c=lt.success({matches:a,count:a.length},{durationMs:s,searchUuid:n,itemCount:a.length});console.log(JSON.stringify(c,null,2))}else switch(t){case"path":for(let c of a)console.log(c.absolutePath);break;case"json":console.log(JSON.stringify(a,null,2));break;case"uri":default:for(let c of a)console.log(c.uri);break}}o(L7,"outputMultipleResults");var Hn=new _r;Hn.name("exocortex").description("CLI tool for Exocortex knowledge management system").version("13.193.0");Hn.command("sparql").description("SPARQL query execution").addCommand(ib());Hn.addCommand(lS());Hn.addCommand(dS());Hn.addCommand(pS());Hn.addCommand(gS());Hn.addCommand(yS());Hn.parse();
297
297
  /*! Bundled license information:
298
298
 
299
299
  reflect-metadata/Reflect.js:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kitelev/exocortex-cli",
3
- "version": "13.191.0",
3
+ "version": "13.193.0",
4
4
  "description": "CLI tool for Exocortex knowledge management system - SPARQL queries, task management, and more",
5
5
  "main": "dist/index.js",
6
6
  "bin": {