exocortex-cli 13.123.0 → 13.124.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 +4 -4
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // exocortex-cli v13.123.0
2
+ // exocortex-cli v13.124.0
3
3
  // CLI tool for Exocortex knowledge management system - SPARQL queries, task management, and more
4
4
  // License: MIT
5
5
 
@@ -104,7 +104,7 @@ Expecting `+sc.join(", ")+", got '"+(this.terminals_[Ue]||Ue)+"'":of="Parse erro
104
104
  `+this.showPosition(),{text:"",token:null,line:this.yylineno});return this},"reject"),less:o(function(E){this.unput(this.match.slice(E))},"less"),pastInput:o(function(){var E=this.matched.substr(0,this.matched.length-this.match.length);return(E.length>20?"...":"")+E.substr(-20).replace(/\n/g,"")},"pastInput"),upcomingInput:o(function(){var E=this.match;return E.length<20&&(E+=this._input.substr(0,20-E.length)),(E.substr(0,20)+(E.length>20?"...":"")).replace(/\n/g,"")},"upcomingInput"),showPosition:o(function(){var E=this.pastInput(),O=new Array(E.length+1).join("-");return E+this.upcomingInput()+`
105
105
  `+O+"^"},"showPosition"),test_match:o(function(E,O){var I,z,pe;if(this.options.backtrack_lexer&&(pe={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(pe.yylloc.range=this.yylloc.range.slice(0))),z=E[0].match(/(?:\r\n?|\n).*/g),z&&(this.yylineno+=z.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:z?z[z.length-1].length-z[z.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+E[0].length},this.yytext+=E[0],this.match+=E[0],this.matches=E,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(E[0].length),this.matched+=E[0],I=this.performAction.call(this,this.yy,this,O,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),I)return I;if(this._backtrack){for(var d in pe)this[d]=pe[d];return!1}return!1},"test_match"),next:o(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var E,O,I,z;this._more||(this.yytext="",this.match="");for(var pe=this._currentRules(),d=0;d<pe.length;d++)if(I=this._input.match(this.rules[pe[d]]),I&&(!O||I[0].length>O[0].length)){if(O=I,z=d,this.options.backtrack_lexer){if(E=this.test_match(I,pe[d]),E!==!1)return E;if(this._backtrack){O=!1;continue}else return!1}else if(!this.options.flex)break}return O?(E=this.test_match(O,pe[z]),E!==!1?E:!1):this._input===""?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+`. Unrecognized text.
106
106
  `+this.showPosition(),{text:"",token:null,line:this.yylineno})},"next"),lex:o(function(){var O=this.next();return O||this.lex()},"lex"),begin:o(function(O){this.conditionStack.push(O)},"begin"),popState:o(function(){var O=this.conditionStack.length-1;return O>0?this.conditionStack.pop():this.conditionStack[0]},"popState"),_currentRules:o(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},"_currentRules"),topState:o(function(O){return O=this.conditionStack.length-1-Math.abs(O||0),O>=0?this.conditionStack[O]:"INITIAL"},"topState"),pushState:o(function(O){this.begin(O)},"pushState"),stateStackSize:o(function(){return this.conditionStack.length},"stateStackSize"),options:{flex:!0,"case-insensitive":!0},performAction:o(function(O,I,z,pe){var d=pe;switch(z){case 0:break;case 1:return 12;case 2:return 15;case 3:return 41;case 4:return 325;case 5:return 326;case 6:return 45;case 7:return 47;case 8:return 48;case 9:return 39;case 10:return 24;case 11:return 28;case 12:return 29;case 13:return 31;case 14:return 32;case 15:return 36;case 16:return 53;case 17:return 327;case 18:return 63;case 19:return 64;case 20:return 70;case 21:return 73;case 22:return 76;case 23:return 78;case 24:return 81;case 25:return 83;case 26:return 85;case 27:return 193;case 28:return 100;case 29:return 328;case 30:return 121;case 31:return 329;case 32:return 330;case 33:return 110;case 34:return 331;case 35:return 109;case 36:return 332;case 37:return 333;case 38:return 113;case 39:return 115;case 40:return 116;case 41:return 131;case 42:return 123;case 43:return 126;case 44:return 128;case 45:return 132;case 46:return 112;case 47:return 334;case 48:return 335;case 49:return 159;case 50:return 161;case 51:return 164;case 52:return 174;case 53:return 160;case 54:return 336;case 55:return 163;case 56:return 312;case 57:return 314;case 58:return 317;case 59:return 318;case 60:return 272;case 61:return 197;case 62:return 337;case 63:return 338;case 64:return 229;case 65:return 340;case 66:return 263;case 67:return 224;case 68:return 231;case 69:return 232;case 70:return 242;case 71:return 246;case 72:return 290;case 73:return 341;case 74:return 342;case 75:return 343;case 76:return 344;case 77:return 345;case 78:return 250;case 79:return 346;case 80:return 265;case 81:return 276;case 82:return 277;case 83:return 268;case 84:return 269;case 85:return 270;case 86:return 271;case 87:return 347;case 88:return 348;case 89:return 273;case 90:return 274;case 91:return 350;case 92:return 349;case 93:return 351;case 94:return 279;case 95:return 280;case 96:return 283;case 97:return 285;case 98:return 289;case 99:return 293;case 100:return 296;case 101:return 13;case 102:return 16;case 103:return 308;case 104:return 309;case 105:return 87;case 106:return 292;case 107:return 82;case 108:return 294;case 109:return 295;case 110:return 297;case 111:return 298;case 112:return 299;case 113:return 300;case 114:return 301;case 115:return 302;case 116:return"EXPONENT";case 117:return 303;case 118:return 304;case 119:return 305;case 120:return 306;case 121:return 89;case 122:return 310;case 123:return 6;case 124:return"INVALID";case 125:console.log(I.yytext);break}},"anonymous"),rules:[/^(?:\s+|(#[^\n\r]*))/i,/^(?:BASE)/i,/^(?:PREFIX)/i,/^(?:SELECT)/i,/^(?:DISTINCT)/i,/^(?:REDUCED)/i,/^(?:\()/i,/^(?:AS)/i,/^(?:\))/i,/^(?:\*)/i,/^(?:CONSTRUCT)/i,/^(?:WHERE)/i,/^(?:\{)/i,/^(?:\})/i,/^(?:DESCRIBE)/i,/^(?:ASK)/i,/^(?:FROM)/i,/^(?:NAMED)/i,/^(?:GROUP)/i,/^(?:BY)/i,/^(?:HAVING)/i,/^(?:ORDER)/i,/^(?:ASC)/i,/^(?:DESC)/i,/^(?:LIMIT)/i,/^(?:OFFSET)/i,/^(?:VALUES)/i,/^(?:;)/i,/^(?:LOAD)/i,/^(?:SILENT)/i,/^(?:INTO)/i,/^(?:CLEAR)/i,/^(?:DROP)/i,/^(?:CREATE)/i,/^(?:ADD)/i,/^(?:TO)/i,/^(?:MOVE)/i,/^(?:COPY)/i,/^(?:INSERT((\s+|(#[^\n\r]*)\n\r?)+)DATA)/i,/^(?:DELETE((\s+|(#[^\n\r]*)\n\r?)+)DATA)/i,/^(?:DELETE((\s+|(#[^\n\r]*)\n\r?)+)WHERE)/i,/^(?:WITH)/i,/^(?:DELETE)/i,/^(?:INSERT)/i,/^(?:USING)/i,/^(?:DEFAULT)/i,/^(?:GRAPH)/i,/^(?:ALL)/i,/^(?:\.)/i,/^(?:OPTIONAL)/i,/^(?:SERVICE)/i,/^(?:BIND)/i,/^(?:UNDEF)/i,/^(?:MINUS)/i,/^(?:UNION)/i,/^(?:FILTER)/i,/^(?:<<)/i,/^(?:>>)/i,/^(?:\{\|)/i,/^(?:\|\})/i,/^(?:,)/i,/^(?:a)/i,/^(?:\|)/i,/^(?:\/)/i,/^(?:\^)/i,/^(?:\?)/i,/^(?:\+)/i,/^(?:!)/i,/^(?:\[)/i,/^(?:\])/i,/^(?:\|\|)/i,/^(?:&&)/i,/^(?:=)/i,/^(?:!=)/i,/^(?:<)/i,/^(?:>)/i,/^(?:<=)/i,/^(?:>=)/i,/^(?:IN)/i,/^(?:NOT)/i,/^(?:-)/i,/^(?:BOUND)/i,/^(?:BNODE)/i,/^(?:(RAND|NOW|UUID|STRUUID))/i,/^(?:(LANG|DATATYPE|IRI|URI|ABS|CEIL|FLOOR|ROUND|STRLEN|STR|UCASE|LCASE|ENCODE_FOR_URI|YEAR|MONTH|DAY|HOURS|MINUTES|SECONDS|TIMEZONE|TZ|MD5|SHA1|SHA256|SHA384|SHA512|isIRI|isURI|isBLANK|isLITERAL|isNUMERIC))/i,/^(?:(SUBJECT|PREDICATE|OBJECT|isTRIPLE))/i,/^(?:(LANGMATCHES|CONTAINS|STRSTARTS|STRENDS|STRBEFORE|STRAFTER|STRLANG|STRDT|sameTerm))/i,/^(?:CONCAT)/i,/^(?:COALESCE)/i,/^(?:IF)/i,/^(?:TRIPLE)/i,/^(?:REGEX)/i,/^(?:SUBSTR)/i,/^(?:REPLACE)/i,/^(?:EXISTS)/i,/^(?:COUNT)/i,/^(?:SUM|MIN|MAX|AVG|SAMPLE)/i,/^(?:GROUP_CONCAT)/i,/^(?:SEPARATOR)/i,/^(?:\^\^)/i,/^(?:true|false)/i,/^(?:(<(?:[^<>\"\{\}\|\^`\\\u0000-\u0020])*>))/i,/^(?:((([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])(?:(?:(((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|-|[0-9]|\u00B7|[\u0300-\u036F\u203F-\u2040])|\.)*(((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|-|[0-9]|\u00B7|[\u0300-\u036F\u203F-\u2040]))?)?:))/i,/^(?:(((([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])(?:(?:(((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|-|[0-9]|\u00B7|[\u0300-\u036F\u203F-\u2040])|\.)*(((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|-|[0-9]|\u00B7|[\u0300-\u036F\u203F-\u2040]))?)?:)((?:((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|:|[0-9]|((%([0-9A-Fa-f])([0-9A-Fa-f]))|(\\(_|~|\.|-|!|\$|&|'|\(|\)|\*|\+|,|;|=|\/|\?|#|@|%))))(?:(?:(((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|-|[0-9]|\u00B7|[\u0300-\u036F\u203F-\u2040])|\.|:|((%([0-9A-Fa-f])([0-9A-Fa-f]))|(\\(_|~|\.|-|!|\$|&|'|\(|\)|\*|\+|,|;|=|\/|\?|#|@|%))))*(?:(((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|-|[0-9]|\u00B7|[\u0300-\u036F\u203F-\u2040])|:|((%([0-9A-Fa-f])([0-9A-Fa-f]))|(\\(_|~|\.|-|!|\$|&|'|\(|\)|\*|\+|,|;|=|\/|\?|#|@|%)))))?)))/i,/^(?:(_:(?:((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|[0-9])(?:(?:(((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|-|[0-9]|\u00B7|[\u0300-\u036F\u203F-\u2040])|\.)*(((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|-|[0-9]|\u00B7|[\u0300-\u036F\u203F-\u2040]))?))/i,/^(?:([\?\$]((?:((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|[0-9])(?:((?:([A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])|_))|[0-9]|\u00B7|[\u0300-\u036F\u203F-\u2040])*)))/i,/^(?:(@[a-zA-Z]+(?:-[a-zA-Z0-9]+)*))/i,/^(?:([0-9]+))/i,/^(?:([0-9]*\.[0-9]+))/i,/^(?:([0-9]+\.[0-9]*([eE][+-]?[0-9]+)|\.([0-9])+([eE][+-]?[0-9]+)|([0-9])+([eE][+-]?[0-9]+)))/i,/^(?:(\+([0-9]+)))/i,/^(?:(\+([0-9]*\.[0-9]+)))/i,/^(?:(\+([0-9]+\.[0-9]*([eE][+-]?[0-9]+)|\.([0-9])+([eE][+-]?[0-9]+)|([0-9])+([eE][+-]?[0-9]+))))/i,/^(?:(-([0-9]+)))/i,/^(?:(-([0-9]*\.[0-9]+)))/i,/^(?:(-([0-9]+\.[0-9]*([eE][+-]?[0-9]+)|\.([0-9])+([eE][+-]?[0-9]+)|([0-9])+([eE][+-]?[0-9]+))))/i,/^(?:([eE][+-]?[0-9]+))/i,/^(?:('(?:(?:[^\u0027\u005C\u000A\u000D])|(\\[tbnrf\\\"']|\\u([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])|\\U([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])))*'))/i,/^(?:("(?:(?:[^\u0022\u005C\u000A\u000D])|(\\[tbnrf\\\"']|\\u([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])|\\U([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])))*"))/i,/^(?:('''(?:(?:'|'')?(?:[^'\\]|(\\[tbnrf\\\"']|\\u([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])|\\U([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f]))))*'''))/i,/^(?:("""(?:(?:"|"")?(?:[^\"\\]|(\\[tbnrf\\\"']|\\u([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])|\\U([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f]))))*"""))/i,/^(?:(\((\u0020|\u0009|\u000D|\u000A)*\)))/i,/^(?:(\[(\u0020|\u0009|\u000D|\u000A)*\]))/i,/^(?:$)/i,/^(?:.)/i,/^(?:.)/i],conditions:{INITIAL:{rules:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125],inclusive:!0}}};return A})();zl.lexer=zS;function ve(){this.yy={}}return o(ve,"Parser"),ve.prototype=zl,zl.Parser=ve,new ve})();xg.exports=Xx});var Ig=y((Vk,Fg)=>{var Zx="http://www.w3.org/2001/XMLSchema#integer",e5="http://www.w3.org/2001/XMLSchema#string";function Xe(r){this._options=r=r||{};var e=r.prefixes||{};this._prefixByIri={};var t=[];for(var n in e){var i=e[n];Wa(i)&&(this._prefixByIri[i]=n,t.push(i))}var s=t.join("|").replace(/[\]\/\(\)\*\+\?\.\\\$]/g,"\\$&");this._prefixRegex=new RegExp("^("+s+")([a-zA-Z][\\-_a-zA-Z0-9]*)$"),this._usedPrefixes={},this._sparqlStar=r.sparqlStar,this._indent=Wa(r.indent)?r.indent:" ",this._newline=Wa(r.newline)?r.newline:`
107
- `,this._explicitDatatype=!!r.explicitDatatype}o(Xe,"Generator");Xe.prototype.toQuery=function(r){var e="";return r.queryType&&(e+=r.queryType.toUpperCase()+" "),r.reduced&&(e+="REDUCED "),r.distinct&&(e+="DISTINCT "),r.variables?e+=vr(r.variables,void 0,function(t){return/^[?$]/.test(t)?t:mi(t)?this.toEntity(t):"("+this.toExpression(t.expression)+" AS "+pu(t.variable)+")"},this)+" ":r.template&&(e+=this.group(r.template,!0)+this._newline),r.from&&(e+=this.graphs("FROM ",r.from.default)+this.graphs("FROM NAMED ",r.from.named)),r.where&&(e+="WHERE "+this.group(r.where,!0)+this._newline),r.updates&&(e+=vr(r.updates,";"+this._newline,this.toUpdate,this)),r.group&&(e+="GROUP BY "+vr(r.group,void 0,function(t){var n=mi(t.expression)?this.toEntity(t.expression):"("+this.toExpression(t.expression)+")";return t.variable?"("+n+" AS "+pu(t.variable)+")":n},this)+this._newline),r.having&&(e+="HAVING ("+vr(r.having,void 0,this.toExpression,this)+")"+this._newline),r.order&&(e+="ORDER BY "+vr(r.order,void 0,function(t){var n="("+this.toExpression(t.expression)+")";return t.descending?"DESC "+n:n},this)+this._newline),r.offset&&(e+="OFFSET "+r.offset+this._newline),r.limit&&(e+="LIMIT "+r.limit+this._newline),r.values&&(e+=this.values(r)),e=this.baseAndPrefixes(r)+e,e.trim()};Xe.prototype.baseAndPrefixes=function(r){var e=r.base?"BASE <"+r.base+">"+this._newline:"",t="";for(var n in r.prefixes)(this._options.allPrefixes||this._usedPrefixes[n])&&(t+="PREFIX "+n+": <"+r.prefixes[n]+">"+this._newline);return e+t};Xe.prototype.toPattern=function(r){var e=r.type||r instanceof Array&&"array"||(r.subject&&r.predicate&&r.object?"triple":"");if(!(e in this))throw new Error("Unknown entry type: "+e);return this[e](r)};Xe.prototype.triple=function(r){return this.toEntity(r.subject)+" "+this.toEntity(r.predicate)+" "+this.toEntity(r.object)+"."};Xe.prototype.array=function(r){return vr(r,this._newline,this.toPattern,this)};Xe.prototype.bgp=function(r){return this.encodeTriples(r.triples)};Xe.prototype.encodeTriples=function(r){if(!r.length)return"";for(var e=[],t=void 0,n=void 0,i=0;i<r.length;i++){var s=r[i];ts(s.subject,t)?ts(s.predicate,n)?e.push(","):(n=s.predicate,e.push(";"+this._newline,this._indent,this.toEntity(n))):(t&&e.push("."+this._newline),t=s.subject,n=s.predicate,e.push(this.toEntity(t)," ",this.toEntity(n))),e.push(" ",this.toEntity(s.object))}return e.push("."),e.join("")};Xe.prototype.graph=function(r){return"GRAPH "+this.toEntity(r.name)+" "+this.group(r)};Xe.prototype.graphs=function(r,e){return!e||e.length===0?"":vr(e,"",function(t){return r+this.toEntity(t)+this._newline},this)};Xe.prototype.group=function(r,e){return r=e!==!0?this.array(r.patterns||r.triples):this.toPattern(r.type!=="group"?r:r.patterns),r.indexOf(this._newline)===-1?"{ "+r+" }":"{"+this._newline+this.indent(r)+this._newline+"}"};Xe.prototype.query=function(r){return this.toQuery(r)};Xe.prototype.filter=function(r){return"FILTER("+this.toExpression(r.expression)+")"};Xe.prototype.bind=function(r){return"BIND("+this.toExpression(r.expression)+" AS "+pu(r.variable)+")"};Xe.prototype.optional=function(r){return"OPTIONAL "+this.group(r)};Xe.prototype.union=function(r){return vr(r.patterns,this._newline+"UNION"+this._newline,function(e){return this.group(e,!0)},this)};Xe.prototype.minus=function(r){return"MINUS "+this.group(r)};Xe.prototype.values=function(r){var e=Object.keys(r.values.reduce(function(i,s){for(var a in s)i[a]=!0;return i},{})),t,n;return e.length===1?t=n="":(t="(",n=")"),"VALUES "+t+e.join(" ")+n+" {"+this._newline+vr(r.values,this._newline,function(i){return" "+t+vr(e,void 0,function(s){return i[s]?this.toEntity(i[s]):"UNDEF"},this)+n},this)+this._newline+"}"};Xe.prototype.service=function(r){return"SERVICE "+(r.silent?"SILENT ":"")+this.toEntity(r.name)+" "+this.group(r)};Xe.prototype.toExpression=function(r){if(mi(r))return this.toEntity(r);switch(r.type.toLowerCase()){case"aggregate":return r.aggregation.toUpperCase()+"("+(r.distinct?"DISTINCT ":"")+this.toExpression(r.expression)+(typeof r.separator=="string"?'; SEPARATOR = "'+r.separator.replace(Cg,Pg)+'"':"")+")";case"functioncall":return this.toEntity(r.function)+"("+vr(r.args,", ",this.toExpression,this)+")";case"operation":var e=r.operator.toUpperCase(),t=r.args||[];switch(r.operator.toLowerCase()){case"<":case">":case">=":case"<=":case"&&":case"||":case"=":case"!=":case"+":case"-":case"*":case"/":return(mi(t[0])?this.toEntity(t[0]):"("+this.toExpression(t[0])+")")+" "+e+" "+(mi(t[1])?this.toEntity(t[1]):"("+this.toExpression(t[1])+")");case"!":return"!("+this.toExpression(t[0])+")";case"uplus":return"+("+this.toExpression(t[0])+")";case"uminus":return"-("+this.toExpression(t[0])+")";case"notin":e="NOT IN";case"in":return this.toExpression(t[0])+" "+e+"("+(Wa(t[1])?t[1]:vr(t[1],", ",this.toExpression,this))+")";case"notexists":e="NOT EXISTS";case"exists":return e+" "+this.group(t[0],!0);default:return e+"("+vr(t,", ",this.toExpression,this)+")"}default:throw new Error("Unknown expression type: "+r.type)}};Xe.prototype.toEntity=function(r){if(mi(r))switch(r.termType){case"Wildcard":return"*";case"Variable":return pu(r);case"BlankNode":return"_:"+r.value;case"Literal":var e=r.value||"",t=r.language||"",n=r.datatype;if(r='"'+e.replace(Cg,Pg)+'"',t)r+="@"+t;else if(n){if(!this._explicitDatatype)switch(n.value){case e5:return r;case Zx:if(/^\d+$/.test(e))return e+" "}r+="^^"+this.encodeIRI(n.value)}return r;case"Quad":if(!this._sparqlStar)throw new Error("SPARQL* support is not enabled");return r.graph&&r.graph.termType!=="DefaultGraph"?"<< GRAPH "+this.toEntity(r.graph)+" { "+this.toEntity(r.subject)+" "+this.toEntity(r.predicate)+" "+this.toEntity(r.object)+" } >>":"<< "+this.toEntity(r.subject)+" "+this.toEntity(r.predicate)+" "+this.toEntity(r.object)+" >>";default:return this.encodeIRI(r.value)}else{var i=r.items.map(this.toEntity,this),s=r.pathType;switch(s){case"^":case"!":return s+i[0];case"*":case"+":case"?":return"("+i[0]+s+")";default:return"("+i.join(s)+")"}}};var Cg=/["\\\t\n\r\b\f]/g,Pg=o(function(r){return t5[r]},"escapeReplacer"),t5={"\\":"\\\\",'"':'\\"'," ":"\\t","\n":"\\n","\r":"\\r","\b":"\\b","\f":"\\f"};Xe.prototype.encodeIRI=function(r){var e=this._prefixRegex.exec(r);if(e){var t=this._prefixByIri[e[1]];return this._usedPrefixes[t]=!0,t+":"+e[2]}return"<"+r+">"};Xe.prototype.toUpdate=function(r){switch(r.type||r.updateType){case"load":return"LOAD"+(r.source?" "+this.toEntity(r.source):"")+(r.destination?" INTO GRAPH "+this.toEntity(r.destination):"");case"insert":return"INSERT DATA "+this.group(r.insert,!0);case"delete":return"DELETE DATA "+this.group(r.delete,!0);case"deletewhere":return"DELETE WHERE "+this.group(r.delete,!0);case"insertdelete":return(r.graph?"WITH "+this.toEntity(r.graph)+this._newline:"")+(r.delete.length?"DELETE "+this.group(r.delete,!0)+this._newline:"")+(r.insert.length?"INSERT "+this.group(r.insert,!0)+this._newline:"")+(r.using?this.graphs("USING ",r.using.default):"")+(r.using?this.graphs("USING NAMED ",r.using.named):"")+"WHERE "+this.group(r.where,!0);case"add":case"copy":case"move":return r.type.toUpperCase()+" "+(r.silent?"SILENT ":"")+(r.source.default?"DEFAULT":this.toEntity(r.source.name))+" TO "+this.toEntity(r.destination.name);case"create":case"clear":case"drop":return r.type.toUpperCase()+(r.silent?" SILENT ":" ")+(r.graph.default?"DEFAULT":r.graph.named?"NAMED":r.graph.all?"ALL":"GRAPH "+this.toEntity(r.graph.name));default:throw new Error("Unknown update query type: "+r.type)}};Xe.prototype.indent=function(r){return r.replace(/^/gm,this._indent)};function pu(r){return"?"+r.value}o(pu,"variableToString");function Wa(r){return typeof r=="string"}o(Wa,"isString");function mi(r){return typeof r.termType=="string"}o(mi,"isTerm");function ts(r,e){if(!r||!mi(r)||!e||!mi(e)||r.termType!==e.termType)return!1;switch(r.termType){case"Literal":return r.value===e.value&&r.language===e.language&&ts(r.datatype,e.datatype);case"Quad":return ts(r.subject,e.subject)&&ts(r.predicate,e.predicate)&&ts(r.object,e.object)&&ts(r.graph,e.graph);default:return r.value===e.value}}o(ts,"equalTerms");function vr(r,e,t,n){return r.map(t,n).join(Wa(e)?e:" ")}o(vr,"mapJoin");function r5(r={}){return{stringify:o(function(e){var t=Object.create(r);return t.prefixes=e.prefixes,new Xe(t).toQuery(e)},"stringify"),createGenerator:o(function(){return new Xe(r)},"createGenerator")}}o(r5,"_Generator");Fg.exports={Generator:r5}});var ip=y(mu=>{"use strict";Object.defineProperty(mu,"__esModule",{value:!0});mu.BlankNode=void 0;var np=class{static{o(this,"BlankNode")}constructor(e){this.termType="BlankNode",this.value=e}equals(e){return!!e&&e.termType==="BlankNode"&&e.value===this.value}};mu.BlankNode=np});var sp=y(gu=>{"use strict";Object.defineProperty(gu,"__esModule",{value:!0});gu.DefaultGraph=void 0;var Ga=class{static{o(this,"DefaultGraph")}constructor(){this.termType="DefaultGraph",this.value=""}equals(e){return!!e&&e.termType==="DefaultGraph"}};gu.DefaultGraph=Ga;Ga.INSTANCE=new Ga});var _u=y(yu=>{"use strict";Object.defineProperty(yu,"__esModule",{value:!0});yu.NamedNode=void 0;var ap=class{static{o(this,"NamedNode")}constructor(e){this.termType="NamedNode",this.value=e}equals(e){return!!e&&e.termType==="NamedNode"&&e.value===this.value}};yu.NamedNode=ap});var op=y(vu=>{"use strict";Object.defineProperty(vu,"__esModule",{value:!0});vu.Literal=void 0;var Dg=_u(),Ha=class r{static{o(this,"Literal")}constructor(e,t){this.termType="Literal",this.value=e,typeof t=="string"?(this.language=t,this.datatype=r.RDF_LANGUAGE_STRING):t?(this.language="",this.datatype=t):(this.language="",this.datatype=r.XSD_STRING)}equals(e){return!!e&&e.termType==="Literal"&&e.value===this.value&&e.language===this.language&&this.datatype.equals(e.datatype)}};vu.Literal=Ha;Ha.RDF_LANGUAGE_STRING=new Dg.NamedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString");Ha.XSD_STRING=new Dg.NamedNode("http://www.w3.org/2001/XMLSchema#string")});var up=y(Su=>{"use strict";Object.defineProperty(Su,"__esModule",{value:!0});Su.Quad=void 0;var cp=class{static{o(this,"Quad")}constructor(e,t,n,i){this.termType="Quad",this.value="",this.subject=e,this.predicate=t,this.object=n,this.graph=i}equals(e){return!!e&&(e.termType==="Quad"||!e.termType)&&this.subject.equals(e.subject)&&this.predicate.equals(e.predicate)&&this.object.equals(e.object)&&this.graph.equals(e.graph)}};Su.Quad=cp});var fp=y(bu=>{"use strict";Object.defineProperty(bu,"__esModule",{value:!0});bu.Variable=void 0;var lp=class{static{o(this,"Variable")}constructor(e){this.termType="Variable",this.value=e}equals(e){return!!e&&e.termType==="Variable"&&e.value===this.value}};bu.Variable=lp});var Ng=y(wu=>{"use strict";Object.defineProperty(wu,"__esModule",{value:!0});wu.DataFactory=void 0;var n5=ip(),i5=sp(),Rg=op(),s5=_u(),a5=up(),o5=fp(),c5=0,hp=class{static{o(this,"DataFactory")}constructor(e){this.blankNodeCounter=0,e=e||{},this.blankNodePrefix=e.blankNodePrefix||`df_${c5++}_`}namedNode(e){return new s5.NamedNode(e)}blankNode(e){return new n5.BlankNode(e||`${this.blankNodePrefix}${this.blankNodeCounter++}`)}literal(e,t){return new Rg.Literal(e,t)}variable(e){return new o5.Variable(e)}defaultGraph(){return i5.DefaultGraph.INSTANCE}quad(e,t,n,i){return new a5.Quad(e,t,n,i||this.defaultGraph())}fromTerm(e){switch(e.termType){case"NamedNode":return this.namedNode(e.value);case"BlankNode":return this.blankNode(e.value);case"Literal":return e.language?this.literal(e.value,e.language):e.datatype.equals(Rg.Literal.XSD_STRING)?this.literal(e.value):this.literal(e.value,this.fromTerm(e.datatype));case"Variable":return this.variable(e.value);case"DefaultGraph":return this.defaultGraph();case"Quad":return this.quad(this.fromTerm(e.subject),this.fromTerm(e.predicate),this.fromTerm(e.object),this.fromTerm(e.graph))}}fromQuad(e){return this.fromTerm(e)}resetBlankNodeCounter(){this.blankNodeCounter=0}};wu.DataFactory=hp});var kg=y(Sr=>{"use strict";var u5=Sr&&Sr.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:o(function(){return e[t]},"get")}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),rs=Sr&&Sr.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&u5(e,r,t)};Object.defineProperty(Sr,"__esModule",{value:!0});rs(ip(),Sr);rs(Ng(),Sr);rs(sp(),Sr);rs(op(),Sr);rs(_u(),Sr);rs(up(),Sr);rs(fp(),Sr)});var Mg=y((nj,jg)=>{var{Parser:Kn}=Og(),{Generator:l5}=Ig(),{Wildcard:f5}=rp(),{DataFactory:h5}=kg();function d5({prefixes:r,baseIRI:e,factory:t,pathOnly:n,sparqlStar:i,skipValidation:s,skipUngroupedVariableCheck:a}={}){let c={};for(let f in r??{})c[f]=r[f];let u=new Kn;return u.parse=function(){return Kn.base=e||"",Kn.prefixes=Object.create(c),Kn.factory=t||new h5,Kn.sparqlStar=!!i,Kn.pathOnly=!!n,Kn.skipValidation=!!s||!!a,Kn.prototype.parse.apply(u,arguments)},u._resetBlanks=Kn._resetBlanks,u}o(d5,"_Parser");jg.exports={Parser:d5,Generator:l5,Wildcard:f5}});var pp=y(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});js.CaseWhenTransformerError=js.CaseWhenTransformer=void 0;var dp=class{static{o(this,"CaseWhenTransformer")}transform(e){let t=e,n,i=0,s=100;do if(n=t,t=this.transformSinglePass(t),i++,i>s)throw new Yn("Too many nested CASE expressions (max 100 iterations)");while(t!==n);return t}transformSinglePass(e){let t=this.findCasePositions(e);if(t.length===0)return e;let n=e;for(let i=t.length-1;i>=0;i--){let s=t[i],a=this.extractCaseExpression(n,s);if(a){let c=this.convertCaseToIf(a.content);n=n.substring(0,s)+c+n.substring(s+a.length)}}return n}findCasePositions(e){let t=[],n=e.toUpperCase(),i=0;for(;i<e.length;){if(e[i]==="'"||e[i]==='"'){let s=e[i];for(i++;i<e.length&&e[i]!==s;)e[i]==="\\"&&i++,i++;i++;continue}if(n.substring(i,i+4)==="CASE"&&this.isWordBoundary(e,i,4)){t.push(i),i+=4;continue}i++}return t}extractCaseExpression(e,t){let n=1,i=t+4,s=e.toUpperCase();for(;i<e.length&&n>0;){if(e[i]==="'"||e[i]==='"'){let a=e[i];for(i++;i<e.length&&e[i]!==a;)e[i]==="\\"&&i++,i++;i++;continue}if(s.substring(i,i+4)==="CASE"&&this.isWordBoundary(e,i,4)){n++,i+=4;continue}if(s.substring(i,i+3)==="END"&&this.isWordBoundary(e,i,3)){if(n--,n===0){let a=e.substring(t,i+3);return{content:a,length:a.length}}i+=3;continue}i++}if(n>0)throw new Yn(`Unclosed CASE expression at position ${t}`);return null}isWordBoundary(e,t,n){let i=t>0?e[t-1]:"",s=t===0||!/[a-zA-Z0-9_?$]/.test(i),a=t+n<e.length?e[t+n]:"",c=t+n>=e.length||!/[a-zA-Z0-9_]/.test(a);return s&&c}convertCaseToIf(e){let t=this.extractWhenClauses(e),n=this.extractElseClause(e);if(t.length===0)throw new Yn("CASE expression must have at least one WHEN clause");let i=n!==null?n:'""';for(let s=t.length-1;s>=0;s--){let{condition:a,result:c}=t[s];i=`IF(${a}, ${c}, ${i})`}return i}extractWhenClauses(e){let t=[],n=e.replace(/^\s*CASE\s+/i,"").replace(/\s*END\s*$/i,""),i=this.findKeywordPositions(n,"WHEN"),s=this.findKeywordPositions(n,"ELSE"),a=s.length>0?s[0]:n.length;for(let c=0;c<i.length;c++){let u=i[c]+4,f=c+1<i.length?i[c+1]:a,l=n.substring(u,f).trim(),h=this.parseWhenClause(l);h&&t.push(h)}return t}findKeywordPositions(e,t){let n=[],i=e.toUpperCase(),s=0,a=0;for(;s<e.length;){let c=e[s];if(c==="'"||c==='"'){let u=c;for(s++;s<e.length&&e[s]!==u;)e[s]==="\\"&&s++,s++;s++;continue}if(c==="("){a++,s++;continue}if(c===")"){a--,s++;continue}if(a===0&&i.substring(s,s+t.length)===t&&this.isWordBoundary(e,s,t.length)){n.push(s),s+=t.length;continue}s++}return n}parseWhenClause(e){let t=this.findKeywordPositions(e,"THEN");if(t.length===0)throw new Yn(`WHEN clause missing THEN keyword: ${e.substring(0,50)}...`);let n=t[0],i=e.substring(0,n).trim(),s=e.substring(n+4).trim();if(!i)throw new Yn("WHEN clause has empty condition");if(!s)throw new Yn("WHEN clause has empty result");return{condition:i,result:s}}extractElseClause(e){let t=e.replace(/^\s*CASE\s+/i,"").replace(/\s*END\s*$/i,""),n=this.findKeywordPositions(t,"ELSE");if(n.length>0){let i=n[0];return t.substring(i+4).trim()}return null}};js.CaseWhenTransformer=dp;var Yn=class extends Error{static{o(this,"CaseWhenTransformerError")}constructor(e){super(`CASE WHEN transformation error: ${e}`),this.name="CaseWhenTransformerError"}};js.CaseWhenTransformerError=Yn});var qg=y(Fr=>{"use strict";var p5=Fr&&Fr.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:o(function(){return e[t]},"get")}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),m5=Fr&&Fr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),g5=Fr&&Fr.__importStar||(function(){var r=o(function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[n.length]=i);return n},r(e)},"ownKeys");return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),i=0;i<n.length;i++)n[i]!=="default"&&p5(t,e,n[i]);return m5(t,e),t}})();Object.defineProperty(Fr,"__esModule",{value:!0});Fr.SPARQLParser=Fr.SPARQLParseError=void 0;var Lg=g5(Mg()),Vg=pp(),En=class extends Error{static{o(this,"SPARQLParseError")}constructor(e,t,n,i){super(e,i?{cause:i}:void 0),this.name="SPARQLParseError",this.line=t,this.column=n}};Fr.SPARQLParseError=En;var mp=class{static{o(this,"SPARQLParser")}constructor(){this.parser=new Lg.Parser,this.generator=new Lg.Generator,this.caseWhenTransformer=new Vg.CaseWhenTransformer}parse(e){try{let t=this.caseWhenTransformer.transform(e),n=this.parser.parse(t);return this.validateQuery(n),n}catch(t){if(t instanceof Vg.CaseWhenTransformerError)throw new En(t.message);if(t instanceof Error){let n=t.message.match(/line (\d+), column (\d+)/),i=n?parseInt(n[1],10):void 0,s=n?parseInt(n[2],10):void 0;throw new En(`SPARQL syntax error: ${t.message}`,i,s,t)}throw t}}toString(e){try{return this.generator.stringify(e)}catch(t){throw t instanceof Error?new En(`Failed to serialize SPARQL query: ${t.message}`,void 0,void 0,t):t}}getQueryType(e){if("queryType"in e&&e.type==="query")return e.queryType;throw new En("Query does not have a valid queryType property")}isSelectQuery(e){return"queryType"in e&&e.type==="query"&&e.queryType==="SELECT"}isConstructQuery(e){return"queryType"in e&&e.type==="query"&&e.queryType==="CONSTRUCT"}isAskQuery(e){return"queryType"in e&&e.type==="query"&&e.queryType==="ASK"}isDescribeQuery(e){return"queryType"in e&&e.type==="query"&&e.queryType==="DESCRIBE"}validateQuery(e){if(!e||typeof e!="object")throw new En("Invalid query: not an object");if(e.type!=="query"&&e.type!=="update")throw new En(`Invalid type: expected "query" or "update", got "${e.type}"`);if(e.type==="query"){let t=["SELECT","CONSTRUCT","ASK","DESCRIBE"];if(!t.includes(e.queryType))throw new En(`Invalid query type: expected one of ${t.join(", ")}, got "${e.queryType}"`)}}};Fr.SPARQLParser=mp});var Bg=y(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});Ms.AlgebraTranslator=Ms.AlgebraTranslatorError=void 0;var Ie=class extends Error{static{o(this,"AlgebraTranslatorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="AlgebraTranslatorError"}};Ms.AlgebraTranslatorError=Ie;var gp=class{static{o(this,"AlgebraTranslator")}constructor(){this.aggregateCounter=0}translate(e){if(e.type!=="query")throw new Ie("Only query operations are supported (not updates)");if(e.queryType==="SELECT")return this.translateSelect(e);if(e.queryType==="CONSTRUCT")return this.translateConstruct(e);throw new Ie(`Query type ${e.queryType} not yet supported`)}translateSelect(e){let t;if(!e.where||e.where.length===0)throw new Ie("SELECT query must have WHERE clause");t=this.translateWhere(e.where),this.aggregateCounter=0;let n=new Map,i=this.extractAggregatesWithMapping(e.variables,n),s=this.extractGroupVariables(e.group);if((i.length>0||s.length>0)&&(t={type:"group",variables:s,aggregates:i,input:t}),e.variables&&e.variables.length>0){for(let c of e.variables){let u=c;if(u.expression&&u.variable){if(u.expression.type==="aggregate")continue;let f=this.transformExpressionWithAggregateVars(u.expression,n);t={type:"extend",variable:u.variable.value,expression:f,input:t}}}let a=e.variables.filter(c=>c.termType==="Variable"||c.variable).map(c=>c.termType==="Variable"?c.value:c.variable.value);a.length>0&&(t={type:"project",variables:a,input:t})}return e.distinct&&(t={type:"distinct",input:t}),e.order&&e.order.length>0&&(t={type:"orderby",comparators:e.order.map(a=>this.translateOrderComparator(a)),input:t}),(e.limit!==void 0||e.offset!==void 0)&&(t={type:"slice",limit:e.limit,offset:e.offset,input:t}),t}translateConstruct(e){let t=this.translateConstructTemplate(e.template??[]);if(!e.where||e.where.length===0)throw new Ie("CONSTRUCT query must have WHERE clause");let n=this.translateWhere(e.where);return{type:"construct",template:t,where:n}}translateConstructTemplate(e){return!e||!Array.isArray(e)?[]:e.map(t=>this.translateTriple(t))}extractAggregatesWithMapping(e,t){if(!e)return[];let n=[];for(let i of e)!i.expression||!i.variable||(i.expression.type==="aggregate"?(n.push({variable:i.variable.value,expression:this.translateAggregateExpression(i.expression)}),t.set(i.expression,i.variable.value)):this.collectNestedAggregates(i.expression,n,t));return n}collectNestedAggregates(e,t,n){if(e){if(e.type==="aggregate"){let i=`__agg${this.aggregateCounter++}`;t.push({variable:i,expression:this.translateAggregateExpression(e)}),n.set(e,i)}else if(e.type==="operation"&&e.args)for(let i of e.args)this.collectNestedAggregates(i,t,n)}}transformExpressionWithAggregateVars(e,t){if(t.has(e))return{type:"variable",name:t.get(e)};if(e.type==="operation"&&e.args){let n=e.args.map(c=>this.transformExpressionWithAggregateVars(c,t)),i=["=","!=","<",">","<=",">="],s=["&&","||","!"],a=["+","-","*","/"];return i.includes(e.operator)?{type:"comparison",operator:e.operator,left:n[0],right:n[1]}:s.includes(e.operator)?{type:"logical",operator:e.operator,operands:n}:a.includes(e.operator)?{type:"arithmetic",operator:e.operator,left:n[0],right:n[1]}:{type:"function",function:e.operator,args:n}}return this.translateExpression(e)}extractGroupVariables(e){return e?e.filter(t=>t.expression&&t.expression.termType==="Variable").map(t=>t.expression.value):[]}translateAggregateExpression(e){return{type:"aggregate",aggregation:e.aggregation.toLowerCase(),expression:e.expression?this.translateExpression(e.expression):void 0,distinct:e.distinct||!1,separator:e.separator}}translateWhere(e){if(e.length===0)throw new Ie("Empty WHERE clause");let t=e.filter(a=>a.type==="filter"),n=e.filter(a=>a.type==="bind"),i=e.filter(a=>a.type!=="filter"&&a.type!=="bind"),s;i.length===0?s={type:"bgp",triples:[]}:i.length===1?s=this.translatePattern(i[0]):s=i.map(c=>this.translatePattern(c)).reduce((c,u)=>({type:"join",left:c,right:u}));for(let a of n)s=this.translateBind(a,s);for(let a of t)s={type:"filter",expression:this.translateExpression(a.expression),input:s};return s}translatePattern(e){if(!e||!e.type)throw new Ie("Invalid pattern: missing type");switch(e.type){case"bgp":return this.translateBGP(e);case"filter":return this.translateFilter(e);case"optional":return this.translateOptional(e);case"union":return this.translateUnion(e);case"minus":return this.translateMinus(e);case"values":return this.translateValues(e);case"group":return this.translateWhere(e.patterns);case"query":return this.translateSubquery(e);default:throw new Ie(`Unsupported pattern type: ${e.type}`)}}translateBGP(e){if(!e.triples||!Array.isArray(e.triples))throw new Ie("BGP pattern must have triples array");return{type:"bgp",triples:e.triples.map(t=>this.translateTriple(t))}}translateTriple(e){if(!e.subject||!e.predicate||!e.object)throw new Ie("Triple must have subject, predicate, and object");return{subject:this.translateTripleElement(e.subject),predicate:this.translatePredicate(e.predicate),object:this.translateTripleElement(e.object)}}translatePredicate(e){return e.type==="path"?this.translatePropertyPath(e):this.translateTripleElement(e)}translatePropertyPath(e){if(!e.pathType)throw new Ie("Property path must have pathType");if(!e.items||!Array.isArray(e.items))throw new Ie("Property path must have items array");let t=e.items.map(n=>this.translatePathItem(n));switch(e.pathType){case"/":return{type:"path",pathType:"/",items:t};case"|":return{type:"path",pathType:"|",items:t};case"^":if(t.length!==1)throw new Ie("Inverse path must have exactly one item");return{type:"path",pathType:"^",items:[t[0]]};case"+":if(t.length!==1)throw new Ie("OneOrMore path must have exactly one item");return{type:"path",pathType:"+",items:[t[0]]};case"*":if(t.length!==1)throw new Ie("ZeroOrMore path must have exactly one item");return{type:"path",pathType:"*",items:[t[0]]};case"?":if(t.length!==1)throw new Ie("ZeroOrOne path must have exactly one item");return{type:"path",pathType:"?",items:[t[0]]};default:throw new Ie(`Unsupported property path type: ${e.pathType}`)}}translatePathItem(e){if(e.type==="path")return this.translatePropertyPath(e);if(e.termType==="NamedNode")return{type:"iri",value:e.value};throw new Ie(`Unsupported path item type: ${e.type||e.termType}`)}translateTripleElement(e){if(!e||!e.termType)throw new Ie("Triple element must have termType");switch(e.termType){case"Variable":return{type:"variable",value:e.value};case"NamedNode":return{type:"iri",value:e.value};case"Literal":return{type:"literal",value:e.value,datatype:e.datatype?.value,language:e.language};case"BlankNode":return{type:"blank",value:e.value};default:throw new Ie(`Unsupported term type: ${e.termType}`)}}translateFilter(e){if(!e.expression)throw new Ie("Filter pattern must have expression");let t=e.patterns?this.translateWhere(e.patterns):{type:"bgp",triples:[]};return{type:"filter",expression:this.translateExpression(e.expression),input:t}}translateExpression(e){if(!e)throw new Ie("Expression cannot be null or undefined");if(e.type==="operation")return this.translateOperationExpression(e);if(e.type==="functioncall"||e.type==="functionCall")return{type:"functionCall",function:e.function,args:e.args.map(t=>this.translateExpression(t))};if(e.termType)return this.translateTermExpression(e);throw new Ie(`Unsupported expression structure: ${JSON.stringify(e)}`)}translateOperationExpression(e){let t=["=","!=","<",">","<=",">="],n=["&&","||","!"],i=["+","-","*","/"];return t.includes(e.operator)?{type:"comparison",operator:e.operator,left:this.translateExpression(e.args[0]),right:this.translateExpression(e.args[1])}:n.includes(e.operator)?{type:"logical",operator:e.operator,operands:e.args.map(s=>this.translateExpression(s))}:i.includes(e.operator)?{type:"arithmetic",operator:e.operator,left:this.translateExpression(e.args[0]),right:this.translateExpression(e.args[1])}:e.operator==="exists"||e.operator==="notexists"?this.translateExistsExpression(e):{type:"function",function:e.operator,args:e.args.map(s=>this.translateExpression(s))}}translateExistsExpression(e){if(!e.args||e.args.length!==1)throw new Ie("EXISTS/NOT EXISTS must have exactly one pattern argument");let t=e.args[0],n;return t.type==="group"&&t.patterns?n=this.translateWhere(t.patterns):t.type==="bgp"?n=this.translateBGP(t):n=this.translatePattern(t),{type:"exists",negated:e.operator==="notexists",pattern:n}}translateTermExpression(e){if(e.termType==="Variable")return{type:"variable",name:e.value};if(e.termType==="Literal"){let t=e.value;return e.datatype&&(e.datatype.value.includes("#integer")||e.datatype.value.includes("#decimal")?t=parseFloat(e.value):e.datatype.value.includes("#boolean")&&(t=e.value==="true")),{type:"literal",value:t,datatype:e.datatype?.value}}return{type:"literal",value:String(e.value||e)}}translateOptional(e){if(!e.patterns||e.patterns.length===0)throw new Ie("OPTIONAL pattern must have patterns");return{type:"leftjoin",left:{type:"bgp",triples:[]},right:this.translateWhere(e.patterns),expression:e.expression?this.translateExpression(e.expression):void 0}}translateUnion(e){if(!e.patterns||e.patterns.length<2)throw new Ie("UNION pattern must have at least 2 patterns");let t=o(i=>i.patterns&&Array.isArray(i.patterns)?this.translateWhere(i.patterns):this.translateWhere([i]),"translateBranch"),n={type:"union",left:t(e.patterns[0]),right:t(e.patterns[1])};for(let i=2;i<e.patterns.length;i++)n={type:"union",left:n,right:t(e.patterns[i])};return n}translateMinus(e){if(!e.patterns||e.patterns.length===0)throw new Ie("MINUS pattern must have patterns");return{type:"minus",left:{type:"bgp",triples:[]},right:this.translateWhere(e.patterns)}}translateValues(e){if(!e.values||!Array.isArray(e.values))throw new Ie("VALUES pattern must have values array");let t=new Set;for(let i of e.values)for(let s of Object.keys(i)){let a=s.startsWith("?")?s.slice(1):s;t.add(a)}let n=e.values.map(i=>this.translateValuesBinding(i));return{type:"values",variables:Array.from(t),bindings:n}}translateValuesBinding(e){let t={};for(let[n,i]of Object.entries(e)){let s=n.startsWith("?")?n.slice(1):n,a=i;if(a.termType==="NamedNode")t[s]={type:"iri",value:a.value};else if(a.termType==="Literal")t[s]={type:"literal",value:a.value,datatype:a.datatype?.value,language:a.language||void 0};else throw new Ie(`Unsupported VALUES term type: ${a.termType}`)}return t}translateBind(e,t){if(!e.variable||!e.expression)throw new Ie("BIND pattern must have variable and expression");return{type:"extend",variable:e.variable.value,expression:this.translateExpression(e.expression),input:t}}translateOrderComparator(e){return{expression:this.translateExpression(e.expression),descending:e.descending||!1}}translateSubquery(e){if(e.queryType!=="SELECT")throw new Ie(`Only SELECT subqueries are supported, got: ${e.queryType}`);return{type:"subquery",query:this.translateSelect(e)}}};Ms.AlgebraTranslator=gp});var Ug=y(Eu=>{"use strict";Object.defineProperty(Eu,"__esModule",{value:!0});Eu.AlgebraOptimizer=void 0;var yp=class{static{o(this,"AlgebraOptimizer")}constructor(){this.stats=new Map}optimize(e){let t=e;return t=this.eliminateEmptyBGPInFilterJoin(t),t=this.filterPushDown(t),t=this.joinReordering(t),t}eliminateEmptyBGPInFilterJoin(e){if(e.type==="join"){if(e.left.type==="filter"){let t=e.left;if(t.input.type==="bgp"&&t.input.triples.length===0)return{type:"filter",expression:t.expression,input:this.eliminateEmptyBGPInFilterJoin(e.right)}}if(e.right.type==="filter"){let t=e.right;if(t.input.type==="bgp"&&t.input.triples.length===0)return{type:"filter",expression:t.expression,input:this.eliminateEmptyBGPInFilterJoin(e.left)}}return{type:"join",left:this.eliminateEmptyBGPInFilterJoin(e.left),right:this.eliminateEmptyBGPInFilterJoin(e.right)}}return e.type==="filter"?{...e,input:this.eliminateEmptyBGPInFilterJoin(e.input)}:e.type==="leftjoin"?{...e,left:this.eliminateEmptyBGPInFilterJoin(e.left),right:this.eliminateEmptyBGPInFilterJoin(e.right)}:e.type==="union"?{...e,left:this.eliminateEmptyBGPInFilterJoin(e.left),right:this.eliminateEmptyBGPInFilterJoin(e.right)}:e.type==="minus"?{...e,left:this.eliminateEmptyBGPInFilterJoin(e.left),right:this.eliminateEmptyBGPInFilterJoin(e.right)}:e.type==="project"?{...e,input:this.eliminateEmptyBGPInFilterJoin(e.input)}:e.type==="orderby"?{...e,input:this.eliminateEmptyBGPInFilterJoin(e.input)}:e.type==="slice"?{...e,input:this.eliminateEmptyBGPInFilterJoin(e.input)}:e.type==="distinct"?{...e,input:this.eliminateEmptyBGPInFilterJoin(e.input)}:e}filterPushDown(e){return e.type==="filter"?this.pushDownFilter(e):e.type==="join"?{type:"join",left:this.filterPushDown(e.left),right:this.filterPushDown(e.right)}:e.type==="leftjoin"?{...e,left:this.filterPushDown(e.left),right:this.filterPushDown(e.right)}:e.type==="union"?{type:"union",left:this.filterPushDown(e.left),right:this.filterPushDown(e.right)}:e.type==="minus"?{...e,left:this.filterPushDown(e.left),right:this.filterPushDown(e.right)}:e.type==="project"?{...e,input:this.filterPushDown(e.input)}:e.type==="orderby"?{...e,input:this.filterPushDown(e.input)}:e.type==="slice"?{...e,input:this.filterPushDown(e.input)}:e.type==="distinct"?{...e,input:this.filterPushDown(e.input)}:e}pushDownFilter(e){let t=e.input;if(t.type==="join"){let n=this.getFilterVariables(e.expression),i=this.getOperationVariables(t.left),s=this.getOperationVariables(t.right),a=n.every(u=>i.has(u)),c=n.every(u=>s.has(u));return a&&!c?{type:"join",left:{type:"filter",expression:e.expression,input:this.filterPushDown(t.left)},right:this.filterPushDown(t.right)}:c&&!a?{type:"join",left:this.filterPushDown(t.left),right:{type:"filter",expression:e.expression,input:this.filterPushDown(t.right)}}:{type:"filter",expression:e.expression,input:{type:"join",left:this.filterPushDown(t.left),right:this.filterPushDown(t.right)}}}return t.type==="union"?{type:"union",left:{type:"filter",expression:e.expression,input:this.filterPushDown(t.left)},right:{type:"filter",expression:e.expression,input:this.filterPushDown(t.right)}}:{type:"filter",expression:e.expression,input:this.filterPushDown(t)}}getFilterVariables(e){let t=[];if(e.type==="variable")t.push(e.name);else if(e.type==="comparison")t.push(...this.getFilterVariables(e.left)),t.push(...this.getFilterVariables(e.right));else if(e.type==="logical")for(let n of e.operands)t.push(...this.getFilterVariables(n));else if(e.type==="function")for(let n of e.args)t.push(...this.getFilterVariables(n));return Array.from(new Set(t))}getOperationVariables(e){let t=new Set;if(e.type==="bgp")for(let n of e.triples)n.subject.type==="variable"&&t.add(n.subject.value),n.predicate.type==="variable"&&t.add(n.predicate.value),n.object.type==="variable"&&t.add(n.object.value);else if(e.type==="join"){let n=this.getOperationVariables(e.left),i=this.getOperationVariables(e.right);return new Set([...n,...i])}else{if(e.type==="filter")return this.getOperationVariables(e.input);if(e.type==="leftjoin"){let n=this.getOperationVariables(e.left),i=this.getOperationVariables(e.right);return new Set([...n,...i])}else if(e.type==="union"){let n=this.getOperationVariables(e.left),i=this.getOperationVariables(e.right);return new Set([...n,...i])}else{if(e.type==="minus")return this.getOperationVariables(e.left);if(e.type==="project")return new Set(e.variables)}}return t}joinReordering(e){return e.type==="join"?this.reorderJoin(e):e.type==="filter"?{...e,input:this.joinReordering(e.input)}:e.type==="leftjoin"?{...e,left:this.joinReordering(e.left),right:this.joinReordering(e.right)}:e.type==="union"?{...e,left:this.joinReordering(e.left),right:this.joinReordering(e.right)}:e.type==="minus"?{...e,left:this.joinReordering(e.left),right:this.joinReordering(e.right)}:e.type==="project"?{...e,input:this.joinReordering(e.input)}:e.type==="orderby"?{...e,input:this.joinReordering(e.input)}:e.type==="slice"?{...e,input:this.joinReordering(e.input)}:e.type==="distinct"?{...e,input:this.joinReordering(e.input)}:e}reorderJoin(e){let t=this.estimateCost(e.left);return this.estimateCost(e.right)<t?{type:"join",left:this.joinReordering(e.right),right:this.joinReordering(e.left)}:{type:"join",left:this.joinReordering(e.left),right:this.joinReordering(e.right)}}estimateCost(e){if(e.type==="bgp"){let t=e.triples.length*100;for(let n of e.triples)n.subject.type==="variable"&&(t+=10),n.predicate.type==="variable"&&(t+=20),n.object.type==="variable"&&(t+=10);return t}return e.type==="filter"?this.estimateCost(e.input)*.3:e.type==="join"?this.estimateCost(e.left)*this.estimateCost(e.right):e.type==="leftjoin"?this.estimateCost(e.left)+this.estimateCost(e.right)*.5:e.type==="union"?this.estimateCost(e.left)+this.estimateCost(e.right):e.type==="minus"?this.estimateCost(e.left)+this.estimateCost(e.right)*.3:100}setStatistics(e,t){this.stats.set(e,t)}getStatistics(e){return this.stats.get(e)}};Eu.AlgebraOptimizer=yp});var $g=y(Tu=>{"use strict";Object.defineProperty(Tu,"__esModule",{value:!0});Tu.AlgebraSerializer=void 0;var _p=class{static{o(this,"AlgebraSerializer")}toString(e,t=0){let n=" ".repeat(t);switch(e.type){case"bgp":return`${n}BGP [
107
+ `,this._explicitDatatype=!!r.explicitDatatype}o(Xe,"Generator");Xe.prototype.toQuery=function(r){var e="";return r.queryType&&(e+=r.queryType.toUpperCase()+" "),r.reduced&&(e+="REDUCED "),r.distinct&&(e+="DISTINCT "),r.variables?e+=vr(r.variables,void 0,function(t){return/^[?$]/.test(t)?t:mi(t)?this.toEntity(t):"("+this.toExpression(t.expression)+" AS "+pu(t.variable)+")"},this)+" ":r.template&&(e+=this.group(r.template,!0)+this._newline),r.from&&(e+=this.graphs("FROM ",r.from.default)+this.graphs("FROM NAMED ",r.from.named)),r.where&&(e+="WHERE "+this.group(r.where,!0)+this._newline),r.updates&&(e+=vr(r.updates,";"+this._newline,this.toUpdate,this)),r.group&&(e+="GROUP BY "+vr(r.group,void 0,function(t){var n=mi(t.expression)?this.toEntity(t.expression):"("+this.toExpression(t.expression)+")";return t.variable?"("+n+" AS "+pu(t.variable)+")":n},this)+this._newline),r.having&&(e+="HAVING ("+vr(r.having,void 0,this.toExpression,this)+")"+this._newline),r.order&&(e+="ORDER BY "+vr(r.order,void 0,function(t){var n="("+this.toExpression(t.expression)+")";return t.descending?"DESC "+n:n},this)+this._newline),r.offset&&(e+="OFFSET "+r.offset+this._newline),r.limit&&(e+="LIMIT "+r.limit+this._newline),r.values&&(e+=this.values(r)),e=this.baseAndPrefixes(r)+e,e.trim()};Xe.prototype.baseAndPrefixes=function(r){var e=r.base?"BASE <"+r.base+">"+this._newline:"",t="";for(var n in r.prefixes)(this._options.allPrefixes||this._usedPrefixes[n])&&(t+="PREFIX "+n+": <"+r.prefixes[n]+">"+this._newline);return e+t};Xe.prototype.toPattern=function(r){var e=r.type||r instanceof Array&&"array"||(r.subject&&r.predicate&&r.object?"triple":"");if(!(e in this))throw new Error("Unknown entry type: "+e);return this[e](r)};Xe.prototype.triple=function(r){return this.toEntity(r.subject)+" "+this.toEntity(r.predicate)+" "+this.toEntity(r.object)+"."};Xe.prototype.array=function(r){return vr(r,this._newline,this.toPattern,this)};Xe.prototype.bgp=function(r){return this.encodeTriples(r.triples)};Xe.prototype.encodeTriples=function(r){if(!r.length)return"";for(var e=[],t=void 0,n=void 0,i=0;i<r.length;i++){var s=r[i];ts(s.subject,t)?ts(s.predicate,n)?e.push(","):(n=s.predicate,e.push(";"+this._newline,this._indent,this.toEntity(n))):(t&&e.push("."+this._newline),t=s.subject,n=s.predicate,e.push(this.toEntity(t)," ",this.toEntity(n))),e.push(" ",this.toEntity(s.object))}return e.push("."),e.join("")};Xe.prototype.graph=function(r){return"GRAPH "+this.toEntity(r.name)+" "+this.group(r)};Xe.prototype.graphs=function(r,e){return!e||e.length===0?"":vr(e,"",function(t){return r+this.toEntity(t)+this._newline},this)};Xe.prototype.group=function(r,e){return r=e!==!0?this.array(r.patterns||r.triples):this.toPattern(r.type!=="group"?r:r.patterns),r.indexOf(this._newline)===-1?"{ "+r+" }":"{"+this._newline+this.indent(r)+this._newline+"}"};Xe.prototype.query=function(r){return this.toQuery(r)};Xe.prototype.filter=function(r){return"FILTER("+this.toExpression(r.expression)+")"};Xe.prototype.bind=function(r){return"BIND("+this.toExpression(r.expression)+" AS "+pu(r.variable)+")"};Xe.prototype.optional=function(r){return"OPTIONAL "+this.group(r)};Xe.prototype.union=function(r){return vr(r.patterns,this._newline+"UNION"+this._newline,function(e){return this.group(e,!0)},this)};Xe.prototype.minus=function(r){return"MINUS "+this.group(r)};Xe.prototype.values=function(r){var e=Object.keys(r.values.reduce(function(i,s){for(var a in s)i[a]=!0;return i},{})),t,n;return e.length===1?t=n="":(t="(",n=")"),"VALUES "+t+e.join(" ")+n+" {"+this._newline+vr(r.values,this._newline,function(i){return" "+t+vr(e,void 0,function(s){return i[s]?this.toEntity(i[s]):"UNDEF"},this)+n},this)+this._newline+"}"};Xe.prototype.service=function(r){return"SERVICE "+(r.silent?"SILENT ":"")+this.toEntity(r.name)+" "+this.group(r)};Xe.prototype.toExpression=function(r){if(mi(r))return this.toEntity(r);switch(r.type.toLowerCase()){case"aggregate":return r.aggregation.toUpperCase()+"("+(r.distinct?"DISTINCT ":"")+this.toExpression(r.expression)+(typeof r.separator=="string"?'; SEPARATOR = "'+r.separator.replace(Cg,Pg)+'"':"")+")";case"functioncall":return this.toEntity(r.function)+"("+vr(r.args,", ",this.toExpression,this)+")";case"operation":var e=r.operator.toUpperCase(),t=r.args||[];switch(r.operator.toLowerCase()){case"<":case">":case">=":case"<=":case"&&":case"||":case"=":case"!=":case"+":case"-":case"*":case"/":return(mi(t[0])?this.toEntity(t[0]):"("+this.toExpression(t[0])+")")+" "+e+" "+(mi(t[1])?this.toEntity(t[1]):"("+this.toExpression(t[1])+")");case"!":return"!("+this.toExpression(t[0])+")";case"uplus":return"+("+this.toExpression(t[0])+")";case"uminus":return"-("+this.toExpression(t[0])+")";case"notin":e="NOT IN";case"in":return this.toExpression(t[0])+" "+e+"("+(Wa(t[1])?t[1]:vr(t[1],", ",this.toExpression,this))+")";case"notexists":e="NOT EXISTS";case"exists":return e+" "+this.group(t[0],!0);default:return e+"("+vr(t,", ",this.toExpression,this)+")"}default:throw new Error("Unknown expression type: "+r.type)}};Xe.prototype.toEntity=function(r){if(mi(r))switch(r.termType){case"Wildcard":return"*";case"Variable":return pu(r);case"BlankNode":return"_:"+r.value;case"Literal":var e=r.value||"",t=r.language||"",n=r.datatype;if(r='"'+e.replace(Cg,Pg)+'"',t)r+="@"+t;else if(n){if(!this._explicitDatatype)switch(n.value){case e5:return r;case Zx:if(/^\d+$/.test(e))return e+" "}r+="^^"+this.encodeIRI(n.value)}return r;case"Quad":if(!this._sparqlStar)throw new Error("SPARQL* support is not enabled");return r.graph&&r.graph.termType!=="DefaultGraph"?"<< GRAPH "+this.toEntity(r.graph)+" { "+this.toEntity(r.subject)+" "+this.toEntity(r.predicate)+" "+this.toEntity(r.object)+" } >>":"<< "+this.toEntity(r.subject)+" "+this.toEntity(r.predicate)+" "+this.toEntity(r.object)+" >>";default:return this.encodeIRI(r.value)}else{var i=r.items.map(this.toEntity,this),s=r.pathType;switch(s){case"^":case"!":return s+i[0];case"*":case"+":case"?":return"("+i[0]+s+")";default:return"("+i.join(s)+")"}}};var Cg=/["\\\t\n\r\b\f]/g,Pg=o(function(r){return t5[r]},"escapeReplacer"),t5={"\\":"\\\\",'"':'\\"'," ":"\\t","\n":"\\n","\r":"\\r","\b":"\\b","\f":"\\f"};Xe.prototype.encodeIRI=function(r){var e=this._prefixRegex.exec(r);if(e){var t=this._prefixByIri[e[1]];return this._usedPrefixes[t]=!0,t+":"+e[2]}return"<"+r+">"};Xe.prototype.toUpdate=function(r){switch(r.type||r.updateType){case"load":return"LOAD"+(r.source?" "+this.toEntity(r.source):"")+(r.destination?" INTO GRAPH "+this.toEntity(r.destination):"");case"insert":return"INSERT DATA "+this.group(r.insert,!0);case"delete":return"DELETE DATA "+this.group(r.delete,!0);case"deletewhere":return"DELETE WHERE "+this.group(r.delete,!0);case"insertdelete":return(r.graph?"WITH "+this.toEntity(r.graph)+this._newline:"")+(r.delete.length?"DELETE "+this.group(r.delete,!0)+this._newline:"")+(r.insert.length?"INSERT "+this.group(r.insert,!0)+this._newline:"")+(r.using?this.graphs("USING ",r.using.default):"")+(r.using?this.graphs("USING NAMED ",r.using.named):"")+"WHERE "+this.group(r.where,!0);case"add":case"copy":case"move":return r.type.toUpperCase()+" "+(r.silent?"SILENT ":"")+(r.source.default?"DEFAULT":this.toEntity(r.source.name))+" TO "+this.toEntity(r.destination.name);case"create":case"clear":case"drop":return r.type.toUpperCase()+(r.silent?" SILENT ":" ")+(r.graph.default?"DEFAULT":r.graph.named?"NAMED":r.graph.all?"ALL":"GRAPH "+this.toEntity(r.graph.name));default:throw new Error("Unknown update query type: "+r.type)}};Xe.prototype.indent=function(r){return r.replace(/^/gm,this._indent)};function pu(r){return"?"+r.value}o(pu,"variableToString");function Wa(r){return typeof r=="string"}o(Wa,"isString");function mi(r){return typeof r.termType=="string"}o(mi,"isTerm");function ts(r,e){if(!r||!mi(r)||!e||!mi(e)||r.termType!==e.termType)return!1;switch(r.termType){case"Literal":return r.value===e.value&&r.language===e.language&&ts(r.datatype,e.datatype);case"Quad":return ts(r.subject,e.subject)&&ts(r.predicate,e.predicate)&&ts(r.object,e.object)&&ts(r.graph,e.graph);default:return r.value===e.value}}o(ts,"equalTerms");function vr(r,e,t,n){return r.map(t,n).join(Wa(e)?e:" ")}o(vr,"mapJoin");function r5(r={}){return{stringify:o(function(e){var t=Object.create(r);return t.prefixes=e.prefixes,new Xe(t).toQuery(e)},"stringify"),createGenerator:o(function(){return new Xe(r)},"createGenerator")}}o(r5,"_Generator");Fg.exports={Generator:r5}});var ip=y(mu=>{"use strict";Object.defineProperty(mu,"__esModule",{value:!0});mu.BlankNode=void 0;var np=class{static{o(this,"BlankNode")}constructor(e){this.termType="BlankNode",this.value=e}equals(e){return!!e&&e.termType==="BlankNode"&&e.value===this.value}};mu.BlankNode=np});var sp=y(gu=>{"use strict";Object.defineProperty(gu,"__esModule",{value:!0});gu.DefaultGraph=void 0;var Ga=class{static{o(this,"DefaultGraph")}constructor(){this.termType="DefaultGraph",this.value=""}equals(e){return!!e&&e.termType==="DefaultGraph"}};gu.DefaultGraph=Ga;Ga.INSTANCE=new Ga});var _u=y(yu=>{"use strict";Object.defineProperty(yu,"__esModule",{value:!0});yu.NamedNode=void 0;var ap=class{static{o(this,"NamedNode")}constructor(e){this.termType="NamedNode",this.value=e}equals(e){return!!e&&e.termType==="NamedNode"&&e.value===this.value}};yu.NamedNode=ap});var op=y(vu=>{"use strict";Object.defineProperty(vu,"__esModule",{value:!0});vu.Literal=void 0;var Dg=_u(),Ha=class r{static{o(this,"Literal")}constructor(e,t){this.termType="Literal",this.value=e,typeof t=="string"?(this.language=t,this.datatype=r.RDF_LANGUAGE_STRING):t?(this.language="",this.datatype=t):(this.language="",this.datatype=r.XSD_STRING)}equals(e){return!!e&&e.termType==="Literal"&&e.value===this.value&&e.language===this.language&&this.datatype.equals(e.datatype)}};vu.Literal=Ha;Ha.RDF_LANGUAGE_STRING=new Dg.NamedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString");Ha.XSD_STRING=new Dg.NamedNode("http://www.w3.org/2001/XMLSchema#string")});var up=y(Su=>{"use strict";Object.defineProperty(Su,"__esModule",{value:!0});Su.Quad=void 0;var cp=class{static{o(this,"Quad")}constructor(e,t,n,i){this.termType="Quad",this.value="",this.subject=e,this.predicate=t,this.object=n,this.graph=i}equals(e){return!!e&&(e.termType==="Quad"||!e.termType)&&this.subject.equals(e.subject)&&this.predicate.equals(e.predicate)&&this.object.equals(e.object)&&this.graph.equals(e.graph)}};Su.Quad=cp});var fp=y(bu=>{"use strict";Object.defineProperty(bu,"__esModule",{value:!0});bu.Variable=void 0;var lp=class{static{o(this,"Variable")}constructor(e){this.termType="Variable",this.value=e}equals(e){return!!e&&e.termType==="Variable"&&e.value===this.value}};bu.Variable=lp});var Ng=y(wu=>{"use strict";Object.defineProperty(wu,"__esModule",{value:!0});wu.DataFactory=void 0;var n5=ip(),i5=sp(),Rg=op(),s5=_u(),a5=up(),o5=fp(),c5=0,hp=class{static{o(this,"DataFactory")}constructor(e){this.blankNodeCounter=0,e=e||{},this.blankNodePrefix=e.blankNodePrefix||`df_${c5++}_`}namedNode(e){return new s5.NamedNode(e)}blankNode(e){return new n5.BlankNode(e||`${this.blankNodePrefix}${this.blankNodeCounter++}`)}literal(e,t){return new Rg.Literal(e,t)}variable(e){return new o5.Variable(e)}defaultGraph(){return i5.DefaultGraph.INSTANCE}quad(e,t,n,i){return new a5.Quad(e,t,n,i||this.defaultGraph())}fromTerm(e){switch(e.termType){case"NamedNode":return this.namedNode(e.value);case"BlankNode":return this.blankNode(e.value);case"Literal":return e.language?this.literal(e.value,e.language):e.datatype.equals(Rg.Literal.XSD_STRING)?this.literal(e.value):this.literal(e.value,this.fromTerm(e.datatype));case"Variable":return this.variable(e.value);case"DefaultGraph":return this.defaultGraph();case"Quad":return this.quad(this.fromTerm(e.subject),this.fromTerm(e.predicate),this.fromTerm(e.object),this.fromTerm(e.graph))}}fromQuad(e){return this.fromTerm(e)}resetBlankNodeCounter(){this.blankNodeCounter=0}};wu.DataFactory=hp});var kg=y(Sr=>{"use strict";var u5=Sr&&Sr.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:o(function(){return e[t]},"get")}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),rs=Sr&&Sr.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&u5(e,r,t)};Object.defineProperty(Sr,"__esModule",{value:!0});rs(ip(),Sr);rs(Ng(),Sr);rs(sp(),Sr);rs(op(),Sr);rs(_u(),Sr);rs(up(),Sr);rs(fp(),Sr)});var Mg=y((nj,jg)=>{var{Parser:Kn}=Og(),{Generator:l5}=Ig(),{Wildcard:f5}=rp(),{DataFactory:h5}=kg();function d5({prefixes:r,baseIRI:e,factory:t,pathOnly:n,sparqlStar:i,skipValidation:s,skipUngroupedVariableCheck:a}={}){let c={};for(let f in r??{})c[f]=r[f];let u=new Kn;return u.parse=function(){return Kn.base=e||"",Kn.prefixes=Object.create(c),Kn.factory=t||new h5,Kn.sparqlStar=!!i,Kn.pathOnly=!!n,Kn.skipValidation=!!s||!!a,Kn.prototype.parse.apply(u,arguments)},u._resetBlanks=Kn._resetBlanks,u}o(d5,"_Parser");jg.exports={Parser:d5,Generator:l5,Wildcard:f5}});var pp=y(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});js.CaseWhenTransformerError=js.CaseWhenTransformer=void 0;var dp=class{static{o(this,"CaseWhenTransformer")}transform(e){let t=e,n,i=0,s=100;do if(n=t,t=this.transformSinglePass(t),i++,i>s)throw new Yn("Too many nested CASE expressions (max 100 iterations)");while(t!==n);return t}transformSinglePass(e){let t=this.findCasePositions(e);if(t.length===0)return e;let n=e;for(let i=t.length-1;i>=0;i--){let s=t[i],a=this.extractCaseExpression(n,s);if(a){let c=this.convertCaseToIf(a.content);n=n.substring(0,s)+c+n.substring(s+a.length)}}return n}findCasePositions(e){let t=[],n=e.toUpperCase(),i=0;for(;i<e.length;){if(e[i]==="'"||e[i]==='"'){let s=e[i];for(i++;i<e.length&&e[i]!==s;)e[i]==="\\"&&i++,i++;i++;continue}if(n.substring(i,i+4)==="CASE"&&this.isWordBoundary(e,i,4)){t.push(i),i+=4;continue}i++}return t}extractCaseExpression(e,t){let n=1,i=t+4,s=e.toUpperCase();for(;i<e.length&&n>0;){if(e[i]==="'"||e[i]==='"'){let a=e[i];for(i++;i<e.length&&e[i]!==a;)e[i]==="\\"&&i++,i++;i++;continue}if(s.substring(i,i+4)==="CASE"&&this.isWordBoundary(e,i,4)){n++,i+=4;continue}if(s.substring(i,i+3)==="END"&&this.isWordBoundary(e,i,3)){if(n--,n===0){let a=e.substring(t,i+3);return{content:a,length:a.length}}i+=3;continue}i++}if(n>0)throw new Yn(`Unclosed CASE expression at position ${t}`);return null}isWordBoundary(e,t,n){let i=t>0?e[t-1]:"",s=t===0||!/[a-zA-Z0-9_?$]/.test(i),a=t+n<e.length?e[t+n]:"",c=t+n>=e.length||!/[a-zA-Z0-9_]/.test(a);return s&&c}convertCaseToIf(e){let t=this.extractWhenClauses(e),n=this.extractElseClause(e);if(t.length===0)throw new Yn("CASE expression must have at least one WHEN clause");let i=n!==null?n:'""';for(let s=t.length-1;s>=0;s--){let{condition:a,result:c}=t[s];i=`IF(${a}, ${c}, ${i})`}return i}extractWhenClauses(e){let t=[],n=e.replace(/^\s*CASE\s+/i,"").replace(/\s*END\s*$/i,""),i=this.findKeywordPositions(n,"WHEN"),s=this.findKeywordPositions(n,"ELSE"),a=s.length>0?s[0]:n.length;for(let c=0;c<i.length;c++){let u=i[c]+4,f=c+1<i.length?i[c+1]:a,l=n.substring(u,f).trim(),h=this.parseWhenClause(l);h&&t.push(h)}return t}findKeywordPositions(e,t){let n=[],i=e.toUpperCase(),s=0,a=0;for(;s<e.length;){let c=e[s];if(c==="'"||c==='"'){let u=c;for(s++;s<e.length&&e[s]!==u;)e[s]==="\\"&&s++,s++;s++;continue}if(c==="("){a++,s++;continue}if(c===")"){a--,s++;continue}if(a===0&&i.substring(s,s+t.length)===t&&this.isWordBoundary(e,s,t.length)){n.push(s),s+=t.length;continue}s++}return n}parseWhenClause(e){let t=this.findKeywordPositions(e,"THEN");if(t.length===0)throw new Yn(`WHEN clause missing THEN keyword: ${e.substring(0,50)}...`);let n=t[0],i=e.substring(0,n).trim(),s=e.substring(n+4).trim();if(!i)throw new Yn("WHEN clause has empty condition");if(!s)throw new Yn("WHEN clause has empty result");return{condition:i,result:s}}extractElseClause(e){let t=e.replace(/^\s*CASE\s+/i,"").replace(/\s*END\s*$/i,""),n=this.findKeywordPositions(t,"ELSE");if(n.length>0){let i=n[0];return t.substring(i+4).trim()}return null}};js.CaseWhenTransformer=dp;var Yn=class extends Error{static{o(this,"CaseWhenTransformerError")}constructor(e){super(`CASE WHEN transformation error: ${e}`),this.name="CaseWhenTransformerError"}};js.CaseWhenTransformerError=Yn});var qg=y(Fr=>{"use strict";var p5=Fr&&Fr.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:o(function(){return e[t]},"get")}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),m5=Fr&&Fr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),g5=Fr&&Fr.__importStar||(function(){var r=o(function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[n.length]=i);return n},r(e)},"ownKeys");return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),i=0;i<n.length;i++)n[i]!=="default"&&p5(t,e,n[i]);return m5(t,e),t}})();Object.defineProperty(Fr,"__esModule",{value:!0});Fr.SPARQLParser=Fr.SPARQLParseError=void 0;var Lg=g5(Mg()),Vg=pp(),En=class extends Error{static{o(this,"SPARQLParseError")}constructor(e,t,n,i){super(e,i?{cause:i}:void 0),this.name="SPARQLParseError",this.line=t,this.column=n}};Fr.SPARQLParseError=En;var mp=class{static{o(this,"SPARQLParser")}constructor(){this.parser=new Lg.Parser,this.generator=new Lg.Generator,this.caseWhenTransformer=new Vg.CaseWhenTransformer}parse(e){try{let t=this.caseWhenTransformer.transform(e),n=this.parser.parse(t);return this.validateQuery(n),n}catch(t){if(t instanceof Vg.CaseWhenTransformerError)throw new En(t.message);if(t instanceof Error){let n=t.message.match(/line (\d+), column (\d+)/),i=n?parseInt(n[1],10):void 0,s=n?parseInt(n[2],10):void 0;throw new En(`SPARQL syntax error: ${t.message}`,i,s,t)}throw t}}toString(e){try{return this.generator.stringify(e)}catch(t){throw t instanceof Error?new En(`Failed to serialize SPARQL query: ${t.message}`,void 0,void 0,t):t}}getQueryType(e){if("queryType"in e&&e.type==="query")return e.queryType;throw new En("Query does not have a valid queryType property")}isSelectQuery(e){return"queryType"in e&&e.type==="query"&&e.queryType==="SELECT"}isConstructQuery(e){return"queryType"in e&&e.type==="query"&&e.queryType==="CONSTRUCT"}isAskQuery(e){return"queryType"in e&&e.type==="query"&&e.queryType==="ASK"}isDescribeQuery(e){return"queryType"in e&&e.type==="query"&&e.queryType==="DESCRIBE"}validateQuery(e){if(!e||typeof e!="object")throw new En("Invalid query: not an object");if(e.type!=="query"&&e.type!=="update")throw new En(`Invalid type: expected "query" or "update", got "${e.type}"`);if(e.type==="query"){let t=["SELECT","CONSTRUCT","ASK","DESCRIBE"];if(!t.includes(e.queryType))throw new En(`Invalid query type: expected one of ${t.join(", ")}, got "${e.queryType}"`)}}};Fr.SPARQLParser=mp});var Bg=y(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});Ms.AlgebraTranslator=Ms.AlgebraTranslatorError=void 0;var Ie=class extends Error{static{o(this,"AlgebraTranslatorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="AlgebraTranslatorError"}};Ms.AlgebraTranslatorError=Ie;var gp=class{static{o(this,"AlgebraTranslator")}constructor(){this.aggregateCounter=0}translate(e){if(e.type!=="query")throw new Ie("Only query operations are supported (not updates)");if(e.queryType==="SELECT")return this.translateSelect(e);if(e.queryType==="CONSTRUCT")return this.translateConstruct(e);throw new Ie(`Query type ${e.queryType} not yet supported`)}translateSelect(e){let t;if(!e.where||e.where.length===0)throw new Ie("SELECT query must have WHERE clause");t=this.translateWhere(e.where),this.aggregateCounter=0;let n=new Map,i=this.extractAggregatesWithMapping(e.variables,n),s=this.extractGroupVariables(e.group);if((i.length>0||s.length>0)&&(t={type:"group",variables:s,aggregates:i,input:t}),e.variables&&e.variables.length>0){for(let c of e.variables){let u=c;if(u.expression&&u.variable){if(u.expression.type==="aggregate")continue;let f=this.transformExpressionWithAggregateVars(u.expression,n);t={type:"extend",variable:u.variable.value,expression:f,input:t}}}let a=e.variables.filter(c=>c.termType==="Variable"||c.variable).map(c=>c.termType==="Variable"?c.value:c.variable.value);a.length>0&&(t={type:"project",variables:a,input:t})}return e.distinct&&(t={type:"distinct",input:t}),e.reduced&&(t={type:"reduced",input:t}),e.order&&e.order.length>0&&(t={type:"orderby",comparators:e.order.map(a=>this.translateOrderComparator(a)),input:t}),(e.limit!==void 0||e.offset!==void 0)&&(t={type:"slice",limit:e.limit,offset:e.offset,input:t}),t}translateConstruct(e){let t=this.translateConstructTemplate(e.template??[]);if(!e.where||e.where.length===0)throw new Ie("CONSTRUCT query must have WHERE clause");let n=this.translateWhere(e.where);return{type:"construct",template:t,where:n}}translateConstructTemplate(e){return!e||!Array.isArray(e)?[]:e.map(t=>this.translateTriple(t))}extractAggregatesWithMapping(e,t){if(!e)return[];let n=[];for(let i of e)!i.expression||!i.variable||(i.expression.type==="aggregate"?(n.push({variable:i.variable.value,expression:this.translateAggregateExpression(i.expression)}),t.set(i.expression,i.variable.value)):this.collectNestedAggregates(i.expression,n,t));return n}collectNestedAggregates(e,t,n){if(e){if(e.type==="aggregate"){let i=`__agg${this.aggregateCounter++}`;t.push({variable:i,expression:this.translateAggregateExpression(e)}),n.set(e,i)}else if(e.type==="operation"&&e.args)for(let i of e.args)this.collectNestedAggregates(i,t,n)}}transformExpressionWithAggregateVars(e,t){if(t.has(e))return{type:"variable",name:t.get(e)};if(e.type==="operation"&&e.args){let n=e.args.map(c=>this.transformExpressionWithAggregateVars(c,t)),i=["=","!=","<",">","<=",">="],s=["&&","||","!"],a=["+","-","*","/"];return i.includes(e.operator)?{type:"comparison",operator:e.operator,left:n[0],right:n[1]}:s.includes(e.operator)?{type:"logical",operator:e.operator,operands:n}:a.includes(e.operator)?{type:"arithmetic",operator:e.operator,left:n[0],right:n[1]}:{type:"function",function:e.operator,args:n}}return this.translateExpression(e)}extractGroupVariables(e){return e?e.filter(t=>t.expression&&t.expression.termType==="Variable").map(t=>t.expression.value):[]}translateAggregateExpression(e){return{type:"aggregate",aggregation:e.aggregation.toLowerCase(),expression:e.expression?this.translateExpression(e.expression):void 0,distinct:e.distinct||!1,separator:e.separator}}translateWhere(e){if(e.length===0)throw new Ie("Empty WHERE clause");let t=e.filter(a=>a.type==="filter"),n=e.filter(a=>a.type==="bind"),i=e.filter(a=>a.type!=="filter"&&a.type!=="bind"),s;i.length===0?s={type:"bgp",triples:[]}:i.length===1?s=this.translatePattern(i[0]):s=i.map(c=>this.translatePattern(c)).reduce((c,u)=>({type:"join",left:c,right:u}));for(let a of n)s=this.translateBind(a,s);for(let a of t)s={type:"filter",expression:this.translateExpression(a.expression),input:s};return s}translatePattern(e){if(!e||!e.type)throw new Ie("Invalid pattern: missing type");switch(e.type){case"bgp":return this.translateBGP(e);case"filter":return this.translateFilter(e);case"optional":return this.translateOptional(e);case"union":return this.translateUnion(e);case"minus":return this.translateMinus(e);case"values":return this.translateValues(e);case"group":return this.translateWhere(e.patterns);case"query":return this.translateSubquery(e);default:throw new Ie(`Unsupported pattern type: ${e.type}`)}}translateBGP(e){if(!e.triples||!Array.isArray(e.triples))throw new Ie("BGP pattern must have triples array");return{type:"bgp",triples:e.triples.map(t=>this.translateTriple(t))}}translateTriple(e){if(!e.subject||!e.predicate||!e.object)throw new Ie("Triple must have subject, predicate, and object");return{subject:this.translateTripleElement(e.subject),predicate:this.translatePredicate(e.predicate),object:this.translateTripleElement(e.object)}}translatePredicate(e){return e.type==="path"?this.translatePropertyPath(e):this.translateTripleElement(e)}translatePropertyPath(e){if(!e.pathType)throw new Ie("Property path must have pathType");if(!e.items||!Array.isArray(e.items))throw new Ie("Property path must have items array");let t=e.items.map(n=>this.translatePathItem(n));switch(e.pathType){case"/":return{type:"path",pathType:"/",items:t};case"|":return{type:"path",pathType:"|",items:t};case"^":if(t.length!==1)throw new Ie("Inverse path must have exactly one item");return{type:"path",pathType:"^",items:[t[0]]};case"+":if(t.length!==1)throw new Ie("OneOrMore path must have exactly one item");return{type:"path",pathType:"+",items:[t[0]]};case"*":if(t.length!==1)throw new Ie("ZeroOrMore path must have exactly one item");return{type:"path",pathType:"*",items:[t[0]]};case"?":if(t.length!==1)throw new Ie("ZeroOrOne path must have exactly one item");return{type:"path",pathType:"?",items:[t[0]]};default:throw new Ie(`Unsupported property path type: ${e.pathType}`)}}translatePathItem(e){if(e.type==="path")return this.translatePropertyPath(e);if(e.termType==="NamedNode")return{type:"iri",value:e.value};throw new Ie(`Unsupported path item type: ${e.type||e.termType}`)}translateTripleElement(e){if(!e||!e.termType)throw new Ie("Triple element must have termType");switch(e.termType){case"Variable":return{type:"variable",value:e.value};case"NamedNode":return{type:"iri",value:e.value};case"Literal":return{type:"literal",value:e.value,datatype:e.datatype?.value,language:e.language};case"BlankNode":return{type:"blank",value:e.value};default:throw new Ie(`Unsupported term type: ${e.termType}`)}}translateFilter(e){if(!e.expression)throw new Ie("Filter pattern must have expression");let t=e.patterns?this.translateWhere(e.patterns):{type:"bgp",triples:[]};return{type:"filter",expression:this.translateExpression(e.expression),input:t}}translateExpression(e){if(!e)throw new Ie("Expression cannot be null or undefined");if(e.type==="operation")return this.translateOperationExpression(e);if(e.type==="functioncall"||e.type==="functionCall")return{type:"functionCall",function:e.function,args:e.args.map(t=>this.translateExpression(t))};if(e.termType)return this.translateTermExpression(e);throw new Ie(`Unsupported expression structure: ${JSON.stringify(e)}`)}translateOperationExpression(e){let t=["=","!=","<",">","<=",">="],n=["&&","||","!"],i=["+","-","*","/"];return t.includes(e.operator)?{type:"comparison",operator:e.operator,left:this.translateExpression(e.args[0]),right:this.translateExpression(e.args[1])}:n.includes(e.operator)?{type:"logical",operator:e.operator,operands:e.args.map(s=>this.translateExpression(s))}:i.includes(e.operator)?{type:"arithmetic",operator:e.operator,left:this.translateExpression(e.args[0]),right:this.translateExpression(e.args[1])}:e.operator==="exists"||e.operator==="notexists"?this.translateExistsExpression(e):{type:"function",function:e.operator,args:e.args.map(s=>this.translateExpression(s))}}translateExistsExpression(e){if(!e.args||e.args.length!==1)throw new Ie("EXISTS/NOT EXISTS must have exactly one pattern argument");let t=e.args[0],n;return t.type==="group"&&t.patterns?n=this.translateWhere(t.patterns):t.type==="bgp"?n=this.translateBGP(t):n=this.translatePattern(t),{type:"exists",negated:e.operator==="notexists",pattern:n}}translateTermExpression(e){if(e.termType==="Variable")return{type:"variable",name:e.value};if(e.termType==="Literal"){let t=e.value;return e.datatype&&(e.datatype.value.includes("#integer")||e.datatype.value.includes("#decimal")?t=parseFloat(e.value):e.datatype.value.includes("#boolean")&&(t=e.value==="true")),{type:"literal",value:t,datatype:e.datatype?.value}}return{type:"literal",value:String(e.value||e)}}translateOptional(e){if(!e.patterns||e.patterns.length===0)throw new Ie("OPTIONAL pattern must have patterns");return{type:"leftjoin",left:{type:"bgp",triples:[]},right:this.translateWhere(e.patterns),expression:e.expression?this.translateExpression(e.expression):void 0}}translateUnion(e){if(!e.patterns||e.patterns.length<2)throw new Ie("UNION pattern must have at least 2 patterns");let t=o(i=>i.patterns&&Array.isArray(i.patterns)?this.translateWhere(i.patterns):this.translateWhere([i]),"translateBranch"),n={type:"union",left:t(e.patterns[0]),right:t(e.patterns[1])};for(let i=2;i<e.patterns.length;i++)n={type:"union",left:n,right:t(e.patterns[i])};return n}translateMinus(e){if(!e.patterns||e.patterns.length===0)throw new Ie("MINUS pattern must have patterns");return{type:"minus",left:{type:"bgp",triples:[]},right:this.translateWhere(e.patterns)}}translateValues(e){if(!e.values||!Array.isArray(e.values))throw new Ie("VALUES pattern must have values array");let t=new Set;for(let i of e.values)for(let s of Object.keys(i)){let a=s.startsWith("?")?s.slice(1):s;t.add(a)}let n=e.values.map(i=>this.translateValuesBinding(i));return{type:"values",variables:Array.from(t),bindings:n}}translateValuesBinding(e){let t={};for(let[n,i]of Object.entries(e)){let s=n.startsWith("?")?n.slice(1):n,a=i;if(a.termType==="NamedNode")t[s]={type:"iri",value:a.value};else if(a.termType==="Literal")t[s]={type:"literal",value:a.value,datatype:a.datatype?.value,language:a.language||void 0};else throw new Ie(`Unsupported VALUES term type: ${a.termType}`)}return t}translateBind(e,t){if(!e.variable||!e.expression)throw new Ie("BIND pattern must have variable and expression");return{type:"extend",variable:e.variable.value,expression:this.translateExpression(e.expression),input:t}}translateOrderComparator(e){return{expression:this.translateExpression(e.expression),descending:e.descending||!1}}translateSubquery(e){if(e.queryType!=="SELECT")throw new Ie(`Only SELECT subqueries are supported, got: ${e.queryType}`);return{type:"subquery",query:this.translateSelect(e)}}};Ms.AlgebraTranslator=gp});var Ug=y(Eu=>{"use strict";Object.defineProperty(Eu,"__esModule",{value:!0});Eu.AlgebraOptimizer=void 0;var yp=class{static{o(this,"AlgebraOptimizer")}constructor(){this.stats=new Map}optimize(e){let t=e;return t=this.eliminateEmptyBGPInFilterJoin(t),t=this.filterPushDown(t),t=this.joinReordering(t),t}eliminateEmptyBGPInFilterJoin(e){if(e.type==="join"){if(e.left.type==="filter"){let t=e.left;if(t.input.type==="bgp"&&t.input.triples.length===0)return{type:"filter",expression:t.expression,input:this.eliminateEmptyBGPInFilterJoin(e.right)}}if(e.right.type==="filter"){let t=e.right;if(t.input.type==="bgp"&&t.input.triples.length===0)return{type:"filter",expression:t.expression,input:this.eliminateEmptyBGPInFilterJoin(e.left)}}return{type:"join",left:this.eliminateEmptyBGPInFilterJoin(e.left),right:this.eliminateEmptyBGPInFilterJoin(e.right)}}return e.type==="filter"?{...e,input:this.eliminateEmptyBGPInFilterJoin(e.input)}:e.type==="leftjoin"?{...e,left:this.eliminateEmptyBGPInFilterJoin(e.left),right:this.eliminateEmptyBGPInFilterJoin(e.right)}:e.type==="union"?{...e,left:this.eliminateEmptyBGPInFilterJoin(e.left),right:this.eliminateEmptyBGPInFilterJoin(e.right)}:e.type==="minus"?{...e,left:this.eliminateEmptyBGPInFilterJoin(e.left),right:this.eliminateEmptyBGPInFilterJoin(e.right)}:e.type==="project"?{...e,input:this.eliminateEmptyBGPInFilterJoin(e.input)}:e.type==="orderby"?{...e,input:this.eliminateEmptyBGPInFilterJoin(e.input)}:e.type==="slice"?{...e,input:this.eliminateEmptyBGPInFilterJoin(e.input)}:e.type==="distinct"?{...e,input:this.eliminateEmptyBGPInFilterJoin(e.input)}:e}filterPushDown(e){return e.type==="filter"?this.pushDownFilter(e):e.type==="join"?{type:"join",left:this.filterPushDown(e.left),right:this.filterPushDown(e.right)}:e.type==="leftjoin"?{...e,left:this.filterPushDown(e.left),right:this.filterPushDown(e.right)}:e.type==="union"?{type:"union",left:this.filterPushDown(e.left),right:this.filterPushDown(e.right)}:e.type==="minus"?{...e,left:this.filterPushDown(e.left),right:this.filterPushDown(e.right)}:e.type==="project"?{...e,input:this.filterPushDown(e.input)}:e.type==="orderby"?{...e,input:this.filterPushDown(e.input)}:e.type==="slice"?{...e,input:this.filterPushDown(e.input)}:e.type==="distinct"?{...e,input:this.filterPushDown(e.input)}:e}pushDownFilter(e){let t=e.input;if(t.type==="join"){let n=this.getFilterVariables(e.expression),i=this.getOperationVariables(t.left),s=this.getOperationVariables(t.right),a=n.every(u=>i.has(u)),c=n.every(u=>s.has(u));return a&&!c?{type:"join",left:{type:"filter",expression:e.expression,input:this.filterPushDown(t.left)},right:this.filterPushDown(t.right)}:c&&!a?{type:"join",left:this.filterPushDown(t.left),right:{type:"filter",expression:e.expression,input:this.filterPushDown(t.right)}}:{type:"filter",expression:e.expression,input:{type:"join",left:this.filterPushDown(t.left),right:this.filterPushDown(t.right)}}}return t.type==="union"?{type:"union",left:{type:"filter",expression:e.expression,input:this.filterPushDown(t.left)},right:{type:"filter",expression:e.expression,input:this.filterPushDown(t.right)}}:{type:"filter",expression:e.expression,input:this.filterPushDown(t)}}getFilterVariables(e){let t=[];if(e.type==="variable")t.push(e.name);else if(e.type==="comparison")t.push(...this.getFilterVariables(e.left)),t.push(...this.getFilterVariables(e.right));else if(e.type==="logical")for(let n of e.operands)t.push(...this.getFilterVariables(n));else if(e.type==="function")for(let n of e.args)t.push(...this.getFilterVariables(n));return Array.from(new Set(t))}getOperationVariables(e){let t=new Set;if(e.type==="bgp")for(let n of e.triples)n.subject.type==="variable"&&t.add(n.subject.value),n.predicate.type==="variable"&&t.add(n.predicate.value),n.object.type==="variable"&&t.add(n.object.value);else if(e.type==="join"){let n=this.getOperationVariables(e.left),i=this.getOperationVariables(e.right);return new Set([...n,...i])}else{if(e.type==="filter")return this.getOperationVariables(e.input);if(e.type==="leftjoin"){let n=this.getOperationVariables(e.left),i=this.getOperationVariables(e.right);return new Set([...n,...i])}else if(e.type==="union"){let n=this.getOperationVariables(e.left),i=this.getOperationVariables(e.right);return new Set([...n,...i])}else{if(e.type==="minus")return this.getOperationVariables(e.left);if(e.type==="project")return new Set(e.variables)}}return t}joinReordering(e){return e.type==="join"?this.reorderJoin(e):e.type==="filter"?{...e,input:this.joinReordering(e.input)}:e.type==="leftjoin"?{...e,left:this.joinReordering(e.left),right:this.joinReordering(e.right)}:e.type==="union"?{...e,left:this.joinReordering(e.left),right:this.joinReordering(e.right)}:e.type==="minus"?{...e,left:this.joinReordering(e.left),right:this.joinReordering(e.right)}:e.type==="project"?{...e,input:this.joinReordering(e.input)}:e.type==="orderby"?{...e,input:this.joinReordering(e.input)}:e.type==="slice"?{...e,input:this.joinReordering(e.input)}:e.type==="distinct"?{...e,input:this.joinReordering(e.input)}:e}reorderJoin(e){let t=this.estimateCost(e.left);return this.estimateCost(e.right)<t?{type:"join",left:this.joinReordering(e.right),right:this.joinReordering(e.left)}:{type:"join",left:this.joinReordering(e.left),right:this.joinReordering(e.right)}}estimateCost(e){if(e.type==="bgp"){let t=e.triples.length*100;for(let n of e.triples)n.subject.type==="variable"&&(t+=10),n.predicate.type==="variable"&&(t+=20),n.object.type==="variable"&&(t+=10);return t}return e.type==="filter"?this.estimateCost(e.input)*.3:e.type==="join"?this.estimateCost(e.left)*this.estimateCost(e.right):e.type==="leftjoin"?this.estimateCost(e.left)+this.estimateCost(e.right)*.5:e.type==="union"?this.estimateCost(e.left)+this.estimateCost(e.right):e.type==="minus"?this.estimateCost(e.left)+this.estimateCost(e.right)*.3:100}setStatistics(e,t){this.stats.set(e,t)}getStatistics(e){return this.stats.get(e)}};Eu.AlgebraOptimizer=yp});var $g=y(Tu=>{"use strict";Object.defineProperty(Tu,"__esModule",{value:!0});Tu.AlgebraSerializer=void 0;var _p=class{static{o(this,"AlgebraSerializer")}toString(e,t=0){let n=" ".repeat(t);switch(e.type){case"bgp":return`${n}BGP [
108
108
  ${e.triples.map(f=>`${n} ${this.tripleToString(f)}`).join(`
109
109
  `)}
110
110
  ${n}]`;case"filter":return`${n}Filter(
@@ -136,7 +136,7 @@ ${n})`;case"extend":return`${n}Extend (?${e.variable} = ${this.expressionToStrin
136
136
  ${this.toString(e.input,t+1)}
137
137
  ${n})`;case"subquery":return`${n}Subquery(
138
138
  ${this.toString(e.query,t+1)}
139
- ${n})`;default:return`${n}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(n=>n.type==="path"?`(${this.propertyPathToString(n)})`:`<${n.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)}};Tu.AlgebraSerializer=_p});var ns=y(Au=>{"use strict";Object.defineProperty(Au,"__esModule",{value:!0});Au.SolutionMapping=void 0;var Wg=jt(),Gg=pt(),Hg=Or(),vp=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,n]of this.bindings.entries()){let i=e.get(t);if(i!==void 0&&!this.areEqual(n,i))return!1}return!0}merge(e){if(!this.isCompatibleWith(e))return null;let t=new r(this.bindings);for(let[n,i]of e.getBindings().entries())t.set(n,i);return t}clone(){return new r(this.bindings)}areEqual(e,t){return e instanceof Wg.Literal&&t instanceof Wg.Literal?e.equals(t):e instanceof Gg.IRI&&t instanceof Gg.IRI?e.value===t.value:e instanceof Hg.BlankNode&&t instanceof Hg.BlankNode?e.id===t.id:!1}toJSON(){let e={};for(let[t,n]of this.bindings.entries())e[t]=n.toString();return e}size(){return this.bindings.size}};Au.SolutionMapping=vp});var Kg=y(Ls=>{"use strict";Object.defineProperty(Ls,"__esModule",{value:!0});Ls.PropertyPathExecutor=Ls.PropertyPathExecutorError=void 0;var y5=ns(),xu=pt(),zg=Or(),za=class extends Error{static{o(this,"PropertyPathExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="PropertyPathExecutorError"}};Ls.PropertyPathExecutorError=za;var Sp=class{static{o(this,"PropertyPathExecutor")}constructor(e){this.tripleStore=e,this.MAX_DEPTH=100}async*execute(e,t,n){let i=await this.resolveElement(e),s=this.isVariable(n)?null:await this.resolveElement(n);for(let a of i){let c=await this.evaluatePath(a,t,s);for(let u of c){let f=new y5.SolutionMapping;this.isVariable(e)&&f.set(e.value,a),this.isVariable(n)&&f.set(n.value,u),yield f}}}async*executeWithBindings(e,t){if(!this.isPropertyPath(e.predicate))throw new za("Predicate is not a property path");let n=this.instantiateElement(e.subject,t),i=this.instantiateElement(e.object,t);for await(let s of this.execute(n,e.predicate,i)){let a=t.merge(s);a!==null&&(yield a)}}async evaluatePath(e,t,n){switch(t.pathType){case"/":return this.evaluateSequencePath(e,t.items,n);case"|":return this.evaluateAlternativePath(e,t.items,n);case"^":return this.evaluateInversePath(e,t.items[0],n);case"+":return this.evaluateOneOrMorePath(e,t.items[0],n);case"*":return this.evaluateZeroOrMorePath(e,t.items[0],n);case"?":return this.evaluateZeroOrOnePath(e,t.items[0],n)}}async evaluateSequencePath(e,t,n){let i=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 f of i){let l=await this.evaluatePathItem(f,a,c?n:null);for(let h of l)u.add(h)}if(i=u,i.size===0)break}return i}async evaluateAlternativePath(e,t,n){let i=new Set;for(let s of t){let a=await this.evaluatePathItem(e,s,n);for(let c of a)i.add(c)}return i}async evaluateInversePath(e,t,n){if(t.type==="iri"){let i=new xu.IRI(t.value),s=await this.tripleStore.match(void 0,i,e),a=new Set;for(let c of s)(n===null||this.nodeInSet(c.subject,n))&&a.add(c.subject);return a}else return this.evaluatePath(e,this.invertPath(t),n)}async evaluateOneOrMorePath(e,t,n){let i=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 f=await this.evaluatePathItem(c,t,null);for(let l of f){let h=this.nodeToKey(l);(n===null||this.nodeInSet(l,n))&&s.add(l),i.has(h)||(i.add(h),a.push({node:l,depth:u+1}))}}return s}async evaluateZeroOrMorePath(e,t,n){let i=await this.evaluateOneOrMorePath(e,t,n);return(n===null||this.nodeInSet(e,n))&&i.add(e),i}async evaluateZeroOrOnePath(e,t,n){let i=new Set;(n===null||this.nodeInSet(e,n))&&i.add(e);let s=await this.evaluatePathItem(e,t,n);for(let a of s)i.add(a);return i}async evaluatePathItem(e,t,n){if(t.type==="iri"){let i=new xu.IRI(t.value),s=await this.tripleStore.match(e,i,void 0),a=new Set;for(let c of s)(n===null||this.nodeInSet(c.object,n))&&a.add(c.object);return a}else return this.evaluatePath(e,t,n)}invertPath(e){switch(e.pathType){case"^":return e.items[0];case"/":return{type:"path",pathType:"/",items:[...e.items].reverse().map(n=>n.type==="iri"?{type:"path",pathType:"^",items:[n]}:this.invertPath(n))};case"|":return{type:"path",pathType:"|",items:e.items.map(n=>n.type==="iri"?{type:"path",pathType:"^",items:[n]}:this.invertPath(n))};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 n=new Set,i=await this.tripleStore.match(void 0,void 0,void 0);for(let s of i)n.add(s.subject),n.add(s.object);return n}let t=new Set;switch(e.type){case"iri":t.add(new xu.IRI(e.value));break;case"blank":t.add(new zg.BlankNode(e.value));break;default:throw new za(`Unsupported element type in subject/object position: ${e.type}`)}return t}instantiateElement(e,t){if(this.isVariable(e)){let n=t.get(e.value);if(n){if(n instanceof xu.IRI)return{type:"iri",value:n.value};if(n instanceof zg.BlankNode)return{type:"blank",value:n.id}}}return e}isVariable(e){return e.type==="variable"}isPropertyPath(e){return e.type==="path"}nodeToKey(e){return e.toString()}nodeInSet(e,t){let n=this.nodeToKey(e);for(let i of t)if(this.nodeToKey(i)===n)return!0;return!1}};Ls.PropertyPathExecutor=Sp});var Ep=y(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});Vs.BGPExecutor=Vs.BGPExecutorError=void 0;var Yg=ns(),Ka=pt(),Qg=jt(),bp=Or(),_5=Kg(),br=class extends Error{static{o(this,"BGPExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="BGPExecutorError"}};Vs.BGPExecutorError=br;var wp=class{static{o(this,"BGPExecutor")}constructor(e){this.tripleStore=e,this.propertyPathExecutor=new _5.PropertyPathExecutor(e)}async*execute(e){if(e.triples.length===0){yield new Yg.SolutionMapping;return}let t=this.matchTriplePattern(e.triples[0]);for(let n=1;n<e.triples.length;n++)t=this.joinWithPattern(t,e.triples[n]);for await(let n of t)yield n}async executeAll(e){let t=[];for await(let n of this.execute(e))t.push(n);return t}async*matchTriplePattern(e){if(this.isPropertyPath(e.predicate)){yield*this.propertyPathExecutor.execute(e.subject,e.predicate,e.object);return}let t=e.predicate,n=this.isVariable(e.subject)?void 0:this.toRDFTermAsSubject(e.subject),i=this.isVariable(t)?void 0:this.toRDFTermAsPredicate(t),s=this.isVariable(e.object)?void 0:this.toRDFTerm(e.object),a=await this.tripleStore.match(n,i,s);for(let c of a){let u=new Yg.SolutionMapping;this.isVariable(e.subject)&&u.set(e.subject.value,c.subject),this.isVariable(t)&&u.set(t.value,c.predicate),this.isVariable(e.object)&&u.set(e.object.value,c.object),yield u}}isPropertyPath(e){return e.type==="path"}async*joinWithPattern(e,t){let n=[];for await(let i of e)n.push(i);for(let i of n){let s=this.instantiatePattern(t,i);for await(let a of this.matchTriplePattern(s)){let c=i.merge(a);c!==null&&(yield c)}}}instantiatePattern(e,t){let n=this.isPropertyPath(e.predicate)?e.predicate:this.instantiateElement(e.predicate,t);return{subject:this.instantiateElement(e.subject,t),predicate:n,object:this.instantiateElement(e.object,t)}}instantiateElement(e,t){if(this.isVariable(e)){let n=t.get(e.value);if(n)return this.toAlgebraElement(n)}return e}isVariable(e){return e.type==="variable"}toRDFTermAsSubject(e){switch(e.type){case"iri":return new Ka.IRI(e.value);case"blank":return new bp.BlankNode(e.value);case"literal":throw new br("Literals cannot appear in subject position");case"variable":throw new br(`Cannot convert variable to RDF term: ${e.value}`);default:throw new br(`Unknown element type: ${e.type}`)}}toRDFTermAsPredicate(e){switch(e.type){case"iri":return new Ka.IRI(e.value);case"literal":throw new br("Literals cannot appear in predicate position");case"blank":throw new br("Blank nodes cannot appear in predicate position");case"variable":throw new br(`Cannot convert variable to RDF term: ${e.value}`);default:throw new br(`Unknown element type: ${e.type}`)}}toRDFTerm(e){switch(e.type){case"iri":return new Ka.IRI(e.value);case"literal":return new Qg.Literal(e.value,e.datatype?new Ka.IRI(e.datatype):void 0,e.language);case"blank":return new bp.BlankNode(e.value);case"variable":throw new br(`Cannot convert variable to RDF term: ${e.value}`);default:throw new br(`Unknown element type: ${e.type}`)}}toAlgebraElement(e){if(e instanceof Ka.IRI)return{type:"iri",value:e.value};if(e instanceof Qg.Literal)return{type:"literal",value:e.value,datatype:e.datatype?.value,language:e.language};if(e instanceof bp.BlankNode)return{type:"blank",value:e.id};throw new br(`Unknown RDF term type: ${e.constructor?.name||"unknown"}`)}};Vs.BGPExecutor=wp});var Ap=y(Ou=>{"use strict";Object.defineProperty(Ou,"__esModule",{value:!0});Ou.BuiltInFunctions=void 0;var Tn=pt(),sn=jt(),Ya=Or(),Tp=class{static{o(this,"BuiltInFunctions")}static str(e){if(e===void 0)throw new Error("STR: argument is undefined");return e instanceof Tn.IRI||e instanceof sn.Literal?e.value:e instanceof Ya.BlankNode?e.id:String(e)}static lang(e){if(e===void 0)throw new Error("LANG: argument is undefined");return e instanceof sn.Literal&&e.language?e.language:""}static datatype(e){if(e===void 0)throw new Error("DATATYPE: argument is undefined");if(e instanceof sn.Literal)return e.datatype?e.datatype:e.language?new Tn.IRI("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"):new Tn.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 Tn.IRI}static isBlank(e){return e===void 0?!1:e instanceof Ya.BlankNode}static isLiteral(e){return e===void 0?!1:e instanceof sn.Literal}static isNumeric(e){if(e===void 0||!(e instanceof sn.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,n){try{return new RegExp(t,n).test(e)}catch(i){throw new Error(`REGEX: invalid pattern '${t}': ${i.message}`)}}static compare(e,t,n){let i=this.toComparableValue(e),s=this.toComparableValue(t);switch(n){case"=":return i===s;case"!=":return i!==s;case"<":return i<s;case">":return i>s;case"<=":return i<=s;case">=":return i>=s;default:throw new Error(`Unknown comparison operator: ${n}`)}}static toComparableValue(e){if(typeof e=="string"||typeof e=="number")return e;if(e instanceof sn.Literal){let t=e.datatype?.value;if(t?.includes("#integer")||t?.includes("#decimal")||t?.includes("#double")){let n=parseFloat(e.value);if(!isNaN(n))return n}return e.value}return e instanceof Tn.IRI?e.value:e instanceof Ya.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,n){let i=t-1;if(i<0){if(n!==void 0){let s=n+i;return s<=0?"":e.substring(0,s)}return e}return n!==void 0?e.substring(i,i+n):e.substring(i)}static strBefore(e,t){if(t==="")return"";let n=e.indexOf(t);return n===-1?"":e.substring(0,n)}static strAfter(e,t){if(t==="")return e;let n=e.indexOf(t);return n===-1?"":e.substring(n+t.length)}static concat(...e){return e.join("")}static replace(e,t,n,i){try{let s=new RegExp(t,i||"g");return e.replace(s,n)}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 n=this.parseDate(e),i=this.parseDate(t);return n<i}static dateAfter(e,t){let n=this.parseDate(e),i=this.parseDate(t);return n>i}static dateInRange(e,t,n){let i=this.parseDate(e),s=this.parseDate(t),a=this.parseDate(n);return i>=s&&i<=a}static dateDiffMinutes(e,t){let n=this.parseDate(e),i=this.parseDate(t),s=Math.abs(i-n);return Math.round(s/(1e3*60))}static dateDiffHours(e,t){let n=this.parseDate(e),i=this.parseDate(t),s=Math.abs(i-n);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}'`);if(e.endsWith("Z"))return"PT0S";let n=e.match(/([+-]\d{2}):?(\d{2})$/);if(n){let u=parseInt(n[1],10),f=parseInt(n[2],10),l=u>=0?"":"-",h=Math.abs(u);return f===0?`${l}PT${h}H`:`${l}PT${h}H${f}M`}let i=-t.getTimezoneOffset(),s=Math.floor(Math.abs(i)/60),a=Math.abs(i)%60,c=i>=0?"":"-";return a===0?`${c}PT${s}H`:`${c}PT${s}H${a}M`}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,n){return e?t:n}static xsdDateTime(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`xsd:dateTime: invalid date string '${e}'`);return new sn.Literal(t.toISOString(),new Tn.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 sn.Literal(String(t),new Tn.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 sn.Literal(String(t),new Tn.IRI("http://www.w3.org/2001/XMLSchema#decimal"))}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 Tn.IRI&&t instanceof Tn.IRI)return e.value===t.value;if(e instanceof Ya.BlankNode&&t instanceof Ya.BlankNode)return e.id===t.id;if(e instanceof sn.Literal&&t instanceof sn.Literal){if(e.value!==t.value||e.language!==t.language)return!1;let n=e.datatype?.value,i=t.datatype?.value;return n===i}return!1}};Ou.BuiltInFunctions=Tp});var Pu=y(qs=>{"use strict";Object.defineProperty(qs,"__esModule",{value:!0});qs.FilterExecutor=qs.FilterExecutorError=void 0;var se=Ap(),Cu=jt(),Ft=class extends Error{static{o(this,"FilterExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="FilterExecutorError"}};qs.FilterExecutorError=Ft;var xp=class{static{o(this,"FilterExecutor")}constructor(){this.existsEvaluator=null}setExistsEvaluator(e){this.existsEvaluator=e}async*execute(e,t){let n=this.expressionContainsExists(e.expression);for await(let i of t)try{let s;n?s=await this.evaluateExpressionAsync(e.expression,i):s=this.evaluateExpression(e.expression,i),s===!0&&(yield i)}catch{continue}}expressionContainsExists(e){return e.type==="exists"?!0:e.type==="logical"?e.operands.some(t=>this.expressionContainsExists(t)):e.type==="comparison"?this.expressionContainsExists(e.left)||this.expressionContainsExists(e.right):!1}async executeAll(e,t){let n=[];async function*i(){for(let s of t)yield s}o(i,"generator");for await(let s of this.execute(e,i()))n.push(s);return n}evaluateExpression(e,t){let n=e;if(n.termType)switch(n.termType){case"Variable":return t.get(n.value);case"Literal":return n.value;case"NamedNode":return n.value;default:throw new Ft(`Unsupported termType: ${n.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"exists":throw new Ft("EXISTS expressions require async evaluation. Use evaluateExpressionAsync instead.");default:throw new Ft(`Unsupported expression type: ${e.type}, expr.termType=${n.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 Ft("EXISTS evaluator not set. Call setExistsEvaluator before evaluating EXISTS expressions.");let n=await this.existsEvaluator(e.pattern,t);return e.negated?!n:n}async evaluateLogicalAsync(e,t){if(e.operator==="!"){let i=await this.evaluateExpressionAsync(e.operands[0],t);return se.BuiltInFunctions.logicalNot(i)}let n=[];for(let i of e.operands){let s=await this.evaluateExpressionAsync(i,t);n.push(s)}if(e.operator==="&&")return se.BuiltInFunctions.logicalAnd(n);if(e.operator==="||")return se.BuiltInFunctions.logicalOr(n);throw new Ft(`Unknown logical operator: ${e.operator}`)}evaluateComparison(e,t){let n=this.evaluateExpression(e.left,t),i=this.evaluateExpression(e.right,t);return se.BuiltInFunctions.compare(n,i,e.operator)}evaluateLogical(e,t){if(e.operator==="!"){let i=this.evaluateExpression(e.operands[0],t);return se.BuiltInFunctions.logicalNot(i)}let n=e.operands.map(i=>this.evaluateExpression(i,t));if(e.operator==="&&")return se.BuiltInFunctions.logicalAnd(n);if(e.operator==="||")return se.BuiltInFunctions.logicalOr(n);throw new Ft(`Unknown logical operator: ${e.operator}`)}evaluateArithmetic(e,t){let n=this.evaluateExpression(e.left,t),i=this.evaluateExpression(e.right,t),s=this.toNumericValue(n),a=this.toNumericValue(i);if(e.operator==="-"&&this.isDateTimeValue(n)&&this.isDateTimeValue(i)){let c=this.parseDateTimeToMs(n),u=this.parseDateTimeToMs(i);return c-u}switch(e.operator){case"+":return s+a;case"-":return s-a;case"*":return s*a;case"/":if(a===0)throw new Ft("Division by zero");return s/a;default:throw new Ft(`Unknown arithmetic operator: ${e.operator}`)}}toNumericValue(e){if(typeof e=="number")return e;if(e instanceof Cu.Literal){let t=e.datatype?.value||"";if(t.includes("#integer")||t.includes("#decimal")||t.includes("#double")||t.includes("#float")){let i=parseFloat(e.value);if(!isNaN(i))return i}let n=parseFloat(e.value);if(!isNaN(n))return n}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 Ft(`Cannot convert to number: ${e}`)}isDateTimeValue(e){if(e instanceof Cu.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}parseDateTimeToMs(e){let t;if(e instanceof Cu.Literal)t=e.value;else if(typeof e=="string")t=e;else if(e&&typeof e=="object"&&"value"in e)t=String(e.value);else throw new Ft(`Cannot parse dateTime: ${e}`);let n=new Date(t);if(isNaN(n.getTime()))throw new Ft(`Invalid dateTime format: ${t}`);return n.getTime()}evaluateFunction(e,t){let n;if(typeof e.function=="string")n=e.function.toLowerCase();else if(e.function&&typeof e.function=="object"&&"value"in e.function){let i=e.function.value;n=((i.includes("#")?i.split("#").pop():i.split("/").pop())||i).toLowerCase()}else throw new Ft(`Unknown function format: ${e.function}`);switch(n){case"str":let i=this.getTermFromExpression(e.args[0],t);return se.BuiltInFunctions.str(i);case"lang":let s=this.getTermFromExpression(e.args[0],t);return se.BuiltInFunctions.lang(s);case"datatype":let a=this.getTermFromExpression(e.args[0],t);return se.BuiltInFunctions.datatype(a).value;case"bound":if(e.args[0].type==="variable"){let U=t.get(e.args[0].name);return se.BuiltInFunctions.bound(U)}return!0;case"isiri":case"isuri":let c=this.getTermFromExpression(e.args[0],t);return se.BuiltInFunctions.isIRI(c);case"isblank":let u=this.getTermFromExpression(e.args[0],t);return se.BuiltInFunctions.isBlank(u);case"isliteral":let f=this.getTermFromExpression(e.args[0],t);return se.BuiltInFunctions.isLiteral(f);case"regex":let l=this.getStringValue(this.evaluateExpression(e.args[0],t)),h=this.getStringValue(this.evaluateExpression(e.args[1],t)),p=e.args[2]?this.getStringValue(this.evaluateExpression(e.args[2],t)):void 0;return se.BuiltInFunctions.regex(l,h,p);case"contains":let g=this.getStringValue(this.evaluateExpression(e.args[0],t)),b=this.getStringValue(this.evaluateExpression(e.args[1],t));return se.BuiltInFunctions.contains(g,b);case"strstarts":let v=this.getStringValue(this.evaluateExpression(e.args[0],t)),x=this.getStringValue(this.evaluateExpression(e.args[1],t));return se.BuiltInFunctions.strStarts(v,x);case"strends":let P=this.getStringValue(this.evaluateExpression(e.args[0],t)),F=this.getStringValue(this.evaluateExpression(e.args[1],t));return se.BuiltInFunctions.strEnds(P,F);case"strlen":let L=this.getStringValue(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.strlen(L);case"ucase":let $=this.getStringValue(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.ucase($);case"lcase":let Y=this.getStringValue(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.lcase(Y);case"substr":let Ce=this.getStringValue(this.evaluateExpression(e.args[0],t)),Ye=Number(this.evaluateExpression(e.args[1],t));if(e.args[2]){let U=Number(this.evaluateExpression(e.args[2],t));return se.BuiltInFunctions.substr(Ce,Ye,U)}return se.BuiltInFunctions.substr(Ce,Ye);case"strbefore":let ut=this.getStringValue(this.evaluateExpression(e.args[0],t)),B=this.getStringValue(this.evaluateExpression(e.args[1],t));return se.BuiltInFunctions.strBefore(ut,B);case"strafter":let ce=this.getStringValue(this.evaluateExpression(e.args[0],t)),xe=this.getStringValue(this.evaluateExpression(e.args[1],t));return se.BuiltInFunctions.strAfter(ce,xe);case"concat":let Ze=e.args.map(U=>this.getStringValue(this.evaluateExpression(U,t)));return se.BuiltInFunctions.concat(...Ze);case"replace":let $e=this.getStringValue(this.evaluateExpression(e.args[0],t)),He=this.getStringValue(this.evaluateExpression(e.args[1],t)),De=this.getStringValue(this.evaluateExpression(e.args[2],t)),Ne=e.args[3]?this.getStringValue(this.evaluateExpression(e.args[3],t)):void 0;return se.BuiltInFunctions.replace($e,He,De,Ne);case"parsedate":let Pe=this.getStringValue(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.parseDate(Pe);case"datebefore":let G=this.getStringValue(this.evaluateExpression(e.args[0],t)),R=this.getStringValue(this.evaluateExpression(e.args[1],t));return se.BuiltInFunctions.dateBefore(G,R);case"dateafter":let ke=this.getStringValue(this.evaluateExpression(e.args[0],t)),qe=this.getStringValue(this.evaluateExpression(e.args[1],t));return se.BuiltInFunctions.dateAfter(ke,qe);case"dateinrange":let j=this.getStringValue(this.evaluateExpression(e.args[0],t)),le=this.getStringValue(this.evaluateExpression(e.args[1],t)),Se=this.getStringValue(this.evaluateExpression(e.args[2],t));return se.BuiltInFunctions.dateInRange(j,le,Se);case"datediffminutes":let W=this.getStringValue(this.evaluateExpression(e.args[0],t)),be=this.getStringValue(this.evaluateExpression(e.args[1],t));return se.BuiltInFunctions.dateDiffMinutes(W,be);case"datediffhours":let we=this.getStringValue(this.evaluateExpression(e.args[0],t)),ge=this.getStringValue(this.evaluateExpression(e.args[1],t));return se.BuiltInFunctions.dateDiffHours(we,ge);case"year":let Ee=this.getStringValue(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.year(Ee);case"month":let ue=this.getStringValue(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.month(ue);case"day":let ye=this.getStringValue(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.day(ye);case"hours":let fe=this.getStringValue(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.hours(fe);case"minutes":let _e=this.getStringValue(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.minutes(_e);case"seconds":let Te=this.getStringValue(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.seconds(Te);case"timezone":case"tz":let J=this.getStringValue(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.timezone(J);case"now":return se.BuiltInFunctions.now();case"datetime":case"xsd:datetime":{let U=this.evaluateExpression(e.args[0],t);return se.BuiltInFunctions.xsdDateTime(this.getStringValue(U))}case"integer":case"xsd:integer":{let U=this.evaluateExpression(e.args[0],t);return se.BuiltInFunctions.xsdInteger(this.getStringValue(U))}case"decimal":case"xsd:decimal":{let U=this.evaluateExpression(e.args[0],t);return se.BuiltInFunctions.xsdDecimal(this.getStringValue(U))}case"mstominutes":let te=Number(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.msToMinutes(te);case"mstohours":let re=Number(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.msToHours(re);case"mstoseconds":let X=Number(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.msToSeconds(X);case"abs":let Z=Number(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.abs(Z);case"round":let ee=Number(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.round(ee);case"ceil":let Q=Number(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.ceil(Q);case"floor":let ne=Number(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.floor(ne);case"rand":return se.BuiltInFunctions.rand();case"coalesce":for(let U of e.args)try{let H=this.evaluateExpression(U,t);if(H!=null)return H}catch{continue}return;case"if":if(!e.args||e.args.length!==3)throw new Ft("IF requires exactly 3 arguments");let ie=this.evaluateExpression(e.args[0],t);return this.toBoolean(ie)?this.evaluateExpression(e.args[1],t):this.evaluateExpression(e.args[2],t);default:throw new Ft(`Unknown function: ${n}`)}}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 Cu.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 n=parseFloat(e.value);return!isNaN(n)&&n!==0}return e.value.length>0}return!!e}};qs.FilterExecutor=xp});var Cp=y(Fu=>{"use strict";Object.defineProperty(Fu,"__esModule",{value:!0});Fu.OptionalExecutor=void 0;var Op=class{static{o(this,"OptionalExecutor")}async*execute(e,t){let n=[];for await(let s of e)n.push(s);let i=[];for await(let s of t)i.push(s);for(let s of n){let a=!1;for(let c of i){let u=s.merge(c);u!==null&&(yield u,a=!0)}a||(yield s)}}async executeAll(e,t){let n=[];async function*i(){for(let a of e)yield a}o(i,"generateLeft");async function*s(){for(let a of t)yield a}o(s,"generateRight");for await(let a of this.execute(i(),s()))n.push(a);return n}};Fu.OptionalExecutor=Op});var Fp=y(Iu=>{"use strict";Object.defineProperty(Iu,"__esModule",{value:!0});Iu.UnionExecutor=void 0;var Pp=class{static{o(this,"UnionExecutor")}async*execute(e,t){let n=new Set;for await(let i of e){let s=this.getSolutionKey(i);n.has(s)||(n.add(s),yield i)}for await(let i of t){let s=this.getSolutionKey(i);n.has(s)||(n.add(s),yield i)}}async executeAll(e,t){let n=[];async function*i(){for(let a of e)yield a}o(i,"generateLeft");async function*s(){for(let a of t)yield a}o(s,"generateRight");for await(let a of this.execute(i(),s()))n.push(a);return n}getSolutionKey(e){let t=e.toJSON();return Object.keys(t).sort().map(i=>`${i}=${t[i]}`).join("|")}};Iu.UnionExecutor=Pp});var Dp=y(Du=>{"use strict";Object.defineProperty(Du,"__esModule",{value:!0});Du.ConstructExecutor=void 0;var v5=Vi(),Jg=pt(),S5=jt(),b5=Or(),Ip=class{static{o(this,"ConstructExecutor")}async execute(e,t){let n=[],i=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()}`;i.has(u)||(i.add(u),n.push(c))}catch{continue}return n}instantiateTriple(e,t){if(this.isPropertyPath(e.predicate))throw new Error("Property paths are not supported in CONSTRUCT templates");let n=this.instantiateElement(e.subject,t),i=this.instantiateElement(e.predicate,t),s=this.instantiateElement(e.object,t);return new v5.Triple(n,i,s)}isPropertyPath(e){return e.type==="path"}instantiateElement(e,t){if(e.type==="variable"){let n=t.get(e.value);if(!n)throw new Error(`Unbound variable: ${e.value}`);return n}if(e.type==="iri")return new Jg.IRI(e.value);if(e.type==="literal")return new S5.Literal(e.value,e.datatype?new Jg.IRI(e.datatype):void 0,e.language);if(e.type==="blank")return new b5.BlankNode(e.value);throw new Error(`Unknown element type: ${e.type}`)}};Du.ConstructExecutor=Ip});var Xg=y(Ru=>{"use strict";Object.defineProperty(Ru,"__esModule",{value:!0});Ru.DescribeExecutor=void 0;var w5=pt(),Rp=class{static{o(this,"DescribeExecutor")}constructor(e){this.tripleStore=e}async execute(e){let t=[],n=new Set;for(let i of e){let s=await this.describeResource(i);for(let a of s){let c=`${a.subject.toString()}|${a.predicate.toString()}|${a.object.toString()}`;n.has(c)||(n.add(c),t.push(a))}}return t}async describeResource(e){let t=[],n=await this.tripleStore.match(e,void 0,void 0);t.push(...n);let i=await this.tripleStore.match(void 0,void 0,e);return t.push(...i),t}async describeByIRI(e){let t=new w5.IRI(e);return this.execute([t])}};Ru.DescribeExecutor=Rp});var Zg=y(Nu=>{"use strict";Object.defineProperty(Nu,"__esModule",{value:!0});Nu.MinusExecutor=void 0;var Np=class{static{o(this,"MinusExecutor")}async*execute(e,t){let n=[];for await(let s of e)n.push(s);let i=[];for await(let s of t)i.push(s);for(let s of n){let a=!1;for(let c of i)if(this.areCompatible(s,c)){a=!0;break}a||(yield s)}}async executeAll(e,t){let n=[];async function*i(){for(let a of e)yield a}o(i,"generateLeft");async function*s(){for(let a of t)yield a}o(s,"generateRight");for await(let a of this.execute(i(),s()))n.push(a);return n}areCompatible(e,t){let n=e.variables(),i=new Set(t.variables()),s=n.filter(a=>i.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}};Nu.MinusExecutor=Np});var ty=y(Bs=>{"use strict";Object.defineProperty(Bs,"__esModule",{value:!0});Bs.ValuesExecutor=Bs.ValuesExecutorError=void 0;var E5=ns(),ey=pt(),T5=jt(),ku=class extends Error{static{o(this,"ValuesExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="ValuesExecutorError"}};Bs.ValuesExecutorError=ku;var kp=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 n of this.execute(e))t.push(n);return t}createSolutionMapping(e){let t=new E5.SolutionMapping;for(let[n,i]of Object.entries(e)){let s=this.toRDFTerm(i);t.set(n,s)}return t}toRDFTerm(e){if(e.type==="iri")return new ey.IRI(e.value);if(e.type==="literal")return new T5.Literal(e.value,e.datatype?new ey.IRI(e.datatype):void 0,e.language);throw new ku(`Unknown term type: ${e.type}`)}};Bs.ValuesExecutor=kp});var ny=y(Us=>{"use strict";Object.defineProperty(Us,"__esModule",{value:!0});Us.AggregateExecutor=Us.AggregateExecutorError=void 0;var dr=jt(),Mp=pt(),A5=Pu(),ry=new Mp.IRI("http://www.w3.org/2001/XMLSchema#integer"),Qa=new Mp.IRI("http://www.w3.org/2001/XMLSchema#decimal"),is=new Mp.IRI("http://www.w3.org/2001/XMLSchema#string"),ju=class extends Error{static{o(this,"AggregateExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="AggregateExecutorError"}};Us.AggregateExecutorError=ju;var jp=class{static{o(this,"AggregateExecutor")}constructor(){this.filterExecutor=new A5.FilterExecutor}execute(e,t){let n=this.groupSolutions(t,e.variables),i=[];for(let[s,a]of n.entries()){let c=new Map;for(let l of e.variables)if(a.length>0){let h=a[0].get(l);h&&c.set(l,h)}for(let l of e.aggregates){let h=this.computeAggregate(l.expression,a);c.set(l.variable,h)}let{SolutionMapping:u}=ns(),f=new u;for(let[l,h]of c.entries())f.set(l,h);i.push(f)}if(i.length===0&&e.aggregates.length>0){let s=this.createEmptyAggregateResult(e);s&&i.push(s)}return i}groupSolutions(e,t){let n=new Map;if(t.length===0)return n.set("",e),n;for(let i of e){let s=this.computeGroupKey(i,t),a=n.get(s);a?a.push(i):n.set(s,[i])}return n}computeGroupKey(e,t){return t.map(n=>{let i=e.get(n);return i?this.termToString(i):""}).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){let n=this.extractValues(e,t);switch(e.aggregation){case"count":{let i=this.computeCount(n,e.distinct);return new dr.Literal(String(i),ry)}case"sum":{let i=this.computeSum(n);return new dr.Literal(String(i),Qa)}case"avg":{let i=this.computeAvg(n);return new dr.Literal(String(i),Qa)}case"min":{let i=this.computeMin(n);return i===void 0?new dr.Literal("",is):typeof i=="number"?new dr.Literal(String(i),Qa):new dr.Literal(String(i),is)}case"max":{let i=this.computeMax(n);return i===void 0?new dr.Literal("",is):typeof i=="number"?new dr.Literal(String(i),Qa):new dr.Literal(String(i),is)}case"group_concat":{let i=this.computeGroupConcat(n,e.separator||" ",e.distinct);return new dr.Literal(i||" ",is)}default:throw new ju(`Unknown aggregation function: ${e.aggregation}`)}}extractValues(e,t){if(!e.expression)return t.map(()=>1);let n=[];for(let i of t){let s=this.evaluateExpression(e.expression,i);s!=null&&n.push(s)}return n}evaluateExpression(e,t){if(e.type==="variable"){let n=t.get(e.name);return n==null?void 0:typeof n=="number"||typeof n=="string"||typeof n=="boolean"?n:typeof n=="object"&&"value"in n?n.value:n}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(n=>String(n))).size:e.length}computeSum(e){return e.map(n=>parseFloat(String(n))).filter(n=>!isNaN(n)).reduce((n,i)=>n+i,0)}computeAvg(e){let t=e.map(n=>parseFloat(String(n))).filter(n=>!isNaN(n));return t.length===0?0:t.reduce((n,i)=>n+i,0)/t.length}computeMin(e){if(e.length===0)return;let t=e.map(i=>parseFloat(String(i))).filter(i=>!isNaN(i));if(t.length>0)return Math.min(...t);let n=e.map(i=>String(i));return n.reduce((i,s)=>s<i?s:i,n[0])}computeMax(e){if(e.length===0)return;let t=e.map(i=>parseFloat(String(i))).filter(i=>!isNaN(i));if(t.length>0)return Math.max(...t);let n=e.map(i=>String(i));return n.reduce((i,s)=>s>i?s:i,n[0])}computeGroupConcat(e,t,n){let i=e.map(s=>String(s));return n&&(i=[...new Set(i)]),i.join(t)}createEmptyAggregateResult(e){let{SolutionMapping:t}=ns(),n=new t;for(let i of e.aggregates)switch(i.expression.aggregation){case"count":n.set(i.variable,new dr.Literal("0",ry));break;case"sum":case"avg":n.set(i.variable,new dr.Literal("0",Qa));break;case"group_concat":n.set(i.variable,new dr.Literal(" ",is));break;default:n.set(i.variable,new dr.Literal("",is))}return n}};Us.AggregateExecutor=jp});var iy=y($s=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});$s.QueryExecutor=$s.QueryExecutorError=void 0;var x5=Ep(),O5=Pu(),C5=Cp(),P5=Fp(),F5=Zg(),I5=ty(),D5=ny(),R5=Dp(),Ja=class extends Error{static{o(this,"QueryExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="QueryExecutorError"}};$s.QueryExecutorError=Ja;var Lp=class{static{o(this,"QueryExecutor")}constructor(e){this.bgpExecutor=new x5.BGPExecutor(e),this.filterExecutor=new O5.FilterExecutor,this.optionalExecutor=new C5.OptionalExecutor,this.unionExecutor=new P5.UnionExecutor,this.minusExecutor=new F5.MinusExecutor,this.valuesExecutor=new I5.ValuesExecutor,this.aggregateExecutor=new D5.AggregateExecutor,this.constructExecutor=new R5.ConstructExecutor,this.filterExecutor.setExistsEvaluator(async(t,n)=>this.evaluateExistsPattern(t,n))}async evaluateExistsPattern(e,t){for await(let n of this.execute(e))if(t.merge(n)!==null)return!0;return!1}async executeAll(e){let t=[];for await(let n of this.execute(e))t.push(n);return t}async*execute(e){switch(e.type){case"bgp":yield*this.executeBGP(e);break;case"filter":yield*this.executeFilter(e);break;case"join":yield*this.executeJoin(e);break;case"leftjoin":yield*this.executeLeftJoin(e);break;case"union":yield*this.executeUnion(e);break;case"minus":yield*this.executeMinus(e);break;case"values":yield*this.executeValues(e);break;case"project":yield*this.executeProject(e);break;case"orderby":yield*this.executeOrderBy(e);break;case"slice":yield*this.executeSlice(e);break;case"distinct":yield*this.executeDistinct(e);break;case"group":yield*this.executeGroup(e);break;case"extend":yield*this.executeExtend(e);break;case"subquery":yield*this.executeSubquery(e);break;default:throw new Ja(`Unknown operation type: ${e.type}`)}}async*executeBGP(e){yield*this.bgpExecutor.execute(e)}async*executeFilter(e){let t=this.execute(e.input);yield*this.filterExecutor.execute(e,t)}async*executeJoin(e){let t=[];for await(let n of this.execute(e.left))t.push(n);for(let n of t)for await(let i of this.execute(e.right)){let s=n.merge(i);s!==null&&(yield s)}}async*executeLeftJoin(e){let t=[];for await(let a of this.execute(e.left))t.push(a);let n=[];for await(let a of this.execute(e.right))n.push(a);async function*i(){for(let a of t)yield a}o(i,"leftGen");async function*s(){for(let a of n)yield a}o(s,"rightGen"),yield*this.optionalExecutor.execute(i(),s())}async*executeUnion(e){let t=[];for await(let a of this.execute(e.left))t.push(a);let n=[];for await(let a of this.execute(e.right))n.push(a);async function*i(){for(let a of t)yield a}o(i,"leftGen");async function*s(){for(let a of n)yield a}o(s,"rightGen"),yield*this.unionExecutor.execute(i(),s())}async*executeMinus(e){let t=[];for await(let a of this.execute(e.left))t.push(a);let n=[];for await(let a of this.execute(e.right))n.push(a);async function*i(){for(let a of t)yield a}o(i,"leftGen");async function*s(){for(let a of n)yield a}o(s,"rightGen"),yield*this.minusExecutor.execute(i(),s())}async*executeValues(e){yield*this.valuesExecutor.execute(e)}async*executeProject(e){for await(let t of this.execute(e.input))yield t}async*executeOrderBy(e){let t=[];for await(let n of this.execute(e.input))t.push(n);t.sort((n,i)=>{for(let s of e.comparators){let a=this.getExpressionValue(s.expression,n),c=this.getExpressionValue(s.expression,i),u=0;if(a===void 0&&c===void 0?u=0:a===void 0?u=1:c===void 0?u=-1:typeof a=="number"&&typeof c=="number"?u=a-c:u=String(a).localeCompare(String(c)),s.descending&&(u=-u),u!==0)return u}return 0});for(let n of t)yield n}async*executeSlice(e){let t=0,n=e.offset??0,i=e.limit;for await(let s of this.execute(e.input)){if(t>=n){if(i!==void 0&&t-n>=i)break;yield s}t++}}async*executeDistinct(e){let t=new Set;for await(let n of this.execute(e.input)){let i=this.getSolutionKey(n);t.has(i)||(t.add(i),yield n)}}async*executeGroup(e){let t=[];for await(let i of this.execute(e.input))t.push(i);let n=this.aggregateExecutor.execute(e,t);for(let i of n)yield i}async*executeExtend(e){for await(let t of this.execute(e.input)){let n=t.clone(),i=this.evaluateExtendExpression(e.expression,t);i!==void 0&&n.set(e.variable,i),yield n}}async*executeSubquery(e){yield*this.execute(e.query)}evaluateExtendExpression(e,t){if(e.type!=="aggregate")try{return this.filterExecutor.evaluateExpression(e,t)}catch{return}}getExpressionValue(e,t){if(e.type==="variable"){let n=t.get(e.name);return n?n.value??n.id??String(n):void 0}return e.value}getSolutionKey(e){let t=e.toJSON();return Object.keys(t).sort().map(i=>`${i}=${t[i]}`).join("|")}isConstructQuery(e){return e.type==="construct"}async executeConstruct(e){if(e.type!=="construct")throw new Ja("executeConstruct requires a CONSTRUCT operation");let t=await this.executeAll(e.where);return this.constructExecutor.execute(e.template,t)}};$s.QueryExecutor=Lp});var ay=y(Mu=>{"use strict";Object.defineProperty(Mu,"__esModule",{value:!0});Mu.AggregateFunctions=void 0;var Vp=jt(),sy=pt(),qp=class{static{o(this,"AggregateFunctions")}static count(e,t){if(!t)return e.length;let n=0;for(let i of e)i.has(t)&&n++;return n}static countDistinct(e,t){let n=new Set;for(let i of e){let s=i.get(t);s&&n.add(s.toString())}return n.size}static sum(e,t){let n=0;for(let i of e){let s=i.get(t);if(s instanceof Vp.Literal){let a=this.toNumber(s);isNaN(a)||(n+=a)}}return n}static avg(e,t){let n=this.sum(e,t),i=this.count(e,t);return i>0?n/i:0}static min(e,t){let n=null;for(let i of e){let s=i.get(t);if(!s)continue;let a=this.toComparable(s);(n===null||a<n)&&(n=a)}return n}static max(e,t){let n=null;for(let i of e){let s=i.get(t);if(!s)continue;let a=this.toComparable(s);(n===null||a>n)&&(n=a)}return n}static groupConcat(e,t,n=" "){let i=[];for(let s of e){let a=s.get(t);a&&(a instanceof Vp.Literal||a instanceof sy.IRI?i.push(a.value):i.push(a.toString()))}return i.join(n)}static toNumber(e){let t=e.datatype?.value;return t?.includes("#integer")||t?.includes("#decimal")||t?.includes("#double"),parseFloat(e.value)}static toComparable(e){if(e instanceof Vp.Literal){let t=this.toNumber(e);return isNaN(t)?e.value:t}return e instanceof sy.IRI?e.value:String(e)}};Mu.AggregateFunctions=qp});var oy=y(Lu=>{"use strict";Object.defineProperty(Lu,"__esModule",{value:!0});Lu.QueryPlanCache=void 0;var N5=Qd(),Bp=class{static{o(this,"QueryPlanCache")}constructor(e=100){this.hits=0,this.misses=0,this.cache=new N5.LRUCache(e)}get(e){let t=this.normalizeQuery(e),n=this.cache.get(t);return n!==void 0?this.hits++:this.misses++,n}set(e,t){let n=this.normalizeQuery(e);this.cache.set(n,t)}has(e){let t=this.normalizeQuery(e);return this.cache.get(t)!==void 0}clear(){this.cache.clear()}getStats(){let e=this.hits+this.misses;return{hits:this.hits,misses:this.misses,hitRate:e>0?this.hits/e:0,size:this.cache.size()}}resetStats(){this.hits=0,this.misses=0}normalizeQuery(e){return e.replace(/\s+/g," ").trim()}};Lu.QueryPlanCache=Bp});var cy=y(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});Ws.FileAlreadyExistsError=Ws.FileNotFoundError=void 0;var Up=class extends Error{static{o(this,"FileNotFoundError")}constructor(e){super(`File not found: ${e}`),this.name="FileNotFoundError"}};Ws.FileNotFoundError=Up;var $p=class extends Error{static{o(this,"FileAlreadyExistsError")}constructor(e){super(`File already exists: ${e}`),this.name="FileAlreadyExistsError"}};Ws.FileAlreadyExistsError=$p});var uy=y(gi=>{"use strict";Object.defineProperty(gi,"__esModule",{value:!0});gi.container=void 0;gi.registerCoreServices=sO;gi.createChildContainer=aO;gi.getContainer=oO;gi.resetContainer=cO;uf();var Xa=Ke();Object.defineProperty(gi,"container",{enumerable:!0,get:o(function(){return Xa.container},"get")});var et=rt(),k5=Kh(),j5=Gc(),M5=xd(),L5=Hc(),V5=_d(),q5=Qh(),B5=rd(),U5=ed(),$5=Jc(),W5=Xc(),G5=hd(),H5=pd(),z5=Sd(),K5=ld(),Y5=Cd(),Q5=Dd(),J5=Fd(),X5=ad(),Z5=cd(),eO=Td(),tO=wd(),rO=tp(),nO=id(),iO=Nd();function sO(r){let e=r||Xa.container;e.registerSingleton(et.DI_TOKENS.TaskFrontmatterGenerator,j5.TaskFrontmatterGenerator),e.registerSingleton(et.DI_TOKENS.DynamicFrontmatterGenerator,M5.DynamicFrontmatterGenerator),e.registerSingleton(et.DI_TOKENS.AlgorithmExtractor,L5.AlgorithmExtractor),e.registerSingleton(et.DI_TOKENS.EffortStatusWorkflow,$5.EffortStatusWorkflow),e.registerSingleton(et.DI_TOKENS.StatusTimestampService,W5.StatusTimestampService),e.registerSingleton(et.DI_TOKENS.TaskStatusService,U5.TaskStatusService),e.registerSingleton(et.DI_TOKENS.TaskCreationService,k5.TaskCreationService),e.registerSingleton(et.DI_TOKENS.ProjectCreationService,q5.ProjectCreationService),e.registerSingleton(et.DI_TOKENS.AreaCreationService,B5.AreaCreationService),e.registerSingleton(et.DI_TOKENS.ClassCreationService,X5.ClassCreationService),e.registerSingleton(et.DI_TOKENS.ConceptCreationService,Z5.ConceptCreationService),e.registerSingleton(et.DI_TOKENS.FleetingNoteCreationService,eO.FleetingNoteCreationService),e.registerSingleton(et.DI_TOKENS.SupervisionCreationService,tO.SupervisionCreationService),e.registerSingleton(et.DI_TOKENS.PropertyCleanupService,V5.PropertyCleanupService),e.registerSingleton(et.DI_TOKENS.FolderRepairService,G5.FolderRepairService),e.registerSingleton(et.DI_TOKENS.LabelToAliasService,H5.LabelToAliasService),e.registerSingleton(et.DI_TOKENS.RenameToUidService,z5.RenameToUidService),e.registerSingleton(et.DI_TOKENS.PlanningService,Y5.PlanningService),e.registerSingleton(et.DI_TOKENS.EffortVotingService,K5.EffortVotingService),e.registerSingleton(et.DI_TOKENS.SessionEventService,Q5.SessionEventService),e.registerSingleton(et.DI_TOKENS.AssetConversionService,J5.AssetConversionService),e.registerSingleton(et.DI_TOKENS.NoteToRDFConverter,rO.NoteToRDFConverter),e.registerSingleton(et.DI_TOKENS.AreaHierarchyBuilder,nO.AreaHierarchyBuilder),e.registerSingleton(et.DI_TOKENS.URIConstructionService,iO.URIConstructionService)}o(sO,"registerCoreServices");function aO(){return Xa.container.createChildContainer()}o(aO,"createChildContainer");function oO(){return Xa.container}o(oO,"getContainer");function cO(){Xa.container.reset()}o(cO,"resetContainer")});var An=y(Vu=>{"use strict";Object.defineProperty(Vu,"__esModule",{value:!0});Vu.ErrorCode=void 0;var ly;(function(r){r[r.INVALID_INPUT=1e3]="INVALID_INPUT",r[r.INVALID_FORMAT=1001]="INVALID_FORMAT",r[r.MISSING_REQUIRED_FIELD=1002]="MISSING_REQUIRED_FIELD",r[r.INVALID_SCHEMA=1003]="INVALID_SCHEMA",r[r.NETWORK_ERROR=2e3]="NETWORK_ERROR",r[r.REQUEST_TIMEOUT=2001]="REQUEST_TIMEOUT",r[r.CONNECTION_FAILED=2002]="CONNECTION_FAILED",r[r.FILE_READ_ERROR=2003]="FILE_READ_ERROR",r[r.FILE_WRITE_ERROR=2004]="FILE_WRITE_ERROR",r[r.INVALID_STATE=3e3]="INVALID_STATE",r[r.INVALID_TRANSITION=3001]="INVALID_TRANSITION",r[r.OPERATION_FAILED=3002]="OPERATION_FAILED",r[r.CONCURRENT_MODIFICATION=3003]="CONCURRENT_MODIFICATION",r[r.PERMISSION_DENIED=4e3]="PERMISSION_DENIED",r[r.UNAUTHORIZED=4001]="UNAUTHORIZED",r[r.FORBIDDEN=4003]="FORBIDDEN",r[r.NOT_FOUND=5e3]="NOT_FOUND",r[r.RESOURCE_EXHAUSTED=5001]="RESOURCE_EXHAUSTED",r[r.ALREADY_EXISTS=5002]="ALREADY_EXISTS",r[r.UNKNOWN_ERROR=9e3]="UNKNOWN_ERROR",r[r.INTERNAL_ERROR=9001]="INTERNAL_ERROR"})(ly||(Vu.ErrorCode=ly={}))});var xn=y(qu=>{"use strict";Object.defineProperty(qu,"__esModule",{value:!0});qu.ApplicationError=void 0;var Wp=class extends Error{static{o(this,"ApplicationError")}constructor(e,t){super(e),this.name=this.constructor.name,this.context=t,this.timestamp=new Date,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}format(){let e=`\u274C ${this.name}: ${this.message}`;if(this.guidance&&(e+=`
139
+ ${n})`;default:return`${n}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(n=>n.type==="path"?`(${this.propertyPathToString(n)})`:`<${n.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)}};Tu.AlgebraSerializer=_p});var ns=y(Au=>{"use strict";Object.defineProperty(Au,"__esModule",{value:!0});Au.SolutionMapping=void 0;var Wg=jt(),Gg=pt(),Hg=Or(),vp=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,n]of this.bindings.entries()){let i=e.get(t);if(i!==void 0&&!this.areEqual(n,i))return!1}return!0}merge(e){if(!this.isCompatibleWith(e))return null;let t=new r(this.bindings);for(let[n,i]of e.getBindings().entries())t.set(n,i);return t}clone(){return new r(this.bindings)}areEqual(e,t){return e instanceof Wg.Literal&&t instanceof Wg.Literal?e.equals(t):e instanceof Gg.IRI&&t instanceof Gg.IRI?e.value===t.value:e instanceof Hg.BlankNode&&t instanceof Hg.BlankNode?e.id===t.id:!1}toJSON(){let e={};for(let[t,n]of this.bindings.entries())e[t]=n.toString();return e}size(){return this.bindings.size}};Au.SolutionMapping=vp});var Kg=y(Ls=>{"use strict";Object.defineProperty(Ls,"__esModule",{value:!0});Ls.PropertyPathExecutor=Ls.PropertyPathExecutorError=void 0;var y5=ns(),xu=pt(),zg=Or(),za=class extends Error{static{o(this,"PropertyPathExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="PropertyPathExecutorError"}};Ls.PropertyPathExecutorError=za;var Sp=class{static{o(this,"PropertyPathExecutor")}constructor(e){this.tripleStore=e,this.MAX_DEPTH=100}async*execute(e,t,n){let i=await this.resolveElement(e),s=this.isVariable(n)?null:await this.resolveElement(n);for(let a of i){let c=await this.evaluatePath(a,t,s);for(let u of c){let f=new y5.SolutionMapping;this.isVariable(e)&&f.set(e.value,a),this.isVariable(n)&&f.set(n.value,u),yield f}}}async*executeWithBindings(e,t){if(!this.isPropertyPath(e.predicate))throw new za("Predicate is not a property path");let n=this.instantiateElement(e.subject,t),i=this.instantiateElement(e.object,t);for await(let s of this.execute(n,e.predicate,i)){let a=t.merge(s);a!==null&&(yield a)}}async evaluatePath(e,t,n){switch(t.pathType){case"/":return this.evaluateSequencePath(e,t.items,n);case"|":return this.evaluateAlternativePath(e,t.items,n);case"^":return this.evaluateInversePath(e,t.items[0],n);case"+":return this.evaluateOneOrMorePath(e,t.items[0],n);case"*":return this.evaluateZeroOrMorePath(e,t.items[0],n);case"?":return this.evaluateZeroOrOnePath(e,t.items[0],n)}}async evaluateSequencePath(e,t,n){let i=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 f of i){let l=await this.evaluatePathItem(f,a,c?n:null);for(let h of l)u.add(h)}if(i=u,i.size===0)break}return i}async evaluateAlternativePath(e,t,n){let i=new Set;for(let s of t){let a=await this.evaluatePathItem(e,s,n);for(let c of a)i.add(c)}return i}async evaluateInversePath(e,t,n){if(t.type==="iri"){let i=new xu.IRI(t.value),s=await this.tripleStore.match(void 0,i,e),a=new Set;for(let c of s)(n===null||this.nodeInSet(c.subject,n))&&a.add(c.subject);return a}else return this.evaluatePath(e,this.invertPath(t),n)}async evaluateOneOrMorePath(e,t,n){let i=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 f=await this.evaluatePathItem(c,t,null);for(let l of f){let h=this.nodeToKey(l);(n===null||this.nodeInSet(l,n))&&s.add(l),i.has(h)||(i.add(h),a.push({node:l,depth:u+1}))}}return s}async evaluateZeroOrMorePath(e,t,n){let i=await this.evaluateOneOrMorePath(e,t,n);return(n===null||this.nodeInSet(e,n))&&i.add(e),i}async evaluateZeroOrOnePath(e,t,n){let i=new Set;(n===null||this.nodeInSet(e,n))&&i.add(e);let s=await this.evaluatePathItem(e,t,n);for(let a of s)i.add(a);return i}async evaluatePathItem(e,t,n){if(t.type==="iri"){let i=new xu.IRI(t.value),s=await this.tripleStore.match(e,i,void 0),a=new Set;for(let c of s)(n===null||this.nodeInSet(c.object,n))&&a.add(c.object);return a}else return this.evaluatePath(e,t,n)}invertPath(e){switch(e.pathType){case"^":return e.items[0];case"/":return{type:"path",pathType:"/",items:[...e.items].reverse().map(n=>n.type==="iri"?{type:"path",pathType:"^",items:[n]}:this.invertPath(n))};case"|":return{type:"path",pathType:"|",items:e.items.map(n=>n.type==="iri"?{type:"path",pathType:"^",items:[n]}:this.invertPath(n))};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 n=new Set,i=await this.tripleStore.match(void 0,void 0,void 0);for(let s of i)n.add(s.subject),n.add(s.object);return n}let t=new Set;switch(e.type){case"iri":t.add(new xu.IRI(e.value));break;case"blank":t.add(new zg.BlankNode(e.value));break;default:throw new za(`Unsupported element type in subject/object position: ${e.type}`)}return t}instantiateElement(e,t){if(this.isVariable(e)){let n=t.get(e.value);if(n){if(n instanceof xu.IRI)return{type:"iri",value:n.value};if(n instanceof zg.BlankNode)return{type:"blank",value:n.id}}}return e}isVariable(e){return e.type==="variable"}isPropertyPath(e){return e.type==="path"}nodeToKey(e){return e.toString()}nodeInSet(e,t){let n=this.nodeToKey(e);for(let i of t)if(this.nodeToKey(i)===n)return!0;return!1}};Ls.PropertyPathExecutor=Sp});var Ep=y(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});Vs.BGPExecutor=Vs.BGPExecutorError=void 0;var Yg=ns(),Ka=pt(),Qg=jt(),bp=Or(),_5=Kg(),br=class extends Error{static{o(this,"BGPExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="BGPExecutorError"}};Vs.BGPExecutorError=br;var wp=class{static{o(this,"BGPExecutor")}constructor(e){this.tripleStore=e,this.propertyPathExecutor=new _5.PropertyPathExecutor(e)}async*execute(e){if(e.triples.length===0){yield new Yg.SolutionMapping;return}let t=this.matchTriplePattern(e.triples[0]);for(let n=1;n<e.triples.length;n++)t=this.joinWithPattern(t,e.triples[n]);for await(let n of t)yield n}async executeAll(e){let t=[];for await(let n of this.execute(e))t.push(n);return t}async*matchTriplePattern(e){if(this.isPropertyPath(e.predicate)){yield*this.propertyPathExecutor.execute(e.subject,e.predicate,e.object);return}let t=e.predicate,n=this.isVariable(e.subject)?void 0:this.toRDFTermAsSubject(e.subject),i=this.isVariable(t)?void 0:this.toRDFTermAsPredicate(t),s=this.isVariable(e.object)?void 0:this.toRDFTerm(e.object),a=await this.tripleStore.match(n,i,s);for(let c of a){let u=new Yg.SolutionMapping;this.isVariable(e.subject)&&u.set(e.subject.value,c.subject),this.isVariable(t)&&u.set(t.value,c.predicate),this.isVariable(e.object)&&u.set(e.object.value,c.object),yield u}}isPropertyPath(e){return e.type==="path"}async*joinWithPattern(e,t){let n=[];for await(let i of e)n.push(i);for(let i of n){let s=this.instantiatePattern(t,i);for await(let a of this.matchTriplePattern(s)){let c=i.merge(a);c!==null&&(yield c)}}}instantiatePattern(e,t){let n=this.isPropertyPath(e.predicate)?e.predicate:this.instantiateElement(e.predicate,t);return{subject:this.instantiateElement(e.subject,t),predicate:n,object:this.instantiateElement(e.object,t)}}instantiateElement(e,t){if(this.isVariable(e)){let n=t.get(e.value);if(n)return this.toAlgebraElement(n)}return e}isVariable(e){return e.type==="variable"}toRDFTermAsSubject(e){switch(e.type){case"iri":return new Ka.IRI(e.value);case"blank":return new bp.BlankNode(e.value);case"literal":throw new br("Literals cannot appear in subject position");case"variable":throw new br(`Cannot convert variable to RDF term: ${e.value}`);default:throw new br(`Unknown element type: ${e.type}`)}}toRDFTermAsPredicate(e){switch(e.type){case"iri":return new Ka.IRI(e.value);case"literal":throw new br("Literals cannot appear in predicate position");case"blank":throw new br("Blank nodes cannot appear in predicate position");case"variable":throw new br(`Cannot convert variable to RDF term: ${e.value}`);default:throw new br(`Unknown element type: ${e.type}`)}}toRDFTerm(e){switch(e.type){case"iri":return new Ka.IRI(e.value);case"literal":return new Qg.Literal(e.value,e.datatype?new Ka.IRI(e.datatype):void 0,e.language);case"blank":return new bp.BlankNode(e.value);case"variable":throw new br(`Cannot convert variable to RDF term: ${e.value}`);default:throw new br(`Unknown element type: ${e.type}`)}}toAlgebraElement(e){if(e instanceof Ka.IRI)return{type:"iri",value:e.value};if(e instanceof Qg.Literal)return{type:"literal",value:e.value,datatype:e.datatype?.value,language:e.language};if(e instanceof bp.BlankNode)return{type:"blank",value:e.id};throw new br(`Unknown RDF term type: ${e.constructor?.name||"unknown"}`)}};Vs.BGPExecutor=wp});var Ap=y(Ou=>{"use strict";Object.defineProperty(Ou,"__esModule",{value:!0});Ou.BuiltInFunctions=void 0;var Tn=pt(),sn=jt(),Ya=Or(),Tp=class{static{o(this,"BuiltInFunctions")}static str(e){if(e===void 0)throw new Error("STR: argument is undefined");return e instanceof Tn.IRI||e instanceof sn.Literal?e.value:e instanceof Ya.BlankNode?e.id:String(e)}static lang(e){if(e===void 0)throw new Error("LANG: argument is undefined");return e instanceof sn.Literal&&e.language?e.language:""}static datatype(e){if(e===void 0)throw new Error("DATATYPE: argument is undefined");if(e instanceof sn.Literal)return e.datatype?e.datatype:e.language?new Tn.IRI("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"):new Tn.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 Tn.IRI}static isBlank(e){return e===void 0?!1:e instanceof Ya.BlankNode}static isLiteral(e){return e===void 0?!1:e instanceof sn.Literal}static isNumeric(e){if(e===void 0||!(e instanceof sn.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,n){try{return new RegExp(t,n).test(e)}catch(i){throw new Error(`REGEX: invalid pattern '${t}': ${i.message}`)}}static compare(e,t,n){let i=this.toComparableValue(e),s=this.toComparableValue(t);switch(n){case"=":return i===s;case"!=":return i!==s;case"<":return i<s;case">":return i>s;case"<=":return i<=s;case">=":return i>=s;default:throw new Error(`Unknown comparison operator: ${n}`)}}static toComparableValue(e){if(typeof e=="string"||typeof e=="number")return e;if(e instanceof sn.Literal){let t=e.datatype?.value;if(t?.includes("#integer")||t?.includes("#decimal")||t?.includes("#double")){let n=parseFloat(e.value);if(!isNaN(n))return n}return e.value}return e instanceof Tn.IRI?e.value:e instanceof Ya.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,n){let i=t-1;if(i<0){if(n!==void 0){let s=n+i;return s<=0?"":e.substring(0,s)}return e}return n!==void 0?e.substring(i,i+n):e.substring(i)}static strBefore(e,t){if(t==="")return"";let n=e.indexOf(t);return n===-1?"":e.substring(0,n)}static strAfter(e,t){if(t==="")return e;let n=e.indexOf(t);return n===-1?"":e.substring(n+t.length)}static concat(...e){return e.join("")}static replace(e,t,n,i){try{let s=new RegExp(t,i||"g");return e.replace(s,n)}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 n=this.parseDate(e),i=this.parseDate(t);return n<i}static dateAfter(e,t){let n=this.parseDate(e),i=this.parseDate(t);return n>i}static dateInRange(e,t,n){let i=this.parseDate(e),s=this.parseDate(t),a=this.parseDate(n);return i>=s&&i<=a}static dateDiffMinutes(e,t){let n=this.parseDate(e),i=this.parseDate(t),s=Math.abs(i-n);return Math.round(s/(1e3*60))}static dateDiffHours(e,t){let n=this.parseDate(e),i=this.parseDate(t),s=Math.abs(i-n);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}'`);if(e.endsWith("Z"))return"PT0S";let n=e.match(/([+-]\d{2}):?(\d{2})$/);if(n){let u=parseInt(n[1],10),f=parseInt(n[2],10),l=u>=0?"":"-",h=Math.abs(u);return f===0?`${l}PT${h}H`:`${l}PT${h}H${f}M`}let i=-t.getTimezoneOffset(),s=Math.floor(Math.abs(i)/60),a=Math.abs(i)%60,c=i>=0?"":"-";return a===0?`${c}PT${s}H`:`${c}PT${s}H${a}M`}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,n){return e?t:n}static xsdDateTime(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`xsd:dateTime: invalid date string '${e}'`);return new sn.Literal(t.toISOString(),new Tn.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 sn.Literal(String(t),new Tn.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 sn.Literal(String(t),new Tn.IRI("http://www.w3.org/2001/XMLSchema#decimal"))}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 Tn.IRI&&t instanceof Tn.IRI)return e.value===t.value;if(e instanceof Ya.BlankNode&&t instanceof Ya.BlankNode)return e.id===t.id;if(e instanceof sn.Literal&&t instanceof sn.Literal){if(e.value!==t.value||e.language!==t.language)return!1;let n=e.datatype?.value,i=t.datatype?.value;return n===i}return!1}};Ou.BuiltInFunctions=Tp});var Pu=y(qs=>{"use strict";Object.defineProperty(qs,"__esModule",{value:!0});qs.FilterExecutor=qs.FilterExecutorError=void 0;var se=Ap(),Cu=jt(),Ft=class extends Error{static{o(this,"FilterExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="FilterExecutorError"}};qs.FilterExecutorError=Ft;var xp=class{static{o(this,"FilterExecutor")}constructor(){this.existsEvaluator=null}setExistsEvaluator(e){this.existsEvaluator=e}async*execute(e,t){let n=this.expressionContainsExists(e.expression);for await(let i of t)try{let s;n?s=await this.evaluateExpressionAsync(e.expression,i):s=this.evaluateExpression(e.expression,i),s===!0&&(yield i)}catch{continue}}expressionContainsExists(e){return e.type==="exists"?!0:e.type==="logical"?e.operands.some(t=>this.expressionContainsExists(t)):e.type==="comparison"?this.expressionContainsExists(e.left)||this.expressionContainsExists(e.right):!1}async executeAll(e,t){let n=[];async function*i(){for(let s of t)yield s}o(i,"generator");for await(let s of this.execute(e,i()))n.push(s);return n}evaluateExpression(e,t){let n=e;if(n.termType)switch(n.termType){case"Variable":return t.get(n.value);case"Literal":return n.value;case"NamedNode":return n.value;default:throw new Ft(`Unsupported termType: ${n.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"exists":throw new Ft("EXISTS expressions require async evaluation. Use evaluateExpressionAsync instead.");default:throw new Ft(`Unsupported expression type: ${e.type}, expr.termType=${n.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 Ft("EXISTS evaluator not set. Call setExistsEvaluator before evaluating EXISTS expressions.");let n=await this.existsEvaluator(e.pattern,t);return e.negated?!n:n}async evaluateLogicalAsync(e,t){if(e.operator==="!"){let i=await this.evaluateExpressionAsync(e.operands[0],t);return se.BuiltInFunctions.logicalNot(i)}let n=[];for(let i of e.operands){let s=await this.evaluateExpressionAsync(i,t);n.push(s)}if(e.operator==="&&")return se.BuiltInFunctions.logicalAnd(n);if(e.operator==="||")return se.BuiltInFunctions.logicalOr(n);throw new Ft(`Unknown logical operator: ${e.operator}`)}evaluateComparison(e,t){let n=this.evaluateExpression(e.left,t),i=this.evaluateExpression(e.right,t);return se.BuiltInFunctions.compare(n,i,e.operator)}evaluateLogical(e,t){if(e.operator==="!"){let i=this.evaluateExpression(e.operands[0],t);return se.BuiltInFunctions.logicalNot(i)}let n=e.operands.map(i=>this.evaluateExpression(i,t));if(e.operator==="&&")return se.BuiltInFunctions.logicalAnd(n);if(e.operator==="||")return se.BuiltInFunctions.logicalOr(n);throw new Ft(`Unknown logical operator: ${e.operator}`)}evaluateArithmetic(e,t){let n=this.evaluateExpression(e.left,t),i=this.evaluateExpression(e.right,t),s=this.toNumericValue(n),a=this.toNumericValue(i);if(e.operator==="-"&&this.isDateTimeValue(n)&&this.isDateTimeValue(i)){let c=this.parseDateTimeToMs(n),u=this.parseDateTimeToMs(i);return c-u}switch(e.operator){case"+":return s+a;case"-":return s-a;case"*":return s*a;case"/":if(a===0)throw new Ft("Division by zero");return s/a;default:throw new Ft(`Unknown arithmetic operator: ${e.operator}`)}}toNumericValue(e){if(typeof e=="number")return e;if(e instanceof Cu.Literal){let t=e.datatype?.value||"";if(t.includes("#integer")||t.includes("#decimal")||t.includes("#double")||t.includes("#float")){let i=parseFloat(e.value);if(!isNaN(i))return i}let n=parseFloat(e.value);if(!isNaN(n))return n}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 Ft(`Cannot convert to number: ${e}`)}isDateTimeValue(e){if(e instanceof Cu.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}parseDateTimeToMs(e){let t;if(e instanceof Cu.Literal)t=e.value;else if(typeof e=="string")t=e;else if(e&&typeof e=="object"&&"value"in e)t=String(e.value);else throw new Ft(`Cannot parse dateTime: ${e}`);let n=new Date(t);if(isNaN(n.getTime()))throw new Ft(`Invalid dateTime format: ${t}`);return n.getTime()}evaluateFunction(e,t){let n;if(typeof e.function=="string")n=e.function.toLowerCase();else if(e.function&&typeof e.function=="object"&&"value"in e.function){let i=e.function.value;n=((i.includes("#")?i.split("#").pop():i.split("/").pop())||i).toLowerCase()}else throw new Ft(`Unknown function format: ${e.function}`);switch(n){case"str":let i=this.getTermFromExpression(e.args[0],t);return se.BuiltInFunctions.str(i);case"lang":let s=this.getTermFromExpression(e.args[0],t);return se.BuiltInFunctions.lang(s);case"datatype":let a=this.getTermFromExpression(e.args[0],t);return se.BuiltInFunctions.datatype(a).value;case"bound":if(e.args[0].type==="variable"){let U=t.get(e.args[0].name);return se.BuiltInFunctions.bound(U)}return!0;case"isiri":case"isuri":let c=this.getTermFromExpression(e.args[0],t);return se.BuiltInFunctions.isIRI(c);case"isblank":let u=this.getTermFromExpression(e.args[0],t);return se.BuiltInFunctions.isBlank(u);case"isliteral":let f=this.getTermFromExpression(e.args[0],t);return se.BuiltInFunctions.isLiteral(f);case"regex":let l=this.getStringValue(this.evaluateExpression(e.args[0],t)),h=this.getStringValue(this.evaluateExpression(e.args[1],t)),p=e.args[2]?this.getStringValue(this.evaluateExpression(e.args[2],t)):void 0;return se.BuiltInFunctions.regex(l,h,p);case"contains":let g=this.getStringValue(this.evaluateExpression(e.args[0],t)),b=this.getStringValue(this.evaluateExpression(e.args[1],t));return se.BuiltInFunctions.contains(g,b);case"strstarts":let v=this.getStringValue(this.evaluateExpression(e.args[0],t)),x=this.getStringValue(this.evaluateExpression(e.args[1],t));return se.BuiltInFunctions.strStarts(v,x);case"strends":let P=this.getStringValue(this.evaluateExpression(e.args[0],t)),F=this.getStringValue(this.evaluateExpression(e.args[1],t));return se.BuiltInFunctions.strEnds(P,F);case"strlen":let L=this.getStringValue(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.strlen(L);case"ucase":let $=this.getStringValue(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.ucase($);case"lcase":let Y=this.getStringValue(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.lcase(Y);case"substr":let Ce=this.getStringValue(this.evaluateExpression(e.args[0],t)),Ye=Number(this.evaluateExpression(e.args[1],t));if(e.args[2]){let U=Number(this.evaluateExpression(e.args[2],t));return se.BuiltInFunctions.substr(Ce,Ye,U)}return se.BuiltInFunctions.substr(Ce,Ye);case"strbefore":let ut=this.getStringValue(this.evaluateExpression(e.args[0],t)),B=this.getStringValue(this.evaluateExpression(e.args[1],t));return se.BuiltInFunctions.strBefore(ut,B);case"strafter":let ce=this.getStringValue(this.evaluateExpression(e.args[0],t)),xe=this.getStringValue(this.evaluateExpression(e.args[1],t));return se.BuiltInFunctions.strAfter(ce,xe);case"concat":let Ze=e.args.map(U=>this.getStringValue(this.evaluateExpression(U,t)));return se.BuiltInFunctions.concat(...Ze);case"replace":let $e=this.getStringValue(this.evaluateExpression(e.args[0],t)),He=this.getStringValue(this.evaluateExpression(e.args[1],t)),De=this.getStringValue(this.evaluateExpression(e.args[2],t)),Ne=e.args[3]?this.getStringValue(this.evaluateExpression(e.args[3],t)):void 0;return se.BuiltInFunctions.replace($e,He,De,Ne);case"parsedate":let Pe=this.getStringValue(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.parseDate(Pe);case"datebefore":let G=this.getStringValue(this.evaluateExpression(e.args[0],t)),R=this.getStringValue(this.evaluateExpression(e.args[1],t));return se.BuiltInFunctions.dateBefore(G,R);case"dateafter":let ke=this.getStringValue(this.evaluateExpression(e.args[0],t)),qe=this.getStringValue(this.evaluateExpression(e.args[1],t));return se.BuiltInFunctions.dateAfter(ke,qe);case"dateinrange":let j=this.getStringValue(this.evaluateExpression(e.args[0],t)),le=this.getStringValue(this.evaluateExpression(e.args[1],t)),Se=this.getStringValue(this.evaluateExpression(e.args[2],t));return se.BuiltInFunctions.dateInRange(j,le,Se);case"datediffminutes":let W=this.getStringValue(this.evaluateExpression(e.args[0],t)),be=this.getStringValue(this.evaluateExpression(e.args[1],t));return se.BuiltInFunctions.dateDiffMinutes(W,be);case"datediffhours":let we=this.getStringValue(this.evaluateExpression(e.args[0],t)),ge=this.getStringValue(this.evaluateExpression(e.args[1],t));return se.BuiltInFunctions.dateDiffHours(we,ge);case"year":let Ee=this.getStringValue(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.year(Ee);case"month":let ue=this.getStringValue(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.month(ue);case"day":let ye=this.getStringValue(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.day(ye);case"hours":let fe=this.getStringValue(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.hours(fe);case"minutes":let _e=this.getStringValue(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.minutes(_e);case"seconds":let Te=this.getStringValue(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.seconds(Te);case"timezone":case"tz":let J=this.getStringValue(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.timezone(J);case"now":return se.BuiltInFunctions.now();case"datetime":case"xsd:datetime":{let U=this.evaluateExpression(e.args[0],t);return se.BuiltInFunctions.xsdDateTime(this.getStringValue(U))}case"integer":case"xsd:integer":{let U=this.evaluateExpression(e.args[0],t);return se.BuiltInFunctions.xsdInteger(this.getStringValue(U))}case"decimal":case"xsd:decimal":{let U=this.evaluateExpression(e.args[0],t);return se.BuiltInFunctions.xsdDecimal(this.getStringValue(U))}case"mstominutes":let te=Number(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.msToMinutes(te);case"mstohours":let re=Number(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.msToHours(re);case"mstoseconds":let X=Number(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.msToSeconds(X);case"abs":let Z=Number(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.abs(Z);case"round":let ee=Number(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.round(ee);case"ceil":let Q=Number(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.ceil(Q);case"floor":let ne=Number(this.evaluateExpression(e.args[0],t));return se.BuiltInFunctions.floor(ne);case"rand":return se.BuiltInFunctions.rand();case"coalesce":for(let U of e.args)try{let H=this.evaluateExpression(U,t);if(H!=null)return H}catch{continue}return;case"if":if(!e.args||e.args.length!==3)throw new Ft("IF requires exactly 3 arguments");let ie=this.evaluateExpression(e.args[0],t);return this.toBoolean(ie)?this.evaluateExpression(e.args[1],t):this.evaluateExpression(e.args[2],t);default:throw new Ft(`Unknown function: ${n}`)}}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 Cu.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 n=parseFloat(e.value);return!isNaN(n)&&n!==0}return e.value.length>0}return!!e}};qs.FilterExecutor=xp});var Cp=y(Fu=>{"use strict";Object.defineProperty(Fu,"__esModule",{value:!0});Fu.OptionalExecutor=void 0;var Op=class{static{o(this,"OptionalExecutor")}async*execute(e,t){let n=[];for await(let s of e)n.push(s);let i=[];for await(let s of t)i.push(s);for(let s of n){let a=!1;for(let c of i){let u=s.merge(c);u!==null&&(yield u,a=!0)}a||(yield s)}}async executeAll(e,t){let n=[];async function*i(){for(let a of e)yield a}o(i,"generateLeft");async function*s(){for(let a of t)yield a}o(s,"generateRight");for await(let a of this.execute(i(),s()))n.push(a);return n}};Fu.OptionalExecutor=Op});var Fp=y(Iu=>{"use strict";Object.defineProperty(Iu,"__esModule",{value:!0});Iu.UnionExecutor=void 0;var Pp=class{static{o(this,"UnionExecutor")}async*execute(e,t){let n=new Set;for await(let i of e){let s=this.getSolutionKey(i);n.has(s)||(n.add(s),yield i)}for await(let i of t){let s=this.getSolutionKey(i);n.has(s)||(n.add(s),yield i)}}async executeAll(e,t){let n=[];async function*i(){for(let a of e)yield a}o(i,"generateLeft");async function*s(){for(let a of t)yield a}o(s,"generateRight");for await(let a of this.execute(i(),s()))n.push(a);return n}getSolutionKey(e){let t=e.toJSON();return Object.keys(t).sort().map(i=>`${i}=${t[i]}`).join("|")}};Iu.UnionExecutor=Pp});var Dp=y(Du=>{"use strict";Object.defineProperty(Du,"__esModule",{value:!0});Du.ConstructExecutor=void 0;var v5=Vi(),Jg=pt(),S5=jt(),b5=Or(),Ip=class{static{o(this,"ConstructExecutor")}async execute(e,t){let n=[],i=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()}`;i.has(u)||(i.add(u),n.push(c))}catch{continue}return n}instantiateTriple(e,t){if(this.isPropertyPath(e.predicate))throw new Error("Property paths are not supported in CONSTRUCT templates");let n=this.instantiateElement(e.subject,t),i=this.instantiateElement(e.predicate,t),s=this.instantiateElement(e.object,t);return new v5.Triple(n,i,s)}isPropertyPath(e){return e.type==="path"}instantiateElement(e,t){if(e.type==="variable"){let n=t.get(e.value);if(!n)throw new Error(`Unbound variable: ${e.value}`);return n}if(e.type==="iri")return new Jg.IRI(e.value);if(e.type==="literal")return new S5.Literal(e.value,e.datatype?new Jg.IRI(e.datatype):void 0,e.language);if(e.type==="blank")return new b5.BlankNode(e.value);throw new Error(`Unknown element type: ${e.type}`)}};Du.ConstructExecutor=Ip});var Xg=y(Ru=>{"use strict";Object.defineProperty(Ru,"__esModule",{value:!0});Ru.DescribeExecutor=void 0;var w5=pt(),Rp=class{static{o(this,"DescribeExecutor")}constructor(e){this.tripleStore=e}async execute(e){let t=[],n=new Set;for(let i of e){let s=await this.describeResource(i);for(let a of s){let c=`${a.subject.toString()}|${a.predicate.toString()}|${a.object.toString()}`;n.has(c)||(n.add(c),t.push(a))}}return t}async describeResource(e){let t=[],n=await this.tripleStore.match(e,void 0,void 0);t.push(...n);let i=await this.tripleStore.match(void 0,void 0,e);return t.push(...i),t}async describeByIRI(e){let t=new w5.IRI(e);return this.execute([t])}};Ru.DescribeExecutor=Rp});var Zg=y(Nu=>{"use strict";Object.defineProperty(Nu,"__esModule",{value:!0});Nu.MinusExecutor=void 0;var Np=class{static{o(this,"MinusExecutor")}async*execute(e,t){let n=[];for await(let s of e)n.push(s);let i=[];for await(let s of t)i.push(s);for(let s of n){let a=!1;for(let c of i)if(this.areCompatible(s,c)){a=!0;break}a||(yield s)}}async executeAll(e,t){let n=[];async function*i(){for(let a of e)yield a}o(i,"generateLeft");async function*s(){for(let a of t)yield a}o(s,"generateRight");for await(let a of this.execute(i(),s()))n.push(a);return n}areCompatible(e,t){let n=e.variables(),i=new Set(t.variables()),s=n.filter(a=>i.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}};Nu.MinusExecutor=Np});var ty=y(Bs=>{"use strict";Object.defineProperty(Bs,"__esModule",{value:!0});Bs.ValuesExecutor=Bs.ValuesExecutorError=void 0;var E5=ns(),ey=pt(),T5=jt(),ku=class extends Error{static{o(this,"ValuesExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="ValuesExecutorError"}};Bs.ValuesExecutorError=ku;var kp=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 n of this.execute(e))t.push(n);return t}createSolutionMapping(e){let t=new E5.SolutionMapping;for(let[n,i]of Object.entries(e)){let s=this.toRDFTerm(i);t.set(n,s)}return t}toRDFTerm(e){if(e.type==="iri")return new ey.IRI(e.value);if(e.type==="literal")return new T5.Literal(e.value,e.datatype?new ey.IRI(e.datatype):void 0,e.language);throw new ku(`Unknown term type: ${e.type}`)}};Bs.ValuesExecutor=kp});var ny=y(Us=>{"use strict";Object.defineProperty(Us,"__esModule",{value:!0});Us.AggregateExecutor=Us.AggregateExecutorError=void 0;var dr=jt(),Mp=pt(),A5=Pu(),ry=new Mp.IRI("http://www.w3.org/2001/XMLSchema#integer"),Qa=new Mp.IRI("http://www.w3.org/2001/XMLSchema#decimal"),is=new Mp.IRI("http://www.w3.org/2001/XMLSchema#string"),ju=class extends Error{static{o(this,"AggregateExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="AggregateExecutorError"}};Us.AggregateExecutorError=ju;var jp=class{static{o(this,"AggregateExecutor")}constructor(){this.filterExecutor=new A5.FilterExecutor}execute(e,t){let n=this.groupSolutions(t,e.variables),i=[];for(let[s,a]of n.entries()){let c=new Map;for(let l of e.variables)if(a.length>0){let h=a[0].get(l);h&&c.set(l,h)}for(let l of e.aggregates){let h=this.computeAggregate(l.expression,a);c.set(l.variable,h)}let{SolutionMapping:u}=ns(),f=new u;for(let[l,h]of c.entries())f.set(l,h);i.push(f)}if(i.length===0&&e.aggregates.length>0){let s=this.createEmptyAggregateResult(e);s&&i.push(s)}return i}groupSolutions(e,t){let n=new Map;if(t.length===0)return n.set("",e),n;for(let i of e){let s=this.computeGroupKey(i,t),a=n.get(s);a?a.push(i):n.set(s,[i])}return n}computeGroupKey(e,t){return t.map(n=>{let i=e.get(n);return i?this.termToString(i):""}).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){let n=this.extractValues(e,t);switch(e.aggregation){case"count":{let i=this.computeCount(n,e.distinct);return new dr.Literal(String(i),ry)}case"sum":{let i=this.computeSum(n);return new dr.Literal(String(i),Qa)}case"avg":{let i=this.computeAvg(n);return new dr.Literal(String(i),Qa)}case"min":{let i=this.computeMin(n);return i===void 0?new dr.Literal("",is):typeof i=="number"?new dr.Literal(String(i),Qa):new dr.Literal(String(i),is)}case"max":{let i=this.computeMax(n);return i===void 0?new dr.Literal("",is):typeof i=="number"?new dr.Literal(String(i),Qa):new dr.Literal(String(i),is)}case"group_concat":{let i=this.computeGroupConcat(n,e.separator||" ",e.distinct);return new dr.Literal(i||" ",is)}default:throw new ju(`Unknown aggregation function: ${e.aggregation}`)}}extractValues(e,t){if(!e.expression)return t.map(()=>1);let n=[];for(let i of t){let s=this.evaluateExpression(e.expression,i);s!=null&&n.push(s)}return n}evaluateExpression(e,t){if(e.type==="variable"){let n=t.get(e.name);return n==null?void 0:typeof n=="number"||typeof n=="string"||typeof n=="boolean"?n:typeof n=="object"&&"value"in n?n.value:n}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(n=>String(n))).size:e.length}computeSum(e){return e.map(n=>parseFloat(String(n))).filter(n=>!isNaN(n)).reduce((n,i)=>n+i,0)}computeAvg(e){let t=e.map(n=>parseFloat(String(n))).filter(n=>!isNaN(n));return t.length===0?0:t.reduce((n,i)=>n+i,0)/t.length}computeMin(e){if(e.length===0)return;let t=e.map(i=>parseFloat(String(i))).filter(i=>!isNaN(i));if(t.length>0)return Math.min(...t);let n=e.map(i=>String(i));return n.reduce((i,s)=>s<i?s:i,n[0])}computeMax(e){if(e.length===0)return;let t=e.map(i=>parseFloat(String(i))).filter(i=>!isNaN(i));if(t.length>0)return Math.max(...t);let n=e.map(i=>String(i));return n.reduce((i,s)=>s>i?s:i,n[0])}computeGroupConcat(e,t,n){let i=e.map(s=>String(s));return n&&(i=[...new Set(i)]),i.join(t)}createEmptyAggregateResult(e){let{SolutionMapping:t}=ns(),n=new t;for(let i of e.aggregates)switch(i.expression.aggregation){case"count":n.set(i.variable,new dr.Literal("0",ry));break;case"sum":case"avg":n.set(i.variable,new dr.Literal("0",Qa));break;case"group_concat":n.set(i.variable,new dr.Literal(" ",is));break;default:n.set(i.variable,new dr.Literal("",is))}return n}};Us.AggregateExecutor=jp});var iy=y($s=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});$s.QueryExecutor=$s.QueryExecutorError=void 0;var x5=Ep(),O5=Pu(),C5=Cp(),P5=Fp(),F5=Zg(),I5=ty(),D5=ny(),R5=Dp(),Ja=class extends Error{static{o(this,"QueryExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="QueryExecutorError"}};$s.QueryExecutorError=Ja;var Lp=class{static{o(this,"QueryExecutor")}constructor(e){this.bgpExecutor=new x5.BGPExecutor(e),this.filterExecutor=new O5.FilterExecutor,this.optionalExecutor=new C5.OptionalExecutor,this.unionExecutor=new P5.UnionExecutor,this.minusExecutor=new F5.MinusExecutor,this.valuesExecutor=new I5.ValuesExecutor,this.aggregateExecutor=new D5.AggregateExecutor,this.constructExecutor=new R5.ConstructExecutor,this.filterExecutor.setExistsEvaluator(async(t,n)=>this.evaluateExistsPattern(t,n))}async evaluateExistsPattern(e,t){for await(let n of this.execute(e))if(t.merge(n)!==null)return!0;return!1}async executeAll(e){let t=[];for await(let n of this.execute(e))t.push(n);return t}async*execute(e){switch(e.type){case"bgp":yield*this.executeBGP(e);break;case"filter":yield*this.executeFilter(e);break;case"join":yield*this.executeJoin(e);break;case"leftjoin":yield*this.executeLeftJoin(e);break;case"union":yield*this.executeUnion(e);break;case"minus":yield*this.executeMinus(e);break;case"values":yield*this.executeValues(e);break;case"project":yield*this.executeProject(e);break;case"orderby":yield*this.executeOrderBy(e);break;case"slice":yield*this.executeSlice(e);break;case"distinct":yield*this.executeDistinct(e);break;case"reduced":yield*this.executeReduced(e);break;case"group":yield*this.executeGroup(e);break;case"extend":yield*this.executeExtend(e);break;case"subquery":yield*this.executeSubquery(e);break;default:throw new Ja(`Unknown operation type: ${e.type}`)}}async*executeBGP(e){yield*this.bgpExecutor.execute(e)}async*executeFilter(e){let t=this.execute(e.input);yield*this.filterExecutor.execute(e,t)}async*executeJoin(e){let t=[];for await(let n of this.execute(e.left))t.push(n);for(let n of t)for await(let i of this.execute(e.right)){let s=n.merge(i);s!==null&&(yield s)}}async*executeLeftJoin(e){let t=[];for await(let a of this.execute(e.left))t.push(a);let n=[];for await(let a of this.execute(e.right))n.push(a);async function*i(){for(let a of t)yield a}o(i,"leftGen");async function*s(){for(let a of n)yield a}o(s,"rightGen"),yield*this.optionalExecutor.execute(i(),s())}async*executeUnion(e){let t=[];for await(let a of this.execute(e.left))t.push(a);let n=[];for await(let a of this.execute(e.right))n.push(a);async function*i(){for(let a of t)yield a}o(i,"leftGen");async function*s(){for(let a of n)yield a}o(s,"rightGen"),yield*this.unionExecutor.execute(i(),s())}async*executeMinus(e){let t=[];for await(let a of this.execute(e.left))t.push(a);let n=[];for await(let a of this.execute(e.right))n.push(a);async function*i(){for(let a of t)yield a}o(i,"leftGen");async function*s(){for(let a of n)yield a}o(s,"rightGen"),yield*this.minusExecutor.execute(i(),s())}async*executeValues(e){yield*this.valuesExecutor.execute(e)}async*executeProject(e){for await(let t of this.execute(e.input))yield t}async*executeOrderBy(e){let t=[];for await(let n of this.execute(e.input))t.push(n);t.sort((n,i)=>{for(let s of e.comparators){let a=this.getExpressionValue(s.expression,n),c=this.getExpressionValue(s.expression,i),u=0;if(a===void 0&&c===void 0?u=0:a===void 0?u=1:c===void 0?u=-1:typeof a=="number"&&typeof c=="number"?u=a-c:u=String(a).localeCompare(String(c)),s.descending&&(u=-u),u!==0)return u}return 0});for(let n of t)yield n}async*executeSlice(e){let t=0,n=e.offset??0,i=e.limit;for await(let s of this.execute(e.input)){if(t>=n){if(i!==void 0&&t-n>=i)break;yield s}t++}}async*executeDistinct(e){let t=new Set;for await(let n of this.execute(e.input)){let i=this.getSolutionKey(n);t.has(i)||(t.add(i),yield n)}}async*executeReduced(e){let t=new Set;for await(let n of this.execute(e.input)){let i=this.getSolutionKey(n);t.has(i)||(t.add(i),yield n)}}async*executeGroup(e){let t=[];for await(let i of this.execute(e.input))t.push(i);let n=this.aggregateExecutor.execute(e,t);for(let i of n)yield i}async*executeExtend(e){for await(let t of this.execute(e.input)){let n=t.clone(),i=this.evaluateExtendExpression(e.expression,t);i!==void 0&&n.set(e.variable,i),yield n}}async*executeSubquery(e){yield*this.execute(e.query)}evaluateExtendExpression(e,t){if(e.type!=="aggregate")try{return this.filterExecutor.evaluateExpression(e,t)}catch{return}}getExpressionValue(e,t){if(e.type==="variable"){let n=t.get(e.name);return n?n.value??n.id??String(n):void 0}return e.value}getSolutionKey(e){let t=e.toJSON();return Object.keys(t).sort().map(i=>`${i}=${t[i]}`).join("|")}isConstructQuery(e){return e.type==="construct"}async executeConstruct(e){if(e.type!=="construct")throw new Ja("executeConstruct requires a CONSTRUCT operation");let t=await this.executeAll(e.where);return this.constructExecutor.execute(e.template,t)}};$s.QueryExecutor=Lp});var ay=y(Mu=>{"use strict";Object.defineProperty(Mu,"__esModule",{value:!0});Mu.AggregateFunctions=void 0;var Vp=jt(),sy=pt(),qp=class{static{o(this,"AggregateFunctions")}static count(e,t){if(!t)return e.length;let n=0;for(let i of e)i.has(t)&&n++;return n}static countDistinct(e,t){let n=new Set;for(let i of e){let s=i.get(t);s&&n.add(s.toString())}return n.size}static sum(e,t){let n=0;for(let i of e){let s=i.get(t);if(s instanceof Vp.Literal){let a=this.toNumber(s);isNaN(a)||(n+=a)}}return n}static avg(e,t){let n=this.sum(e,t),i=this.count(e,t);return i>0?n/i:0}static min(e,t){let n=null;for(let i of e){let s=i.get(t);if(!s)continue;let a=this.toComparable(s);(n===null||a<n)&&(n=a)}return n}static max(e,t){let n=null;for(let i of e){let s=i.get(t);if(!s)continue;let a=this.toComparable(s);(n===null||a>n)&&(n=a)}return n}static groupConcat(e,t,n=" "){let i=[];for(let s of e){let a=s.get(t);a&&(a instanceof Vp.Literal||a instanceof sy.IRI?i.push(a.value):i.push(a.toString()))}return i.join(n)}static toNumber(e){let t=e.datatype?.value;return t?.includes("#integer")||t?.includes("#decimal")||t?.includes("#double"),parseFloat(e.value)}static toComparable(e){if(e instanceof Vp.Literal){let t=this.toNumber(e);return isNaN(t)?e.value:t}return e instanceof sy.IRI?e.value:String(e)}};Mu.AggregateFunctions=qp});var oy=y(Lu=>{"use strict";Object.defineProperty(Lu,"__esModule",{value:!0});Lu.QueryPlanCache=void 0;var N5=Qd(),Bp=class{static{o(this,"QueryPlanCache")}constructor(e=100){this.hits=0,this.misses=0,this.cache=new N5.LRUCache(e)}get(e){let t=this.normalizeQuery(e),n=this.cache.get(t);return n!==void 0?this.hits++:this.misses++,n}set(e,t){let n=this.normalizeQuery(e);this.cache.set(n,t)}has(e){let t=this.normalizeQuery(e);return this.cache.get(t)!==void 0}clear(){this.cache.clear()}getStats(){let e=this.hits+this.misses;return{hits:this.hits,misses:this.misses,hitRate:e>0?this.hits/e:0,size:this.cache.size()}}resetStats(){this.hits=0,this.misses=0}normalizeQuery(e){return e.replace(/\s+/g," ").trim()}};Lu.QueryPlanCache=Bp});var cy=y(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});Ws.FileAlreadyExistsError=Ws.FileNotFoundError=void 0;var Up=class extends Error{static{o(this,"FileNotFoundError")}constructor(e){super(`File not found: ${e}`),this.name="FileNotFoundError"}};Ws.FileNotFoundError=Up;var $p=class extends Error{static{o(this,"FileAlreadyExistsError")}constructor(e){super(`File already exists: ${e}`),this.name="FileAlreadyExistsError"}};Ws.FileAlreadyExistsError=$p});var uy=y(gi=>{"use strict";Object.defineProperty(gi,"__esModule",{value:!0});gi.container=void 0;gi.registerCoreServices=sO;gi.createChildContainer=aO;gi.getContainer=oO;gi.resetContainer=cO;uf();var Xa=Ke();Object.defineProperty(gi,"container",{enumerable:!0,get:o(function(){return Xa.container},"get")});var et=rt(),k5=Kh(),j5=Gc(),M5=xd(),L5=Hc(),V5=_d(),q5=Qh(),B5=rd(),U5=ed(),$5=Jc(),W5=Xc(),G5=hd(),H5=pd(),z5=Sd(),K5=ld(),Y5=Cd(),Q5=Dd(),J5=Fd(),X5=ad(),Z5=cd(),eO=Td(),tO=wd(),rO=tp(),nO=id(),iO=Nd();function sO(r){let e=r||Xa.container;e.registerSingleton(et.DI_TOKENS.TaskFrontmatterGenerator,j5.TaskFrontmatterGenerator),e.registerSingleton(et.DI_TOKENS.DynamicFrontmatterGenerator,M5.DynamicFrontmatterGenerator),e.registerSingleton(et.DI_TOKENS.AlgorithmExtractor,L5.AlgorithmExtractor),e.registerSingleton(et.DI_TOKENS.EffortStatusWorkflow,$5.EffortStatusWorkflow),e.registerSingleton(et.DI_TOKENS.StatusTimestampService,W5.StatusTimestampService),e.registerSingleton(et.DI_TOKENS.TaskStatusService,U5.TaskStatusService),e.registerSingleton(et.DI_TOKENS.TaskCreationService,k5.TaskCreationService),e.registerSingleton(et.DI_TOKENS.ProjectCreationService,q5.ProjectCreationService),e.registerSingleton(et.DI_TOKENS.AreaCreationService,B5.AreaCreationService),e.registerSingleton(et.DI_TOKENS.ClassCreationService,X5.ClassCreationService),e.registerSingleton(et.DI_TOKENS.ConceptCreationService,Z5.ConceptCreationService),e.registerSingleton(et.DI_TOKENS.FleetingNoteCreationService,eO.FleetingNoteCreationService),e.registerSingleton(et.DI_TOKENS.SupervisionCreationService,tO.SupervisionCreationService),e.registerSingleton(et.DI_TOKENS.PropertyCleanupService,V5.PropertyCleanupService),e.registerSingleton(et.DI_TOKENS.FolderRepairService,G5.FolderRepairService),e.registerSingleton(et.DI_TOKENS.LabelToAliasService,H5.LabelToAliasService),e.registerSingleton(et.DI_TOKENS.RenameToUidService,z5.RenameToUidService),e.registerSingleton(et.DI_TOKENS.PlanningService,Y5.PlanningService),e.registerSingleton(et.DI_TOKENS.EffortVotingService,K5.EffortVotingService),e.registerSingleton(et.DI_TOKENS.SessionEventService,Q5.SessionEventService),e.registerSingleton(et.DI_TOKENS.AssetConversionService,J5.AssetConversionService),e.registerSingleton(et.DI_TOKENS.NoteToRDFConverter,rO.NoteToRDFConverter),e.registerSingleton(et.DI_TOKENS.AreaHierarchyBuilder,nO.AreaHierarchyBuilder),e.registerSingleton(et.DI_TOKENS.URIConstructionService,iO.URIConstructionService)}o(sO,"registerCoreServices");function aO(){return Xa.container.createChildContainer()}o(aO,"createChildContainer");function oO(){return Xa.container}o(oO,"getContainer");function cO(){Xa.container.reset()}o(cO,"resetContainer")});var An=y(Vu=>{"use strict";Object.defineProperty(Vu,"__esModule",{value:!0});Vu.ErrorCode=void 0;var ly;(function(r){r[r.INVALID_INPUT=1e3]="INVALID_INPUT",r[r.INVALID_FORMAT=1001]="INVALID_FORMAT",r[r.MISSING_REQUIRED_FIELD=1002]="MISSING_REQUIRED_FIELD",r[r.INVALID_SCHEMA=1003]="INVALID_SCHEMA",r[r.NETWORK_ERROR=2e3]="NETWORK_ERROR",r[r.REQUEST_TIMEOUT=2001]="REQUEST_TIMEOUT",r[r.CONNECTION_FAILED=2002]="CONNECTION_FAILED",r[r.FILE_READ_ERROR=2003]="FILE_READ_ERROR",r[r.FILE_WRITE_ERROR=2004]="FILE_WRITE_ERROR",r[r.INVALID_STATE=3e3]="INVALID_STATE",r[r.INVALID_TRANSITION=3001]="INVALID_TRANSITION",r[r.OPERATION_FAILED=3002]="OPERATION_FAILED",r[r.CONCURRENT_MODIFICATION=3003]="CONCURRENT_MODIFICATION",r[r.PERMISSION_DENIED=4e3]="PERMISSION_DENIED",r[r.UNAUTHORIZED=4001]="UNAUTHORIZED",r[r.FORBIDDEN=4003]="FORBIDDEN",r[r.NOT_FOUND=5e3]="NOT_FOUND",r[r.RESOURCE_EXHAUSTED=5001]="RESOURCE_EXHAUSTED",r[r.ALREADY_EXISTS=5002]="ALREADY_EXISTS",r[r.UNKNOWN_ERROR=9e3]="UNKNOWN_ERROR",r[r.INTERNAL_ERROR=9001]="INTERNAL_ERROR"})(ly||(Vu.ErrorCode=ly={}))});var xn=y(qu=>{"use strict";Object.defineProperty(qu,"__esModule",{value:!0});qu.ApplicationError=void 0;var Wp=class extends Error{static{o(this,"ApplicationError")}constructor(e,t){super(e),this.name=this.constructor.name,this.context=t,this.timestamp=new Date,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}format(){let e=`\u274C ${this.name}: ${this.message}`;if(this.guidance&&(e+=`
140
140
 
141
141
  \u{1F4A1} ${this.guidance}`),this.context&&Object.keys(this.context).length>0){e+=`
142
142
 
@@ -255,7 +255,7 @@ globstar while`,e,p,t,g,b),this.matchOne(e.slice(p),t.slice(g),n))return this.de
255
255
  \u{1F4DD} Note: Actual command execution will be implemented in follow-up issues.`),console.log(" This PR establishes the infrastructure foundation."),process.exit(0)}catch(i){Fe.handle(i)}}getVaultRoot(){return this.context.pathResolver.getVaultRoot()}async executeStart(e){return this.statusExecutor.executeStart(e)}async executeComplete(e){return this.statusExecutor.executeComplete(e)}async executeTrash(e){return this.statusExecutor.executeTrash(e)}async executeArchive(e){return this.statusExecutor.executeArchive(e)}async executeMoveToBacklog(e){return this.statusExecutor.executeMoveToBacklog(e)}async executeMoveToAnalysis(e){return this.statusExecutor.executeMoveToAnalysis(e)}async executeMoveToToDo(e){return this.statusExecutor.executeMoveToToDo(e)}async executeCreateTask(e,t,n={}){return this.creationExecutor.executeCreateTask(e,t,n)}async executeCreateMeeting(e,t,n={}){return this.creationExecutor.executeCreateMeeting(e,t,n)}async executeCreateProject(e,t,n={}){return this.creationExecutor.executeCreateProject(e,t,n)}async executeCreateArea(e,t,n={}){return this.creationExecutor.executeCreateArea(e,t,n)}async executeRenameToUid(e){return this.propertyExecutor.executeRenameToUid(e)}async executeUpdateLabel(e,t){return this.propertyExecutor.executeUpdateLabel(e,t)}async executeSchedule(e,t){return this.propertyExecutor.executeSchedule(e,t)}async executeSetDeadline(e,t){return this.propertyExecutor.executeSetDeadline(e,t)}};function Gt(r,e,t,n,i){if(r==="json"){let s={command:e,filepath:t,action:n,...i&&{changes:i}},a=Ut.success(s);console.log(JSON.stringify(a,null,2))}else console.log(`\u2705 ${n}`)}o(Gt,"outputResult");function ds(r,e,t,n){let i=new st(`--${e} option is required for ${t} command`,n,{command:t,missingOption:e});Fe.handle(i)}o(ds,"handleMissingOption");function FS(){return new _n("command").description("Execute plugin command on single asset").argument("<command-name>","Command to execute (rename-to-uid, start, complete, schedule, set-deadline, etc.)").argument("<filepath>","Path to asset file (relative to vault root or absolute)").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--label <value>","Asset label (required for update-label and creation commands)").option("--prototype <uid>","Prototype UID for inheritance (creation commands)").option("--area <uid>","Area UID for effort linkage (creation commands)").option("--parent <uid>","Parent UID for effort linkage (creation commands)").option("--date <value>","Date in YYYY-MM-DD format (required for schedule and set-deadline commands)").option("--dry-run","Preview changes without modifying files").option("--format <type>","Output format: text|json (default: text)","text").action(async(r,e,t)=>{let n=t.format||"text";Fe.setFormat(n);try{let i=(0,PS.resolve)(t.vault),s=new Ml(i,t.dryRun);switch(r){case"rename-to-uid":await s.executeRenameToUid(e),Gt(n,r,e,"Renamed file to UID-based name");break;case"update-label":t.label||ds(n,"label","update-label",'exocortex command update-label <filepath> --label "<value>"'),await s.executeUpdateLabel(e,t.label),Gt(n,r,e,`Updated label to "${t.label}"`,{label:t.label});break;case"start":await s.executeStart(e),Gt(n,r,e,"Started task");break;case"complete":await s.executeComplete(e),Gt(n,r,e,"Completed task");break;case"trash":await s.executeTrash(e),Gt(n,r,e,"Moved task to trash");break;case"archive":await s.executeArchive(e),Gt(n,r,e,"Archived task");break;case"move-to-backlog":await s.executeMoveToBacklog(e),Gt(n,r,e,"Moved task to backlog");break;case"move-to-analysis":await s.executeMoveToAnalysis(e),Gt(n,r,e,"Moved task to analysis");break;case"move-to-todo":await s.executeMoveToToDo(e),Gt(n,r,e,"Moved task to todo");break;case"create-task":t.label||ds(n,"label","create-task",'exocortex command create-task <filepath> --label "<value>"'),await s.executeCreateTask(e,t.label,{prototype:t.prototype,area:t.area,parent:t.parent}),Gt(n,r,e,`Created task "${t.label}"`,{label:t.label,prototype:t.prototype,area:t.area,parent:t.parent});break;case"create-meeting":t.label||ds(n,"label","create-meeting",'exocortex command create-meeting <filepath> --label "<value>"'),await s.executeCreateMeeting(e,t.label,{prototype:t.prototype,area:t.area,parent:t.parent}),Gt(n,r,e,`Created meeting "${t.label}"`,{label:t.label,prototype:t.prototype,area:t.area,parent:t.parent});break;case"create-project":t.label||ds(n,"label","create-project",'exocortex command create-project <filepath> --label "<value>"'),await s.executeCreateProject(e,t.label,{prototype:t.prototype,area:t.area,parent:t.parent}),Gt(n,r,e,`Created project "${t.label}"`,{label:t.label,prototype:t.prototype,area:t.area,parent:t.parent});break;case"create-area":t.label||ds(n,"label","create-area",'exocortex command create-area <filepath> --label "<value>"'),await s.executeCreateArea(e,t.label,{prototype:t.prototype,area:t.area,parent:t.parent}),Gt(n,r,e,`Created area "${t.label}"`,{label:t.label,prototype:t.prototype,area:t.area,parent:t.parent});break;case"schedule":t.date||ds(n,"date","schedule",'exocortex command schedule <filepath> --date "YYYY-MM-DD"'),await s.executeSchedule(e,t.date),Gt(n,r,e,`Scheduled task for ${t.date}`,{date:t.date});break;case"set-deadline":t.date||ds(n,"date","set-deadline",'exocortex command set-deadline <filepath> --date "YYYY-MM-DD"'),await s.executeSetDeadline(e,t.date),Gt(n,r,e,`Set deadline to ${t.date}`,{date:t.date});break;default:await s.execute(r,e,t),Gt(n,r,e,`Executed ${r}`);break}}catch(i){Fe.handle(i)}})}o(FS,"commandCommand");var DS=require("path");var ni=Je(require("fs")),e1=Je(require("path")),IS=require("events");var _8={watch:ni.default.watch.bind(ni.default),existsSync:ni.default.existsSync.bind(ni.default),statSync:ni.default.statSync.bind(ni.default),readFileSync:ni.default.readFileSync.bind(ni.default)},Ll=class extends IS.EventEmitter{constructor(t,n={}){super();this.watcher=null;this.debounceTimers=new Map;this.isRunning=!1;this.vaultPath=e1.default.resolve(t),this.fsAdapter=n.fsAdapter??_8,this.options={pattern:n.pattern??"**/*.md",assetType:n.assetType??"",debounceMs:n.debounceMs??100,recursive:n.recursive??!0}}static{o(this,"FileSystemWatcher")}start(){this.isRunning||(this.watcher=this.fsAdapter.watch(this.vaultPath,{recursive:this.options.recursive},(t,n)=>{n&&this.handleFileEvent(t,n.toString())}),this.watcher.on("error",t=>{this.emit("error",t)}),this.isRunning=!0,this.emit("started"))}stop(){if(this.isRunning){for(let t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),this.watcher&&(this.watcher.close(),this.watcher=null),this.isRunning=!1,this.emit("stopped")}}isWatching(){return this.isRunning}handleFileEvent(t,n){let i=e1.default.join(this.vaultPath,n),s=n;if(!this.matchesPattern(s))return;let a=this.debounceTimers.get(i);a&&clearTimeout(a);let c=setTimeout(()=>{this.debounceTimers.delete(i),this.processFileEvent(i,s)},this.options.debounceMs);this.debounceTimers.set(i,c)}processFileEvent(t,n){let i=this.fsAdapter.existsSync(t),s;if(!i)s="delete";else{let u=this.fsAdapter.statSync(t);s=Date.now()-u.birthtimeMs<1e3?"create":"modify"}let a;if(i&&t.endsWith(".md")&&(a=this.extractAssetType(t)),this.options.assetType&&a!==this.options.assetType)return;let c={type:s,path:t,relativePath:n,timestamp:new Date().toISOString(),assetType:a};this.emit("change",c)}matchesPattern(t){return this.options.pattern?Nt(t,this.options.pattern):!0}extractAssetType(t){try{let i=this.fsAdapter.readFileSync(t,"utf-8").match(/^---\n([\s\S]*?)\n---/);if(!i)return;let a=i[1].match(/exo__Instance_class:\s*(?:\[?"?\[\[([^\]]+)\]\]"?\]?|"?\[\[([^\]]+)\]\]"?)/);return a?a[1]||a[2]:void 0}catch{return}}};var t1=Je(require("fs"));function RS(){return new _n("watch").description("Watch vault for file changes and emit NDJSON events").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--pattern <glob>","Glob pattern to filter files (e.g., '*.md', 'tasks/**')").option("--asset-type <type>","Filter by asset type (e.g., 'ems__Task', 'ems__Project')").option("--debounce <ms>","Debounce interval in milliseconds","100").action(async r=>{Fe.setFormat("json");try{let e=(0,DS.resolve)(r.vault);if(!t1.default.existsSync(e))throw new us(e);if(!t1.default.statSync(e).isDirectory())throw new st(`Vault path is not a directory: ${e}`,"Provide a path to a directory, not a file",{vaultPath:e});let t=parseInt(r.debounce?.toString()??"100",10);if(isNaN(t)||t<0)throw new st("--debounce must be a non-negative integer","Use a positive integer value for debounce",{debounce:r.debounce});let n=new Ll(e,{pattern:r.pattern,assetType:r.assetType,debounceMs:t});n.on("change",s=>{console.log(JSON.stringify(s))}),n.on("error",s=>{let a=Ut.error("INTERNAL_OPERATION_FAILED",s.message,5,{recovery:{message:"Check file permissions and vault access",suggestion:"Ensure the vault directory is accessible"}});console.log(JSON.stringify(a))});let i=o(()=>{n.stop(),process.exit(0)},"shutdown");process.on("SIGINT",i),process.on("SIGTERM",i),console.error(`Watching vault: ${e}`),r.pattern&&console.error(` Pattern filter: ${r.pattern}`),r.assetType&&console.error(` Asset type filter: ${r.assetType}`),console.error(` Debounce: ${t}ms`),console.error("Press Ctrl+C to stop"),n.start()}catch(e){Fe.handle(e)}})}o(RS,"watchCommand");var n1=require("path"),i1=Je(Qs());var ma=Je(yi());var fn=Je(Qs()),r1=Je(require("crypto"));var Vl=class{constructor(){this.backups=new Map;this.fileHashes=new Map}static{o(this,"TransactionManager")}async begin(e){if(!fn.default.existsSync(e))throw new Error(`Cannot backup non-existent file: ${e}`);let t=await fn.default.readFile(e,"utf-8"),n=r1.default.createHash("sha256").update(t).digest("hex");this.fileHashes.set(e,n);let i=`${e}.backup.${Date.now()}`;await fn.default.writeFile(i,t,"utf-8"),this.backups.set(e,i)}async verify(e){let t=this.fileHashes.get(e);if(!t)return!0;if(!fn.default.existsSync(e))return!1;let n=await fn.default.readFile(e,"utf-8");return r1.default.createHash("sha256").update(n).digest("hex")===t}async commit(){for(let e of this.backups.values())fn.default.existsSync(e)&&await fn.default.remove(e);this.backups.clear(),this.fileHashes.clear()}async rollback(){for(let[e,t]of this.backups.entries())fn.default.existsSync(t)&&(await fn.default.copy(t,e,{overwrite:!0}),await fn.default.remove(t));this.backups.clear(),this.fileHashes.clear()}getTrackedFiles(){return Array.from(this.backups.keys())}};var Mo=class{static{o(this,"BatchExecutor")}constructor(e,t=!1){this.pathResolver=new da(e),this.fsAdapter=new ha(e),this.frontmatterService=new ma.FrontmatterService,this.transactionManager=new Vl,this.dryRun=t}async executeBatch(e,t=!1){let n=Date.now(),i=[],s=0,a=0,c=!1;if(e.length===0)return{success:!0,total:0,succeeded:0,failed:0,results:[],durationMs:Date.now()-n,atomic:t};if(t&&!this.dryRun)try{await this.backupAllFiles(e)}catch(f){return{success:!1,total:e.length,succeeded:0,failed:e.length,results:e.map(l=>({success:!1,command:l.command,filepath:l.filepath,error:`Backup failed: ${f.message}`})),durationMs:Date.now()-n,atomic:t}}for(let f of e){let l=await this.executeSingleOperation(f);if(i.push(l),l.success)s++;else if(a++,t&&!this.dryRun){await this.transactionManager.rollback(),c=!0;let h=i.length;for(let p=h;p<e.length;p++)i.push({success:!1,command:e[p].command,filepath:e[p].filepath,error:"Not executed due to atomic rollback"}),a++;return{success:!1,total:e.length,succeeded:0,failed:e.length,results:i,durationMs:Date.now()-n,atomic:t,rolledBack:!0}}}return t&&!this.dryRun&&!c&&await this.transactionManager.commit(),{success:a===0,total:e.length,succeeded:s,failed:a,results:i,durationMs:Date.now()-n,atomic:t,...t&&{rolledBack:c}}}static parseInput(e){try{let t=JSON.parse(e);if(!Array.isArray(t))throw new st("Batch input must be a JSON array of operations",`exo batch --input '[{"command":"start","filepath":"task.md"}]'`);for(let n of t){if(!n.command||typeof n.command!="string")throw new st('Each operation must have a "command" string property','{"command":"start","filepath":"task.md"}');if(!n.filepath||typeof n.filepath!="string")throw new st('Each operation must have a "filepath" string property','{"command":"start","filepath":"task.md"}')}return t}catch(t){throw t instanceof st?t:new st(`Failed to parse batch input: ${t.message}`,`exo batch --input '[{"command":"start","filepath":"task.md"}]'`)}}async backupAllFiles(e){let t=new Set;for(let n of e){let i=this.pathResolver.resolve(n.filepath);t.add(i)}for(let n of t)await this.transactionManager.begin(n)}async executeSingleOperation(e){try{let t=this.pathResolver.resolve(e.filepath);this.pathResolver.validate(t);let n=t.replace(this.pathResolver.getVaultRoot()+"/",""),i=await this.fsAdapter.readFile(n);if(this.dryRun)return{success:!0,command:e.command,filepath:e.filepath,action:`Would execute ${e.command} (dry-run)`};switch(e.command){case"start":return await this.executeStart(n,e);case"complete":return await this.executeComplete(n,e);case"trash":return await this.executeTrash(n,e);case"archive":return await this.executeArchive(n,e);case"move-to-backlog":return await this.executeStatusUpdate(n,e,"ems__EffortStatusBacklog","Moved to backlog");case"move-to-analysis":return await this.executeStatusUpdate(n,e,"ems__EffortStatusAnalysis","Moved to analysis");case"move-to-todo":return await this.executeStatusUpdate(n,e,"ems__EffortStatusToDo","Moved to todo");case"update-label":return await this.executeUpdateLabel(n,e);case"schedule":return await this.executeSchedule(n,e);case"set-deadline":return await this.executeSetDeadline(n,e);default:return{success:!1,command:e.command,filepath:e.filepath,error:`Unknown command: ${e.command}`}}}catch(t){return{success:!1,command:e.command,filepath:e.filepath,error:t.message}}}getCurrentTimestamp(){return ma.DateFormatter.toLocalTimestamp(new Date)}async executeStart(e,t){let n=await this.fsAdapter.readFile(e),i=this.getCurrentTimestamp(),s=this.frontmatterService.updateProperty(n,"ems__Effort_status",'"[[ems__EffortStatusDoing]]"');return s=this.frontmatterService.updateProperty(s,"ems__Effort_startTimestamp",i),await this.fsAdapter.updateFile(e,s),{success:!0,command:t.command,filepath:t.filepath,action:"Started task",changes:{status:"Doing",startTimestamp:i}}}async executeComplete(e,t){let n=await this.fsAdapter.readFile(e),i=this.getCurrentTimestamp(),s=this.frontmatterService.updateProperty(n,"ems__Effort_status",'"[[ems__EffortStatusDone]]"');return s=this.frontmatterService.updateProperty(s,"ems__Effort_endTimestamp",i),s=this.frontmatterService.updateProperty(s,"ems__Effort_resolutionTimestamp",i),await this.fsAdapter.updateFile(e,s),{success:!0,command:t.command,filepath:t.filepath,action:"Completed task",changes:{status:"Done",endTimestamp:i,resolutionTimestamp:i}}}async executeTrash(e,t){let n=await this.fsAdapter.readFile(e),i=this.getCurrentTimestamp(),s=this.frontmatterService.updateProperty(n,"ems__Effort_status",'"[[ems__EffortStatusTrashed]]"');return s=this.frontmatterService.updateProperty(s,"ems__Effort_resolutionTimestamp",i),await this.fsAdapter.updateFile(e,s),{success:!0,command:t.command,filepath:t.filepath,action:"Trashed task",changes:{status:"Trashed",resolutionTimestamp:i}}}async executeArchive(e,t){let n=await this.fsAdapter.readFile(e),i=this.frontmatterService.updateProperty(n,"archived","true");return i=this.frontmatterService.removeProperty(i,"aliases"),await this.fsAdapter.updateFile(e,i),{success:!0,command:t.command,filepath:t.filepath,action:"Archived task",changes:{archived:!0,aliasesRemoved:!0}}}async executeStatusUpdate(e,t,n,i){let s=await this.fsAdapter.readFile(e),a=this.frontmatterService.updateProperty(s,"ems__Effort_status",`"[[${n}]]"`);return await this.fsAdapter.updateFile(e,a),{success:!0,command:t.command,filepath:t.filepath,action:i,changes:{status:n.replace("ems__EffortStatus","")}}}async executeUpdateLabel(e,t){let n=t.options?.label;if(!n||n.trim()==="")return{success:!1,command:t.command,filepath:t.filepath,error:'Missing required option: "label"'};let i=n.trim(),s=await this.fsAdapter.readFile(e),a=this.frontmatterService.updateProperty(s,"exo__Asset_label",`"${i}"`);return await this.fsAdapter.updateFile(e,a),{success:!0,command:t.command,filepath:t.filepath,action:`Updated label to "${i}"`,changes:{label:i}}}async executeSchedule(e,t){let n=t.options?.date;if(!n)return{success:!1,command:t.command,filepath:t.filepath,error:'Missing required option: "date"'};if(!/^\d{4}-\d{2}-\d{2}$/.test(n))return{success:!1,command:t.command,filepath:t.filepath,error:`Invalid date format: ${n}. Expected YYYY-MM-DD`};let i=await this.fsAdapter.readFile(e),s=ma.DateFormatter.toTimestampAtStartOfDay(n),a=this.frontmatterService.updateProperty(i,"ems__Effort_scheduledTimestamp",s);return await this.fsAdapter.updateFile(e,a),{success:!0,command:t.command,filepath:t.filepath,action:`Scheduled for ${n}`,changes:{scheduledTimestamp:s}}}async executeSetDeadline(e,t){let n=t.options?.date;if(!n)return{success:!1,command:t.command,filepath:t.filepath,error:'Missing required option: "date"'};if(!/^\d{4}-\d{2}-\d{2}$/.test(n))return{success:!1,command:t.command,filepath:t.filepath,error:`Invalid date format: ${n}. Expected YYYY-MM-DD`};let i=await this.fsAdapter.readFile(e),s=ma.DateFormatter.toTimestampAtStartOfDay(n),a=this.frontmatterService.updateProperty(i,"ems__Effort_deadlineTimestamp",s);return await this.fsAdapter.updateFile(e,a),{success:!0,command:t.command,filepath:t.filepath,action:`Set deadline to ${n}`,changes:{deadlineTimestamp:s}}}};function v8(r,e){if(r==="json"){let t=Ut.success(e,{durationMs:e.durationMs,itemCount:e.total});console.log(JSON.stringify(t,null,2))}else{if(console.log(`
256
256
  \u{1F4E6} Batch Execution ${e.success?"Complete":"Failed"}`),console.log(` Total: ${e.total} operations`),console.log(` \u2705 Succeeded: ${e.succeeded}`),console.log(` \u274C Failed: ${e.failed}`),console.log(` \u23F1\uFE0F Duration: ${e.durationMs}ms`),e.atomic&&console.log(` \u{1F512} Atomic mode: ${e.rolledBack?"Rolled back":"Committed"}`),e.failed>0){console.log(`
257
257
  \u{1F4CB} Failed Operations:`);for(let t of e.results.filter(n=>!n.success))console.log(` \u274C ${t.command} ${t.filepath}: ${t.error}`)}if(e.succeeded>0&&r==="text"){console.log(`
258
- \u{1F4CB} Successful Operations:`);for(let t of e.results.filter(n=>n.success))console.log(` \u2705 ${t.command} ${t.filepath}: ${t.action}`)}}}o(v8,"outputResult");function NS(){return new _n("batch").description("Execute multiple operations in a single CLI invocation").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--input <json>","JSON array of operations to execute").option("--file <path>","Path to JSON file containing operations").option("--atomic","All-or-nothing execution (rollback on any failure)").option("--dry-run","Preview changes without modifying files").option("--format <type>","Output format: text|json (default: text)","text").action(async r=>{let e=r.format||"text";Fe.setFormat(e);try{let t=(0,n1.resolve)(r.vault),n;if(r.input)n=r.input;else if(r.file){let c=(0,n1.resolve)(r.file);if(!i1.default.existsSync(c))throw new st(`Batch file not found: ${c}`,"exocortex batch --file operations.json");n=await i1.default.readFile(c,"utf-8")}else throw new st("Either --input or --file option is required",`exocortex batch --input '[{"command":"start","filepath":"task.md"}]' or exocortex batch --file operations.json`);let i=Mo.parseInput(n);if(i.length===0)throw new st("Batch input contains no operations",`exocortex batch --input '[{"command":"start","filepath":"task.md"}]'`);let a=await new Mo(t,r.dryRun).executeBatch(i,r.atomic);v8(e,a),process.exit(a.success?0:5)}catch(t){Fe.handle(t)}})}o(NS,"batchCommand");var ga=new _n;ga.name("exocortex").description("CLI tool for Exocortex knowledge management system").version("13.123.0");ga.command("sparql").description("SPARQL query execution").addCommand(Ev());ga.addCommand(FS());ga.addCommand(RS());ga.addCommand(NS());ga.parse();
258
+ \u{1F4CB} Successful Operations:`);for(let t of e.results.filter(n=>n.success))console.log(` \u2705 ${t.command} ${t.filepath}: ${t.action}`)}}}o(v8,"outputResult");function NS(){return new _n("batch").description("Execute multiple operations in a single CLI invocation").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--input <json>","JSON array of operations to execute").option("--file <path>","Path to JSON file containing operations").option("--atomic","All-or-nothing execution (rollback on any failure)").option("--dry-run","Preview changes without modifying files").option("--format <type>","Output format: text|json (default: text)","text").action(async r=>{let e=r.format||"text";Fe.setFormat(e);try{let t=(0,n1.resolve)(r.vault),n;if(r.input)n=r.input;else if(r.file){let c=(0,n1.resolve)(r.file);if(!i1.default.existsSync(c))throw new st(`Batch file not found: ${c}`,"exocortex batch --file operations.json");n=await i1.default.readFile(c,"utf-8")}else throw new st("Either --input or --file option is required",`exocortex batch --input '[{"command":"start","filepath":"task.md"}]' or exocortex batch --file operations.json`);let i=Mo.parseInput(n);if(i.length===0)throw new st("Batch input contains no operations",`exocortex batch --input '[{"command":"start","filepath":"task.md"}]'`);let a=await new Mo(t,r.dryRun).executeBatch(i,r.atomic);v8(e,a),process.exit(a.success?0:5)}catch(t){Fe.handle(t)}})}o(NS,"batchCommand");var ga=new _n;ga.name("exocortex").description("CLI tool for Exocortex knowledge management system").version("13.124.0");ga.command("sparql").description("SPARQL query execution").addCommand(Ev());ga.addCommand(FS());ga.addCommand(RS());ga.addCommand(NS());ga.parse();
259
259
  /*! Bundled license information:
260
260
 
261
261
  reflect-metadata/Reflect.js:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "exocortex-cli",
3
- "version": "13.123.0",
3
+ "version": "13.124.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": {