@kitelev/exocortex-cli 15.14.1 → 15.15.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.
- package/dist/index.js +4 -4
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// @kitelev/exocortex-cli v15.
|
|
2
|
+
// @kitelev/exocortex-cli v15.15.0
|
|
3
3
|
// CLI tool for Exocortex knowledge management system - SPARQL queries, task management, and more
|
|
4
4
|
// License: MIT
|
|
5
5
|
|
|
@@ -257,7 +257,7 @@ Expecting `+ml.join(", ")+", got '"+(this.terminals_[Ze]||Ze)+"'":lp="Parse erro
|
|
|
257
257
|
`;)n++;continue}if(e[n]==="{"){i++,n++;continue}if(e[n]==="}"){if(i--,i===0){let s=e.substring(t,n+1);return{content:s,length:s.length}}n++;continue}n++}if(i>0)throw new ps(`Unclosed LATERAL block at position ${t}`);return null}transformLateral(e){let t=e.indexOf("{");if(t===-1)throw new ps("LATERAL expression missing opening brace");let n=e.substring(t+1,e.length-1).trim();if(!n.toUpperCase().trim().startsWith("SELECT"))throw new ps("LATERAL block must contain a SELECT subquery");let a=n.toUpperCase().indexOf("SELECT")+6;for(;a<n.length&&/\s/.test(n[a]);)a++;let c=n.substring(a).toUpperCase();return c.startsWith("DISTINCT")?a+=8:c.startsWith("REDUCED")&&(a+=7),`{ ${n.substring(0,a)+` ?${r.LATERAL_MARKER}`+n.substring(a)} }`}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}};to.LateralTransformer=zf;zf.LATERAL_MARKER="__LATERAL_JOIN__";var ps=class extends Error{static{o(this,"LateralTransformerError")}constructor(e){super(`LATERAL transformation error: ${e}`),this.name="LateralTransformerError"}};to.LateralTransformerError=ps});var Cb=_(ms=>{"use strict";Object.defineProperty(ms,"__esModule",{value:!0});ms.PrefixStarTransformerError=ms.PrefixStarTransformer=ms.WellKnownPrefixResolver=void 0;var Yf=class{static{o(this,"WellKnownPrefixResolver")}constructor(){this.wellKnownPrefixes=new Map;let e=new Map;e.set("schema","http://schema.org/"),this.wellKnownPrefixes.set("http://schema.org/",e);let t=new Map;t.set("foaf","http://xmlns.com/foaf/0.1/"),this.wellKnownPrefixes.set("http://xmlns.com/foaf/0.1/",t);let n=new Map;n.set("dc","http://purl.org/dc/elements/1.1/"),n.set("dcterms","http://purl.org/dc/terms/"),this.wellKnownPrefixes.set("http://purl.org/dc/elements/1.1/",n),this.wellKnownPrefixes.set("http://purl.org/dc/terms/",n);let i=new Map;i.set("rdf","http://www.w3.org/1999/02/22-rdf-syntax-ns#"),i.set("rdfs","http://www.w3.org/2000/01/rdf-schema#"),this.wellKnownPrefixes.set("http://www.w3.org/1999/02/22-rdf-syntax-ns#",i),this.wellKnownPrefixes.set("http://www.w3.org/2000/01/rdf-schema#",i);let s=new Map;s.set("owl","http://www.w3.org/2002/07/owl#"),this.wellKnownPrefixes.set("http://www.w3.org/2002/07/owl#",s);let a=new Map;a.set("xsd","http://www.w3.org/2001/XMLSchema#"),this.wellKnownPrefixes.set("http://www.w3.org/2001/XMLSchema#",a);let c=new Map;c.set("skos","http://www.w3.org/2004/02/skos/core#"),this.wellKnownPrefixes.set("http://www.w3.org/2004/02/skos/core#",c);let u=new Map;u.set("prov","http://www.w3.org/ns/prov#"),this.wellKnownPrefixes.set("http://www.w3.org/ns/prov#",u);let l=new Map;l.set("geo","http://www.w3.org/2003/01/geo/wgs84_pos#"),this.wellKnownPrefixes.set("http://www.w3.org/2003/01/geo/wgs84_pos#",l);let f=new Map;f.set("dcat","http://www.w3.org/ns/dcat#"),this.wellKnownPrefixes.set("http://www.w3.org/ns/dcat#",f)}async resolve(e){let t=e.endsWith("#")||e.endsWith("/")?e:e+(e.includes("#")?"":"/"),n=this.wellKnownPrefixes.get(t);if(n)return n;let i=t.slice(0,-1),s=this.wellKnownPrefixes.get(i);return s||new Map}addVocabulary(e,t){this.wellKnownPrefixes.set(e,t)}};ms.WellKnownPrefixResolver=Yf;var W0=class{static{o(this,"PrefixStarTransformer")}constructor(e){this.resolver=e??new Yf}async transform(e){let t=this.findPrefixStarDeclarations(e);if(t.length===0)return e;let n=[],i=[];for(let a of t)try{let c=await this.resolver.resolve(a.uri);for(let[u,l]of c)n.push(`PREFIX ${u}: <${l}>`);if(c.size===0){let u=this.extractPrefixFromUri(a.uri);u&&n.push(`PREFIX ${u}: <${a.uri}>`)}}catch(c){let u=c instanceof Error?c.message:String(c);i.push(`Failed to resolve vocabulary ${a.uri}: ${u}`)}if(n.length===0&&i.length>0)throw new ro(i.join("; "));let s=e;for(let a=t.length-1;a>=0;a--){let c=t[a];s=s.substring(0,c.startPos)+s.substring(c.endPos)}return n.length>0&&(s=n.join(`
|
|
258
258
|
`)+`
|
|
259
259
|
`+s.trimStart()),s}findPrefixStarDeclarations(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+6)==="PREFIX"){let s=i;for(i+=6;i<e.length&&/\s/.test(e[i]);)i++;if(e[i]==="*"){for(i++;i<e.length&&/\s/.test(e[i]);)i++;if(e[i]==="<"){i++;let a=i;for(;i<e.length&&e[i]!==">";)i++;if(e[i]===">"){let c=e.substring(a,i);i++;let u=this.findDeclarationEnd(e,i);t.push({uri:c,startPos:s,endPos:u}),i=u;continue}else throw new ro(`Unclosed IRI in PREFIX* declaration at position ${a}`)}else throw new ro(`Expected IRI after PREFIX* at position ${i}`)}else continue}i++}return t}findDeclarationEnd(e,t){let n=t;for(;n<e.length;){let i=e[n];if(i===`
|
|
260
|
-
`)return n+1;let s=e.substring(n).toUpperCase();if(s.startsWith("PREFIX")||s.startsWith("BASE")||s.startsWith("SELECT")||s.startsWith("CONSTRUCT")||s.startsWith("DESCRIBE")||s.startsWith("ASK"))return n;if(/\s/.test(i)){n++;continue}break}return n}extractPrefixFromUri(e){let t=e.replace(/^https?:\/\//,"");t=t.replace(/\/$/,"").replace(/#$/,"");let n=t.split(/[/.#]+/).filter(Boolean);if(n.length===0)return null;let i=n[n.length-1];return/^(ontology|vocab|schema|ns|core)$/i.test(i)&&n.length>1?n[n.length-2].toLowerCase():i.toLowerCase().replace(/[^a-z0-9]/g,"")}};ms.PrefixStarTransformer=W0;var ro=class extends Error{static{o(this,"PrefixStarTransformerError")}constructor(e){super(`PREFIX* transformation error: ${e}`),this.name="PrefixStarTransformerError"}};ms.PrefixStarTransformerError=ro});var H0=_(io=>{"use strict";Object.defineProperty(io,"__esModule",{value:!0});io.DescribeOptionsTransformer=io.DescribeOptionsTransformerError=void 0;var Qf=class extends Error{static{o(this,"DescribeOptionsTransformerError")}constructor(e){super(e),this.name="DescribeOptionsTransformerError"}};io.DescribeOptionsTransformerError=Qf;var no=class r{static{o(this,"DescribeOptionsTransformer")}transform(e){if(!r.DESCRIBE_QUERY_PATTERN.test(e))return{query:e};let t=e,n={},i=!1,s=r.DEPTH_PATTERN.exec(e);if(s){let a=parseInt(s[1],10);if(a<0)throw new Qf(`DESCRIBE DEPTH must be a non-negative integer, got: ${a}`);n.depth=a,i=!0,r.DEPTH_PATTERN.lastIndex=0,t=t.replace(r.DEPTH_PATTERN,"")}return r.DEPTH_PATTERN.lastIndex=0,r.SYMMETRIC_PATTERN.test(e)&&(n.symmetric=!0,i=!0,r.SYMMETRIC_PATTERN.lastIndex=0,t=t.replace(r.SYMMETRIC_PATTERN,"")),r.SYMMETRIC_PATTERN.lastIndex=0,t=t.replace(/\s{2,}/g," ").trim(),{query:t,options:i?n:void 0}}hasDescribeOptions(e){let t=r.DEPTH_PATTERN.test(e);r.DEPTH_PATTERN.lastIndex=0;let n=r.SYMMETRIC_PATTERN.test(e);return r.SYMMETRIC_PATTERN.lastIndex=0,t||n}};io.DescribeOptionsTransformer=no;no.DEPTH_PATTERN=/\bDEPTH\s+(\d+)/gi;no.SYMMETRIC_PATTERN=/\bSYMMETRIC\b/gi;no.DESCRIBE_QUERY_PATTERN=/\bDESCRIBE\b/i});var Ib=_(so=>{"use strict";Object.defineProperty(so,"__esModule",{value:!0});so.DirectionalLangTagTransformerError=so.DirectionalLangTagTransformer=void 0;var Kf=class r{static{o(this,"DirectionalLangTagTransformer")}constructor(){this.directionMappings=new Map}transform(e){return this.directionMappings.clear(),e.replace(r.DIRECTIONAL_TAG_REGEX,(t,n,i,s,a)=>{let c=s.toLowerCase();return this.directionMappings.set(c,a),`${n}${i}${n}@${s}`})}getDirection(e){return this.directionMappings.get(e.toLowerCase())}getAllMappings(){return new Map(this.directionMappings)}hasDirectionalTags(e){return r.DIRECTIONAL_TAG_REGEX.lastIndex=0,r.DIRECTIONAL_TAG_REGEX.test(e)}clearMappings(){this.directionMappings.clear()}};so.DirectionalLangTagTransformer=Kf;Kf.DIRECTIONAL_TAG_REGEX=/(["'])((?:[^\\]|\\.)*?)\1@([a-zA-Z]+(?:-[a-zA-Z0-9]+)*)--(ltr|rtl)/g;var z0=class extends Error{static{o(this,"DirectionalLangTagTransformerError")}constructor(e){super(`Directional language tag transformation error: ${e}`),this.name="DirectionalLangTagTransformerError"}};so.DirectionalLangTagTransformerError=z0});var Ob=_(oo=>{"use strict";Object.defineProperty(oo,"__esModule",{value:!0});oo.TripleTermTransformerError=oo.TripleTermTransformer=void 0;var Y0=class{static{o(this,"TripleTermTransformer")}transform(e){let t=e,n,i=0,s=100;do if(n=t,t=this.transformSinglePass(t),i++,i>s)throw new ao("Too many nested triple terms (max 100 iterations)");while(t!==n);return t}hasTripleTermSyntax(e){return this.findTripleTermPositions(e).length>0}transformSinglePass(e){let t=this.findTripleTermPositions(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.extractTripleTerm(n,s);if(a){let c=this.convertToStandardSyntax(a.content);n=n.substring(0,s)+c+n.substring(s+a.length)}}return n}findTripleTermPositions(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="'"){n=this.skipStringLiteral(e,n,"'");continue}if(e[n]==='"'){n=this.skipStringLiteral(e,n,'"');continue}if(e.substring(n,n+2)==="<<"&&this.isParenthesizedTripleTerm(e,n)){t.push(n),n+=2;continue}n++}return t}skipStringLiteral(e,t,n){let i=n.repeat(3);if(e.substring(t,t+3)===i){for(t+=3;t<e.length;){if(e.substring(t,t+3)===i)return t+3;e[t]==="\\"&&t++,t++}return t}for(t++;t<e.length&&e[t]!==n;)e[t]==="\\"&&t++,t++;return t+1}isParenthesizedTripleTerm(e,t){let n=t+2;for(;n<e.length&&/\s/.test(e[n]);)n++;return e[n]==="("}extractTripleTerm(e,t){let n=t+2;for(;n<e.length&&/\s/.test(e[n]);)n++;if(e[n]!=="(")return null;n++;let i=1;for(;n<e.length&&i>0;){if(e[n]==="'"||e[n]==='"'){n=this.skipStringLiteral(e,n,e[n]);continue}if(e.substring(n,n+2)==="<<"&&this.isParenthesizedTripleTerm(e,n)){for(n+=2;n<e.length&&/\s/.test(e[n]);)n++;e[n]==="("&&(i++,n++);continue}if(e.substring(n,n+2)==="<<"){n+=2;let s=1;for(;n<e.length&&s>0;){if(e[n]==="'"||e[n]==='"'){n=this.skipStringLiteral(e,n,e[n]);continue}if(e.substring(n,n+2)==="<<"){s++,n+=2;continue}if(e.substring(n,n+2)===">>"){s--,n+=2;continue}n++}continue}if(e[n]==="("){i++,n++;continue}if(e[n]===")"){let s=n+1;for(;s<e.length&&/\s/.test(e[s]);)s++;if(e.substring(s,s+2)===">>"){if(i--,i===0){let a=e.substring(t,s+2);return{content:a,length:a.length}}n=s+2;continue}n++;continue}n++}if(i>0)throw new ao(`Unclosed triple term at position ${t}: missing )>>`);return null}convertToStandardSyntax(e){let t=e.match(/^<<\s*\(\s*([\s\S]*?)\s*\)\s*>>$/);if(!t)throw new ao(`Invalid triple term syntax: ${e.substring(0,50)}...`);return`<< ${t[1]} >>`}};oo.TripleTermTransformer=Y0;var ao=class extends Error{static{o(this,"TripleTermTransformerError")}constructor(e){super(`Triple term transformation error: ${e}`),this.name="TripleTermTransformerError"}};oo.TripleTermTransformerError=ao});var Fb=_(mn=>{"use strict";var NN=mn&&mn.__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]})),LN=mn&&mn.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),MN=mn&&mn.__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"&&NN(t,e,n[i]);return LN(t,e),t}})();Object.defineProperty(mn,"__esModule",{value:!0});mn.SPARQLParser=mn.SPARQLParseError=void 0;var Pb=MN(xb()),Q0=q0(),K0=G0(),Db=Cb(),X0=H0(),kN=Ib(),J0=Ob(),Nt=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}};mn.SPARQLParseError=Nt;var Z0=class{static{o(this,"SPARQLParser")}constructor(e){this.lastDirectionMappings=new Map,this.parser=new Pb.Parser({sparqlStar:!0}),this.generator=new Pb.Generator({sparqlStar:!0}),this.caseWhenTransformer=new Q0.CaseWhenTransformer,this.lateralTransformer=new K0.LateralTransformer,this.prefixStarTransformer=new Db.PrefixStarTransformer(e?.vocabularyResolver),this.describeOptionsTransformer=new X0.DescribeOptionsTransformer,this.directionalLangTagTransformer=new kN.DirectionalLangTagTransformer,this.tripleTermTransformer=new J0.TripleTermTransformer}parse(e){try{let t=this.describeOptionsTransformer.transform(e);this.lastDescribeOptions=t.options;let n=t.query;n=this.directionalLangTagTransformer.transform(n),this.lastDirectionMappings=this.directionalLangTagTransformer.getAllMappings(),n=this.lateralTransformer.transform(n),n=this.caseWhenTransformer.transform(n),n=this.tripleTermTransformer.transform(n);let i=this.parser.parse(n);return this.validateQuery(i),this.lastDescribeOptions&&this.isDescribeQuery(i)&&(i.describeOptions=this.lastDescribeOptions),i}catch(t){if(t instanceof X0.DescribeOptionsTransformerError)throw new Nt(t.message);if(t instanceof K0.LateralTransformerError)throw new Nt(t.message);if(t instanceof Q0.CaseWhenTransformerError)throw new Nt(t.message);if(t instanceof J0.TripleTermTransformerError)throw new Nt(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 Nt(`SPARQL syntax error: ${t.message}`,i,s,t)}throw t}}parseWithOptions(e){return{query:this.parse(e),describeOptions:this.lastDescribeOptions}}getLastDescribeOptions(){return this.lastDescribeOptions}async parseAsync(e){try{let t=this.describeOptionsTransformer.transform(e);this.lastDescribeOptions=t.options;let n=t.query;n=this.directionalLangTagTransformer.transform(n),this.lastDirectionMappings=this.directionalLangTagTransformer.getAllMappings(),n=await this.prefixStarTransformer.transform(n),n=this.lateralTransformer.transform(n),n=this.caseWhenTransformer.transform(n),n=this.tripleTermTransformer.transform(n);let i=this.parser.parse(n);return this.validateQuery(i),this.lastDescribeOptions&&this.isDescribeQuery(i)&&(i.describeOptions=this.lastDescribeOptions),i}catch(t){if(t instanceof X0.DescribeOptionsTransformerError)throw new Nt(t.message);if(t instanceof Db.PrefixStarTransformerError)throw new Nt(t.message);if(t instanceof K0.LateralTransformerError)throw new Nt(t.message);if(t instanceof Q0.CaseWhenTransformerError)throw new Nt(t.message);if(t instanceof J0.TripleTermTransformerError)throw new Nt(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 Nt(`SPARQL syntax error: ${t.message}`,i,s,t)}throw t}}async parseAsyncWithOptions(e){return{query:await this.parseAsync(e),describeOptions:this.lastDescribeOptions}}hasPrefixStar(e){return/PREFIX\s*\*/i.test(e)}hasLateral(e){return this.lateralTransformer.hasLateral(e)}hasDescribeOptions(e){return this.describeOptionsTransformer.hasDescribeOptions(e)}hasDirectionalLangTags(e){return this.directionalLangTagTransformer.hasDirectionalTags(e)}hasTripleTermSyntax(e){return this.tripleTermTransformer.hasTripleTermSyntax(e)}getLastDirectionMappings(){return new Map(this.lastDirectionMappings)}getDirectionForLanguage(e){return this.lastDirectionMappings.get(e.toLowerCase())}toString(e){try{return this.generator.stringify(e)}catch(t){throw t instanceof Error?new Nt(`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 Nt("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"}isUpdateQuery(e){return e.type==="update"}isInsertDataOperation(e){return"updateType"in e&&e.updateType==="insert"}isDeleteDataOperation(e){return"updateType"in e&&e.updateType==="delete"}validateQuery(e){if(!e||typeof e!="object")throw new Nt("Invalid query: not an object");if(e.type!=="query"&&e.type!=="update")throw new Nt(`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 Nt(`Invalid query type: expected one of ${t.join(", ")}, got "${e.queryType}"`)}}};mn.SPARQLParser=Z0});var Nb=_(co=>{"use strict";Object.defineProperty(co,"__esModule",{value:!0});co.AlgebraTranslator=co.AlgebraTranslatorError=void 0;var Rb=G0(),me=class extends Error{static{o(this,"AlgebraTranslatorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="AlgebraTranslatorError"}};co.AlgebraTranslatorError=me;var ey=class{static{o(this,"AlgebraTranslator")}constructor(){this.directionMappings=new Map,this.aggregateCounter=0}setDirectionMappings(e){this.directionMappings=e}translate(e){if(e.type!=="query")throw new me("Only query operations are supported (not updates)");if(e.queryType==="SELECT")return this.translateSelect(e);if(e.queryType==="CONSTRUCT")return this.translateConstruct(e);if(e.queryType==="ASK")return this.translateAsk(e);if(e.queryType==="DESCRIBE")return this.translateDescribe(e);throw new me(`Query type ${e.queryType} not yet supported`)}translateSelect(e){let t;if(!e.where||e.where.length===0)throw new me("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 l=this.transformExpressionWithAggregateVars(u.expression,n);t={type:"extend",variable:u.variable.value,expression:l,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 me("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))}translateAsk(e){return{type:"ask",where:e.where&&e.where.length>0?this.translateWhere(e.where):{type:"bgp",triples:[]}}}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){let t=e.aggregation;if(typeof t=="string"){let n=t.toLowerCase();return["count","sum","avg","min","max","group_concat","sample"].includes(n)?{type:"aggregate",aggregation:n,expression:e.expression?this.translateExpression(e.expression):void 0,distinct:e.distinct||!1,separator:e.separator}:{type:"aggregate",aggregation:{type:"custom",iri:t},expression:e.expression?this.translateExpression(e.expression):void 0,distinct:e.distinct||!1,separator:e.separator}}if(t&&typeof t=="object"){let n;if(t.termType==="NamedNode"&&t.value)n=t.value;else if("value"in t)n=String(t.value);else throw new me(`Invalid custom aggregate: expected IRI but got ${JSON.stringify(t)}`);return{type:"aggregate",aggregation:{type:"custom",iri:n},expression:e.expression?this.translateExpression(e.expression):void 0,distinct:e.distinct||!1,separator:e.separator}}throw new me(`Unknown aggregate format: ${JSON.stringify(t)}`)}isLateralPattern(e){if(e.type==="query"&&this.isLateralSubquery(e))return!0;if(e.type==="group"&&e.patterns?.length===1){let t=e.patterns[0];if(t.type==="query"&&this.isLateralSubquery(t))return!0}return!1}extractLateralSubquery(e){if(e.type==="query")return e;if(e.type==="group"&&e.patterns?.length===1)return e.patterns[0];throw new me("Invalid lateral pattern structure")}translateWhere(e){if(e.length===0)throw new me("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;if(i.length===0)s={type:"bgp",triples:[]};else if(i.length===1)i[0].type==="optional"?s={type:"leftjoin",left:{type:"bgp",triples:[]},right:this.translateWhere(i[0].patterns),expression:i[0].expression?this.translateExpression(i[0].expression):void 0}:s=this.translatePattern(i[0]);else{i[0].type==="optional"?s={type:"leftjoin",left:{type:"bgp",triples:[]},right:this.translateWhere(i[0].patterns),expression:i[0].expression?this.translateExpression(i[0].expression):void 0}:s=this.translatePattern(i[0]);for(let a=1;a<i.length;a++){let c=i[a];if(this.isLateralPattern(c)){let u=this.extractLateralSubquery(c),l=this.removeLateralMarker(u),f=this.translateSelect(l);s={type:"lateraljoin",left:s,right:f}}else if(c.type==="optional")s={type:"leftjoin",left:s,right:this.translateWhere(c.patterns),expression:c.expression?this.translateExpression(c.expression):void 0};else{let u=this.translatePattern(c);s={type:"join",left:s,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 me("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);case"service":return this.translateService(e);case"graph":return this.translateGraph(e);default:throw new me(`Unsupported pattern type: ${e.type}`)}}translateBGP(e){if(!e.triples||!Array.isArray(e.triples))throw new me("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 me("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 me("Property path must have pathType");if(!e.items||!Array.isArray(e.items))throw new me("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 me("Inverse path must have exactly one item");return{type:"path",pathType:"^",items:[t[0]]};case"+":if(t.length!==1)throw new me("OneOrMore path must have exactly one item");return{type:"path",pathType:"+",items:[t[0]]};case"*":if(t.length!==1)throw new me("ZeroOrMore path must have exactly one item");return{type:"path",pathType:"*",items:[t[0]]};case"?":if(t.length!==1)throw new me("ZeroOrOne path must have exactly one item");return{type:"path",pathType:"?",items:[t[0]]};default:throw new me(`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 me(`Unsupported path item type: ${e.type||e.termType}`)}translateTripleElement(e){if(!e||!e.termType)throw new me("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":{let t={type:"literal",value:e.value,datatype:e.datatype?.value,language:e.language};if(e.language){let n=this.directionMappings.get(e.language.toLowerCase());n&&(t.direction=n)}return t}case"BlankNode":return{type:"blank",value:e.value};case"Quad":return this.translateQuotedTriple(e);default:throw new me(`Unsupported term type: ${e.termType}`)}}translateQuotedTriple(e){if(!e.subject||!e.predicate||!e.object)throw new me("Quoted triple must have subject, predicate, and object");let t=this.translateTripleElement(e.subject),n=this.translateQuotedTriplePredicate(e.predicate),i=this.translateTripleElement(e.object);return{type:"quoted",subject:t,predicate:n,object:i}}translateQuotedTriplePredicate(e){if(!e||!e.termType)throw new me("Quoted triple predicate must have termType");switch(e.termType){case"Variable":return{type:"variable",value:e.value};case"NamedNode":return{type:"iri",value:e.value};default:throw new me(`Quoted triple predicate must be IRI or Variable, got: ${e.termType}`)}}translateFilter(e){if(!e.expression)throw new me("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 me("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 me(`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):e.operator==="in"||e.operator==="notin"?this.translateInExpression(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 me("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}}translateInExpression(e){if(!e.args||e.args.length!==2)throw new me("IN/NOT IN must have exactly 2 arguments (expression and list)");let t=e.args[0],n=e.args[1];if(!Array.isArray(n))throw new me("IN/NOT IN second argument must be an array of values");return{type:"in",expression:this.translateExpression(t),list:n.map(i=>this.translateExpression(i)),negated:e.operator==="notin"}}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 me("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 me("UNION pattern must have at least 2 patterns");let t=o(i=>i.type==="graph"?this.translateGraph(i):i.type==="service"?this.translateService(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 me("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 me("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)if(a.termType==="NamedNode")t[s]={type:"iri",value:a.value};else if(a.termType==="Literal"){let c={type:"literal",value:a.value,datatype:a.datatype?.value,language:a.language||void 0};if(a.language){let u=this.directionMappings.get(a.language.toLowerCase());u&&(c.direction=u)}t[s]=c}else throw new me(`Unsupported VALUES term type: ${a.termType}`)}return t}translateBind(e,t){if(!e.variable||!e.expression)throw new me("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}}isLateralSubquery(e){return e.queryType!=="SELECT"||!e.variables?!1:e.variables.some(t=>t.termType==="Variable"&&t.value===Rb.LateralTransformer.LATERAL_MARKER)}removeLateralMarker(e){return e.variables?{...e,variables:e.variables.filter(t=>!(t.termType==="Variable"&&t.value===Rb.LateralTransformer.LATERAL_MARKER))}:e}translateSubquery(e){if(e.queryType!=="SELECT")throw new me(`Only SELECT subqueries are supported, got: ${e.queryType}`);let t=this.removeLateralMarker(e);return{type:"subquery",query:this.translateSelect(t)}}translateService(e){if(!e.name||e.name.termType!=="NamedNode")throw new me("SERVICE pattern must have a NamedNode endpoint");if(!e.patterns||!Array.isArray(e.patterns))throw new me("SERVICE pattern must have patterns array");let t=this.translateWhere(e.patterns);return{type:"service",endpoint:e.name.value,pattern:t,silent:e.silent||!1}}translateGraph(e){if(!e.name)throw new me("GRAPH pattern must have a name (IRI or variable)");if(!e.patterns||!Array.isArray(e.patterns))throw new me("GRAPH pattern must have patterns array");let t;if(e.name.termType==="NamedNode")t={type:"iri",value:e.name.value};else if(e.name.termType==="Variable")t={type:"variable",value:e.name.value};else throw new me(`GRAPH pattern name must be NamedNode or Variable, got: ${e.name.termType}`);let n=this.translateWhere(e.patterns);return{type:"graph",name:t,pattern:n}}translateDescribe(e){let t=[];if(e.variables&&Array.isArray(e.variables))for(let s of e.variables){let a=s;a.termType==="Wildcard"||a.value==="*"||(a.termType==="Variable"?t.push({type:"variable",value:a.value}):a.termType==="NamedNode"&&t.push({type:"iri",value:a.value}))}let n;e.where&&e.where.length>0&&(n=this.translateWhere(e.where));let i=e.describeOptions;return{type:"describe",resources:t,where:n,depth:i?.depth,symmetric:i?.symmetric}}};co.AlgebraTranslator=ey});var ry=_(Xf=>{"use strict";Object.defineProperty(Xf,"__esModule",{value:!0});Xf.FilterContainsOptimizer=void 0;var jN=Ye(),$N=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i,ty=class{static{o(this,"FilterContainsOptimizer")}constructor(){this.tripleStore=null,this.lastOptimizationHints=[]}setTripleStore(e){this.tripleStore=e}getLastOptimizationHints(){return this.lastOptimizationHints}clearHints(){this.lastOptimizationHints=[]}async optimize(e){return this.clearHints(),this.optimizeRecursive(e)}optimizeSync(e,t){return this.clearHints(),this.optimizeSyncRecursive(e,t)}async optimizeRecursive(e){return e.type==="filter"?this.optimizeFilter(e):e.type==="join"?{type:"join",left:await this.optimizeRecursive(e.left),right:await this.optimizeRecursive(e.right)}:e.type==="leftjoin"?{...e,left:await this.optimizeRecursive(e.left),right:await this.optimizeRecursive(e.right)}:e.type==="union"?{type:"union",left:await this.optimizeRecursive(e.left),right:await this.optimizeRecursive(e.right)}:e.type==="minus"?{...e,left:await this.optimizeRecursive(e.left),right:await this.optimizeRecursive(e.right)}:e.type==="project"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="orderby"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="slice"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="distinct"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="reduced"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="group"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="extend"?{...e,input:await this.optimizeRecursive(e.input)}:e}optimizeSyncRecursive(e,t){return e.type==="filter"?this.optimizeFilterSync(e,t):e.type==="join"?{type:"join",left:this.optimizeSyncRecursive(e.left,t),right:this.optimizeSyncRecursive(e.right,t)}:e.type==="leftjoin"?{...e,left:this.optimizeSyncRecursive(e.left,t),right:this.optimizeSyncRecursive(e.right,t)}:e.type==="union"?{type:"union",left:this.optimizeSyncRecursive(e.left,t),right:this.optimizeSyncRecursive(e.right,t)}:e.type==="minus"?{...e,left:this.optimizeSyncRecursive(e.left,t),right:this.optimizeSyncRecursive(e.right,t)}:e.type==="project"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="orderby"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="slice"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="distinct"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="reduced"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="group"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="extend"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e}async optimizeFilter(e){let t=this.detectContainsUUIDPattern(e.expression);if(!t)return{type:"filter",expression:e.expression,input:await this.optimizeRecursive(e.input)};let n=[];return this.tripleStore&&(n=await this.findSubjectsContainingUUID(t.uuid)),this.rewriteFilter(e,t,n)}optimizeFilterSync(e,t){let n=this.detectContainsUUIDPattern(e.expression);if(!n)return{type:"filter",expression:e.expression,input:this.optimizeSyncRecursive(e.input,t)};let i=t?t.filter(s=>s.includes(n.uuid)):[];return this.rewriteFilter(e,n,i)}rewriteFilter(e,t,n){if(this.lastOptimizationHints.push({type:"uuid-index-lookup",originalPattern:`FILTER(CONTAINS(STR(?${t.variable}), "${t.uuid}"))`,suggestedRewrite:n.length===1?`VALUES ?${t.variable} { <${n[0]}> }`:n.length>1?`VALUES ?${t.variable} { ${n.map(i=>`<${i}>`).join(" ")} }`:"No matching URIs found for UUID",estimatedSpeedup:n.length>0?"O(n) \u2192 O(1)":"N/A",matchedUri:n.length===1?n[0]:void 0}),n.length===0)return{type:"filter",expression:e.expression,input:this.optimizeSyncRecursive(e.input)};if(n.length===1){let i=this.injectSubjectConstraint(e.input,t.variable,n[0]);if(i!==e.input)return i}return this.createValuesJoin(e,t,n)}detectContainsUUIDPattern(e){if(e.type==="function"||e.type==="functionCall"){let t=e;if((typeof t.function=="string"?t.function.toLowerCase():t.function?.value?.toLowerCase()??"")==="contains"&&t.args.length===2)return this.analyzeContainsArgs(t.args[0],t.args[1],e)}if(e.type==="logical"&&e.operator==="&&")for(let t of e.operands){let n=this.detectContainsUUIDPattern(t);if(n)return n}return null}analyzeContainsArgs(e,t,n){let i=null;if(e.type==="function"||e.type==="functionCall"){let s=e;if((typeof s.function=="string"?s.function.toLowerCase():s.function?.value?.toLowerCase()??"")==="str"&&s.args.length===1){let c=s.args[0];c.type==="variable"&&(i=c.name)}}if(!i&&e.type==="variable"&&(i=e.name),!i)return null;if(t.type==="literal"){let c=String(t.value).match($N);if(c)return{variable:i,uuid:c[0].toLowerCase(),originalExpression:n}}return null}async findSubjectsContainingUUID(e){if(!this.tripleStore)return[];if(this.tripleStore.findSubjectsByUUID)return(await this.tripleStore.findSubjectsByUUID(e)).map(s=>s.value);let t=await this.tripleStore.subjects(),n=[];for(let i of t)i instanceof jN.IRI&&i.value.toLowerCase().includes(e.toLowerCase())&&n.push(i.value);return n}injectSubjectConstraint(e,t,n){if(e.type==="bgp"){let i=e.triples.map(a=>a.subject.type==="variable"&&a.subject.value===t?{...a,subject:{type:"iri",value:n}}:a);if(i.some((a,c)=>a.subject!==e.triples[c].subject))return{type:"bgp",triples:i}}if(e.type==="join"){let i=this.injectSubjectConstraint(e.left,t,n),s=this.injectSubjectConstraint(e.right,t,n);if(i!==e.left||s!==e.right)return{type:"join",left:i,right:s}}if(e.type==="filter"){let i=this.injectSubjectConstraint(e.input,t,n);if(i!==e.input)return{...e,input:i}}return e}createValuesJoin(e,t,n){return{type:"join",left:{type:"values",variables:[t.variable],bindings:n.map(a=>({[t.variable]:{type:"iri",value:a}}))},right:this.optimizeSyncRecursive(e.input)}}analyzeQuery(e){let t=[];return this.analyzeRecursive(e,t),t}analyzeRecursive(e,t){if(e.type==="filter"){let n=this.detectContainsUUIDPattern(e.expression);n&&t.push({type:"uuid-index-lookup",originalPattern:`FILTER(CONTAINS(STR(?${n.variable}), "${n.uuid}"))`,suggestedRewrite:`Use --optimize flag or rewrite as VALUES ?${n.variable} { <uri-containing-uuid> }`,estimatedSpeedup:"O(n) \u2192 O(1) with UUID index lookup"}),this.analyzeRecursive(e.input,t);return}e.type==="join"?(this.analyzeRecursive(e.left,t),this.analyzeRecursive(e.right,t)):e.type==="leftjoin"?(this.analyzeRecursive(e.left,t),this.analyzeRecursive(e.right,t)):e.type==="union"?(this.analyzeRecursive(e.left,t),this.analyzeRecursive(e.right,t)):e.type==="minus"?(this.analyzeRecursive(e.left,t),this.analyzeRecursive(e.right,t)):e.type==="project"?this.analyzeRecursive(e.input,t):e.type==="orderby"?this.analyzeRecursive(e.input,t):e.type==="slice"?this.analyzeRecursive(e.input,t):e.type==="distinct"?this.analyzeRecursive(e.input,t):e.type==="reduced"?this.analyzeRecursive(e.input,t):e.type==="group"?this.analyzeRecursive(e.input,t):e.type==="extend"&&this.analyzeRecursive(e.input,t)}};Xf.FilterContainsOptimizer=ty});var Lb=_(Jf=>{"use strict";Object.defineProperty(Jf,"__esModule",{value:!0});Jf.AlgebraOptimizer=void 0;var BN=ry(),ny=class{static{o(this,"AlgebraOptimizer")}constructor(){this.stats=new Map,this.tripleStore=null,this.filterContainsOptimizer=new BN.FilterContainsOptimizer}setTripleStore(e){this.tripleStore=e,this.filterContainsOptimizer.setTripleStore(e)}getOptimizationHints(){return this.filterContainsOptimizer.getLastOptimizationHints()}analyzeQuery(e){return this.filterContainsOptimizer.analyzeQuery(e)}optimize(e){let t=e;return t=this.eliminateEmptyBGPInFilterJoin(t),t=this.filterPushDown(t),t=this.joinReordering(t),t}async optimizeAsync(e){let t=e;return t=this.eliminateEmptyBGPInFilterJoin(t),this.tripleStore&&(t=await this.filterContainsOptimizer.optimize(t)),t=this.filterPushDown(t),t=this.joinReordering(t),t}optimizeWithSubjects(e,t){let n=e;return n=this.eliminateEmptyBGPInFilterJoin(n),n=this.filterContainsOptimizer.optimizeSync(n,t),n=this.filterPushDown(n),n=this.joinReordering(n),n}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)}};Jf.AlgebraOptimizer=ny});var Mb=_(Zf=>{"use strict";Object.defineProperty(Zf,"__esModule",{value:!0});Zf.AlgebraSerializer=void 0;var iy=class{static{o(this,"AlgebraSerializer")}toString(e,t=0){let n=" ".repeat(t);switch(e.type){case"bgp":return`${n}BGP [
|
|
260
|
+
`)return n+1;let s=e.substring(n).toUpperCase();if(s.startsWith("PREFIX")||s.startsWith("BASE")||s.startsWith("SELECT")||s.startsWith("CONSTRUCT")||s.startsWith("DESCRIBE")||s.startsWith("ASK"))return n;if(/\s/.test(i)){n++;continue}break}return n}extractPrefixFromUri(e){let t=e.replace(/^https?:\/\//,"");t=t.replace(/\/$/,"").replace(/#$/,"");let n=t.split(/[/.#]+/).filter(Boolean);if(n.length===0)return null;let i=n[n.length-1];return/^(ontology|vocab|schema|ns|core)$/i.test(i)&&n.length>1?n[n.length-2].toLowerCase():i.toLowerCase().replace(/[^a-z0-9]/g,"")}};ms.PrefixStarTransformer=W0;var ro=class extends Error{static{o(this,"PrefixStarTransformerError")}constructor(e){super(`PREFIX* transformation error: ${e}`),this.name="PrefixStarTransformerError"}};ms.PrefixStarTransformerError=ro});var H0=_(io=>{"use strict";Object.defineProperty(io,"__esModule",{value:!0});io.DescribeOptionsTransformer=io.DescribeOptionsTransformerError=void 0;var Qf=class extends Error{static{o(this,"DescribeOptionsTransformerError")}constructor(e){super(e),this.name="DescribeOptionsTransformerError"}};io.DescribeOptionsTransformerError=Qf;var no=class r{static{o(this,"DescribeOptionsTransformer")}transform(e){if(!r.DESCRIBE_QUERY_PATTERN.test(e))return{query:e};let t=e,n={},i=!1,s=r.DEPTH_PATTERN.exec(e);if(s){let a=parseInt(s[1],10);if(a<0)throw new Qf(`DESCRIBE DEPTH must be a non-negative integer, got: ${a}`);n.depth=a,i=!0,r.DEPTH_PATTERN.lastIndex=0,t=t.replace(r.DEPTH_PATTERN,"")}return r.DEPTH_PATTERN.lastIndex=0,r.SYMMETRIC_PATTERN.test(e)&&(n.symmetric=!0,i=!0,r.SYMMETRIC_PATTERN.lastIndex=0,t=t.replace(r.SYMMETRIC_PATTERN,"")),r.SYMMETRIC_PATTERN.lastIndex=0,t=t.replace(/\s{2,}/g," ").trim(),{query:t,options:i?n:void 0}}hasDescribeOptions(e){let t=r.DEPTH_PATTERN.test(e);r.DEPTH_PATTERN.lastIndex=0;let n=r.SYMMETRIC_PATTERN.test(e);return r.SYMMETRIC_PATTERN.lastIndex=0,t||n}};io.DescribeOptionsTransformer=no;no.DEPTH_PATTERN=/\bDEPTH\s+(\d+)/gi;no.SYMMETRIC_PATTERN=/\bSYMMETRIC\b/gi;no.DESCRIBE_QUERY_PATTERN=/\bDESCRIBE\b/i});var Ib=_(so=>{"use strict";Object.defineProperty(so,"__esModule",{value:!0});so.DirectionalLangTagTransformerError=so.DirectionalLangTagTransformer=void 0;var Kf=class r{static{o(this,"DirectionalLangTagTransformer")}constructor(){this.directionMappings=new Map}transform(e){return this.directionMappings.clear(),e.replace(r.DIRECTIONAL_TAG_REGEX,(t,n,i,s,a)=>{let c=s.toLowerCase();return this.directionMappings.set(c,a),`${n}${i}${n}@${s}`})}getDirection(e){return this.directionMappings.get(e.toLowerCase())}getAllMappings(){return new Map(this.directionMappings)}hasDirectionalTags(e){return r.DIRECTIONAL_TAG_REGEX.lastIndex=0,r.DIRECTIONAL_TAG_REGEX.test(e)}clearMappings(){this.directionMappings.clear()}};so.DirectionalLangTagTransformer=Kf;Kf.DIRECTIONAL_TAG_REGEX=/(["'])((?:[^\\]|\\.)*?)\1@([a-zA-Z]+(?:-[a-zA-Z0-9]+)*)--(ltr|rtl)/g;var z0=class extends Error{static{o(this,"DirectionalLangTagTransformerError")}constructor(e){super(`Directional language tag transformation error: ${e}`),this.name="DirectionalLangTagTransformerError"}};so.DirectionalLangTagTransformerError=z0});var Ob=_(oo=>{"use strict";Object.defineProperty(oo,"__esModule",{value:!0});oo.TripleTermTransformerError=oo.TripleTermTransformer=void 0;var Y0=class{static{o(this,"TripleTermTransformer")}transform(e){let t=e,n,i=0,s=100;do if(n=t,t=this.transformSinglePass(t),i++,i>s)throw new ao("Too many nested triple terms (max 100 iterations)");while(t!==n);return t}hasTripleTermSyntax(e){return this.findTripleTermPositions(e).length>0}transformSinglePass(e){let t=this.findTripleTermPositions(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.extractTripleTerm(n,s);if(a){let c=this.convertToStandardSyntax(a.content);n=n.substring(0,s)+c+n.substring(s+a.length)}}return n}findTripleTermPositions(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="'"){n=this.skipStringLiteral(e,n,"'");continue}if(e[n]==='"'){n=this.skipStringLiteral(e,n,'"');continue}if(e.substring(n,n+2)==="<<"&&this.isParenthesizedTripleTerm(e,n)){t.push(n),n+=2;continue}n++}return t}skipStringLiteral(e,t,n){let i=n.repeat(3);if(e.substring(t,t+3)===i){for(t+=3;t<e.length;){if(e.substring(t,t+3)===i)return t+3;e[t]==="\\"&&t++,t++}return t}for(t++;t<e.length&&e[t]!==n;)e[t]==="\\"&&t++,t++;return t+1}isParenthesizedTripleTerm(e,t){let n=t+2;for(;n<e.length&&/\s/.test(e[n]);)n++;return e[n]==="("}extractTripleTerm(e,t){let n=t+2;for(;n<e.length&&/\s/.test(e[n]);)n++;if(e[n]!=="(")return null;n++;let i=1;for(;n<e.length&&i>0;){if(e[n]==="'"||e[n]==='"'){n=this.skipStringLiteral(e,n,e[n]);continue}if(e.substring(n,n+2)==="<<"&&this.isParenthesizedTripleTerm(e,n)){for(n+=2;n<e.length&&/\s/.test(e[n]);)n++;e[n]==="("&&(i++,n++);continue}if(e.substring(n,n+2)==="<<"){n+=2;let s=1;for(;n<e.length&&s>0;){if(e[n]==="'"||e[n]==='"'){n=this.skipStringLiteral(e,n,e[n]);continue}if(e.substring(n,n+2)==="<<"){s++,n+=2;continue}if(e.substring(n,n+2)===">>"){s--,n+=2;continue}n++}continue}if(e[n]==="("){i++,n++;continue}if(e[n]===")"){let s=n+1;for(;s<e.length&&/\s/.test(e[s]);)s++;if(e.substring(s,s+2)===">>"){if(i--,i===0){let a=e.substring(t,s+2);return{content:a,length:a.length}}n=s+2;continue}n++;continue}n++}if(i>0)throw new ao(`Unclosed triple term at position ${t}: missing )>>`);return null}convertToStandardSyntax(e){let t=e.match(/^<<\s*\(\s*([\s\S]*?)\s*\)\s*>>$/);if(!t)throw new ao(`Invalid triple term syntax: ${e.substring(0,50)}...`);return`<< ${t[1]} >>`}};oo.TripleTermTransformer=Y0;var ao=class extends Error{static{o(this,"TripleTermTransformerError")}constructor(e){super(`Triple term transformation error: ${e}`),this.name="TripleTermTransformerError"}};oo.TripleTermTransformerError=ao});var Fb=_(mn=>{"use strict";var NN=mn&&mn.__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]})),LN=mn&&mn.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),MN=mn&&mn.__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"&&NN(t,e,n[i]);return LN(t,e),t}})();Object.defineProperty(mn,"__esModule",{value:!0});mn.SPARQLParser=mn.SPARQLParseError=void 0;var Pb=MN(xb()),Q0=q0(),K0=G0(),Db=Cb(),X0=H0(),kN=Ib(),J0=Ob(),Nt=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}};mn.SPARQLParseError=Nt;var Z0=class{static{o(this,"SPARQLParser")}constructor(e){this.lastDirectionMappings=new Map,this.parser=new Pb.Parser({sparqlStar:!0}),this.generator=new Pb.Generator({sparqlStar:!0}),this.caseWhenTransformer=new Q0.CaseWhenTransformer,this.lateralTransformer=new K0.LateralTransformer,this.prefixStarTransformer=new Db.PrefixStarTransformer(e?.vocabularyResolver),this.describeOptionsTransformer=new X0.DescribeOptionsTransformer,this.directionalLangTagTransformer=new kN.DirectionalLangTagTransformer,this.tripleTermTransformer=new J0.TripleTermTransformer}parse(e){try{let t=this.describeOptionsTransformer.transform(e);this.lastDescribeOptions=t.options;let n=t.query;n=this.directionalLangTagTransformer.transform(n),this.lastDirectionMappings=this.directionalLangTagTransformer.getAllMappings(),n=this.lateralTransformer.transform(n),n=this.caseWhenTransformer.transform(n),n=this.tripleTermTransformer.transform(n);let i=this.parser.parse(n);return this.validateQuery(i),this.lastDescribeOptions&&this.isDescribeQuery(i)&&(i.describeOptions=this.lastDescribeOptions),i}catch(t){if(t instanceof X0.DescribeOptionsTransformerError)throw new Nt(t.message);if(t instanceof K0.LateralTransformerError)throw new Nt(t.message);if(t instanceof Q0.CaseWhenTransformerError)throw new Nt(t.message);if(t instanceof J0.TripleTermTransformerError)throw new Nt(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 Nt(`SPARQL syntax error: ${t.message}`,i,s,t)}throw t}}parseWithOptions(e){return{query:this.parse(e),describeOptions:this.lastDescribeOptions}}getLastDescribeOptions(){return this.lastDescribeOptions}async parseAsync(e){try{let t=this.describeOptionsTransformer.transform(e);this.lastDescribeOptions=t.options;let n=t.query;n=this.directionalLangTagTransformer.transform(n),this.lastDirectionMappings=this.directionalLangTagTransformer.getAllMappings(),n=await this.prefixStarTransformer.transform(n),n=this.lateralTransformer.transform(n),n=this.caseWhenTransformer.transform(n),n=this.tripleTermTransformer.transform(n);let i=this.parser.parse(n);return this.validateQuery(i),this.lastDescribeOptions&&this.isDescribeQuery(i)&&(i.describeOptions=this.lastDescribeOptions),i}catch(t){if(t instanceof X0.DescribeOptionsTransformerError)throw new Nt(t.message);if(t instanceof Db.PrefixStarTransformerError)throw new Nt(t.message);if(t instanceof K0.LateralTransformerError)throw new Nt(t.message);if(t instanceof Q0.CaseWhenTransformerError)throw new Nt(t.message);if(t instanceof J0.TripleTermTransformerError)throw new Nt(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 Nt(`SPARQL syntax error: ${t.message}`,i,s,t)}throw t}}async parseAsyncWithOptions(e){return{query:await this.parseAsync(e),describeOptions:this.lastDescribeOptions}}hasPrefixStar(e){return/PREFIX\s*\*/i.test(e)}hasLateral(e){return this.lateralTransformer.hasLateral(e)}hasDescribeOptions(e){return this.describeOptionsTransformer.hasDescribeOptions(e)}hasDirectionalLangTags(e){return this.directionalLangTagTransformer.hasDirectionalTags(e)}hasTripleTermSyntax(e){return this.tripleTermTransformer.hasTripleTermSyntax(e)}getLastDirectionMappings(){return new Map(this.lastDirectionMappings)}getDirectionForLanguage(e){return this.lastDirectionMappings.get(e.toLowerCase())}toString(e){try{return this.generator.stringify(e)}catch(t){throw t instanceof Error?new Nt(`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 Nt("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"}isUpdateQuery(e){return e.type==="update"}isInsertDataOperation(e){return"updateType"in e&&e.updateType==="insert"}isDeleteDataOperation(e){return"updateType"in e&&e.updateType==="delete"}validateQuery(e){if(!e||typeof e!="object")throw new Nt("Invalid query: not an object");if(e.type!=="query"&&e.type!=="update")throw new Nt(`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 Nt(`Invalid query type: expected one of ${t.join(", ")}, got "${e.queryType}"`)}}};mn.SPARQLParser=Z0});var Nb=_(co=>{"use strict";Object.defineProperty(co,"__esModule",{value:!0});co.AlgebraTranslator=co.AlgebraTranslatorError=void 0;var Rb=G0(),me=class extends Error{static{o(this,"AlgebraTranslatorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="AlgebraTranslatorError"}};co.AlgebraTranslatorError=me;var ey=class{static{o(this,"AlgebraTranslator")}constructor(){this.directionMappings=new Map,this.aggregateCounter=0}setDirectionMappings(e){this.directionMappings=e}translate(e){if(e.type!=="query")throw new me("Only query operations are supported (not updates)");if(e.queryType==="SELECT")return this.translateSelect(e);if(e.queryType==="CONSTRUCT")return this.translateConstruct(e);if(e.queryType==="ASK")return this.translateAsk(e);if(e.queryType==="DESCRIBE")return this.translateDescribe(e);throw new me(`Query type ${e.queryType} not yet supported`)}translateSelect(e){let t;if(!e.where||e.where.length===0)throw new me("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),a=this.extractHavingExpressions(e.having,i,n);if((i.length>0||s.length>0||a.length>0)&&(t={type:"group",variables:s,aggregates:i,having:a.length>0?a:void 0,input:t}),e.variables&&e.variables.length>0){for(let u of e.variables){let l=u;if(l.expression&&l.variable){if(l.expression.type==="aggregate")continue;let f=this.transformExpressionWithAggregateVars(l.expression,n);t={type:"extend",variable:l.variable.value,expression:f,input:t}}}let c=e.variables.filter(u=>u.termType==="Variable"||u.variable).map(u=>u.termType==="Variable"?u.value:u.variable.value);c.length>0&&(t={type:"project",variables:c,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(c=>this.translateOrderComparator(c)),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 me("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))}translateAsk(e){return{type:"ask",where:e.where&&e.where.length>0?this.translateWhere(e.where):{type:"bgp",triples:[]}}}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):[]}extractHavingExpressions(e,t,n){if(!e||e.length===0)return[];for(let i of e)this.collectNestedAggregates(i,t,n);return e.map(i=>this.transformExpressionWithAggregateVars(i,n))}translateAggregateExpression(e){let t=e.aggregation;if(typeof t=="string"){let n=t.toLowerCase();return["count","sum","avg","min","max","group_concat","sample"].includes(n)?{type:"aggregate",aggregation:n,expression:e.expression?this.translateExpression(e.expression):void 0,distinct:e.distinct||!1,separator:e.separator}:{type:"aggregate",aggregation:{type:"custom",iri:t},expression:e.expression?this.translateExpression(e.expression):void 0,distinct:e.distinct||!1,separator:e.separator}}if(t&&typeof t=="object"){let n;if(t.termType==="NamedNode"&&t.value)n=t.value;else if("value"in t)n=String(t.value);else throw new me(`Invalid custom aggregate: expected IRI but got ${JSON.stringify(t)}`);return{type:"aggregate",aggregation:{type:"custom",iri:n},expression:e.expression?this.translateExpression(e.expression):void 0,distinct:e.distinct||!1,separator:e.separator}}throw new me(`Unknown aggregate format: ${JSON.stringify(t)}`)}isLateralPattern(e){if(e.type==="query"&&this.isLateralSubquery(e))return!0;if(e.type==="group"&&e.patterns?.length===1){let t=e.patterns[0];if(t.type==="query"&&this.isLateralSubquery(t))return!0}return!1}extractLateralSubquery(e){if(e.type==="query")return e;if(e.type==="group"&&e.patterns?.length===1)return e.patterns[0];throw new me("Invalid lateral pattern structure")}translateWhere(e){if(e.length===0)throw new me("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;if(i.length===0)s={type:"bgp",triples:[]};else if(i.length===1)i[0].type==="optional"?s={type:"leftjoin",left:{type:"bgp",triples:[]},right:this.translateWhere(i[0].patterns),expression:i[0].expression?this.translateExpression(i[0].expression):void 0}:s=this.translatePattern(i[0]);else{i[0].type==="optional"?s={type:"leftjoin",left:{type:"bgp",triples:[]},right:this.translateWhere(i[0].patterns),expression:i[0].expression?this.translateExpression(i[0].expression):void 0}:s=this.translatePattern(i[0]);for(let a=1;a<i.length;a++){let c=i[a];if(this.isLateralPattern(c)){let u=this.extractLateralSubquery(c),l=this.removeLateralMarker(u),f=this.translateSelect(l);s={type:"lateraljoin",left:s,right:f}}else if(c.type==="optional")s={type:"leftjoin",left:s,right:this.translateWhere(c.patterns),expression:c.expression?this.translateExpression(c.expression):void 0};else{let u=this.translatePattern(c);s={type:"join",left:s,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 me("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);case"service":return this.translateService(e);case"graph":return this.translateGraph(e);default:throw new me(`Unsupported pattern type: ${e.type}`)}}translateBGP(e){if(!e.triples||!Array.isArray(e.triples))throw new me("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 me("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 me("Property path must have pathType");if(!e.items||!Array.isArray(e.items))throw new me("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 me("Inverse path must have exactly one item");return{type:"path",pathType:"^",items:[t[0]]};case"+":if(t.length!==1)throw new me("OneOrMore path must have exactly one item");return{type:"path",pathType:"+",items:[t[0]]};case"*":if(t.length!==1)throw new me("ZeroOrMore path must have exactly one item");return{type:"path",pathType:"*",items:[t[0]]};case"?":if(t.length!==1)throw new me("ZeroOrOne path must have exactly one item");return{type:"path",pathType:"?",items:[t[0]]};default:throw new me(`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 me(`Unsupported path item type: ${e.type||e.termType}`)}translateTripleElement(e){if(!e||!e.termType)throw new me("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":{let t={type:"literal",value:e.value,datatype:e.datatype?.value,language:e.language};if(e.language){let n=this.directionMappings.get(e.language.toLowerCase());n&&(t.direction=n)}return t}case"BlankNode":return{type:"blank",value:e.value};case"Quad":return this.translateQuotedTriple(e);default:throw new me(`Unsupported term type: ${e.termType}`)}}translateQuotedTriple(e){if(!e.subject||!e.predicate||!e.object)throw new me("Quoted triple must have subject, predicate, and object");let t=this.translateTripleElement(e.subject),n=this.translateQuotedTriplePredicate(e.predicate),i=this.translateTripleElement(e.object);return{type:"quoted",subject:t,predicate:n,object:i}}translateQuotedTriplePredicate(e){if(!e||!e.termType)throw new me("Quoted triple predicate must have termType");switch(e.termType){case"Variable":return{type:"variable",value:e.value};case"NamedNode":return{type:"iri",value:e.value};default:throw new me(`Quoted triple predicate must be IRI or Variable, got: ${e.termType}`)}}translateFilter(e){if(!e.expression)throw new me("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 me("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 me(`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):e.operator==="in"||e.operator==="notin"?this.translateInExpression(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 me("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}}translateInExpression(e){if(!e.args||e.args.length!==2)throw new me("IN/NOT IN must have exactly 2 arguments (expression and list)");let t=e.args[0],n=e.args[1];if(!Array.isArray(n))throw new me("IN/NOT IN second argument must be an array of values");return{type:"in",expression:this.translateExpression(t),list:n.map(i=>this.translateExpression(i)),negated:e.operator==="notin"}}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 me("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 me("UNION pattern must have at least 2 patterns");let t=o(i=>i.type==="graph"?this.translateGraph(i):i.type==="service"?this.translateService(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 me("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 me("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)if(a.termType==="NamedNode")t[s]={type:"iri",value:a.value};else if(a.termType==="Literal"){let c={type:"literal",value:a.value,datatype:a.datatype?.value,language:a.language||void 0};if(a.language){let u=this.directionMappings.get(a.language.toLowerCase());u&&(c.direction=u)}t[s]=c}else throw new me(`Unsupported VALUES term type: ${a.termType}`)}return t}translateBind(e,t){if(!e.variable||!e.expression)throw new me("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}}isLateralSubquery(e){return e.queryType!=="SELECT"||!e.variables?!1:e.variables.some(t=>t.termType==="Variable"&&t.value===Rb.LateralTransformer.LATERAL_MARKER)}removeLateralMarker(e){return e.variables?{...e,variables:e.variables.filter(t=>!(t.termType==="Variable"&&t.value===Rb.LateralTransformer.LATERAL_MARKER))}:e}translateSubquery(e){if(e.queryType!=="SELECT")throw new me(`Only SELECT subqueries are supported, got: ${e.queryType}`);let t=this.removeLateralMarker(e);return{type:"subquery",query:this.translateSelect(t)}}translateService(e){if(!e.name||e.name.termType!=="NamedNode")throw new me("SERVICE pattern must have a NamedNode endpoint");if(!e.patterns||!Array.isArray(e.patterns))throw new me("SERVICE pattern must have patterns array");let t=this.translateWhere(e.patterns);return{type:"service",endpoint:e.name.value,pattern:t,silent:e.silent||!1}}translateGraph(e){if(!e.name)throw new me("GRAPH pattern must have a name (IRI or variable)");if(!e.patterns||!Array.isArray(e.patterns))throw new me("GRAPH pattern must have patterns array");let t;if(e.name.termType==="NamedNode")t={type:"iri",value:e.name.value};else if(e.name.termType==="Variable")t={type:"variable",value:e.name.value};else throw new me(`GRAPH pattern name must be NamedNode or Variable, got: ${e.name.termType}`);let n=this.translateWhere(e.patterns);return{type:"graph",name:t,pattern:n}}translateDescribe(e){let t=[];if(e.variables&&Array.isArray(e.variables))for(let s of e.variables){let a=s;a.termType==="Wildcard"||a.value==="*"||(a.termType==="Variable"?t.push({type:"variable",value:a.value}):a.termType==="NamedNode"&&t.push({type:"iri",value:a.value}))}let n;e.where&&e.where.length>0&&(n=this.translateWhere(e.where));let i=e.describeOptions;return{type:"describe",resources:t,where:n,depth:i?.depth,symmetric:i?.symmetric}}};co.AlgebraTranslator=ey});var ry=_(Xf=>{"use strict";Object.defineProperty(Xf,"__esModule",{value:!0});Xf.FilterContainsOptimizer=void 0;var jN=Ye(),$N=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i,ty=class{static{o(this,"FilterContainsOptimizer")}constructor(){this.tripleStore=null,this.lastOptimizationHints=[]}setTripleStore(e){this.tripleStore=e}getLastOptimizationHints(){return this.lastOptimizationHints}clearHints(){this.lastOptimizationHints=[]}async optimize(e){return this.clearHints(),this.optimizeRecursive(e)}optimizeSync(e,t){return this.clearHints(),this.optimizeSyncRecursive(e,t)}async optimizeRecursive(e){return e.type==="filter"?this.optimizeFilter(e):e.type==="join"?{type:"join",left:await this.optimizeRecursive(e.left),right:await this.optimizeRecursive(e.right)}:e.type==="leftjoin"?{...e,left:await this.optimizeRecursive(e.left),right:await this.optimizeRecursive(e.right)}:e.type==="union"?{type:"union",left:await this.optimizeRecursive(e.left),right:await this.optimizeRecursive(e.right)}:e.type==="minus"?{...e,left:await this.optimizeRecursive(e.left),right:await this.optimizeRecursive(e.right)}:e.type==="project"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="orderby"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="slice"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="distinct"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="reduced"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="group"?{...e,input:await this.optimizeRecursive(e.input)}:e.type==="extend"?{...e,input:await this.optimizeRecursive(e.input)}:e}optimizeSyncRecursive(e,t){return e.type==="filter"?this.optimizeFilterSync(e,t):e.type==="join"?{type:"join",left:this.optimizeSyncRecursive(e.left,t),right:this.optimizeSyncRecursive(e.right,t)}:e.type==="leftjoin"?{...e,left:this.optimizeSyncRecursive(e.left,t),right:this.optimizeSyncRecursive(e.right,t)}:e.type==="union"?{type:"union",left:this.optimizeSyncRecursive(e.left,t),right:this.optimizeSyncRecursive(e.right,t)}:e.type==="minus"?{...e,left:this.optimizeSyncRecursive(e.left,t),right:this.optimizeSyncRecursive(e.right,t)}:e.type==="project"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="orderby"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="slice"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="distinct"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="reduced"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="group"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e.type==="extend"?{...e,input:this.optimizeSyncRecursive(e.input,t)}:e}async optimizeFilter(e){let t=this.detectContainsUUIDPattern(e.expression);if(!t)return{type:"filter",expression:e.expression,input:await this.optimizeRecursive(e.input)};let n=[];return this.tripleStore&&(n=await this.findSubjectsContainingUUID(t.uuid)),this.rewriteFilter(e,t,n)}optimizeFilterSync(e,t){let n=this.detectContainsUUIDPattern(e.expression);if(!n)return{type:"filter",expression:e.expression,input:this.optimizeSyncRecursive(e.input,t)};let i=t?t.filter(s=>s.includes(n.uuid)):[];return this.rewriteFilter(e,n,i)}rewriteFilter(e,t,n){if(this.lastOptimizationHints.push({type:"uuid-index-lookup",originalPattern:`FILTER(CONTAINS(STR(?${t.variable}), "${t.uuid}"))`,suggestedRewrite:n.length===1?`VALUES ?${t.variable} { <${n[0]}> }`:n.length>1?`VALUES ?${t.variable} { ${n.map(i=>`<${i}>`).join(" ")} }`:"No matching URIs found for UUID",estimatedSpeedup:n.length>0?"O(n) \u2192 O(1)":"N/A",matchedUri:n.length===1?n[0]:void 0}),n.length===0)return{type:"filter",expression:e.expression,input:this.optimizeSyncRecursive(e.input)};if(n.length===1){let i=this.injectSubjectConstraint(e.input,t.variable,n[0]);if(i!==e.input)return i}return this.createValuesJoin(e,t,n)}detectContainsUUIDPattern(e){if(e.type==="function"||e.type==="functionCall"){let t=e;if((typeof t.function=="string"?t.function.toLowerCase():t.function?.value?.toLowerCase()??"")==="contains"&&t.args.length===2)return this.analyzeContainsArgs(t.args[0],t.args[1],e)}if(e.type==="logical"&&e.operator==="&&")for(let t of e.operands){let n=this.detectContainsUUIDPattern(t);if(n)return n}return null}analyzeContainsArgs(e,t,n){let i=null;if(e.type==="function"||e.type==="functionCall"){let s=e;if((typeof s.function=="string"?s.function.toLowerCase():s.function?.value?.toLowerCase()??"")==="str"&&s.args.length===1){let c=s.args[0];c.type==="variable"&&(i=c.name)}}if(!i&&e.type==="variable"&&(i=e.name),!i)return null;if(t.type==="literal"){let c=String(t.value).match($N);if(c)return{variable:i,uuid:c[0].toLowerCase(),originalExpression:n}}return null}async findSubjectsContainingUUID(e){if(!this.tripleStore)return[];if(this.tripleStore.findSubjectsByUUID)return(await this.tripleStore.findSubjectsByUUID(e)).map(s=>s.value);let t=await this.tripleStore.subjects(),n=[];for(let i of t)i instanceof jN.IRI&&i.value.toLowerCase().includes(e.toLowerCase())&&n.push(i.value);return n}injectSubjectConstraint(e,t,n){if(e.type==="bgp"){let i=e.triples.map(a=>a.subject.type==="variable"&&a.subject.value===t?{...a,subject:{type:"iri",value:n}}:a);if(i.some((a,c)=>a.subject!==e.triples[c].subject))return{type:"bgp",triples:i}}if(e.type==="join"){let i=this.injectSubjectConstraint(e.left,t,n),s=this.injectSubjectConstraint(e.right,t,n);if(i!==e.left||s!==e.right)return{type:"join",left:i,right:s}}if(e.type==="filter"){let i=this.injectSubjectConstraint(e.input,t,n);if(i!==e.input)return{...e,input:i}}return e}createValuesJoin(e,t,n){return{type:"join",left:{type:"values",variables:[t.variable],bindings:n.map(a=>({[t.variable]:{type:"iri",value:a}}))},right:this.optimizeSyncRecursive(e.input)}}analyzeQuery(e){let t=[];return this.analyzeRecursive(e,t),t}analyzeRecursive(e,t){if(e.type==="filter"){let n=this.detectContainsUUIDPattern(e.expression);n&&t.push({type:"uuid-index-lookup",originalPattern:`FILTER(CONTAINS(STR(?${n.variable}), "${n.uuid}"))`,suggestedRewrite:`Use --optimize flag or rewrite as VALUES ?${n.variable} { <uri-containing-uuid> }`,estimatedSpeedup:"O(n) \u2192 O(1) with UUID index lookup"}),this.analyzeRecursive(e.input,t);return}e.type==="join"?(this.analyzeRecursive(e.left,t),this.analyzeRecursive(e.right,t)):e.type==="leftjoin"?(this.analyzeRecursive(e.left,t),this.analyzeRecursive(e.right,t)):e.type==="union"?(this.analyzeRecursive(e.left,t),this.analyzeRecursive(e.right,t)):e.type==="minus"?(this.analyzeRecursive(e.left,t),this.analyzeRecursive(e.right,t)):e.type==="project"?this.analyzeRecursive(e.input,t):e.type==="orderby"?this.analyzeRecursive(e.input,t):e.type==="slice"?this.analyzeRecursive(e.input,t):e.type==="distinct"?this.analyzeRecursive(e.input,t):e.type==="reduced"?this.analyzeRecursive(e.input,t):e.type==="group"?this.analyzeRecursive(e.input,t):e.type==="extend"&&this.analyzeRecursive(e.input,t)}};Xf.FilterContainsOptimizer=ty});var Lb=_(Jf=>{"use strict";Object.defineProperty(Jf,"__esModule",{value:!0});Jf.AlgebraOptimizer=void 0;var BN=ry(),ny=class{static{o(this,"AlgebraOptimizer")}constructor(){this.stats=new Map,this.tripleStore=null,this.filterContainsOptimizer=new BN.FilterContainsOptimizer}setTripleStore(e){this.tripleStore=e,this.filterContainsOptimizer.setTripleStore(e)}getOptimizationHints(){return this.filterContainsOptimizer.getLastOptimizationHints()}analyzeQuery(e){return this.filterContainsOptimizer.analyzeQuery(e)}optimize(e){let t=e;return t=this.eliminateEmptyBGPInFilterJoin(t),t=this.filterPushDown(t),t=this.joinReordering(t),t}async optimizeAsync(e){let t=e;return t=this.eliminateEmptyBGPInFilterJoin(t),this.tripleStore&&(t=await this.filterContainsOptimizer.optimize(t)),t=this.filterPushDown(t),t=this.joinReordering(t),t}optimizeWithSubjects(e,t){let n=e;return n=this.eliminateEmptyBGPInFilterJoin(n),n=this.filterContainsOptimizer.optimizeSync(n,t),n=this.filterPushDown(n),n=this.joinReordering(n),n}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)}};Jf.AlgebraOptimizer=ny});var Mb=_(Zf=>{"use strict";Object.defineProperty(Zf,"__esModule",{value:!0});Zf.AlgebraSerializer=void 0;var iy=class{static{o(this,"AlgebraSerializer")}toString(e,t=0){let n=" ".repeat(t);switch(e.type){case"bgp":return`${n}BGP [
|
|
261
261
|
${e.triples.map(l=>`${n} ${this.tripleToString(l)}`).join(`
|
|
262
262
|
`)}
|
|
263
263
|
${n}]`;case"filter":return`${n}Filter(
|
|
@@ -311,7 +311,7 @@ ${n}}`}default:throw new wo(`Unsupported operation type for SPARQL generation: $
|
|
|
311
311
|
`)}generateTriple(e){let t=this.generateElement(e.subject),n=this.generatePredicate(e.predicate),i=this.generateElement(e.object);return`${t} ${n} ${i}`}generatePredicate(e){return"pathType"in e?this.generatePropertyPath(e):this.generateElement(e)}generatePropertyPath(e){let t=e.items.map(n=>"pathType"in n?`(${this.generatePropertyPath(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]}?`}}generateElement(e){switch(e.type){case"variable":return`?${e.value}`;case"iri":return`<${e.value}>`;case"literal":{let n=`"${e.value.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`;return e.language?n+=`@${e.language}`:e.datatype&&(n+=`^^<${e.datatype}>`),n}case"blank":return`_:${e.value}`;default:throw new wo(`Unknown element type: ${e.type}`)}}generateValues(e,t){let n=" ".repeat(t);if(e.variables.length===0||e.bindings.length===0)return"";if(e.variables.length===1){let a=e.variables[0],c=e.bindings.map(u=>{let l=u[a];return l?this.generateValuesTerm(l):"UNDEF"}).join(" ");return`${n}VALUES ?${a} { ${c} }`}let i=e.variables.map(a=>`?${a}`).join(" "),s=e.bindings.map(a=>`(${e.variables.map(u=>{let l=a[u];return l?this.generateValuesTerm(l):"UNDEF"}).join(" ")})`);return`${n}VALUES (${i}) {
|
|
312
312
|
${s.map(a=>`${n} ${a}`).join(`
|
|
313
313
|
`)}
|
|
314
|
-
${n}}`}generateValuesTerm(e){if(e.type==="iri")return`<${e.value}>`;let n=`"${e.value.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`;return e.language?n+=`@${e.language}`:e.datatype&&(n+=`^^<${e.datatype}>`),n}generateExpression(e){switch(e.type){case"variable":return`?${e.name}`;case"literal":return typeof e.value=="string"?`"${e.value.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:typeof e.value=="boolean"?e.value?"true":"false":String(e.value);case"comparison":return`(${this.generateExpression(e.left)} ${e.operator} ${this.generateExpression(e.right)})`;case"logical":return e.operator==="!"?`!(${this.generateExpression(e.operands[0])})`:`(${e.operands.map(t=>this.generateExpression(t)).join(` ${e.operator} `)})`;case"arithmetic":return`(${this.generateExpression(e.left)} ${e.operator} ${this.generateExpression(e.right)})`;case"function":return`${e.function.toUpperCase()}(${e.args.map(t=>this.generateExpression(t)).join(", ")})`;case"functionCall":return`${(typeof e.function=="string"?e.function:e.function.value).toUpperCase()}(${e.args.map(n=>this.generateExpression(n)).join(", ")})`;case"exists":return`${e.negated?"NOT EXISTS":"EXISTS"} { ${this.generateWhereClause(e.pattern,0)} }`;case"in":{let t=this.generateExpression(e.expression),n=e.list.map(i=>this.generateExpression(i)).join(", ");return e.negated?`${t} NOT IN (${n})`:`${t} IN (${n})`}default:throw new wo(`Unknown expression type: ${e.type}`)}}collectVariablesFromOperation(e,t){switch(e.type){case"bgp":for(let n of e.triples)this.collectVariablesFromTriple(n,t);break;case"filter":this.collectVariablesFromOperation(e.input,t),this.collectVariablesFromExpression(e.expression,t);break;case"join":case"leftjoin":case"union":case"minus":this.collectVariablesFromOperation(e.left,t),this.collectVariablesFromOperation(e.right,t);break;case"values":for(let n of e.variables)t.add(n);break;case"project":for(let n of e.variables)t.add(n);this.collectVariablesFromOperation(e.input,t);break;case"extend":t.add(e.variable),this.collectVariablesFromOperation(e.input,t);break;case"orderby":case"slice":case"distinct":case"reduced":this.collectVariablesFromOperation(e.input,t);break;case"group":for(let n of e.variables)t.add(n);for(let n of e.aggregates)t.add(n.variable);this.collectVariablesFromOperation(e.input,t);break;case"subquery":this.collectVariablesFromOperation(e.query,t);break}}collectVariablesFromTriple(e,t){e.subject.type==="variable"&&t.add(e.subject.value),"type"in e.predicate&&e.predicate.type==="variable"&&t.add(e.predicate.value),e.object.type==="variable"&&t.add(e.object.value)}collectVariablesFromExpression(e,t){switch(e.type){case"variable":t.add(e.name);break;case"comparison":case"arithmetic":this.collectVariablesFromExpression(e.left,t),this.collectVariablesFromExpression(e.right,t);break;case"logical":for(let n of e.operands)this.collectVariablesFromExpression(n,t);break;case"function":case"functionCall":for(let n of e.args)this.collectVariablesFromExpression(n,t);break;case"exists":this.collectVariablesFromOperation(e.pattern,t);break;case"in":this.collectVariablesFromExpression(e.expression,t);for(let n of e.list)this.collectVariablesFromExpression(n,t);break}}};Eo.SPARQLGenerator=Oy});var lw=_(gn=>{"use strict";var n5=gn&&gn.__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]})),i5=gn&&gn.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),s5=gn&&gn.__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"&&n5(t,e,n[i]);return i5(t,e),t}})();Object.defineProperty(gn,"__esModule",{value:!0});gn.QueryExecutor=gn.QueryExecutorError=void 0;var a5=uy(),o5=oh(),c5=dy(),u5=my(),l5=Zb(),f5=tw(),h5=iw(),d5=vy(),p5=aw(),m5=cw(),g5=uw(),y5=Ye(),To=class extends Error{static{o(this,"QueryExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="QueryExecutorError"}};gn.QueryExecutorError=To;var Py=class{static{o(this,"QueryExecutor")}constructor(e,t={}){this.tripleStore=e,this.bgpExecutor=new a5.BGPExecutor(e),this.filterExecutor=new o5.FilterExecutor,this.optionalExecutor=new c5.OptionalExecutor,this.unionExecutor=new u5.UnionExecutor,this.minusExecutor=new l5.MinusExecutor,this.valuesExecutor=new f5.ValuesExecutor,this.aggregateExecutor=new h5.AggregateExecutor,this.constructExecutor=new d5.ConstructExecutor,this.serviceExecutor=new p5.ServiceExecutor(t.serviceConfig),this.graphExecutor=new m5.GraphExecutor(e),this.sparqlGenerator=new g5.SPARQLGenerator,this.filterExecutor.setExistsEvaluator(async(n,i)=>this.evaluateExistsPattern(n,i)),this.filterExecutor.setTripleStore(e)}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;case"lateraljoin":yield*this.executeLateralJoin(e);break;case"service":yield*this.executeService(e);break;case"graph":yield*this.executeGraph(e);break;default:throw new To(`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)}async*executeLateralJoin(e){let t=[];for await(let n of this.execute(e.left))t.push(n);for(let n of t){let i=this.substituteVariables(e.right,n);for await(let s of this.execute(i)){let a=n.merge(s);a!==null&&(yield a)}}}substituteVariables(e,t){let n=JSON.parse(JSON.stringify(e));return this.substituteInOperation(n,t)}substituteInOperation(e,t){return!e||typeof e!="object"?e:e.type==="bgp"&&e.triples?(e.triples=e.triples.map(n=>this.substituteInTriple(n,t)),e):(e.input&&(e.input=this.substituteInOperation(e.input,t)),e.left&&(e.left=this.substituteInOperation(e.left,t)),e.right&&(e.right=this.substituteInOperation(e.right,t)),e.pattern&&(e.pattern=this.substituteInOperation(e.pattern,t)),e.query&&(e.query=this.substituteInOperation(e.query,t)),e.where&&(e.where=this.substituteInOperation(e.where,t)),e)}substituteInTriple(e,t){return{subject:this.substituteInTripleElement(e.subject,t),predicate:e.predicate,object:this.substituteInTripleElement(e.object,t)}}substituteInTripleElement(e,t){if(e&&e.type==="variable"){let n=t.get(e.value);if(n){if(n instanceof y5.IRI||n.termType==="NamedNode")return{type:"iri",value:n.value};if(n.termType==="Literal"||typeof n.value=="string"){let i=n;return{type:"literal",value:i.value,datatype:i.datatype?.value||i._datatype?.value,language:i.language||i._language}}}}return e}async*executeService(e){yield*this.serviceExecutor.execute(e,t=>this.sparqlGenerator.generateSelect(t))}async*executeGraph(e){let t=async function*(n,i){let s=this.currentGraphContext;this.currentGraphContext=i;try{n.type==="bgp"&&i&&this.tripleStore.matchInGraph?yield*this.executeBGPInGraph(n,i):yield*this.execute(n)}finally{this.currentGraphContext=s}}.bind(this);yield*this.graphExecutor.execute(e,t)}async*executeBGPInGraph(e,t){if(e.triples.length===0){let{SolutionMapping:n}=await Promise.resolve().then(()=>s5(Hi()));yield new n;return}yield*this.bgpExecutor.executeInGraph(e,t)}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 To("executeConstruct requires a CONSTRUCT operation");let t=await this.executeAll(e.where);return this.constructExecutor.execute(e.template,t)}isAskQuery(e){return e.type==="ask"}async executeAsk(e){if(e.type!=="ask")throw new To("executeAsk requires an ASK operation");for await(let t of this.execute(e.where))return!0;return!1}};gn.QueryExecutor=Py});var hw=_(xo=>{"use strict";Object.defineProperty(xo,"__esModule",{value:!0});xo.UpdateExecutor=xo.UpdateExecutorError=void 0;var _5=$i(),Ao=Ye(),Dy=ht(),fw=Rt(),hr=class extends Error{static{o(this,"UpdateExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="UpdateExecutorError"}};xo.UpdateExecutorError=hr;var Fy=class{static{o(this,"UpdateExecutor")}constructor(e){this.tripleStore=e}async execute(e){if(e.type!=="update")throw new hr("Expected UPDATE request");let t=[];for(let n of e.updates){let i=await this.executeOperation(n);t.push(i)}return t}async executeOperation(e){if("updateType"in e)switch(e.updateType){case"insert":return this.executeInsertData(e);case"delete":return this.executeDeleteData(e);case"insertdelete":throw new hr("INSERT/DELETE with WHERE clause not yet implemented");case"deletewhere":throw new hr("DELETE WHERE not yet implemented");default:throw new hr(`Unknown update type: ${e.updateType}`)}if("type"in e)switch(e.type){case"clear":case"drop":case"load":case"create":case"copy":case"move":case"add":throw new hr(`${e.type.toUpperCase()} operation not yet implemented`);default:throw new hr(`Unknown operation type: ${e.type}`)}throw new hr("Unknown update operation structure")}async executeInsertData(e){if(e.updateType!=="insert")throw new hr("Expected INSERT DATA operation");let t=e,n=0;for(let i of t.insert)if(i.type==="bgp"){let s=this.resolveGraphName(t.graph);n+=await this.insertTriples(i.triples,s)}else if(i.type==="graph"){let s=i,a=this.parseGraphName(s.name);n+=await this.insertTriples(s.triples,a)}return{type:"insert",inserted:n,success:!0}}async executeDeleteData(e){if(e.updateType!=="delete")throw new hr("Expected DELETE DATA operation");let t=e,n=0;for(let i of t.delete)if(i.type==="bgp"){let s=this.resolveGraphName(t.graph);n+=await this.deleteTriples(i.triples,s)}else if(i.type==="graph"){let s=i,a=this.parseGraphName(s.name);n+=await this.deleteTriples(s.triples,a)}return{type:"delete",deleted:n,success:!0}}async insertTriples(e,t){let n=0;for(let i of e){let s=this.convertTriple(i);t&&this.tripleStore.addToGraph?await this.tripleStore.addToGraph(s,t):await this.tripleStore.add(s),n++}return n}async deleteTriples(e,t){let n=0;for(let i of e){let s=this.convertTriple(i),a;t&&this.tripleStore.removeFromGraph?a=await this.tripleStore.removeFromGraph(s,t):a=await this.tripleStore.remove(s),a&&n++}return n}convertTriple(e){return new _5.Triple(this.convertSubject(e.subject),this.convertPredicate(e.predicate),this.convertObject(e.object))}convertSubject(e){if(e.termType==="NamedNode")return new Ao.IRI(e.value);if(e.termType==="BlankNode")return new fw.BlankNode(e.value);throw new hr(`Invalid subject term type: ${e.termType}. Variables are not allowed in INSERT DATA.`)}convertPredicate(e){if("termType"in e&&e.termType==="NamedNode")return new Ao.IRI(e.value);throw new hr("Invalid predicate term type. Only IRIs are allowed in INSERT DATA.")}convertObject(e){if(e.termType==="NamedNode")return new Ao.IRI(e.value);if(e.termType==="BlankNode")return new fw.BlankNode(e.value);if(e.termType==="Literal"){let t=e;return t.language?new Dy.Literal(t.value,void 0,t.language):t.datatype?new Dy.Literal(t.value,new Ao.IRI(t.datatype.value)):new Dy.Literal(t.value)}throw new hr(`Invalid object term type: ${e.termType}. Variables are not allowed in INSERT DATA.`)}resolveGraphName(e){if(e&&!e.default&&e.name)return new Ao.IRI(e.name.value)}parseGraphName(e){if(e.termType==="Variable")throw new hr("Variables are not allowed as graph names in INSERT DATA / DELETE DATA.");return new Ao.IRI(e.value)}};xo.UpdateExecutor=Fy});var pw=_(yh=>{"use strict";Object.defineProperty(yh,"__esModule",{value:!0});yh.AggregateFunctions=void 0;var Ry=ht(),dw=Ye(),Ny=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 Ry.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 Ry.Literal||a instanceof dw.IRI?i.push(a.value):i.push(a.toString()))}return i.join(n)}static sample(e,t){for(let n of e){let i=n.get(t);if(i)return this.toComparable(i)}return null}static sampleDistinct(e,t){return this.sample(e,t)}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 Ry.Literal){let t=this.toNumber(e);return isNaN(t)?e.value:t}return e instanceof dw.IRI?e.value:String(e)}};yh.AggregateFunctions=Ny});var mw=_(_h=>{"use strict";Object.defineProperty(_h,"__esModule",{value:!0});_h.QueryPlanCache=void 0;var v5=Nf(),Ly=class{static{o(this,"QueryPlanCache")}constructor(e=100){this.hits=0,this.misses=0,this.cache=new v5.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()}};_h.QueryPlanCache=Ly});var gw=_(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});Xc.SPARQLResultCache=void 0;Xc.createSPARQLResultCache=w5;var S5=Nf(),b5={maxSize:500,ttlMs:300*1e3,enableFileInvalidation:!0,maxResultSizeBytes:10*1024*1024},vh=class{static{o(this,"SPARQLResultCache")}constructor(e={}){this.fileToQueries=new Map,this.stats={hits:0,misses:0,evictions:0,ttlInvalidations:0,fileInvalidations:0,totalTimeSavedMs:0},this.avgQueryTimeMs=100,this.options={...b5,...e},this.cache=new S5.LRUCache(this.options.maxSize)}normalizeQuery(e){return e.replace(/\s+/g," ").trim()}hashResult(e){return this.isTripleArray(e)?`T:${e.length}`:`S:${e.length}`}isTripleArray(e){return e.length>0&&"subject"in e[0]}estimateResultSize(e){return this.isTripleArray(e)?e.length*300:e.length*200}get(e){let t=this.normalizeQuery(e),n=this.cache.get(t);if(n===void 0){this.stats.misses++;return}if(Date.now()-n.timestamp>this.options.ttlMs){this.cache.set(t,void 0),this.stats.ttlInvalidations++,this.stats.misses++;return}return this.stats.hits++,this.stats.totalTimeSavedMs+=this.avgQueryTimeMs,n.result}set(e,t,n,i){if(this.estimateResultSize(t)>this.options.maxResultSizeBytes)return;i!==void 0&&(this.avgQueryTimeMs=(this.avgQueryTimeMs+i)/2);let a=this.normalizeQuery(e),c=n??new Set,u={result:t,timestamp:Date.now(),affectedFiles:c,resultHash:this.hashResult(t)};if(this.cache.size()>=this.options.maxSize&&this.stats.evictions++,this.cache.set(a,u),this.options.enableFileInvalidation)for(let f of c){let h=this.fileToQueries.get(f);h||(h=new Set,this.fileToQueries.set(f,h)),h.add(a)}}has(e){let t=this.normalizeQuery(e),n=this.cache.get(t);return n===void 0?!1:Date.now()-n.timestamp<=this.options.ttlMs}invalidateByFile(e){if(!this.options.enableFileInvalidation)return 0;let t=this.fileToQueries.get(e);if(!t)return 0;let n=0;for(let i of t)this.cache.set(i,void 0),n++,this.stats.fileInvalidations++;return this.fileToQueries.delete(e),n}clear(){this.cache.clear(),this.fileToQueries.clear()}getStats(){let e=this.stats.hits+this.stats.misses,t=e>0?this.stats.hits/e:0;return{hits:this.stats.hits,misses:this.stats.misses,hitRate:t,size:this.cache.size(),maxSize:this.options.maxSize,evictions:this.stats.evictions,ttlInvalidations:this.stats.ttlInvalidations,fileInvalidations:this.stats.fileInvalidations,avgTimeSavedMs:this.stats.hits>0?this.stats.totalTimeSavedMs/this.stats.hits:0}}resetStats(){this.stats={hits:0,misses:0,evictions:0,ttlInvalidations:0,fileInvalidations:0,totalTimeSavedMs:0}}size(){return this.cache.size()}pruneExpired(){return 0}};Xc.SPARQLResultCache=vh;function w5(r){return new vh(r)}o(w5,"createSPARQLResultCache")});var yw=_(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});Jc.IncrementalIndexer=void 0;Jc.createIncrementalIndexer=T5;var E5={throttleMs:500,maxBatchSize:100,useContentHashing:!1},Sh=class{static{o(this,"IncrementalIndexer")}constructor(e={}){this.fileMetadata=new Map,this.pendingChanges=[],this.throttleTimer=null,this.invalidateCallbacks=[],this.lastIndexTime=0,this.stats={totalChanges:0,invalidations:0,noOpChanges:0,indexDurations:[]},this.options={...E5,...e}}recordChange(e){this.pendingChanges.push(e),this.stats.totalChanges++,this.throttleTimer===null&&(this.throttleTimer=setTimeout(()=>{this.processPendingChanges(),this.throttleTimer=null},this.options.throttleMs))}processPendingChanges(){if(this.pendingChanges.length===0)return;let e=performance.now(),t=new Map;for(let a of this.pendingChanges)t.set(a.path,a);let n=Array.from(t.values()),i=[];for(let a of n)switch(a.type){case"deleted":this.fileMetadata.delete(a.path),i.push(a);break;case"renamed":a.oldPath&&this.fileMetadata.delete(a.oldPath),i.push(a);break;case"created":case"modified":i.push(a);break}if(i.length>0){this.stats.invalidations+=i.length;for(let a of this.invalidateCallbacks)try{a(i)}catch(c){console.error("IncrementalIndexer: Error in invalidation callback:",c)}}let s=performance.now()-e;this.stats.indexDurations.push(s),this.stats.indexDurations.length>100&&this.stats.indexDurations.shift(),this.lastIndexTime=Date.now(),this.pendingChanges=[]}flush(){this.throttleTimer!==null&&(clearTimeout(this.throttleTimer),this.throttleTimer=null),this.processPendingChanges()}updateMetadata(e,t,n,i){this.fileMetadata.set(e,{mtime:t,size:n,contentHash:i})}hasChanged(e,t,n){let i=this.fileMetadata.get(e);return i===void 0||i.mtime!==t||n!==void 0&&i.size!==n}getChangedFiles(e){let t=[];for(let[n,i]of this.fileMetadata.entries())i.mtime>e&&t.push(n);return t}onInvalidate(e){return this.invalidateCallbacks.push(e),()=>{let t=this.invalidateCallbacks.indexOf(e);t!==-1&&this.invalidateCallbacks.splice(t,1)}}getStats(){let e=this.stats.indexDurations,t=e.length>0?e.reduce((i,s)=>i+s,0)/e.length:0,n=e.length>0?e[e.length-1]:0;return{trackedFiles:this.fileMetadata.size,totalChanges:this.stats.totalChanges,invalidations:this.stats.invalidations,noOpChanges:this.stats.noOpChanges,lastIndexDurationMs:n,avgIndexDurationMs:t,lastIndexTime:this.lastIndexTime}}resetStats(){this.stats={totalChanges:0,invalidations:0,noOpChanges:0,indexDurations:[]}}clear(){this.fileMetadata.clear(),this.pendingChanges=[],this.throttleTimer!==null&&(clearTimeout(this.throttleTimer),this.throttleTimer=null)}size(){return this.fileMetadata.size}isTracked(e){return this.fileMetadata.has(e)}getMetadata(e){return this.fileMetadata.get(e)}dispose(){this.throttleTimer!==null&&(clearTimeout(this.throttleTimer),this.throttleTimer=null),this.invalidateCallbacks=[],this.pendingChanges=[],this.fileMetadata.clear()}};Jc.IncrementalIndexer=Sh;function T5(r){return new Sh(r)}o(T5,"createIncrementalIndexer")});var _w=_(Th=>{"use strict";Object.defineProperty(Th,"__esModule",{value:!0});Th.ResultSerializer=void 0;var bh=ht(),wh=Ye(),Eh=Rt(),My=class{static{o(this,"ResultSerializer")}serialize(e,t,n={}){switch(t){case"json":return this.serializeJSON(e,n);case"xml":return this.serializeXML(e,n);case"csv":return this.serializeCSV(e,n);case"turtle":return this.serializeTurtle(e,n);default:throw new Error(`Unsupported result format: ${t}`)}}serializeJSON(e,t={}){let n=this.toJSONResultSet(e,t),i=t.pretty?t.indent??2:void 0;return JSON.stringify(n,null,i)}toJSONResultSet(e,t={}){let n=new Set;for(let a of e)for(let c of a.variables())n.add(c);let i=t.variables??Array.from(n).sort(),s=e.map(a=>{let c={};for(let u of i){let l=a.get(u);l!==void 0&&(c[u]=this.termToJSONBinding(l))}return c});return{head:{vars:i},results:{bindings:s}}}termToJSONBinding(e){return e instanceof wh.IRI?{type:"uri",value:e.value}:e instanceof Eh.BlankNode?{type:"bnode",value:e.id}:e instanceof bh.Literal?this.literalToJSONBinding(e):{type:"literal",value:String(e)}}literalToJSONBinding(e){let t={type:"literal",value:e.value};return e.datatype?t.datatype=e.datatype.value:e.language&&(t["xml:lang"]=e.language,e.hasDirection()&&e.direction&&(t.direction=e.direction)),t}serializeXML(e,t={}){let n=new Set;for(let a of e)for(let c of a.variables())n.add(c);let i=t.variables??Array.from(n).sort(),s=['<?xml version="1.0"?>','<sparql xmlns="http://www.w3.org/2005/sparql-results#">'," <head>"];for(let a of i)s.push(` <variable name="${this.escapeXML(a)}"/>`);s.push(" </head>"),s.push(" <results>");for(let a of e){s.push(" <result>");for(let c of i){let u=a.get(c);u!==void 0&&(s.push(` <binding name="${this.escapeXML(c)}">`),s.push(" "+this.termToXML(u)),s.push(" </binding>"))}s.push(" </result>")}return s.push(" </results>"),s.push("</sparql>"),s.join(`
|
|
314
|
+
${n}}`}generateValuesTerm(e){if(e.type==="iri")return`<${e.value}>`;let n=`"${e.value.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`;return e.language?n+=`@${e.language}`:e.datatype&&(n+=`^^<${e.datatype}>`),n}generateExpression(e){switch(e.type){case"variable":return`?${e.name}`;case"literal":return typeof e.value=="string"?`"${e.value.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:typeof e.value=="boolean"?e.value?"true":"false":String(e.value);case"comparison":return`(${this.generateExpression(e.left)} ${e.operator} ${this.generateExpression(e.right)})`;case"logical":return e.operator==="!"?`!(${this.generateExpression(e.operands[0])})`:`(${e.operands.map(t=>this.generateExpression(t)).join(` ${e.operator} `)})`;case"arithmetic":return`(${this.generateExpression(e.left)} ${e.operator} ${this.generateExpression(e.right)})`;case"function":return`${e.function.toUpperCase()}(${e.args.map(t=>this.generateExpression(t)).join(", ")})`;case"functionCall":return`${(typeof e.function=="string"?e.function:e.function.value).toUpperCase()}(${e.args.map(n=>this.generateExpression(n)).join(", ")})`;case"exists":return`${e.negated?"NOT EXISTS":"EXISTS"} { ${this.generateWhereClause(e.pattern,0)} }`;case"in":{let t=this.generateExpression(e.expression),n=e.list.map(i=>this.generateExpression(i)).join(", ");return e.negated?`${t} NOT IN (${n})`:`${t} IN (${n})`}default:throw new wo(`Unknown expression type: ${e.type}`)}}collectVariablesFromOperation(e,t){switch(e.type){case"bgp":for(let n of e.triples)this.collectVariablesFromTriple(n,t);break;case"filter":this.collectVariablesFromOperation(e.input,t),this.collectVariablesFromExpression(e.expression,t);break;case"join":case"leftjoin":case"union":case"minus":this.collectVariablesFromOperation(e.left,t),this.collectVariablesFromOperation(e.right,t);break;case"values":for(let n of e.variables)t.add(n);break;case"project":for(let n of e.variables)t.add(n);this.collectVariablesFromOperation(e.input,t);break;case"extend":t.add(e.variable),this.collectVariablesFromOperation(e.input,t);break;case"orderby":case"slice":case"distinct":case"reduced":this.collectVariablesFromOperation(e.input,t);break;case"group":for(let n of e.variables)t.add(n);for(let n of e.aggregates)t.add(n.variable);this.collectVariablesFromOperation(e.input,t);break;case"subquery":this.collectVariablesFromOperation(e.query,t);break}}collectVariablesFromTriple(e,t){e.subject.type==="variable"&&t.add(e.subject.value),"type"in e.predicate&&e.predicate.type==="variable"&&t.add(e.predicate.value),e.object.type==="variable"&&t.add(e.object.value)}collectVariablesFromExpression(e,t){switch(e.type){case"variable":t.add(e.name);break;case"comparison":case"arithmetic":this.collectVariablesFromExpression(e.left,t),this.collectVariablesFromExpression(e.right,t);break;case"logical":for(let n of e.operands)this.collectVariablesFromExpression(n,t);break;case"function":case"functionCall":for(let n of e.args)this.collectVariablesFromExpression(n,t);break;case"exists":this.collectVariablesFromOperation(e.pattern,t);break;case"in":this.collectVariablesFromExpression(e.expression,t);for(let n of e.list)this.collectVariablesFromExpression(n,t);break}}};Eo.SPARQLGenerator=Oy});var lw=_(gn=>{"use strict";var n5=gn&&gn.__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]})),i5=gn&&gn.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),s5=gn&&gn.__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"&&n5(t,e,n[i]);return i5(t,e),t}})();Object.defineProperty(gn,"__esModule",{value:!0});gn.QueryExecutor=gn.QueryExecutorError=void 0;var a5=uy(),o5=oh(),c5=dy(),u5=my(),l5=Zb(),f5=tw(),h5=iw(),d5=vy(),p5=aw(),m5=cw(),g5=uw(),y5=Ye(),To=class extends Error{static{o(this,"QueryExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="QueryExecutorError"}};gn.QueryExecutorError=To;var Py=class{static{o(this,"QueryExecutor")}constructor(e,t={}){this.tripleStore=e,this.bgpExecutor=new a5.BGPExecutor(e),this.filterExecutor=new o5.FilterExecutor,this.optionalExecutor=new c5.OptionalExecutor,this.unionExecutor=new u5.UnionExecutor,this.minusExecutor=new l5.MinusExecutor,this.valuesExecutor=new f5.ValuesExecutor,this.aggregateExecutor=new h5.AggregateExecutor,this.constructExecutor=new d5.ConstructExecutor,this.serviceExecutor=new p5.ServiceExecutor(t.serviceConfig),this.graphExecutor=new m5.GraphExecutor(e),this.sparqlGenerator=new g5.SPARQLGenerator,this.filterExecutor.setExistsEvaluator(async(n,i)=>this.evaluateExistsPattern(n,i)),this.filterExecutor.setTripleStore(e)}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;case"lateraljoin":yield*this.executeLateralJoin(e);break;case"service":yield*this.executeService(e);break;case"graph":yield*this.executeGraph(e);break;default:throw new To(`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);if(e.having&&e.having.length>0)for(let i of n)e.having.every(a=>this.filterExecutor.evaluateExpression(a,i)===!0)&&(yield i);else 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)}async*executeLateralJoin(e){let t=[];for await(let n of this.execute(e.left))t.push(n);for(let n of t){let i=this.substituteVariables(e.right,n);for await(let s of this.execute(i)){let a=n.merge(s);a!==null&&(yield a)}}}substituteVariables(e,t){let n=JSON.parse(JSON.stringify(e));return this.substituteInOperation(n,t)}substituteInOperation(e,t){return!e||typeof e!="object"?e:e.type==="bgp"&&e.triples?(e.triples=e.triples.map(n=>this.substituteInTriple(n,t)),e):(e.input&&(e.input=this.substituteInOperation(e.input,t)),e.left&&(e.left=this.substituteInOperation(e.left,t)),e.right&&(e.right=this.substituteInOperation(e.right,t)),e.pattern&&(e.pattern=this.substituteInOperation(e.pattern,t)),e.query&&(e.query=this.substituteInOperation(e.query,t)),e.where&&(e.where=this.substituteInOperation(e.where,t)),e)}substituteInTriple(e,t){return{subject:this.substituteInTripleElement(e.subject,t),predicate:e.predicate,object:this.substituteInTripleElement(e.object,t)}}substituteInTripleElement(e,t){if(e&&e.type==="variable"){let n=t.get(e.value);if(n){if(n instanceof y5.IRI||n.termType==="NamedNode")return{type:"iri",value:n.value};if(n.termType==="Literal"||typeof n.value=="string"){let i=n;return{type:"literal",value:i.value,datatype:i.datatype?.value||i._datatype?.value,language:i.language||i._language}}}}return e}async*executeService(e){yield*this.serviceExecutor.execute(e,t=>this.sparqlGenerator.generateSelect(t))}async*executeGraph(e){let t=async function*(n,i){let s=this.currentGraphContext;this.currentGraphContext=i;try{n.type==="bgp"&&i&&this.tripleStore.matchInGraph?yield*this.executeBGPInGraph(n,i):yield*this.execute(n)}finally{this.currentGraphContext=s}}.bind(this);yield*this.graphExecutor.execute(e,t)}async*executeBGPInGraph(e,t){if(e.triples.length===0){let{SolutionMapping:n}=await Promise.resolve().then(()=>s5(Hi()));yield new n;return}yield*this.bgpExecutor.executeInGraph(e,t)}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 To("executeConstruct requires a CONSTRUCT operation");let t=await this.executeAll(e.where);return this.constructExecutor.execute(e.template,t)}isAskQuery(e){return e.type==="ask"}async executeAsk(e){if(e.type!=="ask")throw new To("executeAsk requires an ASK operation");for await(let t of this.execute(e.where))return!0;return!1}};gn.QueryExecutor=Py});var hw=_(xo=>{"use strict";Object.defineProperty(xo,"__esModule",{value:!0});xo.UpdateExecutor=xo.UpdateExecutorError=void 0;var _5=$i(),Ao=Ye(),Dy=ht(),fw=Rt(),hr=class extends Error{static{o(this,"UpdateExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="UpdateExecutorError"}};xo.UpdateExecutorError=hr;var Fy=class{static{o(this,"UpdateExecutor")}constructor(e){this.tripleStore=e}async execute(e){if(e.type!=="update")throw new hr("Expected UPDATE request");let t=[];for(let n of e.updates){let i=await this.executeOperation(n);t.push(i)}return t}async executeOperation(e){if("updateType"in e)switch(e.updateType){case"insert":return this.executeInsertData(e);case"delete":return this.executeDeleteData(e);case"insertdelete":throw new hr("INSERT/DELETE with WHERE clause not yet implemented");case"deletewhere":throw new hr("DELETE WHERE not yet implemented");default:throw new hr(`Unknown update type: ${e.updateType}`)}if("type"in e)switch(e.type){case"clear":case"drop":case"load":case"create":case"copy":case"move":case"add":throw new hr(`${e.type.toUpperCase()} operation not yet implemented`);default:throw new hr(`Unknown operation type: ${e.type}`)}throw new hr("Unknown update operation structure")}async executeInsertData(e){if(e.updateType!=="insert")throw new hr("Expected INSERT DATA operation");let t=e,n=0;for(let i of t.insert)if(i.type==="bgp"){let s=this.resolveGraphName(t.graph);n+=await this.insertTriples(i.triples,s)}else if(i.type==="graph"){let s=i,a=this.parseGraphName(s.name);n+=await this.insertTriples(s.triples,a)}return{type:"insert",inserted:n,success:!0}}async executeDeleteData(e){if(e.updateType!=="delete")throw new hr("Expected DELETE DATA operation");let t=e,n=0;for(let i of t.delete)if(i.type==="bgp"){let s=this.resolveGraphName(t.graph);n+=await this.deleteTriples(i.triples,s)}else if(i.type==="graph"){let s=i,a=this.parseGraphName(s.name);n+=await this.deleteTriples(s.triples,a)}return{type:"delete",deleted:n,success:!0}}async insertTriples(e,t){let n=0;for(let i of e){let s=this.convertTriple(i);t&&this.tripleStore.addToGraph?await this.tripleStore.addToGraph(s,t):await this.tripleStore.add(s),n++}return n}async deleteTriples(e,t){let n=0;for(let i of e){let s=this.convertTriple(i),a;t&&this.tripleStore.removeFromGraph?a=await this.tripleStore.removeFromGraph(s,t):a=await this.tripleStore.remove(s),a&&n++}return n}convertTriple(e){return new _5.Triple(this.convertSubject(e.subject),this.convertPredicate(e.predicate),this.convertObject(e.object))}convertSubject(e){if(e.termType==="NamedNode")return new Ao.IRI(e.value);if(e.termType==="BlankNode")return new fw.BlankNode(e.value);throw new hr(`Invalid subject term type: ${e.termType}. Variables are not allowed in INSERT DATA.`)}convertPredicate(e){if("termType"in e&&e.termType==="NamedNode")return new Ao.IRI(e.value);throw new hr("Invalid predicate term type. Only IRIs are allowed in INSERT DATA.")}convertObject(e){if(e.termType==="NamedNode")return new Ao.IRI(e.value);if(e.termType==="BlankNode")return new fw.BlankNode(e.value);if(e.termType==="Literal"){let t=e;return t.language?new Dy.Literal(t.value,void 0,t.language):t.datatype?new Dy.Literal(t.value,new Ao.IRI(t.datatype.value)):new Dy.Literal(t.value)}throw new hr(`Invalid object term type: ${e.termType}. Variables are not allowed in INSERT DATA.`)}resolveGraphName(e){if(e&&!e.default&&e.name)return new Ao.IRI(e.name.value)}parseGraphName(e){if(e.termType==="Variable")throw new hr("Variables are not allowed as graph names in INSERT DATA / DELETE DATA.");return new Ao.IRI(e.value)}};xo.UpdateExecutor=Fy});var pw=_(yh=>{"use strict";Object.defineProperty(yh,"__esModule",{value:!0});yh.AggregateFunctions=void 0;var Ry=ht(),dw=Ye(),Ny=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 Ry.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 Ry.Literal||a instanceof dw.IRI?i.push(a.value):i.push(a.toString()))}return i.join(n)}static sample(e,t){for(let n of e){let i=n.get(t);if(i)return this.toComparable(i)}return null}static sampleDistinct(e,t){return this.sample(e,t)}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 Ry.Literal){let t=this.toNumber(e);return isNaN(t)?e.value:t}return e instanceof dw.IRI?e.value:String(e)}};yh.AggregateFunctions=Ny});var mw=_(_h=>{"use strict";Object.defineProperty(_h,"__esModule",{value:!0});_h.QueryPlanCache=void 0;var v5=Nf(),Ly=class{static{o(this,"QueryPlanCache")}constructor(e=100){this.hits=0,this.misses=0,this.cache=new v5.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()}};_h.QueryPlanCache=Ly});var gw=_(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});Xc.SPARQLResultCache=void 0;Xc.createSPARQLResultCache=w5;var S5=Nf(),b5={maxSize:500,ttlMs:300*1e3,enableFileInvalidation:!0,maxResultSizeBytes:10*1024*1024},vh=class{static{o(this,"SPARQLResultCache")}constructor(e={}){this.fileToQueries=new Map,this.stats={hits:0,misses:0,evictions:0,ttlInvalidations:0,fileInvalidations:0,totalTimeSavedMs:0},this.avgQueryTimeMs=100,this.options={...b5,...e},this.cache=new S5.LRUCache(this.options.maxSize)}normalizeQuery(e){return e.replace(/\s+/g," ").trim()}hashResult(e){return this.isTripleArray(e)?`T:${e.length}`:`S:${e.length}`}isTripleArray(e){return e.length>0&&"subject"in e[0]}estimateResultSize(e){return this.isTripleArray(e)?e.length*300:e.length*200}get(e){let t=this.normalizeQuery(e),n=this.cache.get(t);if(n===void 0){this.stats.misses++;return}if(Date.now()-n.timestamp>this.options.ttlMs){this.cache.set(t,void 0),this.stats.ttlInvalidations++,this.stats.misses++;return}return this.stats.hits++,this.stats.totalTimeSavedMs+=this.avgQueryTimeMs,n.result}set(e,t,n,i){if(this.estimateResultSize(t)>this.options.maxResultSizeBytes)return;i!==void 0&&(this.avgQueryTimeMs=(this.avgQueryTimeMs+i)/2);let a=this.normalizeQuery(e),c=n??new Set,u={result:t,timestamp:Date.now(),affectedFiles:c,resultHash:this.hashResult(t)};if(this.cache.size()>=this.options.maxSize&&this.stats.evictions++,this.cache.set(a,u),this.options.enableFileInvalidation)for(let f of c){let h=this.fileToQueries.get(f);h||(h=new Set,this.fileToQueries.set(f,h)),h.add(a)}}has(e){let t=this.normalizeQuery(e),n=this.cache.get(t);return n===void 0?!1:Date.now()-n.timestamp<=this.options.ttlMs}invalidateByFile(e){if(!this.options.enableFileInvalidation)return 0;let t=this.fileToQueries.get(e);if(!t)return 0;let n=0;for(let i of t)this.cache.set(i,void 0),n++,this.stats.fileInvalidations++;return this.fileToQueries.delete(e),n}clear(){this.cache.clear(),this.fileToQueries.clear()}getStats(){let e=this.stats.hits+this.stats.misses,t=e>0?this.stats.hits/e:0;return{hits:this.stats.hits,misses:this.stats.misses,hitRate:t,size:this.cache.size(),maxSize:this.options.maxSize,evictions:this.stats.evictions,ttlInvalidations:this.stats.ttlInvalidations,fileInvalidations:this.stats.fileInvalidations,avgTimeSavedMs:this.stats.hits>0?this.stats.totalTimeSavedMs/this.stats.hits:0}}resetStats(){this.stats={hits:0,misses:0,evictions:0,ttlInvalidations:0,fileInvalidations:0,totalTimeSavedMs:0}}size(){return this.cache.size()}pruneExpired(){return 0}};Xc.SPARQLResultCache=vh;function w5(r){return new vh(r)}o(w5,"createSPARQLResultCache")});var yw=_(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});Jc.IncrementalIndexer=void 0;Jc.createIncrementalIndexer=T5;var E5={throttleMs:500,maxBatchSize:100,useContentHashing:!1},Sh=class{static{o(this,"IncrementalIndexer")}constructor(e={}){this.fileMetadata=new Map,this.pendingChanges=[],this.throttleTimer=null,this.invalidateCallbacks=[],this.lastIndexTime=0,this.stats={totalChanges:0,invalidations:0,noOpChanges:0,indexDurations:[]},this.options={...E5,...e}}recordChange(e){this.pendingChanges.push(e),this.stats.totalChanges++,this.throttleTimer===null&&(this.throttleTimer=setTimeout(()=>{this.processPendingChanges(),this.throttleTimer=null},this.options.throttleMs))}processPendingChanges(){if(this.pendingChanges.length===0)return;let e=performance.now(),t=new Map;for(let a of this.pendingChanges)t.set(a.path,a);let n=Array.from(t.values()),i=[];for(let a of n)switch(a.type){case"deleted":this.fileMetadata.delete(a.path),i.push(a);break;case"renamed":a.oldPath&&this.fileMetadata.delete(a.oldPath),i.push(a);break;case"created":case"modified":i.push(a);break}if(i.length>0){this.stats.invalidations+=i.length;for(let a of this.invalidateCallbacks)try{a(i)}catch(c){console.error("IncrementalIndexer: Error in invalidation callback:",c)}}let s=performance.now()-e;this.stats.indexDurations.push(s),this.stats.indexDurations.length>100&&this.stats.indexDurations.shift(),this.lastIndexTime=Date.now(),this.pendingChanges=[]}flush(){this.throttleTimer!==null&&(clearTimeout(this.throttleTimer),this.throttleTimer=null),this.processPendingChanges()}updateMetadata(e,t,n,i){this.fileMetadata.set(e,{mtime:t,size:n,contentHash:i})}hasChanged(e,t,n){let i=this.fileMetadata.get(e);return i===void 0||i.mtime!==t||n!==void 0&&i.size!==n}getChangedFiles(e){let t=[];for(let[n,i]of this.fileMetadata.entries())i.mtime>e&&t.push(n);return t}onInvalidate(e){return this.invalidateCallbacks.push(e),()=>{let t=this.invalidateCallbacks.indexOf(e);t!==-1&&this.invalidateCallbacks.splice(t,1)}}getStats(){let e=this.stats.indexDurations,t=e.length>0?e.reduce((i,s)=>i+s,0)/e.length:0,n=e.length>0?e[e.length-1]:0;return{trackedFiles:this.fileMetadata.size,totalChanges:this.stats.totalChanges,invalidations:this.stats.invalidations,noOpChanges:this.stats.noOpChanges,lastIndexDurationMs:n,avgIndexDurationMs:t,lastIndexTime:this.lastIndexTime}}resetStats(){this.stats={totalChanges:0,invalidations:0,noOpChanges:0,indexDurations:[]}}clear(){this.fileMetadata.clear(),this.pendingChanges=[],this.throttleTimer!==null&&(clearTimeout(this.throttleTimer),this.throttleTimer=null)}size(){return this.fileMetadata.size}isTracked(e){return this.fileMetadata.has(e)}getMetadata(e){return this.fileMetadata.get(e)}dispose(){this.throttleTimer!==null&&(clearTimeout(this.throttleTimer),this.throttleTimer=null),this.invalidateCallbacks=[],this.pendingChanges=[],this.fileMetadata.clear()}};Jc.IncrementalIndexer=Sh;function T5(r){return new Sh(r)}o(T5,"createIncrementalIndexer")});var _w=_(Th=>{"use strict";Object.defineProperty(Th,"__esModule",{value:!0});Th.ResultSerializer=void 0;var bh=ht(),wh=Ye(),Eh=Rt(),My=class{static{o(this,"ResultSerializer")}serialize(e,t,n={}){switch(t){case"json":return this.serializeJSON(e,n);case"xml":return this.serializeXML(e,n);case"csv":return this.serializeCSV(e,n);case"turtle":return this.serializeTurtle(e,n);default:throw new Error(`Unsupported result format: ${t}`)}}serializeJSON(e,t={}){let n=this.toJSONResultSet(e,t),i=t.pretty?t.indent??2:void 0;return JSON.stringify(n,null,i)}toJSONResultSet(e,t={}){let n=new Set;for(let a of e)for(let c of a.variables())n.add(c);let i=t.variables??Array.from(n).sort(),s=e.map(a=>{let c={};for(let u of i){let l=a.get(u);l!==void 0&&(c[u]=this.termToJSONBinding(l))}return c});return{head:{vars:i},results:{bindings:s}}}termToJSONBinding(e){return e instanceof wh.IRI?{type:"uri",value:e.value}:e instanceof Eh.BlankNode?{type:"bnode",value:e.id}:e instanceof bh.Literal?this.literalToJSONBinding(e):{type:"literal",value:String(e)}}literalToJSONBinding(e){let t={type:"literal",value:e.value};return e.datatype?t.datatype=e.datatype.value:e.language&&(t["xml:lang"]=e.language,e.hasDirection()&&e.direction&&(t.direction=e.direction)),t}serializeXML(e,t={}){let n=new Set;for(let a of e)for(let c of a.variables())n.add(c);let i=t.variables??Array.from(n).sort(),s=['<?xml version="1.0"?>','<sparql xmlns="http://www.w3.org/2005/sparql-results#">'," <head>"];for(let a of i)s.push(` <variable name="${this.escapeXML(a)}"/>`);s.push(" </head>"),s.push(" <results>");for(let a of e){s.push(" <result>");for(let c of i){let u=a.get(c);u!==void 0&&(s.push(` <binding name="${this.escapeXML(c)}">`),s.push(" "+this.termToXML(u)),s.push(" </binding>"))}s.push(" </result>")}return s.push(" </results>"),s.push("</sparql>"),s.join(`
|
|
315
315
|
`)}termToXML(e){return e instanceof wh.IRI?`<uri>${this.escapeXML(e.value)}</uri>`:e instanceof Eh.BlankNode?`<bnode>${this.escapeXML(e.id)}</bnode>`:e instanceof bh.Literal?this.literalToXML(e):`<literal>${this.escapeXML(String(e))}</literal>`}literalToXML(e){let t=this.escapeXML(e.value);if(e.datatype)return`<literal datatype="${this.escapeXML(e.datatype.value)}">${t}</literal>`;if(e.language){let n=`xml:lang="${this.escapeXML(e.language)}"`;return e.hasDirection()&&e.direction&&(n+=` direction="${e.direction}"`),`<literal ${n}>${t}</literal>`}return`<literal>${t}</literal>`}serializeCSV(e,t={}){let n=new Set;for(let a of e)for(let c of a.variables())n.add(c);let i=t.variables??Array.from(n).sort(),s=[];s.push(i.map(a=>this.escapeCSV(a)).join(","));for(let a of e){let c=i.map(u=>{let l=a.get(u);return l===void 0?"":this.escapeCSV(this.termToCSV(l))});s.push(c.join(","))}return s.join(`
|
|
316
316
|
`)}termToCSV(e){return e instanceof wh.IRI?e.value:e instanceof Eh.BlankNode?`_:${e.id}`:e instanceof bh.Literal?this.literalToCSV(e):String(e)}literalToCSV(e){if(e.datatype)return`${e.value}^^<${e.datatype.value}>`;if(e.language){let t=e.language;return e.hasDirection()&&e.direction&&(t+=`--${e.direction}`),`${e.value}@${t}`}return e.value}serializeTurtle(e,t={}){let n=new Set;for(let a of e)for(let c of a.variables())n.add(c);let i=t.variables??Array.from(n).sort(),s=[];s.push(`# SPARQL Results - ${e.length} solution(s)`),s.push(`# Variables: ${i.join(", ")}`),s.push("");for(let a=0;a<e.length;a++){let c=e[a];s.push(`# Solution ${a+1}`);for(let u of i){let l=c.get(u);l!==void 0&&s.push(`?${u} = ${this.termToTurtle(l)}`)}s.push("")}return s.join(`
|
|
317
317
|
`).trimEnd()}termToTurtle(e){return e instanceof wh.IRI?`<${e.value}>`:e instanceof Eh.BlankNode?`_:${e.id}`:e instanceof bh.Literal?e.toString():`"${String(e)}"`}escapeXML(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}escapeCSV(e){return e.includes(",")||e.includes('"')||e.includes(`
|
|
@@ -461,7 +461,7 @@ globstar while`,e,d,t,p,v),this.matchOne(e.slice(d),t.slice(p),n))return this.de
|
|
|
461
461
|
${t}
|
|
462
462
|
Continue? (y/n): `,s=>{n.close(),i(s.toLowerCase()==="y"||s.toLowerCase()==="yes")})})}};var qd=class{static{o(this,"CLIContainer")}static setup(){ac.container.register(Hu.DI_TOKENS.ILogger,{useFactory:o(()=>new jd("exocortex-cli"),"useFactory")}),ac.container.register(Hu.DI_TOKENS.IEventBus,{useClass:$d}),ac.container.register(Hu.DI_TOKENS.IConfiguration,{useClass:Bd}),ac.container.register(Hu.DI_TOKENS.INotificationService,{useClass:Ud})}static reset(){ac.container.clearInstances()}};function zu(r){qd.setup(),Pa.container.register(Ds.DI_TOKENS.IVaultAdapter,{useFactory:o(()=>new Ti(r),"useFactory")})}o(zu,"setupContainer");function w$(r){if(r.length===0)return"No practices found.";let e=[];for(let t of r){let n="\u2B1C";t.doneToday?n="\u2705":t.inProgressToday&&(n="\u{1F504}");let i=t.estimatedDuration?` (${t.estimatedDuration}m)`:"";e.push(`${n} ${t.label}${i}`)}return e.join(`
|
|
463
463
|
`)}o(w$,"formatPractices");function E$(r){let e=[`\u{1F4C5} Daily Review: ${r.date}`,"","\u{1F4CA} Tasks:",` Planned: ${r.plannedCount}`,` Completed: ${r.completedCount}`,` In Progress: ${r.inProgressCount}`,` Progress: ${r.completionPercentage}%`,"",`\u23F1\uFE0F Total time: ${Math.round(r.totalTimeMinutes)} minutes`];if(r.practicesDue.length>0){e.push(""),e.push(`\u{1F4CB} Practices due (${r.practicesDue.length}):`);for(let t of r.practicesDue){let n=t.estimatedDuration?` (${t.estimatedDuration}m)`:"";e.push(` \u2B1C ${t.label}${n}`)}}return e.join(`
|
|
464
|
-
`)}o(E$,"formatSummary");function Yx(){let r=new It("daily").description("Daily review operations for mobile-friendly workflow");return r.command("practices").description("List today's practices (recurring tasks)").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--format <type>","Output format: text|json","text").action(async e=>{let t=e.format||"text";Y.setFormat(t);try{let n=(0,oc.resolve)(e.vault);if(!(0,cc.existsSync)(n))throw new jt(n);zu(n);let s=await Pa.container.resolve(Ds.DailyReviewService).getPractices();if(t==="json"){let a=$e.success({practices:s,count:s.length});console.log(JSON.stringify(a,null,2))}else console.log(w$(s))}catch(n){Y.handle(n)}}),r.command("summary").description("Show today's daily review summary").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--format <type>","Output format: text|json","text").option("--date <value>","Date in YYYY-MM-DD format (default: today)").action(async e=>{let t=e.format||"text";Y.setFormat(t);try{let n=(0,oc.resolve)(e.vault);if(!(0,cc.existsSync)(n))throw new jt(n);zu(n);let i=Pa.container.resolve(Ds.DailyReviewService),s;if(e.date&&(s=new Date(e.date),isNaN(s.getTime())))throw new st(`Invalid date format: ${e.date}`,"exocortex daily summary --date YYYY-MM-DD",{date:e.date});let a=await i.getDailyReviewSummary(s);if(t==="json"){let c=$e.success(a);console.log(JSON.stringify(c,null,2))}else console.log(E$(a))}catch(n){Y.handle(n)}}),r.command("log").description("Quick capture an activity").argument("<label>","Activity label/description").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--format <type>","Output format: text|json","text").option("--start","Start the task immediately (default: true)").option("--no-start","Don't start the task immediately").action(async(e,t)=>{let n=t.format||"text";Y.setFormat(n);try{let i=(0,oc.resolve)(t.vault);if(!(0,cc.existsSync)(i))throw new jt(i);zu(i);let s=Pa.container.resolve(Ds.DailyReviewService),a=t.start!==!1,c=await s.quickCapture(e,a);if(n==="json"){let u=$e.success(c);console.log(JSON.stringify(u,null,2))}else{let u=c.started?"\u{1F504}":"\u2B1C";console.log(`${u} Created: ${c.label}`),console.log(` Path: ${c.path}`)}}catch(i){Y.handle(i)}}),r.command("start").description("Start a practice (create task instance from prototype)").argument("<prototype-uid>","Practice/prototype UID to start").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--format <type>","Output format: text|json","text").action(async(e,t)=>{let n=t.format||"text";Y.setFormat(n);try{let i=(0,oc.resolve)(t.vault);if(!(0,cc.existsSync)(i))throw new jt(i);zu(i);let a=await Pa.container.resolve(Ds.DailyReviewService).createFromPractice({prototypeUid:e,startImmediately:!0});if(n==="json"){let c=$e.success(a);console.log(JSON.stringify(c,null,2))}else console.log(`\u{1F504} Started: ${a.label}`),console.log(` Path: ${a.path}`)}catch(i){Y.handle(i)}}),r.command("done").description("Mark a practice as done").argument("<prototype-uid>","Practice/prototype UID to mark as done").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--format <type>","Output format: text|json","text").action(async(e,t)=>{let n=t.format||"text";Y.setFormat(n);try{let i=(0,oc.resolve)(t.vault);if(!(0,cc.existsSync)(i))throw new jt(i);if(zu(i),await Pa.container.resolve(Ds.DailyReviewService).markPracticeDone(e),n==="json"){let a=$e.success({prototypeUid:e,status:"done"});console.log(JSON.stringify(a,null,2))}else console.log(`\u2705 Marked as done: ${e}`)}catch(i){Y.handle(i)}}),r}o(Yx,"dailyReviewCommand");var Oi=new It;Oi.name("exocortex").description("CLI tool for Exocortex knowledge management system").version("15.
|
|
464
|
+
`)}o(E$,"formatSummary");function Yx(){let r=new It("daily").description("Daily review operations for mobile-friendly workflow");return r.command("practices").description("List today's practices (recurring tasks)").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--format <type>","Output format: text|json","text").action(async e=>{let t=e.format||"text";Y.setFormat(t);try{let n=(0,oc.resolve)(e.vault);if(!(0,cc.existsSync)(n))throw new jt(n);zu(n);let s=await Pa.container.resolve(Ds.DailyReviewService).getPractices();if(t==="json"){let a=$e.success({practices:s,count:s.length});console.log(JSON.stringify(a,null,2))}else console.log(w$(s))}catch(n){Y.handle(n)}}),r.command("summary").description("Show today's daily review summary").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--format <type>","Output format: text|json","text").option("--date <value>","Date in YYYY-MM-DD format (default: today)").action(async e=>{let t=e.format||"text";Y.setFormat(t);try{let n=(0,oc.resolve)(e.vault);if(!(0,cc.existsSync)(n))throw new jt(n);zu(n);let i=Pa.container.resolve(Ds.DailyReviewService),s;if(e.date&&(s=new Date(e.date),isNaN(s.getTime())))throw new st(`Invalid date format: ${e.date}`,"exocortex daily summary --date YYYY-MM-DD",{date:e.date});let a=await i.getDailyReviewSummary(s);if(t==="json"){let c=$e.success(a);console.log(JSON.stringify(c,null,2))}else console.log(E$(a))}catch(n){Y.handle(n)}}),r.command("log").description("Quick capture an activity").argument("<label>","Activity label/description").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--format <type>","Output format: text|json","text").option("--start","Start the task immediately (default: true)").option("--no-start","Don't start the task immediately").action(async(e,t)=>{let n=t.format||"text";Y.setFormat(n);try{let i=(0,oc.resolve)(t.vault);if(!(0,cc.existsSync)(i))throw new jt(i);zu(i);let s=Pa.container.resolve(Ds.DailyReviewService),a=t.start!==!1,c=await s.quickCapture(e,a);if(n==="json"){let u=$e.success(c);console.log(JSON.stringify(u,null,2))}else{let u=c.started?"\u{1F504}":"\u2B1C";console.log(`${u} Created: ${c.label}`),console.log(` Path: ${c.path}`)}}catch(i){Y.handle(i)}}),r.command("start").description("Start a practice (create task instance from prototype)").argument("<prototype-uid>","Practice/prototype UID to start").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--format <type>","Output format: text|json","text").action(async(e,t)=>{let n=t.format||"text";Y.setFormat(n);try{let i=(0,oc.resolve)(t.vault);if(!(0,cc.existsSync)(i))throw new jt(i);zu(i);let a=await Pa.container.resolve(Ds.DailyReviewService).createFromPractice({prototypeUid:e,startImmediately:!0});if(n==="json"){let c=$e.success(a);console.log(JSON.stringify(c,null,2))}else console.log(`\u{1F504} Started: ${a.label}`),console.log(` Path: ${a.path}`)}catch(i){Y.handle(i)}}),r.command("done").description("Mark a practice as done").argument("<prototype-uid>","Practice/prototype UID to mark as done").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--format <type>","Output format: text|json","text").action(async(e,t)=>{let n=t.format||"text";Y.setFormat(n);try{let i=(0,oc.resolve)(t.vault);if(!(0,cc.existsSync)(i))throw new jt(i);if(zu(i),await Pa.container.resolve(Ds.DailyReviewService).markPracticeDone(e),n==="json"){let a=$e.success({prototypeUid:e,status:"done"});console.log(JSON.stringify(a,null,2))}else console.log(`\u2705 Marked as done: ${e}`)}catch(i){Y.handle(i)}}),r}o(Yx,"dailyReviewCommand");var Oi=new It;Oi.name("exocortex").description("CLI tool for Exocortex knowledge management system").version("15.15.0");var Qx=Oi.command("sparql").description("SPARQL query execution and cache management");Qx.addCommand(wA());Qx.addCommand(AA());Oi.addCommand(Fx());Oi.addCommand(Lx());Oi.addCommand(Mx());Oi.addCommand(jx());Oi.addCommand($x());Oi.addCommand(Gx());Oi.addCommand(Yx());Oi.parse();
|
|
465
465
|
/*! Bundled license information:
|
|
466
466
|
|
|
467
467
|
reflect-metadata/Reflect.js:
|