@_linked/core 2.28.0 → 2.28.2

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.
@@ -1 +1 @@
1
- {"version":3,"file":"irToAlgebra.js","sourceRoot":"","sources":["../../../src/sparql/irToAlgebra.ts"],"names":[],"mappings":"AAkBA,OAAO,EAAC,qBAAqB,EAAE,iBAAiB,EAAC,MAAM,4BAA4B,CAAC;AAEpF,OAAO,EAAC,gBAAgB,EAAE,eAAe,EAAC,MAAM,8BAA8B,CAAC;AAmB/E,OAAO,EAAqB,iBAAiB,EAAC,MAAM,kBAAkB,CAAC;AACvE,OAAO,EACL,kBAAkB,EAClB,eAAe,EACf,sBAAsB,EACtB,wBAAwB,GACzB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAC,GAAG,EAAC,MAAM,sBAAsB,CAAC;AACzC,OAAO,EAAC,KAAK,EAAC,MAAM,wBAAwB,CAAC;AAC7C,OAAO,EAAC,GAAG,EAAC,MAAM,sBAAsB,CAAC;AACzC,OAAO,EAAC,eAAe,EAAC,MAAM,mCAAmC,CAAC;AAClE,OAAO,EACL,gBAAgB,EAChB,YAAY,EACZ,kBAAkB,EAClB,aAAa,EACb,gBAAgB,GACjB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAC,sBAAsB,EAAC,MAAM,4BAA4B,CAAC;AAElE,8EAA8E;AAC9E,YAAY;AACZ,8EAA8E;AAE9E,MAAM,QAAQ,GAAG,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;AAC7B,MAAM,YAAY,GAAG,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC;AACrC,MAAM,QAAQ,GAAG,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;AAC7B,MAAM,QAAQ,GAAG,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;AAC7B,MAAM,WAAW,GAAG,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC;AACnC,MAAM,WAAW,GAAG,GAAG,C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import type {\n IRSelectQuery,\n IRAskQuery,\n IRCountQuery,\n IRCreateMutation,\n IRUpdateMutation,\n IRUpsertMutation,\n IRDeleteMutation,\n IRDeleteAllMutation,\n IRDeleteWhereMutation,\n IRUpdateWhereMutation,\n IRGraphPattern,\n IRExpression,\n IRFieldValue,\n IRNodeData,\n IRSetModificationValue,\n IRTraversePattern,\n} from '../queries/IntermediateRepresentation.js';\nimport {findPropertyShapeById, getPropertyShapes} from '../shapes/nodeShapeData.js';\nimport type {NodeReferenceValue} from '../utils/NodeReference.js';\nimport {pathExprToSparql, collectPathUris} from '../paths/pathExprToSparql.js';\nimport type {PathExpr} from '../paths/PropertyPathExpr.js';\nimport type {\n SparqlSelectPlan,\n SparqlAskPlan,\n SparqlInsertDataPlan,\n SparqlDeleteInsertPlan,\n SparqlAlgebraNode,\n SparqlBGP,\n SparqlTriple,\n SparqlTerm,\n SparqlExpression,\n SparqlProjectionItem,\n SparqlOrderCondition,\n SparqlAggregateBinding,\n SparqlAggregateExpr,\n SparqlLeftJoin,\n SparqlFilter,\n} from './SparqlAlgebra.js';\nimport {type SparqlOptions, generateEntityUri} from './sparqlUtils.js';\nimport {\n selectPlanToSparql,\n askPlanToSparql,\n insertDataPlanToSparql,\n deleteInsertPlanToSparql,\n} from './algebraToString.js';\nimport {rdf} from '../ontologies/rdf.js';\nimport {shacl} from '../ontologies/shacl.js';\nimport {xsd} from '../ontologies/xsd.js';\nimport {getSimplePathId} from '../paths/normalizePropertyPath.js';\nimport {\n getAllNodeShapes,\n getNodeShape,\n getRegistryVersion,\n getShapeClass,\n getTargetClassId,\n} from '../utils/ShapeClass.js';\nimport {UnresolvedContextError} from '../queries/QueryContext.js';\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst RDF_TYPE = rdf.type.id;\nconst XSD_DATETIME = xsd.dateTime.id;\nconst XSD_DATE = xsd.date.id;\nconst XSD_TIME = xsd.time.id;\nconst XSD_BOOLEAN = xsd.boolean.id;\nconst XSD_INTEGER = xsd.integer.id;\nconst XSD_DOUBLE = xsd.double.id;\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction iriTerm(value: string): SparqlTerm {\n return {kind: 'iri', value};\n}\n\nfunction varTerm(name: string): SparqlTerm {\n return {kind: 'variable', name};\n}\n\nfunction literalTerm(value: string, datatype?: string): SparqlTerm {\n if (datatype) {\n return {kind: 'literal', value, datatype};\n }\n return {kind: 'literal', value};\n}\n\nfunction tripleOf(\n subject: SparqlTerm,\n predicate: SparqlTerm,\n object: SparqlTerm,\n): SparqlTriple {\n return {subject, predicate, object};\n}\n\n/**\n * Resolve the shape a query scans to the IRI written and matched as its `rdf:type`.\n *\n * That IRI is the shape's declared `targetClass` — a node in its own right, which in\n * a real dataset carries `rdf:type rdfs:Class`. `targetClass` is read off the shape\n * *class*, so JavaScript static inheritance already walks the superclass chain: a\n * subclass that declares none inherits its parent's.\n *\n * A temporary (`linked://tmp/`) targetClass is honoured like any other. It is a real,\n * separate node — just one whose IRI has not been finalised — and it round-trips\n * consistently through both the scan and the create side.\n *\n * **A shape with no targetClass anywhere in its chain throws.** It used to fall back\n * to the shape's *own* IRI, which typed instances as the shape that describes them —\n * conflating a class with its description, and silently disagreeing with the declared\n * `targetClass` whenever that was still temporary.\n */\nfunction resolveShapeScanIri(shapeId: string): string {\n // `getTargetClassId` reads the METAMODEL registry as well as the class registry, and\n // walks `extends` for a data-only shape — reading only `getShapeClass(...)` here made\n // `SelectBuilder.from(dataOnlyIri)` resolve, build an IR, and then die at this line.\n const targetClassId = getTargetClassId(shapeId);\n if (!targetClassId) {\n throw new Error(\n `Cannot resolve an rdf:type for shape \"${shapeId}\": no targetClass is declared ` +\n 'on it or on any shape it extends. Declare one — `static targetClass = ' +\n \"{id: 'https://example.org/Person'}` — pointing at the class node instances are \" +\n 'typed with. The shape\\'s own IRI is not a substitute: it identifies the ' +\n 'description, not the class being described.',\n );\n }\n return targetClassId;\n}\n\n/**\n * Resolve a SHACL property-shape id to the predicate term used in a triple.\n *\n * - Simple single-IRI path → `{kind:'iri'}` (byte-for-byte unchanged behaviour).\n * - Structured path (sequence / inverse / alternative / …) → `{kind:'path'}` built from the property\n * shape's `sh:path`, reusing the same `pathExprToSparql` / `collectPathUris` machinery as the\n * inline-`pathExpr` branches. Without this, structured named-property paths collapsed to a shadow IRI\n * that matched nothing.\n * - No matching property shape at all → `{kind:'iri'}` of the id as given (nothing\n * better is knowable; the caller passed an id no registered shape declares).\n */\n// Memoizes resolved predicate terms across the many call sites that resolve the\n// same property. Guarded by the shape-registry size so it self-invalidates when\n// new shapes register (e.g. across test-file module instances). Only successful\n// resolutions are cached — a not-found fallback is never stored, so a predicate\n// resolved before its shape registers can still resolve correctly afterwards.\nconst predicateTermCache = new Map<string, SparqlTerm>();\nlet predicateTermCacheSize = -1;\n\n/**\n * The `sh:datatype` declared for a property, if any. Lets the serializer emit the\n * term the shape asks for rather than one inferred from the JavaScript value: a\n * numeric property gets the numeric type it declares, and an `xsd:date` /\n * `xsd:time` property its own lexical form instead of a full timestamp.\n */\nfunction resolvePropertyDatatype(propertyId: string): string | undefined {\n return findPropertyShapeById(propertyId)?.datatype?.id;\n}\n\nfunction resolvePropertyPredicateTerm(propertyId: string): SparqlTerm {\n const version = getRegistryVersion();\n if (version !== predicateTermCacheSize) {\n predicateTermCache.clear();\n predicateTermCacheSize = version;\n }\n const cached = predicateTermCache.get(propertyId);\n if (cached) return cached;\n\n const propertyShape = findPropertyShapeById(propertyId);\n if (propertyShape) {\n const simplePathId = getSimplePathId(propertyShape.path);\n let term: SparqlTerm;\n if (simplePathId !== null) {\n // Simple single-IRI path: the declared `sh:path` IS the predicate. There is\n // no fallback to the property shape's own IRI — that identifies the\n // *description* of the property, not the property itself.\n term = iriTerm(simplePathId);\n } else {\n // Structured sh:path — emit a property-path predicate instead of a shadow IRI.\n term = {\n kind: 'path',\n value: pathExprToSparql(propertyShape.path),\n uris: collectPathUris(propertyShape.path),\n };\n }\n predicateTermCache.set(propertyId, term);\n return term;\n }\n return iriTerm(propertyId);\n}\n\n/**\n * Resolve the predicate term for a traversal/property node: a structured\n * property-path when an explicit `pathExpr` is present, otherwise the\n * registry-resolved predicate for `property`. Centralizes the invariant that\n * these two branches stay in lockstep across every triple-building site.\n */\nfunction buildPredicateTerm(spec: {pathExpr?: PathExpr; property: string}): SparqlTerm {\n return spec.pathExpr\n ? {\n kind: 'path',\n value: pathExprToSparql(spec.pathExpr),\n uris: collectPathUris(spec.pathExpr),\n }\n : resolvePropertyPredicateTerm(spec.property);\n}\n\n/** Produce variable name suffix from the last segment of a property URI. */\nfunction propertySuffix(propertyUri: string): string {\n const hashIdx = propertyUri.lastIndexOf('#');\n if (hashIdx >= 0) return propertyUri.substring(hashIdx + 1);\n const slashIdx = propertyUri.lastIndexOf('/');\n return slashIdx >= 0 ? propertyUri.substring(slashIdx + 1) : propertyUri;\n}\n\n/**\n * Sanitize a string so it's valid in a SPARQL variable name.\n * Replaces any non-alphanumeric/underscore characters with underscores.\n */\nfunction sanitizeVarName(name: string): string {\n return name.replace(/[^A-Za-z0-9_]/g, '_');\n}\n\nconst IR_EXPRESSION_KINDS = new Set([\n 'literal_expr', 'property_expr', 'binary_expr', 'logical_expr',\n 'not_expr', 'function_expr', 'aggregate_expr', 'reference_expr',\n 'alias_expr', 'context_property_expr', 'exists_expr', 'in_expr',\n]);\n\nfunction isIRExpression(value: unknown): value is IRExpression {\n return !!value && typeof value === 'object' && 'kind' in value &&\n typeof (value as {kind: unknown}).kind === 'string' &&\n IR_EXPRESSION_KINDS.has((value as {kind: string}).kind);\n}\n\n/**\n * Wrap a single node in a LeftJoin, making `right` optional relative to `left`.\n */\nfunction wrapOptional(\n left: SparqlAlgebraNode,\n right: SparqlAlgebraNode,\n): SparqlLeftJoin {\n return {type: 'left_join', left, right};\n}\n\n/**\n * Join two algebra nodes. If left is null, returns right.\n */\nfunction joinNodes(\n left: SparqlAlgebraNode | null,\n right: SparqlAlgebraNode,\n): SparqlAlgebraNode {\n if (!left) return right;\n return {type: 'join', left, right};\n}\n\nfunction bindingKey(alias: string, property: string): string {\n return `${alias}::${property}`;\n}\n\nfunction contextAliasKey(contextIri: string): string {\n return `__ctx__${contextIri}`;\n}\n\n/**\n * Defense-in-depth: a `reference_expr`/`context_property_expr` must arrive here with its\n * IRI already resolved (lowering's `resolveContextRefs` fills it from `contextName`). If it\n * didn't — an unresolved `{@ctx}` reaching the algebra through some path that bypassed\n * resolution — fail with a clear `UnresolvedContextError` instead of an opaque\n * `undefined.substring` crash deeper in URI formatting.\n */\nfunction resolvedContextIri(iri: string | undefined, contextName?: string): string {\n if (iri === undefined) {\n throw new UnresolvedContextError(contextName ?? '<unknown>');\n }\n return iri;\n}\n\nfunction mergeKeySets(...sets: ReadonlySet<string>[]): Set<string> {\n const merged = new Set<string>();\n for (const set of sets) {\n for (const key of set) {\n merged.add(key);\n }\n }\n return merged;\n}\n\nfunction intersectKeySets(sets: ReadonlySet<string>[]): Set<string> {\n if (sets.length === 0) {\n return new Set<string>();\n }\n\n const [first, ...rest] = sets;\n const intersection = new Set(first);\n for (const value of intersection) {\n if (!rest.every((set) => set.has(value))) {\n intersection.delete(value);\n }\n }\n return intersection;\n}\n\n// ---------------------------------------------------------------------------\n// Pattern helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Recursively collects all traversal alias target variables from IR patterns.\n * Used to ensure traversal aliases appear in the SELECT projection for result grouping.\n */\nfunction collectTraversalAliases(patterns: IRGraphPattern[]): string[] {\n const aliases: string[] = [];\n for (const p of patterns) {\n if (p.kind === 'traverse') {\n aliases.push(p.to);\n } else if (p.kind === 'join') {\n aliases.push(...collectTraversalAliases(p.patterns));\n } else if (p.kind === 'optional') {\n aliases.push(...collectTraversalAliases([p.pattern]));\n } else if (p.kind === 'union') {\n for (const branch of p.branches) {\n aliases.push(...collectTraversalAliases([branch]));\n }\n }\n }\n return aliases;\n}\n\nfunction buildTraverseTriple(pattern: IRTraversePattern): SparqlTriple {\n const predicate = buildPredicateTerm(pattern);\n return tripleOf(\n varTerm(pattern.from),\n predicate,\n varTerm(pattern.to),\n );\n}\n\nfunction collectTraversePatternsInOrder(\n patterns: IRGraphPattern[],\n out: IRTraversePattern[] = [],\n): IRTraversePattern[] {\n for (const pattern of patterns) {\n switch (pattern.kind) {\n case 'traverse':\n out.push(pattern);\n break;\n case 'join':\n collectTraversePatternsInOrder(pattern.patterns, out);\n break;\n case 'optional':\n case 'exists':\n collectTraversePatternsInOrder([pattern.pattern], out);\n break;\n case 'union':\n for (const branch of pattern.branches) {\n collectTraversePatternsInOrder([branch], out);\n }\n break;\n case 'shape_scan':\n case 'minus':\n break;\n }\n }\n return out;\n}\n\nfunction collectDirectProjectionAliases(\n query: IRSelectQuery,\n rootAlias: string,\n): Set<string> {\n const aliases = new Set<string>();\n for (const item of query.projection) {\n if (item.expression.kind === 'property_expr') {\n if (item.expression.sourceAlias !== rootAlias) {\n aliases.add(item.expression.sourceAlias);\n }\n } else if (item.expression.kind === 'alias_expr') {\n if (item.expression.alias !== rootAlias) {\n aliases.add(item.expression.alias);\n }\n }\n }\n return aliases;\n}\n\nfunction collectExpressionAliases(\n expr: IRExpression,\n aliases: Set<string>,\n): void {\n switch (expr.kind) {\n case 'property_expr':\n aliases.add(expr.sourceAlias);\n break;\n case 'alias_expr':\n aliases.add(expr.alias);\n break;\n case 'binary_expr':\n collectExpressionAliases(expr.left, aliases);\n collectExpressionAliases(expr.right, aliases);\n break;\n case 'in_expr':\n collectExpressionAliases(expr.value, aliases);\n for (const el of expr.source.list) collectExpressionAliases(el, aliases);\n break;\n case 'logical_expr':\n for (const sub of expr.expressions) {\n collectExpressionAliases(sub, aliases);\n }\n break;\n case 'not_expr':\n collectExpressionAliases(expr.expression, aliases);\n break;\n case 'function_expr':\n case 'aggregate_expr':\n for (const arg of expr.args) {\n collectExpressionAliases(arg, aliases);\n }\n break;\n case 'exists_expr':\n if (expr.filter) {\n collectExpressionAliases(expr.filter, aliases);\n }\n break;\n case 'literal_expr':\n case 'reference_expr':\n case 'context_property_expr':\n break;\n }\n}\n\nfunction markAliasAndAncestors(\n alias: string,\n traversePatternMap: ReadonlyMap<string, IRTraversePattern>,\n target: Set<string>,\n): void {\n let currentAlias: string | undefined = alias;\n while (currentAlias && traversePatternMap.has(currentAlias)) {\n if (target.has(currentAlias)) {\n return;\n }\n target.add(currentAlias);\n currentAlias = traversePatternMap.get(currentAlias)?.from;\n }\n}\n\nfunction collectRequiredTraversalAliases(\n query: IRSelectQuery,\n traversePatternMap: ReadonlyMap<string, IRTraversePattern>,\n): Set<string> {\n const directAliases = new Set<string>();\n\n if (query.where) {\n collectExpressionAliases(query.where, directAliases);\n }\n\n if (query.orderBy) {\n for (const item of query.orderBy) {\n collectExpressionAliases(item.expression, directAliases);\n }\n }\n\n for (const pattern of traversePatternMap.values()) {\n if (pattern.filter) {\n directAliases.add(pattern.to);\n }\n }\n\n const requiredAliases = new Set<string>();\n for (const alias of directAliases) {\n markAliasAndAncestors(alias, traversePatternMap, requiredAliases);\n }\n return requiredAliases;\n}\n\nfunction buildOptionalTraversalSubtree(\n alias: string,\n traversePatternMap: ReadonlyMap<string, IRTraversePattern>,\n childOptionalAliasesByParent: ReadonlyMap<string, string[]>,\n propertyTriplesByAlias: ReadonlyMap<string, SparqlTriple[]>,\n): SparqlAlgebraNode {\n const pattern = traversePatternMap.get(alias);\n if (!pattern) {\n throw new Error(`Missing traverse pattern for alias \"${alias}\"`);\n }\n\n let subtree: SparqlAlgebraNode = {\n type: 'bgp',\n triples: [buildTraverseTriple(pattern)],\n };\n\n for (const propTriple of propertyTriplesByAlias.get(alias) ?? []) {\n subtree = wrapOptional(subtree, {\n type: 'bgp',\n triples: [propTriple],\n });\n }\n\n for (const childAlias of childOptionalAliasesByParent.get(alias) ?? []) {\n subtree = wrapOptional(\n subtree,\n buildOptionalTraversalSubtree(\n childAlias,\n traversePatternMap,\n childOptionalAliasesByParent,\n propertyTriplesByAlias,\n ),\n );\n }\n\n return subtree;\n}\n\n// ---------------------------------------------------------------------------\n// Variable Registry\n// ---------------------------------------------------------------------------\n\n/**\n * Maps (alias, property) → SPARQL variable name.\n * Used to deduplicate variables across traverse and property_expr nodes.\n */\nclass VariableRegistry {\n private map = new Map<string, string>();\n private usedVarNames = new Set<string>();\n\n private key(alias: string, property: string): string {\n return bindingKey(alias, property);\n }\n\n has(alias: string, property: string): boolean {\n return this.map.has(this.key(alias, property));\n }\n\n get(alias: string, property: string): string | undefined {\n return this.map.get(this.key(alias, property));\n }\n\n set(alias: string, property: string, variable: string): void {\n this.map.set(this.key(alias, property), variable);\n this.usedVarNames.add(variable);\n }\n\n getOrCreate(alias: string, property: string): string {\n const existing = this.get(alias, property);\n if (existing) return existing;\n const suffix = propertySuffix(property);\n let varName = `${sanitizeVarName(alias)}_${suffix}`;\n // Deduplicate: if varName is already used by a different (alias, property),\n // append a counter to ensure unique SPARQL variable names\n let counter = 2;\n while (this.usedVarNames.has(varName)) {\n varName = `${sanitizeVarName(alias)}_${suffix}_${counter}`;\n counter++;\n }\n this.set(alias, property, varName);\n return varName;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Aggregate detection\n// ---------------------------------------------------------------------------\n\n/**\n * Checks whether a SparqlExpression tree contains an aggregate sub-expression.\n * Used to route aggregate-containing filters to HAVING instead of FILTER.\n */\nfunction containsAggregate(expr: SparqlExpression): boolean {\n switch (expr.kind) {\n case 'aggregate_expr':\n return true;\n case 'in_expr':\n return containsAggregate(expr.value) || expr.list.some(containsAggregate);\n case 'binary_expr':\n return containsAggregate(expr.left) || containsAggregate(expr.right);\n case 'logical_expr':\n return expr.exprs.some(containsAggregate);\n case 'not_expr':\n return containsAggregate(expr.inner);\n case 'function_expr':\n return expr.args.some(containsAggregate);\n default:\n return false;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Select conversion\n// ---------------------------------------------------------------------------\n\n/**\n * Converts an IRSelectQuery to a SparqlSelectPlan.\n */\nexport function selectToAlgebra(\n query: IRSelectQuery,\n _options?: SparqlOptions,\n): SparqlSelectPlan {\n const registry = new VariableRegistry();\n\n // Promote bindings only when the top-level WHERE would reject rows without\n // them. This keeps human-like SPARQL for null-rejecting filters without\n // over-constraining OR cases that can still match through other branches.\n const requiredPropertyKeys = query.where\n ? collectRequiredBindingKeys(query.where)\n : new Set<string>();\n\n const requiredPropertyTriples: SparqlTriple[] = [];\n // Track property triples that need to be added as OPTIONAL\n const optionalPropertyTriples: SparqlTriple[] = [];\n\n // Track filtered traversals (inline where) — these get their own OPTIONAL blocks\n const filteredTraverseBlocks: Array<{\n traverseTriple: SparqlTriple;\n filter: IRExpression;\n toAlias: string;\n }> = [];\n\n // 1. Root shape scan → BGP with type triple\n if (!query?.root) {\n throw new Error(\n 'selectToAlgebra: query.root is undefined. The query IR is missing its root shape scan. ' +\n 'This usually means the query was built with a null/undefined subject (e.g. getQueryContext returned null).',\n );\n }\n const rootAlias = query.root.alias;\n const shapeUri = query.root.shape;\n const typeTriple = tripleOf(\n varTerm(rootAlias),\n iriTerm(RDF_TYPE),\n iriTerm(resolveShapeScanIri(shapeUri)),\n );\n const requiredTriples: SparqlTriple[] = [typeTriple];\n\n // Track traverse triples (required pattern)\n const traverseTriples: SparqlTriple[] = [];\n const traversePatternsInOrder = collectTraversePatternsInOrder(query.patterns);\n const traversePatternMap = new Map(\n traversePatternsInOrder.map((pattern) => [pattern.to, pattern] as const),\n );\n\n // ── Nested-select inner LIMIT/OFFSET (Option A: single-subject only) ──────\n // A nested select on a related collection may carry an inner LIMIT/OFFSET.\n // A plain SPARQL sub-SELECT is uncorrelated, so its LIMIT bounds GLOBALLY.\n // That only equals per-parent windowing when the outer query targets exactly\n // ONE root subject — then we inline that subject into the sub-SELECT.\n const paginatedTraversePatterns = traversePatternsInOrder.filter(\n (p) =>\n typeof p.innerLimit === 'number' ||\n typeof p.innerOffset === 'number' ||\n (p.innerOrderBy && p.innerOrderBy.length > 0),\n );\n const singleSubjectIri: string | undefined =\n query.subjectId ??\n (query.subjectIds && query.subjectIds.length === 1\n ? query.subjectIds[0]\n : undefined);\n if (paginatedTraversePatterns.length > 0 && !singleSubjectIri) {\n throw new Error(\n 'Inner LIMIT/OFFSET on a nested select is only supported when the outer ' +\n 'query targets a single subject; multi-parent per-group pagination is not ' +\n 'yet implemented.',\n );\n }\n // Only root→child traversals can be inlined against the single subject.\n // A paginated traversal deeper than root→child has a parent collection that is\n // itself multi-valued (effectively multi-parent), so a sub-SELECT LIMIT there\n // would bound globally, not per-parent. Reject it loudly rather than silently\n // dropping the inner limit.\n const deepPaginated = paginatedTraversePatterns.filter((p) => p.from !== rootAlias);\n if (deepPaginated.length > 0) {\n throw new Error(\n 'Inner LIMIT/OFFSET on a nested select is only supported on a direct nested ' +\n 'select of the single root subject; pagination on a deeper (grandchild) ' +\n 'collection is multi-parent and not yet implemented.',\n );\n }\n const subSelectAliases = new Set<string>(\n paginatedTraversePatterns.map((p) => p.to),\n );\n\n // 2. Process patterns → traverse triples, populate variable registry.\n // Skip sub-SELECT-wrapped traversals here — they are emitted separately\n // (their child variable is still registered so projection/optionals work).\n for (const pattern of query.patterns) {\n processPattern(\n pattern,\n registry,\n traverseTriples,\n optionalPropertyTriples,\n filteredTraverseBlocks,\n subSelectAliases,\n );\n }\n\n // 3. Pre-register filter property references BEFORE processing projections.\n // This ensures that property triples needed by inline where filters are\n // co-located inside the filtered OPTIONAL block, not in separate OPTIONALs.\n const filterPropertyTriplesMap = new Map<number, SparqlTriple[]>();\n filteredTraverseBlocks.forEach((block, idx) => {\n const filterPropertyTriples: SparqlTriple[] = [];\n processExpressionForProperties(block.filter, registry, filterPropertyTriples);\n filterPropertyTriplesMap.set(idx, filterPropertyTriples);\n });\n\n // 4. Process projection expressions, where clause, orderBy expressions\n // to discover any additional property_expr references.\n // Properties already registered by inline filters (above) will be skipped.\n for (const item of query.projection) {\n processExpressionForProperties(\n item.expression,\n registry,\n optionalPropertyTriples,\n requiredPropertyTriples,\n requiredPropertyKeys,\n );\n }\n\n if (query.where) {\n processExpressionForProperties(\n query.where,\n registry,\n optionalPropertyTriples,\n requiredPropertyTriples,\n requiredPropertyKeys,\n );\n }\n\n if (query.orderBy) {\n for (const orderItem of query.orderBy) {\n processExpressionForProperties(\n orderItem.expression,\n registry,\n optionalPropertyTriples,\n requiredPropertyTriples,\n requiredPropertyKeys,\n );\n }\n }\n\n const projectedTraversalAliases = new Set<string>();\n const directProjectionAliases = collectDirectProjectionAliases(query, rootAlias);\n for (const alias of directProjectionAliases) {\n markAliasAndAncestors(alias, traversePatternMap, projectedTraversalAliases);\n }\n\n const requiredTraversalAliases = collectRequiredTraversalAliases(\n query,\n traversePatternMap,\n );\n\n const optionalTraversalAliases = new Set(\n [...projectedTraversalAliases].filter((alias) => {\n const pattern = traversePatternMap.get(alias);\n // Lower projection-only traversals into OPTIONAL subtrees regardless of\n // cardinality, so a parent with an empty relationship is preserved (with\n // an empty array / null child) instead of being inner-joined away. The\n // result grouper already collects multiple child bindings into an array.\n //\n // Excluded:\n // - filtered traversals (`.where(...)`) — the filter makes the child required\n // - aliases otherwise required by the query (e.g. used in a top-level filter)\n // - paginated traversals — emitted separately as a sub-SELECT (section 5a),\n // so lowering them here too would double-emit the traverse triple\n return !!pattern &&\n !pattern.filter &&\n !subSelectAliases.has(alias) &&\n !requiredTraversalAliases.has(alias);\n }),\n );\n\n const requiredTraverseTriples = traverseTriples.filter((triple) =>\n !(triple.object.kind === 'variable' &&\n optionalTraversalAliases.has(triple.object.name))\n );\n\n const nestedOptionalPropertyTriplesByAlias = new Map<string, SparqlTriple[]>();\n const topLevelOptionalPropertyTriples: SparqlTriple[] = [];\n // Property triples whose subject is a sub-SELECT child alias must be nested\n // INSIDE the sub-SELECT's OPTIONAL block (keyed by alias), so that ?childVar\n // stays scoped — otherwise an empty window leaves ?childVar unbound and the\n // outer property OPTIONAL leaks across the whole graph.\n const subSelectChildPropertyTriplesByAlias = new Map<string, SparqlTriple[]>();\n // Same scoping rule for filtered traversals (`.where(...)`): anything anchored\n // on the filtered alias must live inside its filtered OPTIONAL block — when\n // the filter matches nothing, the alias is unbound and a top-level OPTIONAL\n // would range over the whole graph.\n const filteredTraverseAliases = new Set(filteredTraverseBlocks.map((b) => b.toAlias));\n const filteredChildPropertyTriplesByAlias = new Map<string, SparqlTriple[]>();\n for (const propTriple of optionalPropertyTriples) {\n if (propTriple.subject.kind === 'variable' &&\n subSelectAliases.has(propTriple.subject.name)) {\n const triples = subSelectChildPropertyTriplesByAlias.get(propTriple.subject.name) ?? [];\n triples.push(propTriple);\n subSelectChildPropertyTriplesByAlias.set(propTriple.subject.name, triples);\n } else if (propTriple.subject.kind === 'variable' &&\n filteredTraverseAliases.has(propTriple.subject.name)) {\n const triples = filteredChildPropertyTriplesByAlias.get(propTriple.subject.name) ?? [];\n triples.push(propTriple);\n filteredChildPropertyTriplesByAlias.set(propTriple.subject.name, triples);\n } else if (propTriple.subject.kind === 'variable' &&\n optionalTraversalAliases.has(propTriple.subject.name)) {\n const triples = nestedOptionalPropertyTriplesByAlias.get(propTriple.subject.name) ?? [];\n triples.push(propTriple);\n nestedOptionalPropertyTriplesByAlias.set(propTriple.subject.name, triples);\n } else {\n topLevelOptionalPropertyTriples.push(propTriple);\n }\n }\n\n const childOptionalAliasesByParent = new Map<string, string[]>();\n for (const pattern of traversePatternsInOrder) {\n if (!optionalTraversalAliases.has(pattern.to)) continue;\n const siblings = childOptionalAliasesByParent.get(pattern.from) ?? [];\n siblings.push(pattern.to);\n childOptionalAliasesByParent.set(pattern.from, siblings);\n }\n\n const rootOptionalTraversalAliases = traversePatternsInOrder\n .filter((pattern) =>\n optionalTraversalAliases.has(pattern.to) &&\n !optionalTraversalAliases.has(pattern.from) &&\n // Children of a filtered traversal nest inside its filtered block (5b)\n !filteredTraverseAliases.has(pattern.from),\n )\n .map((pattern) => pattern.to);\n\n // 5. Build the algebra tree\n // - Start with the required BGP (type triple + traverse triples)\n // - Wrap each optional property triple in a LeftJoin\n const requiredBgp: SparqlBGP = {\n type: 'bgp',\n triples: [...requiredTriples, ...requiredTraverseTriples, ...requiredPropertyTriples],\n };\n\n let algebra: SparqlAlgebraNode = requiredBgp;\n\n // 5a. Nested-select inner LIMIT/OFFSET → sub-SELECT (single-subject only).\n // Wrap each root→child paginated traversal in a sub-SELECT that inlines\n // the single subject, projecting only the child variable. The child's own\n // property triples stay OUTSIDE (as OPTIONALs), joined on the child var —\n // so the flat-row structure and result mapping are unchanged.\n // Every pattern here is a root→child paginated traversal (the deep-pagination\n // guard above rejected anything else), so each maps 1:1 to a sub-SELECT.\n for (const pattern of paginatedTraversePatterns) {\n const predicate = buildPredicateTerm(pattern);\n const innerTriple = tripleOf(\n iriTerm(singleSubjectIri!),\n predicate,\n varTerm(pattern.to),\n );\n // Default ORDER BY ?childVar for a deterministic window, unless the nested\n // select supplied its own ordering. When it did, each ordered property must\n // also be bound inside the sub-SELECT so the ORDER BY variable resolves.\n let orderBy: SparqlOrderCondition[];\n let innerNode: SparqlAlgebraNode = {type: 'bgp', triples: [innerTriple]};\n if (pattern.innerOrderBy && pattern.innerOrderBy.length > 0) {\n orderBy = pattern.innerOrderBy.map((o) => {\n const orderVar = registry.getOrCreate(pattern.to, o.property);\n innerNode = joinNodes(innerNode, {\n type: 'bgp',\n triples: [tripleOf(varTerm(pattern.to), resolvePropertyPredicateTerm(o.property), varTerm(orderVar))],\n });\n return {\n expression: {kind: 'variable_expr' as const, name: orderVar},\n direction: o.direction,\n };\n });\n } else {\n orderBy = [{\n expression: {kind: 'variable_expr', name: pattern.to},\n direction: 'ASC',\n }];\n }\n const subSelect: SparqlAlgebraNode = {\n type: 'subselect',\n projection: [pattern.to],\n inner: innerNode,\n orderBy,\n ...(typeof pattern.innerLimit === 'number' ? {limit: pattern.innerLimit} : {}),\n ...(typeof pattern.innerOffset === 'number' ? {offset: pattern.innerOffset} : {}),\n };\n // Nest the child's own property triples (e.g. ?a1 <name> ?a1_name) INSIDE\n // this block, each as its own OPTIONAL, so they only bind when the window\n // produced a ?childVar. This keeps the flat-row projection unchanged.\n let childBlock: SparqlAlgebraNode = subSelect;\n for (const propTriple of subSelectChildPropertyTriplesByAlias.get(pattern.to) ?? []) {\n childBlock = wrapOptional(childBlock, {type: 'bgp', triples: [propTriple]});\n }\n // OPTIONAL so a parent with an empty (or fully-windowed-out) child set is\n // still returned — the sub-SELECT yields no ?a1 binding, but the parent row\n // survives (mirrors the plain nested-traverse OPTIONAL behaviour).\n algebra = wrapOptional(algebra, childBlock);\n }\n\n // 5b. Build filtered OPTIONAL blocks for inline where traversals.\n // Each block contains: traverse triple + OPTIONAL property triples + FILTER.\n // Filter property triples are nested as OPTIONALs so that OR filters work\n // even when some entities lack certain properties.\n // First pass: build each filtered block's inner group and filter expression.\n const filteredBlockInners: SparqlAlgebraNode[] = [];\n const filteredBlockExprs: SparqlExpression[] = [];\n const filteredBlockIdxByAlias = new Map<string, number>(\n filteredTraverseBlocks.map((block, i) => [block.toAlias, i]),\n );\n for (let i = 0; i < filteredTraverseBlocks.length; i++) {\n const block = filteredTraverseBlocks[i];\n const filterPropertyTriples = filterPropertyTriplesMap.get(i) || [];\n const filterExpr = convertExpression(block.filter, registry, filterPropertyTriples);\n // Start with the traverse triple as the required BGP\n let blockInner: SparqlAlgebraNode = {type: 'bgp', triples: [block.traverseTriple]};\n // Wrap each filter property triple in its own nested OPTIONAL\n for (const propTriple of filterPropertyTriples) {\n blockInner = wrapOptional(blockInner, {type: 'bgp', triples: [propTriple]});\n }\n // Projected property triples on the filtered alias that aren't part of the\n // filter (e.g. `.where(name=...).select(pp => [pp.hobby])`)\n for (const propTriple of filteredChildPropertyTriplesByAlias.get(block.toAlias) ?? []) {\n blockInner = wrapOptional(blockInner, {type: 'bgp', triples: [propTriple]});\n }\n // Optional child traversal subtrees (nested sub-selects below the filtered\n // alias) — kept inside the block so an empty filter match leaves them unbound\n for (const childAlias of childOptionalAliasesByParent.get(block.toAlias) ?? []) {\n blockInner = wrapOptional(\n blockInner,\n buildOptionalTraversalSubtree(\n childAlias,\n traversePatternMap,\n childOptionalAliasesByParent,\n nestedOptionalPropertyTriplesByAlias,\n ),\n );\n }\n filteredBlockInners.push(blockInner);\n filteredBlockExprs.push(filterExpr);\n }\n // Second pass, children first (blocks are created parent-before-child):\n // finish each block and either nest it inside its parent's filtered block —\n // a filtered sub-select inside another filtered sub-select must stay scoped\n // to the parent alias, or an empty parent match leaves the alias unbound and\n // the block cross-products over the whole graph — or attach it at top level.\n const rootFilteredBlocks: SparqlAlgebraNode[] = [];\n for (let i = filteredTraverseBlocks.length - 1; i >= 0; i--) {\n const block = filteredTraverseBlocks[i];\n const finished: SparqlFilter = {\n type: 'filter',\n expression: filteredBlockExprs[i],\n inner: filteredBlockInners[i],\n };\n const subject = block.traverseTriple.subject;\n const parentIdx = subject.kind === 'variable'\n ? filteredBlockIdxByAlias.get(subject.name)\n : undefined;\n if (parentIdx !== undefined && parentIdx !== i) {\n filteredBlockInners[parentIdx] = wrapOptional(filteredBlockInners[parentIdx], finished);\n } else {\n rootFilteredBlocks.unshift(finished);\n }\n }\n for (const filteredBlock of rootFilteredBlocks) {\n algebra = wrapOptional(algebra, filteredBlock);\n }\n\n for (const alias of rootOptionalTraversalAliases) {\n algebra = wrapOptional(\n algebra,\n buildOptionalTraversalSubtree(\n alias,\n traversePatternMap,\n childOptionalAliasesByParent,\n nestedOptionalPropertyTriplesByAlias,\n ),\n );\n }\n\n // Wrap each optional property triple in its own OPTIONAL (LeftJoin)\n for (const propTriple of topLevelOptionalPropertyTriples) {\n algebra = wrapOptional(algebra, {\n type: 'bgp',\n triples: [propTriple],\n });\n }\n\n // 5. Where clause → Filter wrapping (or HAVING if aggregate-containing)\n let havingExpr: SparqlExpression | undefined;\n if (query.where) {\n const filterExpr = convertExpression(query.where, registry, optionalPropertyTriples);\n if (containsAggregate(filterExpr)) {\n havingExpr = filterExpr;\n } else {\n algebra = {\n type: 'filter',\n expression: filterExpr,\n inner: algebra,\n };\n }\n }\n\n // 5b. MINUS patterns — wrap algebra in SparqlMinus for each minus pattern\n for (const pattern of query.patterns) {\n if (pattern.kind === 'minus') {\n let minusAlgebra = convertExistsPattern(pattern.pattern, registry);\n if (pattern.filter) {\n const minusPropertyTriples: SparqlTriple[] = [];\n processExpressionForProperties(pattern.filter, registry, minusPropertyTriples);\n // Add property triples into the MINUS block\n if (minusPropertyTriples.length > 0) {\n minusAlgebra = joinNodes(minusAlgebra, {type: 'bgp', triples: minusPropertyTriples});\n }\n const filterExpr = convertExpression(pattern.filter, registry, minusPropertyTriples);\n minusAlgebra = {type: 'filter', expression: filterExpr, inner: minusAlgebra};\n }\n algebra = {type: 'minus', left: algebra, right: minusAlgebra};\n }\n }\n\n // 6. SubjectId → Filter / SubjectIds → VALUES\n if (query.subjectIds && query.subjectIds.length > 0) {\n // Multiple subjects: use VALUES clause for efficient filtering\n algebra = joinNodes(\n {type: 'values', variable: rootAlias, iris: query.subjectIds},\n algebra,\n );\n } else if (query.subjectId) {\n const subjectFilter: SparqlExpression = {\n kind: 'binary_expr',\n op: '=',\n left: {kind: 'variable_expr', name: rootAlias},\n right: {kind: 'iri_expr', value: query.subjectId},\n };\n algebra = {\n type: 'filter',\n expression: subjectFilter,\n inner: algebra,\n };\n }\n\n // 7. Build projection\n const projection: SparqlProjectionItem[] = [];\n const aggregates: SparqlAggregateBinding[] = [];\n let hasAggregates = false;\n\n // Always include root alias as first projection variable\n projection.push({kind: 'variable', name: rootAlias});\n\n // Collect traversal aliases upfront to detect aggregate alias collisions\n const traversalAliasSet = new Set(collectTraversalAliases(query.patterns));\n // Track traversal aliases consumed by aggregate renames (should not be\n // re-projected as plain variables, which would alter GROUP BY semantics)\n const aggregateRenamedAliases = new Set<string>();\n\n for (const item of query.projection) {\n const sparqlExpr = convertExpression(item.expression, registry, optionalPropertyTriples);\n\n if (sparqlExpr.kind === 'aggregate_expr') {\n hasAggregates = true;\n // Avoid collision: if aggregate alias matches a traversal alias,\n // rename it so SPARQL doesn't produce duplicate variable bindings\n let aggAlias = item.alias;\n if (traversalAliasSet.has(aggAlias)) {\n aggregateRenamedAliases.add(aggAlias);\n aggAlias = `${aggAlias}_agg`;\n // Update resultMap so result mapping uses the renamed alias\n for (const rm of query.resultMap) {\n if (rm.alias === item.alias) rm.alias = aggAlias;\n }\n }\n projection.push({\n kind: 'aggregate',\n expression: sparqlExpr,\n alias: aggAlias,\n });\n aggregates.push({\n variable: aggAlias,\n aggregate: sparqlExpr,\n });\n } else {\n // For property_expr, the variable is the resolved name from registry\n const varName = resolveExpressionVariable(item.expression, registry);\n if (varName && varName !== rootAlias) {\n projection.push({kind: 'variable', name: varName});\n } else if (!varName) {\n // Non-variable expression (binary_expr, function_expr, etc.)\n // → project as (expr AS ?alias)\n let exprAlias = item.alias;\n if (traversalAliasSet.has(exprAlias)) {\n // The output alias collides with a traversal target variable — e.g. a\n // computed expression over a traversed path lowers to\n // (UCASE(?a1_name) AS ?a1), and ?a1 is already bound by the traverse\n // triple. Rename the output so SPARQL doesn't reuse an in-scope var.\n exprAlias = `${exprAlias}_expr`;\n for (const rm of query.resultMap) {\n if (rm.alias === item.alias) rm.alias = exprAlias;\n }\n }\n projection.push({kind: 'expression', expression: sparqlExpr, alias: exprAlias});\n }\n }\n }\n\n // 7b. Include traversal aliases needed for result grouping\n // When nested results are projected (e.g. p.friends.name), the result\n // mapping needs the traversal alias variable (?a1) in the bindings to\n // group nested rows by entity. Without this, mapNestedRows() can't\n // identify which nested fields belong to which traversed entity.\n const projectedNames = new Set<string>();\n for (const p of projection) {\n if (p.kind === 'variable') projectedNames.add(p.name);\n else if (p.kind === 'aggregate' || p.kind === 'expression') projectedNames.add(p.alias);\n }\n for (const alias of collectTraversalAliases(query.patterns)) {\n if (!projectedNames.has(alias) && !aggregateRenamedAliases.has(alias)) {\n projection.push({kind: 'variable', name: alias});\n projectedNames.add(alias);\n }\n }\n\n // 8. GROUP BY inference\n let groupBy: string[] | undefined;\n if (havingExpr) {\n hasAggregates = true;\n }\n if (hasAggregates) {\n // All non-aggregate projected variables become GROUP BY targets\n groupBy = projection\n .filter((p): p is {kind: 'variable'; name: string} => p.kind === 'variable')\n .map((p) => p.name);\n }\n\n // 9. OrderBy\n let orderBy: SparqlOrderCondition[] | undefined;\n if (query.orderBy) {\n orderBy = query.orderBy.map((item) => ({\n expression: convertExpression(item.expression, registry, optionalPropertyTriples),\n direction: item.direction,\n }));\n }\n\n // `.one()` lowers to limit=1 + singleResult, but LIMIT bounds ROWS, not\n // entities. When the query yields multiple rows per root entity (traversals\n // or plural properties), a row-level LIMIT would truncate the entity's own\n // nested data — omit it and let the result mapper pick the single entity.\n const multiRowPerEntity =\n query.patterns.some((p) => p.kind === 'traverse') ||\n query.projection.some(\n (item) =>\n item.expression.kind === 'property_expr' &&\n !(typeof item.expression.maxCount === 'number' && item.expression.maxCount <= 1),\n );\n const limit =\n query.singleResult && query.limit === 1 && multiRowPerEntity\n ? undefined\n : query.limit;\n\n return {\n type: 'select',\n algebra,\n projection,\n distinct: !hasAggregates ? true : undefined,\n orderBy,\n limit,\n offset: query.offset,\n groupBy,\n having: havingExpr,\n aggregates: aggregates.length > 0 ? aggregates : undefined,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Pattern processing\n// ---------------------------------------------------------------------------\n\nfunction processPattern(\n pattern: IRGraphPattern,\n registry: VariableRegistry,\n traverseTriples: SparqlTriple[],\n optionalPropertyTriples: SparqlTriple[],\n filteredTraverseBlocks?: Array<{traverseTriple: SparqlTriple; filter: IRExpression; toAlias: string}>,\n subSelectAliases?: ReadonlySet<string>,\n): void {\n switch (pattern.kind) {\n case 'shape_scan':\n // Additional shape scans (non-root) are handled as type triples\n // but this case is rare — root is handled separately\n break;\n\n case 'traverse': {\n // Register the traverse variable: (from, property) → to\n registry.set(pattern.from, pattern.property, pattern.to);\n // Traversals wrapped in a sub-SELECT (inner LIMIT/OFFSET) are emitted\n // separately — don't add their triple to the required BGP here.\n if (subSelectAliases?.has(pattern.to)) {\n break;\n }\n // Add traverse triple to required pattern (or filtered block if inline where)\n const triple = buildTraverseTriple(pattern);\n if (pattern.filter && filteredTraverseBlocks) {\n filteredTraverseBlocks.push({\n traverseTriple: triple,\n filter: pattern.filter,\n toAlias: pattern.to,\n });\n } else {\n traverseTriples.push(triple);\n }\n break;\n }\n\n case 'join': {\n for (const sub of pattern.patterns) {\n processPattern(sub, registry, traverseTriples, optionalPropertyTriples, filteredTraverseBlocks, subSelectAliases);\n }\n break;\n }\n\n case 'optional': {\n // Optional patterns — process inner patterns but keep them optional\n processPattern(pattern.pattern, registry, traverseTriples, optionalPropertyTriples, filteredTraverseBlocks, subSelectAliases);\n break;\n }\n\n case 'union': {\n for (const branch of pattern.branches) {\n processPattern(branch, registry, traverseTriples, optionalPropertyTriples, filteredTraverseBlocks, subSelectAliases);\n }\n break;\n }\n\n case 'exists': {\n processPattern(pattern.pattern, registry, traverseTriples, optionalPropertyTriples, filteredTraverseBlocks, subSelectAliases);\n break;\n }\n\n case 'minus': {\n // MINUS patterns are handled separately in selectToAlgebra — skip in processPattern.\n break;\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Expression processing — discover property_expr references\n// ---------------------------------------------------------------------------\n\nfunction processExpressionForProperties(\n expr: IRExpression,\n registry: VariableRegistry,\n optionalPropertyTriples: SparqlTriple[],\n requiredPropertyTriples: SparqlTriple[] = [],\n requiredPropertyKeys = new Set<string>(),\n): void {\n switch (expr.kind) {\n case 'property_expr': {\n if (!registry.has(expr.sourceAlias, expr.property)) {\n const varName = registry.getOrCreate(expr.sourceAlias, expr.property);\n const predicate = buildPredicateTerm(expr);\n const triple = tripleOf(\n varTerm(expr.sourceAlias),\n predicate,\n varTerm(varName),\n );\n const triples = requiredPropertyKeys.has(bindingKey(expr.sourceAlias, expr.property))\n ? requiredPropertyTriples\n : optionalPropertyTriples;\n triples.push(triple);\n }\n break;\n }\n case 'binary_expr':\n processExpressionForProperties(\n expr.left,\n registry,\n optionalPropertyTriples,\n requiredPropertyTriples,\n requiredPropertyKeys,\n );\n processExpressionForProperties(\n expr.right,\n registry,\n optionalPropertyTriples,\n requiredPropertyTriples,\n requiredPropertyKeys,\n );\n break;\n case 'in_expr':\n // The tested value binds a property; list elements are constants.\n processExpressionForProperties(\n expr.value,\n registry,\n optionalPropertyTriples,\n requiredPropertyTriples,\n requiredPropertyKeys,\n );\n break;\n case 'logical_expr':\n for (const sub of expr.expressions) {\n processExpressionForProperties(\n sub,\n registry,\n optionalPropertyTriples,\n requiredPropertyTriples,\n requiredPropertyKeys,\n );\n }\n break;\n case 'not_expr':\n processExpressionForProperties(\n expr.expression,\n registry,\n optionalPropertyTriples,\n requiredPropertyTriples,\n requiredPropertyKeys,\n );\n break;\n case 'function_expr':\n for (const arg of expr.args) {\n processExpressionForProperties(\n arg,\n registry,\n optionalPropertyTriples,\n requiredPropertyTriples,\n requiredPropertyKeys,\n );\n }\n break;\n case 'aggregate_expr':\n for (const arg of expr.args) {\n processExpressionForProperties(\n arg,\n registry,\n optionalPropertyTriples,\n requiredPropertyTriples,\n requiredPropertyKeys,\n );\n }\n break;\n case 'exists_expr':\n // exists_expr filter properties belong INSIDE the EXISTS block, not in\n // the outer scope. Do NOT register them here — convertExpression's\n // exists_expr handler will collect and emit them locally.\n break;\n case 'context_property_expr': {\n // Context entity property — emit a triple with fixed IRI as subject.\n // Use raw IRI as registry key to avoid collision between IRIs that\n // sanitize to the same string (e.g. ctx-1 vs ctx_1).\n const contextIri = resolvedContextIri(expr.contextIri, expr.contextName);\n const ctxKey = contextAliasKey(contextIri);\n if (!registry.has(ctxKey, expr.property)) {\n const varName = registry.getOrCreate(ctxKey, expr.property);\n const triple = tripleOf(\n iriTerm(contextIri),\n resolvePropertyPredicateTerm(expr.property),\n varTerm(varName),\n );\n const triples = requiredPropertyKeys.has(bindingKey(ctxKey, expr.property))\n ? requiredPropertyTriples\n : optionalPropertyTriples;\n triples.push(triple);\n }\n break;\n }\n case 'literal_expr':\n case 'reference_expr':\n case 'alias_expr':\n // No property references to discover\n break;\n }\n}\n\n/**\n * Compute which bindings are mandatory for a top-level FILTER to keep a row.\n * AND makes either side required; OR only keeps bindings required by every branch.\n */\nfunction collectRequiredBindingKeys(expr: IRExpression): Set<string> {\n switch (expr.kind) {\n case 'property_expr':\n return new Set([bindingKey(expr.sourceAlias, expr.property)]);\n case 'context_property_expr':\n return new Set([bindingKey(contextAliasKey(resolvedContextIri(expr.contextIri, expr.contextName)), expr.property)]);\n case 'in_expr':\n // The tested value must be bound; list elements are constants.\n return collectRequiredBindingKeys(expr.value);\n case 'binary_expr':\n return mergeKeySets(\n collectRequiredBindingKeys(expr.left),\n collectRequiredBindingKeys(expr.right),\n );\n case 'function_expr': {\n const fn = expr.name.toUpperCase();\n // BOUND explicitly tests boundness — forcing its argument into a\n // required (inner-join) pattern would make !BOUND unsatisfiable.\n // COALESCE is unbound-tolerant by design — requiring its arguments\n // would make the fallback unreachable.\n if (fn === 'BOUND' || fn === 'COALESCE') {\n return new Set<string>();\n }\n // IF: an unbound variable in the condition errors the row out either\n // way, so the condition may keep its requirements — but the then/else\n // branches must stay optional (the untaken branch may reference a\n // property the entity doesn't have).\n if (fn === 'IF') {\n return expr.args.length > 0\n ? collectRequiredBindingKeys(expr.args[0])\n : new Set<string>();\n }\n return mergeKeySets(...expr.args.map((arg) => collectRequiredBindingKeys(arg)));\n }\n case 'not_expr':\n return collectRequiredBindingKeys(expr.expression);\n case 'logical_expr': {\n const childSets = expr.expressions.map((sub) => collectRequiredBindingKeys(sub));\n if (expr.operator === 'and') {\n return mergeKeySets(...childSets);\n }\n return intersectKeySets(childSets);\n }\n case 'aggregate_expr':\n case 'exists_expr':\n case 'literal_expr':\n case 'reference_expr':\n case 'alias_expr':\n return new Set<string>();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Expression conversion\n// ---------------------------------------------------------------------------\n\n/**\n * The `sh:datatype` of the property a literal is being compared AGAINST, when the\n * comparison has one. Only temporal values use it (see the `literal_expr` case):\n * it is what tells an `xsd:date` property's filter to render `\"2020-01-01\"^^xsd:date`\n * rather than a full timestamp that can never equal the stored term.\n */\nfunction siblingDatatype(expr: IRExpression | undefined): string | undefined {\n if (!expr) return undefined;\n if (expr.kind === 'property_expr' || expr.kind === 'context_property_expr') {\n return resolvePropertyDatatype(expr.property);\n }\n return undefined;\n}\n\nfunction convertExpression(\n expr: IRExpression,\n registry: VariableRegistry,\n optionalPropertyTriples: SparqlTriple[],\n datatypeHint?: string,\n): SparqlExpression {\n switch (expr.kind) {\n case 'literal_expr': {\n const value = expr.value;\n if (value === null || value === undefined) {\n return {kind: 'literal_expr', value: ''};\n }\n // A temporal literal must carry its datatype. SPARQL's `=` on a plain literal\n // and an `^^xsd:dateTime` one is a type error, so the row is dropped: an\n // untyped date filter matched NOTHING against data core itself wrote. The\n // lexical form follows the compared property's declared datatype, the same\n // rule `dateToTerm` applies on the mutation side.\n if (value instanceof Date) {\n const term = dateToTerm(value, datatypeHint);\n return {\n kind: 'literal_expr',\n value: term.kind === 'literal' ? term.value : String(value),\n datatype: term.kind === 'literal' ? term.datatype : XSD_DATETIME,\n };\n }\n if (typeof value === 'boolean') {\n return {\n kind: 'literal_expr',\n value: String(value),\n datatype: XSD_BOOLEAN,\n };\n }\n if (typeof value === 'number') {\n if (Number.isInteger(value)) {\n return {\n kind: 'literal_expr',\n value: String(value),\n datatype: XSD_INTEGER,\n };\n }\n return {\n kind: 'literal_expr',\n value: String(value),\n datatype: XSD_DOUBLE,\n };\n }\n return {kind: 'literal_expr', value: String(value)};\n }\n\n case 'reference_expr':\n return {kind: 'iri_expr', value: resolvedContextIri(expr.value, expr.contextName)};\n\n case 'alias_expr':\n return {kind: 'variable_expr', name: expr.alias};\n\n case 'context_property_expr': {\n const ctxKey = `__ctx__${resolvedContextIri(expr.contextIri, expr.contextName)}`;\n const ctxVarName = registry.getOrCreate(ctxKey, expr.property);\n return {kind: 'variable_expr', name: ctxVarName};\n }\n\n case 'property_expr': {\n const varName = registry.getOrCreate(expr.sourceAlias, expr.property);\n return {kind: 'variable_expr', name: varName};\n }\n\n case 'in_expr': {\n const listHint = siblingDatatype(expr.value);\n return {\n kind: 'in_expr',\n negated: expr.negated,\n value: convertExpression(expr.value, registry, optionalPropertyTriples),\n list: expr.source.list.map((e) =>\n convertExpression(e, registry, optionalPropertyTriples, listHint),\n ),\n };\n }\n\n case 'binary_expr':\n return {\n kind: 'binary_expr',\n op: expr.operator,\n left: convertExpression(\n expr.left, registry, optionalPropertyTriples, siblingDatatype(expr.right),\n ),\n right: convertExpression(\n expr.right, registry, optionalPropertyTriples, siblingDatatype(expr.left),\n ),\n };\n\n case 'logical_expr':\n return {\n kind: 'logical_expr',\n op: expr.operator,\n exprs: expr.expressions.map((e) =>\n convertExpression(e, registry, optionalPropertyTriples),\n ),\n };\n\n case 'not_expr':\n return {\n kind: 'not_expr',\n inner: convertExpression(expr.expression, registry, optionalPropertyTriples),\n };\n\n case 'function_expr':\n return {\n kind: 'function_expr',\n name: expr.name,\n args: expr.args.map((a) =>\n convertExpression(a, registry, optionalPropertyTriples),\n ),\n };\n\n case 'aggregate_expr':\n return {\n kind: 'aggregate_expr',\n name: expr.name,\n args: expr.args.map((a) =>\n convertExpression(a, registry, optionalPropertyTriples),\n ),\n };\n\n case 'exists_expr': {\n // Convert exists expression with inner pattern + filter.\n // Filter property triples must live INSIDE the EXISTS block\n // (not in the outer scope), so we collect them locally.\n let innerAlgebra = convertExistsPattern(\n expr.pattern,\n registry,\n );\n\n if (expr.filter) {\n // First, discover and register filter property references,\n // collecting their triples into a local array (NOT the outer scope).\n const existsPropertyTriples: SparqlTriple[] = [];\n processExpressionForProperties(expr.filter, registry, existsPropertyTriples);\n\n // Now convert the filter expression (variables are registered above).\n const filterExpr = convertExpression(\n expr.filter,\n registry,\n existsPropertyTriples, // unused — properties already registered\n );\n // Add filter property triples inside the EXISTS\n for (const propTriple of existsPropertyTriples) {\n innerAlgebra = joinNodes(innerAlgebra, {type: 'bgp', triples: [propTriple]})!;\n }\n // Wrap the inner pattern with a filter\n const filteredInner: SparqlFilter = {\n type: 'filter',\n expression: filterExpr,\n inner: innerAlgebra,\n };\n return {\n kind: 'exists_expr',\n pattern: filteredInner,\n negated: false,\n };\n }\n\n return {\n kind: 'exists_expr',\n pattern: innerAlgebra,\n negated: false,\n };\n }\n\n default:\n throw new Error(`Unknown IR expression kind: ${(expr as never as {kind: string}).kind}`);\n }\n}\n\n/**\n * Convert an exists pattern (from exists_expr) into an algebra node.\n * Recursively handles all IR graph pattern kinds.\n */\nfunction convertExistsPattern(\n pattern: IRGraphPattern,\n registry: VariableRegistry,\n): SparqlAlgebraNode {\n switch (pattern.kind) {\n case 'traverse': {\n const existsPredicate = buildPredicateTerm(pattern);\n const triple = tripleOf(\n varTerm(pattern.from),\n existsPredicate,\n varTerm(pattern.to),\n );\n return {type: 'bgp', triples: [triple]};\n }\n\n case 'join': {\n let result: SparqlAlgebraNode | null = null;\n for (const sub of pattern.patterns) {\n const subNode = convertExistsPattern(sub, registry);\n result = result ? joinNodes(result, subNode) : subNode;\n }\n return result || {type: 'bgp', triples: []};\n }\n\n case 'shape_scan': {\n return {\n type: 'bgp',\n triples: [\n tripleOf(\n varTerm(pattern.alias),\n iriTerm(RDF_TYPE),\n iriTerm(resolveShapeScanIri(pattern.shape)),\n ),\n ],\n };\n }\n\n case 'optional': {\n const inner = convertExistsPattern(pattern.pattern, registry);\n return wrapOptional({type: 'bgp', triples: []}, inner);\n }\n\n case 'union': {\n let result: SparqlAlgebraNode | null = null;\n for (const branch of pattern.branches) {\n const branchNode = convertExistsPattern(branch, registry);\n if (!result) {\n result = branchNode;\n } else {\n result = {type: 'union', left: result, right: branchNode};\n }\n }\n return result || {type: 'bgp', triples: []};\n }\n\n case 'exists': {\n return convertExistsPattern(pattern.pattern, registry);\n }\n\n case 'minus': {\n return convertExistsPattern(pattern.pattern, registry);\n }\n\n default:\n throw new Error(`Unsupported pattern kind in EXISTS: ${(pattern as never as {kind: string}).kind}`);\n }\n}\n\n/**\n * Resolve what variable name an IR expression ultimately refers to.\n */\nfunction resolveExpressionVariable(\n expr: IRExpression,\n registry: VariableRegistry,\n): string | null {\n switch (expr.kind) {\n case 'alias_expr':\n return expr.alias;\n case 'property_expr':\n return registry.getOrCreate(expr.sourceAlias, expr.property);\n default:\n return null;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Mutation conversions\n// ---------------------------------------------------------------------------\n\n/** The numeric datatypes a shape may declare, and the DSL accepts a number for. */\nconst NUMERIC_DATATYPES = new Set([\n XSD_INTEGER,\n XSD_DOUBLE,\n xsd.long.id,\n xsd.decimal.id,\n xsd.float.id,\n]);\n\n/**\n * The datatype to write a number as: the one its property declares, falling back\n * to the shape of the value itself. Without the declared datatype a property\n * typed `xsd:long` stored `xsd:integer` and one typed `xsd:decimal` stored\n * `xsd:double` — a value the store round-trips as a different term than the\n * shape says it holds.\n */\nfunction numericDatatype(value: number, datatype?: string): string {\n if (datatype && NUMERIC_DATATYPES.has(datatype)) return datatype;\n return Number.isInteger(value) ? XSD_INTEGER : XSD_DOUBLE;\n}\n\n/**\n * A `Date` in the lexical form its property asks for. `xsd:date` and `xsd:dateTime` take a `Date`\n * and only a `Date`, so the declared `sh:datatype` is what decides whether that instant is\n * written as a date or a full timestamp. With no declared datatype the term stays `xsd:dateTime`.\n *\n * `xsd:time` takes a STRING instead (see `STRING_LEXICAL_DATATYPES`): a `Date` cannot represent a\n * time of day without inventing a date alongside it, which then has to be discarded here and\n * makes two identical clock times on different days compare unequal. The `XSD_TIME` branch below\n * remains for a `Date` that reaches an `xsd:time` property some other way.\n */\nfunction dateToTerm(value: Date, datatype?: string): SparqlTerm {\n const iso = value.toISOString();\n if (datatype === XSD_DATE) return literalTerm(iso.slice(0, 10), XSD_DATE);\n if (datatype === XSD_TIME) return literalTerm(iso.slice(11), XSD_TIME);\n return literalTerm(iso, XSD_DATETIME);\n}\n\n/**\n * Datatypes whose lexical form IS a string, so a plain string value must be typed from the\n * DECLARED datatype rather than written as a plain literal.\n *\n * A deliberate allow-list rather than \"type every string from whatever is declared\". A string\n * reaching a numeric or boolean property is a mistake that `assertValid` rejects; typing it here\n * would instead write a well-formed-looking `\"abc\"^^xsd:integer` and hide the error in the data.\n * Only datatypes a string is a VALID lexical form for belong here.\n */\nconst STRING_LEXICAL_DATATYPES = new Set<string>([XSD_TIME]);\n\n/**\n * Convert a field value to one or more SparqlTerm objects for triple objects.\n *\n * `datatype` is the property's declared `sh:datatype`. It decides the term type for temporal\n * values and for the string-lexical datatypes above; every other literal is still typed from the\n * JavaScript value, because that is what makes a wrong JS type a visible failure rather than a\n * silently mistyped triple.\n */\nfunction fieldValueToTerms(\n value: IRFieldValue,\n options?: SparqlOptions,\n datatype?: string,\n): SparqlTerm[] {\n if (value === null || value === undefined) {\n return [];\n }\n\n if (typeof value === 'string') {\n // A plain literal is `xsd:string` in RDF 1.1, so a string for an `xsd:string` property needs\n // no explicit datatype. Anything else in the allow-list must carry one, or it is written\n // untyped and stops matching the property it was meant to fill.\n if (datatype && STRING_LEXICAL_DATATYPES.has(datatype)) {\n return [literalTerm(value, datatype)];\n }\n return [literalTerm(value)];\n }\n\n if (typeof value === 'number') {\n return [literalTerm(String(value), numericDatatype(value, datatype))];\n }\n\n if (typeof value === 'boolean') {\n return [literalTerm(String(value), XSD_BOOLEAN)];\n }\n\n if (value instanceof Date) {\n return [dateToTerm(value, datatype)];\n }\n\n // Computed/expression value in create: create lowers to INSERT DATA (ground\n // triples, no WHERE), so an expression can't be evaluated here. Fail loudly\n // instead of silently emitting no triple (report 021 §3, G4).\n if (\n value &&\n typeof value === 'object' &&\n (isIRExpression(value) || 'ir' in (value as object))\n ) {\n throw new Error(\n 'Computed/expression values are not supported in create (INSERT DATA has no WHERE clause to evaluate them). Use a literal value, or use update.',\n );\n }\n\n // NodeReferenceValue\n if (typeof value === 'object' && 'id' in value && !('shape' in value) && !('fields' in value)) {\n return [iriTerm((value as NodeReferenceValue).id)];\n }\n\n // IRNodeData — should not produce a term directly (handled by nested create)\n if (typeof value === 'object' && 'shape' in value && 'fields' in value) {\n return []; // Handled separately\n }\n\n // Array\n if (Array.isArray(value)) {\n const terms: SparqlTerm[] = [];\n for (const item of value) {\n terms.push(...fieldValueToTerms(item, options, datatype));\n }\n return terms;\n }\n\n return [];\n}\n\n/**\n * Recursively generate triples for an IRNodeData (used in create and nested creates).\n * Returns the URI used for this node and all generated triples.\n */\nfunction generateNodeDataTriples(\n data: IRNodeData,\n options?: SparqlOptions,\n): {uri: string; triples: SparqlTriple[]} {\n const uri = data.id || generateEntityUri(data.shape, options);\n const triples: SparqlTriple[] = [];\n const subjectTerm = iriTerm(uri);\n\n // Type triple — resolve the SHACL NodeShapeData id in the IR to the ontology\n // targetClass URI (sibling of PR #77's SELECT-side resolveShapeScanIri).\n // Mutations were not covered by #77; see mutation-uri-fidelity.test.ts.\n triples.push(tripleOf(subjectTerm, iriTerm(RDF_TYPE), iriTerm(resolveShapeScanIri(data.shape))));\n\n // Field triples\n for (const field of data.fields) {\n // Resolve the SHACL PropertyShapeData id to its declared `path` URI.\n const propertyTerm = resolvePropertyPredicateTerm(field.property);\n\n if (field.value === null || field.value === undefined) {\n continue;\n }\n\n // Handle arrays (including mixed arrays of references and nested creates)\n if (Array.isArray(field.value)) {\n for (const item of field.value) {\n if (item && typeof item === 'object' && 'shape' in item && 'fields' in item) {\n // Nested create\n const nested = generateNodeDataTriples(item as IRNodeData, options);\n triples.push(tripleOf(subjectTerm, propertyTerm, iriTerm(nested.uri)));\n triples.push(...nested.triples);\n } else {\n const terms = fieldValueToTerms(item, options, resolvePropertyDatatype(field.property));\n for (const term of terms) {\n triples.push(tripleOf(subjectTerm, propertyTerm, term));\n }\n }\n }\n continue;\n }\n\n // Handle nested IRNodeData\n if (typeof field.value === 'object' && 'shape' in field.value && 'fields' in field.value) {\n const nested = generateNodeDataTriples(field.value as IRNodeData, options);\n triples.push(tripleOf(subjectTerm, propertyTerm, iriTerm(nested.uri)));\n triples.push(...nested.triples);\n continue;\n }\n\n // Simple values\n const terms = fieldValueToTerms(field.value, options, resolvePropertyDatatype(field.property));\n for (const term of terms) {\n triples.push(tripleOf(subjectTerm, propertyTerm, term));\n }\n }\n\n return {uri, triples};\n}\n\n/**\n * Converts an IRCreateMutation to a SparqlInsertDataPlan.\n */\nexport function createToAlgebra(\n query: IRCreateMutation,\n options?: SparqlOptions,\n): SparqlInsertDataPlan {\n const {triples} = generateNodeDataTriples(query.data, options);\n return {\n type: 'insert_data',\n triples,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Shared update field processing\n// ---------------------------------------------------------------------------\n\n/**\n * Processes IRNodeData fields into DELETE/INSERT/WHERE triples.\n * Shared between updateToAlgebra (IRI subject) and updateWhereToAlgebra (variable subject).\n */\nfunction processUpdateFields(\n data: IRNodeData,\n subjectTerm: SparqlTerm,\n options?: SparqlOptions,\n): {\n deletePatterns: SparqlTriple[];\n insertPatterns: SparqlTriple[];\n oldValueTriples: SparqlTriple[];\n extends: Array<{variable: string; expression: SparqlExpression}>;\n cascadeOptionals: SparqlAlgebraNode[];\n} {\n const deletePatterns: SparqlTriple[] = [];\n const insertPatterns: SparqlTriple[] = [];\n const oldValueTriples: SparqlTriple[] = [];\n const extends_: Array<{variable: string; expression: SparqlExpression}> = [];\n // Owned cleanup on `contains` replace/remove: dropping a `contains` edge must delete\n // the old object itself (its own triples) AND its owned subtree, not just unlink the\n // one-hop edge — otherwise the old node orphans (backlog 032).\n const {containsPreds: updContainsPreds} = collectContainment();\n const containsOldVars: Array<{oldVar: string; propertyTerm: SparqlTerm}> = [];\n const cascadeOptionals: SparqlAlgebraNode[] = [];\n\n for (const field of data.fields) {\n const propertyTerm = resolvePropertyPredicateTerm(field.property);\n const suffix = propertySuffix(field.property);\n const isContainsField =\n propertyTerm.kind === 'iri' && updContainsPreds.includes(propertyTerm.value);\n\n // Check for set modification ({add, remove})\n if (\n field.value &&\n typeof field.value === 'object' &&\n !Array.isArray(field.value) &&\n !(field.value instanceof Date) &&\n !('id' in field.value) &&\n !('shape' in field.value) &&\n ('add' in field.value || 'remove' in field.value)\n ) {\n const setMod = field.value as IRSetModificationValue;\n\n if (setMod.remove) {\n setMod.remove.forEach((removeItem, ri) => {\n const removeTerm = iriTerm((removeItem as NodeReferenceValue).id);\n deletePatterns.push(tripleOf(subjectTerm, propertyTerm, removeTerm));\n oldValueTriples.push(tripleOf(subjectTerm, propertyTerm, removeTerm));\n // For a `contains` set, removing a value deletes the removed node itself\n // (its own triples) and its owned subtree — exclusive ownership via the edge.\n if (isContainsField) {\n const self = buildOwnedSelfDelete(\n subjectTerm,\n propertyTerm,\n removeTerm,\n `ucr_${suffix}_${ri}_`,\n );\n deletePatterns.push(...self.deletePatterns);\n cascadeOptionals.push(...self.whereOptionals);\n const cascade = buildOwnedCascade(removeTerm, `ucr_${suffix}_${ri}_`);\n deletePatterns.push(...cascade.deletePatterns);\n cascadeOptionals.push(...cascade.whereOptionals);\n }\n });\n }\n\n if (setMod.add) {\n for (const addItem of setMod.add) {\n if (addItem && typeof addItem === 'object' && 'shape' in addItem && 'fields' in addItem) {\n const nested = generateNodeDataTriples(addItem as IRNodeData, options);\n insertPatterns.push(tripleOf(subjectTerm, propertyTerm, iriTerm(nested.uri)));\n insertPatterns.push(...nested.triples);\n } else {\n const terms = fieldValueToTerms(addItem, options, resolvePropertyDatatype(field.property));\n for (const term of terms) {\n insertPatterns.push(tripleOf(subjectTerm, propertyTerm, term));\n }\n }\n }\n }\n\n continue;\n }\n\n // Non-set-modification replace of a `contains` property: cascade the old value's\n // subtree (every branch below binds `old_${suffix}` in the WHERE).\n if (isContainsField) {\n containsOldVars.push({oldVar: `old_${suffix}`, propertyTerm});\n }\n\n // Unset (undefined/null) — delete only\n if (field.value === undefined || field.value === null) {\n const oldVar = varTerm(`old_${suffix}`);\n deletePatterns.push(tripleOf(subjectTerm, propertyTerm, oldVar));\n oldValueTriples.push(tripleOf(subjectTerm, propertyTerm, oldVar));\n continue;\n }\n\n // Array overwrite — delete old values + insert new ones\n if (Array.isArray(field.value)) {\n const oldVar = varTerm(`old_${suffix}`);\n deletePatterns.push(tripleOf(subjectTerm, propertyTerm, oldVar));\n oldValueTriples.push(tripleOf(subjectTerm, propertyTerm, oldVar));\n\n for (const item of field.value) {\n if (item && typeof item === 'object' && 'shape' in item && 'fields' in item) {\n const nested = generateNodeDataTriples(item as IRNodeData, options);\n insertPatterns.push(tripleOf(subjectTerm, propertyTerm, iriTerm(nested.uri)));\n insertPatterns.push(...nested.triples);\n } else {\n const terms = fieldValueToTerms(item, options, resolvePropertyDatatype(field.property));\n for (const term of terms) {\n insertPatterns.push(tripleOf(subjectTerm, propertyTerm, term));\n }\n }\n }\n continue;\n }\n\n // Nested create (single object field)\n if (typeof field.value === 'object' && 'shape' in field.value && 'fields' in field.value) {\n const oldVar = varTerm(`old_${suffix}`);\n deletePatterns.push(tripleOf(subjectTerm, propertyTerm, oldVar));\n oldValueTriples.push(tripleOf(subjectTerm, propertyTerm, oldVar));\n\n const nested = generateNodeDataTriples(field.value as IRNodeData, options);\n insertPatterns.push(tripleOf(subjectTerm, propertyTerm, iriTerm(nested.uri)));\n insertPatterns.push(...nested.triples);\n continue;\n }\n\n // IRExpression — computed value update (e.g. p.age.plus(1))\n if (isIRExpression(field.value)) {\n const expr = field.value as IRExpression;\n const oldVar = varTerm(`old_${suffix}`);\n const computedVarName = `computed_${suffix}`;\n const computedVar = varTerm(computedVarName);\n\n // DELETE old value\n deletePatterns.push(tripleOf(subjectTerm, propertyTerm, oldVar));\n\n // WHERE: OPTIONAL for old value\n oldValueTriples.push(tripleOf(subjectTerm, propertyTerm, oldVar));\n\n // Discover additional property references in the expression and add OPTIONAL triples\n const registry = new VariableRegistry();\n const mutationSubjectAlias = '__mutation_subject__';\n // Pre-register the subject variable mapping for the field being updated\n registry.set(mutationSubjectAlias, field.property, `old_${suffix}`);\n\n const additionalOptionals: SparqlTriple[] = [];\n processExpressionForProperties(expr, registry, additionalOptionals);\n\n // Add any additional property OPTIONAL triples (for refs to other properties)\n for (const triple of additionalOptionals) {\n // Rewrite the subject from the placeholder variable to the actual subject term\n if (triple.subject.kind === 'variable' && triple.subject.name === mutationSubjectAlias) {\n oldValueTriples.push(tripleOf(subjectTerm, triple.predicate, triple.object));\n } else {\n oldValueTriples.push(triple);\n }\n }\n\n // Convert IRExpression to SparqlExpression\n const sparqlExpr = convertExpression(expr, registry, additionalOptionals);\n\n // BIND computed expression\n extends_.push({variable: computedVarName, expression: sparqlExpr});\n\n // INSERT computed value\n insertPatterns.push(tripleOf(subjectTerm, propertyTerm, computedVar));\n continue;\n }\n\n // Simple value update — delete old + insert new\n const oldVar = varTerm(`old_${suffix}`);\n deletePatterns.push(tripleOf(subjectTerm, propertyTerm, oldVar));\n oldValueTriples.push(tripleOf(subjectTerm, propertyTerm, oldVar));\n\n const terms = fieldValueToTerms(field.value, options, resolvePropertyDatatype(field.property));\n for (const term of terms) {\n insertPatterns.push(tripleOf(subjectTerm, propertyTerm, term));\n }\n }\n\n // For each replaced `contains` property: delete the old value's own triples\n // (exclusive ownership via the edge — backlog 032) then cascade any owned descendants.\n containsOldVars.forEach(({oldVar, propertyTerm}, n) => {\n const oldTerm = varTerm(oldVar);\n const self = buildOwnedSelfDelete(subjectTerm, propertyTerm, oldTerm, `uc${n}_`);\n deletePatterns.push(...self.deletePatterns);\n cascadeOptionals.push(...self.whereOptionals);\n const cascade = buildOwnedCascade(oldTerm, `uc${n}_`);\n deletePatterns.push(...cascade.deletePatterns);\n cascadeOptionals.push(...cascade.whereOptionals);\n });\n\n return {\n deletePatterns,\n insertPatterns,\n oldValueTriples,\n extends: extends_,\n cascadeOptionals,\n };\n}\n\n/**\n * Wraps old-value triples in OPTIONAL (LEFT JOIN) so UPDATE succeeds\n * even when the old value doesn't exist.\n */\nfunction wrapOldValueOptionals(\n base: SparqlAlgebraNode,\n oldValueTriples: SparqlTriple[],\n): SparqlAlgebraNode {\n let algebra = base;\n if (oldValueTriples.length === 0) {\n return algebra;\n }\n for (const triple of oldValueTriples) {\n algebra = {\n type: 'left_join',\n left: algebra,\n right: {type: 'bgp', triples: [triple]},\n };\n }\n return algebra;\n}\n\n/**\n * Converts an IRUpdateMutation to a SparqlDeleteInsertPlan.\n */\nexport function updateToAlgebra(\n query: IRUpdateMutation,\n options?: SparqlOptions,\n): SparqlDeleteInsertPlan {\n return buildDeleteInsertPlan(query, options);\n}\n\n/**\n * Converts an IRUpsertMutation to a SparqlDeleteInsertPlan.\n *\n * The same plan `update` produces, plus `<id> a <targetClass>` in the INSERT. Nothing else\n * differs: `update`'s WHERE is already a bare OPTIONAL, so it matches — and therefore\n * inserts — whether or not the node exists. The type triple is what turns that into a\n * create. Re-asserting it on an existing node is a no-op, RDF graphs being sets, so it\n * needs no guard.\n */\nexport function upsertToAlgebra(\n query: IRUpsertMutation,\n options?: SparqlOptions,\n): SparqlDeleteInsertPlan {\n return buildDeleteInsertPlan(query, options, {\n // Must match the IRI `create` asserts and `select` scans for; the raw shape id is\n // not the same thing, and a node typed with it would be invisible to queries.\n ensureType: resolveShapeScanIri(query.shape),\n });\n}\n\n/**\n * Shared body of the id-targeted DELETE/INSERT/WHERE plans. `ensureType` is the only\n * difference between `update` and `upsert`; when absent the output is exactly what the\n * update path has always emitted.\n */\nfunction buildDeleteInsertPlan(\n query: IRUpdateMutation | IRUpsertMutation,\n options?: SparqlOptions,\n opts?: {ensureType?: string},\n): SparqlDeleteInsertPlan {\n const subjectTerm = iriTerm(query.id);\n const result = processUpdateFields(query.data, subjectTerm, options);\n\n // Partition old-value/optional triples into subject-anchored ones and those\n // anchored on a traversal target variable (e.g. `?a1 <name> ?a1_name` from a\n // `p.bestFriend.name.ucase()` expression). Traversal-anchored triples MUST be\n // nested inside the same OPTIONAL group as their traversal edge — otherwise,\n // when the subject has no such edge, the leaf variable is unbound and the\n // property triple matches every entity in the graph (data-corruption bug).\n const travTos = new Set(\n (query.traversalPatterns ?? []).map((t) => t.to),\n );\n const travAnchoredByTo = new Map<string, SparqlTriple[]>();\n const subjectAnchored: SparqlTriple[] = [];\n for (const triple of result.oldValueTriples) {\n if (triple.subject.kind === 'variable' && travTos.has(triple.subject.name)) {\n const list = travAnchoredByTo.get(triple.subject.name) ?? [];\n list.push(triple);\n travAnchoredByTo.set(triple.subject.name, list);\n } else {\n subjectAnchored.push(triple);\n }\n }\n\n let whereAlgebra = wrapOldValueOptionals(\n {type: 'bgp', triples: []},\n subjectAnchored,\n );\n\n // Add traversal OPTIONAL patterns (for multi-segment expression refs). The\n // traversal edge and its dependent leaf property triples share one OPTIONAL\n // group so the leaf variable is scoped to the traversal target. These come\n // BEFORE expression BINDs since the BINDs reference the traversal variables.\n if (query.traversalPatterns) {\n for (const trav of query.traversalPatterns) {\n const fromTerm =\n trav.from === '__mutation_subject__' ? subjectTerm : varTerm(trav.from);\n const traversalTriple = tripleOf(\n fromTerm,\n // The declared `sh:path`, like every other predicate — not the property\n // shape's own IRI, which identifies the description of the property.\n resolvePropertyPredicateTerm(trav.property),\n varTerm(trav.to),\n );\n // The traversal edge binds the target var; each dependent leaf property is\n // a nested OPTIONAL *within* that scope, so a missing optional property\n // (e.g. a bestFriend with no hobby) doesn't drop the whole group, while an\n // absent edge still leaves every leaf var unbound (no cross-entity match).\n let travNode: SparqlAlgebraNode = {type: 'bgp', triples: [traversalTriple]};\n for (const leaf of travAnchoredByTo.get(trav.to) ?? []) {\n travNode = {\n type: 'left_join',\n left: travNode,\n right: {type: 'bgp', triples: [leaf]},\n };\n }\n whereAlgebra = {type: 'left_join', left: whereAlgebra, right: travNode};\n }\n }\n\n // Owned-subtree cascade OPTIONALs for replaced `contains` properties.\n for (const optional of result.cascadeOptionals) {\n whereAlgebra = {type: 'left_join', left: whereAlgebra, right: optional};\n }\n\n // Add BIND expressions for computed fields\n for (const ext of result.extends) {\n whereAlgebra = {\n type: 'extend',\n inner: whereAlgebra,\n variable: ext.variable,\n expression: ext.expression,\n };\n }\n\n // The type triple leads the INSERT, mirroring `create`'s triple order.\n const insertPatterns = opts?.ensureType\n ? [\n tripleOf(subjectTerm, iriTerm(RDF_TYPE), iriTerm(opts.ensureType)),\n ...result.insertPatterns,\n ]\n : result.insertPatterns;\n\n return {\n type: 'delete_insert',\n deletePatterns: result.deletePatterns,\n insertPatterns,\n whereAlgebra,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Owned-subtree cascade\n//\n// Composition cleanup driven by two declarative flags:\n// - a property marked `contains` → the cascade FOLLOWS that edge,\n// - a shape marked `dependent` → its instances may be DELETED when reached.\n// Both are read from the live registry, so no vocabulary is hardcoded. From a root\n// node we follow `(c1|c2|…)+` over all contains predicates and, for each dependent\n// targetClass, wildcard-delete the reached typed nodes. Requiring an asserted\n// `?owned a <dependentType>` naturally excludes shared predicate IRIs (e.g. a simple\n// `sh:path`) and `rdf:nil` (never typed), so only owned structural nodes are removed.\n// ---------------------------------------------------------------------------\n\n/** True when the shape (or an ancestor) declares at least one `contains` property. */\nfunction shapeHasContainsProperty(shapeId: string): boolean {\n const nodeShape = getShapeClass(shapeId)?.shape ?? getNodeShape(shapeId);\n if (!nodeShape) return false;\n return getPropertyShapes(nodeShape, true)\n .some((ps) => (ps as {contains?: boolean}).contains);\n}\n\n// Memoized registry scan for cascade lowering — called once per update/delete and\n// again per owned-cascade item inside loops. Guarded by registry size (same rationale\n// as predicateTermCache). Callers treat the result as read-only.\nlet containmentCache: {containsPreds: string[]; dependentTypes: string[]} | null = null;\nlet containmentCacheSize = -1;\n\n/** Gather contains-predicate IRIs and dependent targetClass IRIs from the registry. */\nfunction collectContainment(): {containsPreds: string[]; dependentTypes: string[]} {\n const version = getRegistryVersion();\n if (containmentCache && version === containmentCacheSize) {\n return containmentCache;\n }\n const containsPreds = new Set<string>();\n const dependentTypes = new Set<string>();\n for (const nodeShape of getAllNodeShapes().values()) {\n if (!nodeShape) continue;\n if ((nodeShape as {dependent?: boolean}).dependent && nodeShape.targetClass?.id) {\n dependentTypes.add(nodeShape.targetClass.id);\n }\n const propertyShapes = getPropertyShapes(nodeShape, false);\n for (const ps of propertyShapes) {\n if ((ps as {contains?: boolean}).contains) {\n const predId = getSimplePathId(ps.path);\n if (predId) containsPreds.add(predId);\n }\n }\n }\n containmentCache = {containsPreds: [...containsPreds], dependentTypes: [...dependentTypes]};\n containmentCacheSize = version;\n return containmentCache;\n}\n\n/**\n * Build DELETE patterns + WHERE OPTIONAL blocks that cascade-delete the owned subtree\n * reachable from `rootTerm` via `contains` edges. `varPrefix` keeps generated variables\n * unique across multiple roots in one query. Returns empty when nothing is owned.\n */\nexport function buildOwnedCascade(\n rootTerm: SparqlTerm,\n varPrefix: string,\n): {deletePatterns: SparqlTriple[]; whereOptionals: SparqlAlgebraNode[]} {\n const {containsPreds, dependentTypes} = collectContainment();\n if (containsPreds.length === 0 || dependentTypes.length === 0) {\n return {deletePatterns: [], whereOptionals: []};\n }\n // (c1|c2|…)+ — follow one-or-more contains edges from the root.\n const pathExpr: PathExpr =\n containsPreds.length === 1\n ? {oneOrMore: {id: containsPreds[0]}}\n : {oneOrMore: {alt: containsPreds.map((id) => ({id}))}};\n const pathTerm: SparqlTerm = {\n kind: 'path',\n value: pathExprToSparql(pathExpr),\n uris: collectPathUris(pathExpr),\n };\n\n const deletePatterns: SparqlTriple[] = [];\n const whereOptionals: SparqlAlgebraNode[] = [];\n dependentTypes.forEach((typeId, i) => {\n const owned = varTerm(`${varPrefix}own${i}`);\n const p = varTerm(`${varPrefix}op${i}`);\n const o = varTerm(`${varPrefix}ov${i}`);\n deletePatterns.push(tripleOf(owned, p, o));\n whereOptionals.push({\n type: 'bgp',\n triples: [\n tripleOf(rootTerm, pathTerm, owned),\n tripleOf(owned, iriTerm(RDF_TYPE), iriTerm(typeId)),\n tripleOf(owned, p, o),\n ],\n });\n });\n return {deletePatterns, whereOptionals};\n}\n\n/**\n * Build DELETE + WHERE OPTIONAL that removes the *old node's own* one-hop triples when a\n * `contains` edge is replaced, unset, or set-removed. A `contains` edge asserts exclusive\n * ownership, so overwriting it must delete the previously owned child fully — not merely\n * unlink it — or the child orphans (backlog 032). This is `contains`-driven and deliberately\n * does NOT require the child shape to be `dependent`: ownership via the edge is sufficient.\n * Owned descendants *below* the old node are cascaded separately by `buildOwnedCascade`.\n *\n * The owning edge `<subject> <prop> ?old` is re-asserted INSIDE the WHERE group so `?old`\n * is bound there: when no old value exists the group matches nothing and the DELETE is a\n * no-op, rather than an unbound `?old` matching (and deleting) the whole graph. When\n * `oldTerm` is a concrete IRI (set-remove), the guard just confirms the link still holds.\n */\nexport function buildOwnedSelfDelete(\n subjectTerm: SparqlTerm,\n propertyTerm: SparqlTerm,\n oldTerm: SparqlTerm,\n varPrefix: string,\n): {deletePatterns: SparqlTriple[]; whereOptionals: SparqlAlgebraNode[]} {\n const p = varTerm(`${varPrefix}sp`);\n const o = varTerm(`${varPrefix}so`);\n const wildcard = tripleOf(oldTerm, p, o);\n return {\n deletePatterns: [wildcard],\n whereOptionals: [\n {\n type: 'bgp',\n triples: [tripleOf(subjectTerm, propertyTerm, oldTerm), wildcard],\n },\n ],\n };\n}\n\n/**\n * Converts an IRDeleteMutation to a SparqlDeleteInsertPlan (DELETE + WHERE).\n */\nexport function deleteToAlgebra(\n query: IRDeleteMutation,\n _options?: SparqlOptions,\n): SparqlDeleteInsertPlan {\n const deletePatterns: SparqlTriple[] = [];\n const requiredTriples: SparqlTriple[] = [];\n const optionalTriples: SparqlTriple[] = [];\n const cascadeOptionals: SparqlAlgebraNode[] = [];\n\n for (let i = 0; i < query.ids.length; i++) {\n const subjectTerm = iriTerm(query.ids[i].id);\n const idx = query.ids.length > 1 ? `_${i}` : '';\n\n const subjWild = tripleOf(subjectTerm, varTerm(`p${idx}`), varTerm(`o${idx}`));\n const objWild = tripleOf(varTerm(`s${idx}`), varTerm(`p2${idx}`), subjectTerm);\n const typeGuard = tripleOf(subjectTerm, iriTerm(RDF_TYPE), iriTerm(resolveShapeScanIri(query.shape)));\n\n // DELETE block: all patterns (subject-wildcard, object-wildcard, type)\n deletePatterns.push(subjWild, objWild, typeGuard);\n\n // WHERE block: subject-wildcard and type guard are required;\n // object-wildcard is OPTIONAL (entity may have no incoming references)\n requiredTriples.push(subjWild, typeGuard);\n optionalTriples.push(objWild);\n\n // Cascade-delete the owned subtree — only for shapes that actually own something\n // (have a `contains` property); a plain entity delete is left untouched.\n if (shapeHasContainsProperty(query.shape)) {\n const cascade = buildOwnedCascade(subjectTerm, `c${idx}_`);\n deletePatterns.push(...cascade.deletePatterns);\n cascadeOptionals.push(...cascade.whereOptionals);\n }\n }\n\n // Build WHERE algebra: required BGP + OPTIONAL for each object-wildcard + cascade OPTIONALs\n let whereAlgebra: SparqlAlgebraNode = {type: 'bgp', triples: requiredTriples};\n for (const triple of optionalTriples) {\n whereAlgebra = {\n type: 'left_join',\n left: whereAlgebra,\n right: {type: 'bgp', triples: [triple]},\n };\n }\n for (const optional of cascadeOptionals) {\n whereAlgebra = {type: 'left_join', left: whereAlgebra, right: optional};\n }\n\n return {\n type: 'delete_insert',\n deletePatterns,\n insertPatterns: [],\n whereAlgebra,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Blank node tree walking for schema-aware delete cleanup\n// ---------------------------------------------------------------------------\n\n/**\n * Checks whether a PropertyShapeData points to blank nodes (sh:BlankNode or\n * sh:BlankNodeOrIRI). Returns true when the property's range *may* include\n * blank node values that should be cleaned up on delete.\n */\nfunction isBlankNodeProperty(prop: {nodeKind?: {id?: string}}): boolean {\n const nk = prop.nodeKind?.id;\n if (!nk) return false;\n return nk === shacl.BlankNode.id || nk === shacl.BlankNodeOrIRI.id;\n}\n\n/**\n * Recursively builds DELETE + WHERE patterns for blank-node-typed properties.\n *\n * For each blank-node property on the shape:\n * - DELETE: `?bnVar ?pN ?oN .` (wildcard all triples on the blank node)\n * - WHERE: `OPTIONAL { ?parent <property> ?bnVar . FILTER(isBlank(?bnVar)) . ?bnVar ?pN ?oN . }`\n *\n * Recurses into the property's valueShape to handle nested blank nodes\n * (e.g. Person → Address (blank) → GeoPoint (blank)).\n */\nfunction walkBlankNodeTree(\n shapeId: string,\n parentVar: string,\n depth: number,\n deletePatterns: SparqlTriple[],\n): SparqlAlgebraNode | null {\n const nodeShape = getShapeClass(shapeId)?.shape ?? getNodeShape(shapeId);\n if (!nodeShape) return null;\n\n let optionals: SparqlAlgebraNode | null = null;\n\n const props = getPropertyShapes(nodeShape, true);\n for (const prop of props) {\n if (!isBlankNodeProperty(prop)) continue;\n\n const bnVar = `bn${depth}`;\n const pVar = `p${depth}`;\n const oVar = `o${depth}`;\n\n // DELETE pattern: wildcard all triples on the blank node\n deletePatterns.push(tripleOf(varTerm(bnVar), varTerm(pVar), varTerm(oVar)));\n\n // WHERE: parent --<property>--> ?bnVar\n const traverseTriple = tripleOf(\n varTerm(parentVar),\n resolvePropertyPredicateTerm(prop.id),\n varTerm(bnVar),\n );\n // FILTER(isBlank(?bnVar))\n const isBlankFilter: SparqlExpression = {\n kind: 'function_expr',\n name: 'isBlank',\n args: [{kind: 'variable_expr', name: bnVar}],\n };\n // ?bnVar ?pN ?oN\n const wildcardTriple = tripleOf(varTerm(bnVar), varTerm(pVar), varTerm(oVar));\n\n // Build inner pattern: traverse + filter + wildcard\n let innerPattern: SparqlAlgebraNode = {\n type: 'bgp',\n triples: [traverseTriple, wildcardTriple],\n };\n innerPattern = {type: 'filter', expression: isBlankFilter, inner: innerPattern};\n\n // Recurse into valueShape for nested blank nodes\n if (prop.valueShape?.id) {\n const nestedOptional = walkBlankNodeTree(\n prop.valueShape.id,\n bnVar,\n depth + 1,\n deletePatterns,\n );\n if (nestedOptional) {\n innerPattern = {type: 'left_join', left: innerPattern, right: nestedOptional};\n }\n }\n\n // Wrap in OPTIONAL (left_join)\n if (optionals) {\n optionals = {type: 'left_join', left: optionals, right: innerPattern};\n } else {\n optionals = innerPattern;\n }\n\n depth++;\n }\n\n return optionals;\n}\n\n/**\n * Converts an IRDeleteAllMutation to a SparqlDeleteInsertPlan.\n *\n * Generates DELETE { ?a0 ?p ?o . [blank node wildcards] }\n * WHERE { ?a0 a <Shape> . ?a0 ?p ?o . OPTIONAL { [blank node traversals] } }\n */\nexport function deleteAllToAlgebra(\n query: IRDeleteAllMutation,\n _options?: SparqlOptions,\n): SparqlDeleteInsertPlan {\n const subjectVar = 'a0';\n\n // DELETE patterns: root wildcard\n const deletePatterns: SparqlTriple[] = [\n tripleOf(varTerm(subjectVar), varTerm('p'), varTerm('o')),\n ];\n\n // WHERE: type triple + root wildcard\n const typeTriple = tripleOf(varTerm(subjectVar), iriTerm(RDF_TYPE), iriTerm(resolveShapeScanIri(query.shape)));\n const rootWildcard = tripleOf(varTerm(subjectVar), varTerm('p'), varTerm('o'));\n let whereAlgebra: SparqlAlgebraNode = {type: 'bgp', triples: [typeTriple, rootWildcard]};\n\n // Walk blank node tree for cleanup\n const blankNodeOptional = walkBlankNodeTree(query.shape, subjectVar, 1, deletePatterns);\n if (blankNodeOptional) {\n whereAlgebra = {type: 'left_join', left: whereAlgebra, right: blankNodeOptional};\n }\n\n return {\n type: 'delete_insert',\n deletePatterns,\n insertPatterns: [],\n whereAlgebra,\n };\n}\n\n/**\n * Converts an IRDeleteWhereMutation to a SparqlDeleteInsertPlan.\n *\n * Like deleteAllToAlgebra but adds filter conditions from the where clause.\n */\nexport function deleteWhereToAlgebra(\n query: IRDeleteWhereMutation,\n _options?: SparqlOptions,\n): SparqlDeleteInsertPlan {\n const subjectVar = 'a0';\n const registry = new VariableRegistry();\n\n // DELETE patterns: root wildcard\n const deletePatterns: SparqlTriple[] = [\n tripleOf(varTerm(subjectVar), varTerm('p'), varTerm('o')),\n ];\n\n // WHERE: type triple + root wildcard\n const typeTriple = tripleOf(varTerm(subjectVar), iriTerm(RDF_TYPE), iriTerm(resolveShapeScanIri(query.shape)));\n const rootWildcard = tripleOf(varTerm(subjectVar), varTerm('p'), varTerm('o'));\n let whereAlgebra: SparqlAlgebraNode = {type: 'bgp', triples: [typeTriple, rootWildcard]};\n\n // Process where patterns (traversals from the where clause)\n const traverseTriples: SparqlTriple[] = [];\n const optionalPropertyTriples: SparqlTriple[] = [];\n for (const pattern of query.wherePatterns) {\n processPattern(pattern, registry, traverseTriples, optionalPropertyTriples);\n }\n\n // Add traverse triples to required BGP\n if (traverseTriples.length > 0) {\n whereAlgebra = joinNodes(whereAlgebra, {type: 'bgp', triples: traverseTriples});\n }\n\n // Process expression to discover property triples\n processExpressionForProperties(query.where, registry, optionalPropertyTriples);\n\n // Add optional property triples\n for (const triple of optionalPropertyTriples) {\n whereAlgebra = joinNodes(whereAlgebra, {type: 'bgp', triples: [triple]});\n }\n\n // Convert and add filter expression\n const filterExpr = convertExpression(query.where, registry, []);\n whereAlgebra = {type: 'filter', expression: filterExpr, inner: whereAlgebra};\n\n // Walk blank node tree for cleanup\n const blankNodeOptional = walkBlankNodeTree(query.shape, subjectVar, 1, deletePatterns);\n if (blankNodeOptional) {\n whereAlgebra = {type: 'left_join', left: whereAlgebra, right: blankNodeOptional};\n }\n\n return {\n type: 'delete_insert',\n deletePatterns,\n insertPatterns: [],\n whereAlgebra,\n };\n}\n\n/**\n * Converts an IRUpdateWhereMutation to a SparqlDeleteInsertPlan.\n *\n * Like updateToAlgebra but uses a variable subject (?a0) instead of a\n * hardcoded entity IRI, adds a type triple, and optionally includes\n * filter conditions from the where clause.\n */\nexport function updateWhereToAlgebra(\n query: IRUpdateWhereMutation,\n options?: SparqlOptions,\n): SparqlDeleteInsertPlan {\n const subjectTerm = varTerm('a0');\n const result = processUpdateFields(query.data, subjectTerm, options);\n\n // WHERE: type triple is always required\n const typeTriple = tripleOf(subjectTerm, iriTerm(RDF_TYPE), iriTerm(resolveShapeScanIri(query.data.shape)));\n let whereAlgebra: SparqlAlgebraNode = {type: 'bgp', triples: [typeTriple]};\n\n // Process where filter conditions (if any)\n if (query.where && query.wherePatterns) {\n const registry = new VariableRegistry();\n const traverseTriples: SparqlTriple[] = [];\n const optionalPropertyTriples: SparqlTriple[] = [];\n\n for (const pattern of query.wherePatterns) {\n processPattern(pattern, registry, traverseTriples, optionalPropertyTriples);\n }\n\n if (traverseTriples.length > 0) {\n whereAlgebra = joinNodes(whereAlgebra, {type: 'bgp', triples: traverseTriples});\n }\n\n processExpressionForProperties(query.where, registry, optionalPropertyTriples);\n\n for (const triple of optionalPropertyTriples) {\n whereAlgebra = joinNodes(whereAlgebra, {type: 'bgp', triples: [triple]});\n }\n\n const filterExpr = convertExpression(query.where, registry, []);\n whereAlgebra = {type: 'filter', expression: filterExpr, inner: whereAlgebra};\n }\n\n // Old-value triples anchored on a traversal *target* belong INSIDE that\n // traversal's OPTIONAL group, not beside it. Emitted beside it, the leaf's\n // subject variable is introduced by an OPTIONAL that shares no variable with\n // anything to its left — a left join with no join condition, i.e. a cartesian\n // product over every node in the store carrying that predicate. The following\n // OPTIONAL cannot repair it: the variable is already bound, and OPTIONAL never\n // removes rows. `updateToAlgebra` performs the same split; this path did not.\n const travTos = new Set((query.traversalPatterns ?? []).map((t) => t.to));\n const travAnchoredByTo = new Map<string, SparqlTriple[]>();\n const subjectAnchored: SparqlTriple[] = [];\n for (const triple of result.oldValueTriples) {\n if (triple.subject.kind === 'variable' && travTos.has(triple.subject.name)) {\n const list = travAnchoredByTo.get(triple.subject.name) ?? [];\n list.push(triple);\n travAnchoredByTo.set(triple.subject.name, list);\n } else {\n subjectAnchored.push(triple);\n }\n }\n\n whereAlgebra = wrapOldValueOptionals(whereAlgebra, subjectAnchored);\n\n // Add traversal OPTIONAL patterns (for multi-segment expression refs)\n // These must come BEFORE expression BINDs since the BINDs reference traversal variables.\n if (query.traversalPatterns) {\n for (const trav of query.traversalPatterns) {\n const fromTerm =\n trav.from === '__mutation_subject__' ? varTerm('a0') : varTerm(trav.from);\n const traversalTriple = tripleOf(\n fromTerm,\n // The declared `sh:path`, like every other predicate — not the property\n // shape's own IRI, which identifies the description of the property.\n resolvePropertyPredicateTerm(trav.property),\n varTerm(trav.to),\n );\n // The edge binds the target variable; each dependent leaf property is a\n // nested OPTIONAL within that scope, so a missing leaf does not drop the\n // group while an absent edge leaves every leaf variable unbound.\n let travNode: SparqlAlgebraNode = {type: 'bgp', triples: [traversalTriple]};\n for (const leaf of travAnchoredByTo.get(trav.to) ?? []) {\n travNode = {\n type: 'left_join',\n left: travNode,\n right: {type: 'bgp', triples: [leaf]},\n };\n }\n whereAlgebra = {type: 'left_join', left: whereAlgebra, right: travNode};\n }\n }\n\n // Owned-subtree cascade OPTIONALs for replaced `contains` properties.\n for (const optional of result.cascadeOptionals) {\n whereAlgebra = {type: 'left_join', left: whereAlgebra, right: optional};\n }\n\n // Add BIND expressions for computed fields\n for (const ext of result.extends) {\n whereAlgebra = {\n type: 'extend',\n inner: whereAlgebra,\n variable: ext.variable,\n expression: ext.expression,\n };\n }\n\n return {\n type: 'delete_insert',\n deletePatterns: result.deletePatterns,\n insertPatterns: result.insertPatterns,\n whereAlgebra,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Ask conversion\n// ---------------------------------------------------------------------------\n\n/**\n * Converts an {@link IRAskQuery} to a {@link SparqlAskPlan}.\n *\n * Two cases:\n *\n * - **Rootless** (no shape scan) — a bare subject, emitted as `<iri> ?p ?o`. This\n * is \"does a node with this IRI exist at all\", with no `rdf:type` constraint.\n * - **Shaped** — the pattern is built by {@link selectToAlgebra}, so shape scans,\n * traversals, filters and `MINUS` have exactly one implementation. Only the\n * pattern is kept; the select plan's projection is discarded.\n *\n * `IRAskQuery` has no projection, `orderBy`, `limit` or `offset` to ignore or\n * reject — an `ASK` cannot express them, so the IR cannot carry them. The one\n * thing that *does* need guarding is an aggregate in the where clause, which\n * lowers to `GROUP BY` + `HAVING` rather than to a `FILTER`; see below.\n */\nexport function askToAlgebra(\n query: IRAskQuery,\n options?: SparqlOptions,\n): SparqlAskPlan {\n if (!query.root) {\n if (!query.subjectId) {\n throw new Error(\n 'askToAlgebra: a shapeless ask needs a subject — there is no shape to scan ' +\n 'and no subject to test, so the query matches every node in the store.',\n );\n }\n // ASK { <iri> ?p ?o } — existence of the node itself, under any type or none.\n const bgp: SparqlBGP = {\n type: 'bgp',\n triples: [\n tripleOf(iriTerm(query.subjectId), varTerm('p'), varTerm('o')),\n ],\n };\n return {type: 'ask', algebra: bgp};\n }\n const inner = selectToAlgebra(\n {\n kind: 'select',\n root: query.root,\n patterns: query.patterns,\n projection: [],\n where: query.where,\n subjectId: query.subjectId,\n subjectIds: query.subjectIds,\n },\n options,\n );\n if (inner.having) {\n // Same trap as in `countToAlgebra`: an aggregate in the WHERE clause (e.g.\n // `p.friends.size().gt(2)`) lowers to HAVING + GROUP BY on the select plan, and\n // only `algebra` is carried over here — so the HAVING would vanish and the ASK\n // would answer the UNFILTERED question, `true` for any store holding one\n // instance of the shape. A boolean of the right type for the wrong question is\n // worse than an error: nothing downstream can tell. Asking it properly needs\n // `ASK { SELECT ?a0 WHERE { … } GROUP BY ?a0 HAVING(…) }`, and `SparqlSubSelect`\n // carries no groupBy/having today. Refuse it rather than answer it wrongly.\n throw new Error(\n 'Cannot ask a query whose where clause contains an aggregate (e.g. ' +\n '`.where(p => p.friends.size().gt(2))`). That filter lowers to HAVING over a ' +\n 'per-subject group, and testing whether any group survives needs a nested ' +\n 'sub-SELECT that this layer does not emit yet. Filter without an aggregate, or ' +\n 'run the select and check for rows.',\n );\n }\n return {type: 'ask', algebra: inner.algebra};\n}\n\n/**\n * Converts an {@link IRCountQuery} to a {@link SparqlSelectPlan} shaped as a\n * root-level count:\n *\n * ```sparql\n * SELECT (COUNT(DISTINCT ?a0) AS ?count) WHERE { … }\n * ```\n *\n * The **pattern** is built by {@link selectToAlgebra}, so shape scans, traversals,\n * filters and `MINUS` have exactly one implementation; only the pattern is kept and\n * the select plan's projection is discarded. That discard is load-bearing:\n * `selectToAlgebra` unconditionally projects the root alias as a plain variable, and\n * then makes every plain projected variable a `GROUP BY` target once an aggregate is\n * present — so reusing its projection would yield `SELECT ?a0 (COUNT(…) AS ?count) …\n * GROUP BY ?a0`, one row per entity each counting 1.\n *\n * `DISTINCT` inside the aggregate is likewise load-bearing. A shape scan joined with\n * property triples yields one row per property-value combination (which is why the\n * plain select path emits `SELECT DISTINCT`), so `COUNT(?a0)` would count *rows* and\n * a filter on a multi-valued property would inflate the total. `COUNT(DISTINCT ?a0)`\n * counts subjects, which is what \"how many instances match\" means.\n *\n * There is no `groupBy`, `orderBy`, `limit` or `offset` on the returned plan — and\n * nothing to guard against, because {@link IRCountQuery} cannot carry them.\n */\nexport function countToAlgebra(\n query: IRCountQuery,\n options?: SparqlOptions,\n): SparqlSelectPlan {\n if (!query.root) {\n throw new Error(\n 'countToAlgebra: query.root is undefined. A count needs a shape to scan — a ' +\n 'shapeless count would count every node in the store.',\n );\n }\n const inner = selectToAlgebra(\n {\n kind: 'select',\n root: query.root,\n patterns: query.patterns,\n projection: [],\n where: query.where,\n subjectId: query.subjectId,\n subjectIds: query.subjectIds,\n },\n options,\n );\n if (inner.having) {\n // An aggregate in the WHERE clause (e.g. `p.friends.size().gt(2)`) lowers to\n // HAVING + GROUP BY on the select plan. Only `algebra` is carried over here, so\n // the HAVING would vanish and the count would be of the UNFILTERED match set —\n // a plausible-looking wrong number. Counting a HAVING-filtered group set needs\n // `SELECT (COUNT(DISTINCT ?a0) AS ?count) WHERE { SELECT ?a0 WHERE { … }\n // GROUP BY ?a0 HAVING(…) }`, and `SparqlSubSelect` carries no groupBy/having\n // today. Refuse it rather than answer it wrongly.\n throw new Error(\n 'Cannot count a query whose where clause contains an aggregate (e.g. ' +\n '`.where(p => p.friends.size().gt(2))`). That filter lowers to HAVING over a ' +\n 'per-subject group, and counting the surviving groups needs a nested ' +\n 'sub-SELECT that this layer does not emit yet. Filter without an aggregate, or ' +\n 'count the rows of the select.',\n );\n }\n const aggregate: SparqlAggregateExpr = {\n kind: 'aggregate_expr',\n name: 'count',\n args: [{kind: 'variable_expr', name: query.root.alias}],\n distinct: true,\n };\n return {\n type: 'select',\n algebra: inner.algebra,\n projection: [{kind: 'aggregate', expression: aggregate, alias: query.alias}],\n aggregates: [{variable: query.alias, aggregate}],\n };\n}\n\n// ---------------------------------------------------------------------------\n// Convenience wrappers: IR → algebra → SPARQL string in one call\n// ---------------------------------------------------------------------------\n\n/**\n * Converts an IRSelectQuery to a SPARQL string.\n */\nexport function selectToSparql(\n query: IRSelectQuery,\n options?: SparqlOptions,\n): string {\n const plan = selectToAlgebra(query, options);\n return selectPlanToSparql(plan, options);\n}\n\n/**\n * Converts an {@link IRAskQuery} to a SPARQL `ASK` string.\n */\nexport function askToSparql(\n query: IRAskQuery,\n options?: SparqlOptions,\n): string {\n const plan = askToAlgebra(query, options);\n return askPlanToSparql(plan, options);\n}\n\n/**\n * Converts an {@link IRCountQuery} to a SPARQL `SELECT (COUNT(DISTINCT …) AS …)`\n * string, through the same {@link selectPlanToSparql} every select uses.\n */\nexport function countToSparql(\n query: IRCountQuery,\n options?: SparqlOptions,\n): string {\n const plan = countToAlgebra(query, options);\n return selectPlanToSparql(plan, options);\n}\n\n/**\n * Converts an IRCreateMutation to a SPARQL string.\n * Stub: will be implemented when algebraToString is available.\n */\nexport function createToSparql(\n query: IRCreateMutation,\n options?: SparqlOptions,\n): string {\n const plan = createToAlgebra(query, options);\n return insertDataPlanToSparql(plan, options);\n}\n\n/**\n * Converts an IRUpdateMutation to a SPARQL string.\n * Stub: will be implemented when algebraToString is available.\n */\nexport function updateToSparql(\n query: IRUpdateMutation,\n options?: SparqlOptions,\n): string {\n const plan = updateToAlgebra(query, options);\n return deleteInsertPlanToSparql(plan, options);\n}\n\n/** Lowers an IRUpsertMutation all the way to a SPARQL update string. */\nexport function upsertToSparql(\n query: IRUpsertMutation,\n options?: SparqlOptions,\n): string {\n const plan = upsertToAlgebra(query, options);\n return deleteInsertPlanToSparql(plan, options);\n}\n\n/**\n * Converts an IRDeleteMutation to a SPARQL string.\n */\nexport function deleteToSparql(\n query: IRDeleteMutation,\n options?: SparqlOptions,\n): string {\n const plan = deleteToAlgebra(query, options);\n return deleteInsertPlanToSparql(plan, options);\n}\n\n/**\n * Converts an IRDeleteAllMutation to a SPARQL string.\n */\nexport function deleteAllToSparql(\n query: IRDeleteAllMutation,\n options?: SparqlOptions,\n): string {\n const plan = deleteAllToAlgebra(query, options);\n return deleteInsertPlanToSparql(plan, options);\n}\n\n/**\n * Converts an IRDeleteWhereMutation to a SPARQL string.\n */\nexport function deleteWhereToSparql(\n query: IRDeleteWhereMutation,\n options?: SparqlOptions,\n): string {\n const plan = deleteWhereToAlgebra(query, options);\n return deleteInsertPlanToSparql(plan, options);\n}\n\n/**\n * Converts an IRUpdateWhereMutation to a SPARQL string.\n */\nexport function updateWhereToSparql(\n query: IRUpdateWhereMutation,\n options?: SparqlOptions,\n): string {\n const plan = updateWhereToAlgebra(query, options);\n return deleteInsertPlanToSparql(plan, options);\n}\n"]}
1
+ {"version":3,"file":"irToAlgebra.js","sourceRoot":"","sources":["../../../src/sparql/irToAlgebra.ts"],"names":[],"mappings":"AAkBA,OAAO,EAAC,qBAAqB,EAAE,iBAAiB,EAAC,MAAM,4BAA4B,CAAC;AAEpF,OAAO,EAAC,gBAAgB,EAAE,eAAe,EAAC,MAAM,8BAA8B,CAAC;AAmB/E,OAAO,EAAqB,iBAAiB,EAAC,MAAM,kBAAkB,CAAC;AACvE,OAAO,EACL,kBAAkB,EAClB,eAAe,EACf,sBAAsB,EACtB,wBAAwB,GACzB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAC,GAAG,EAAC,MAAM,sBAAsB,CAAC;AACzC,OAAO,EAAC,KAAK,EAAC,MAAM,wBAAwB,CAAC;AAC7C,OAAO,EAAC,GAAG,EAAC,MAAM,sBAAsB,CAAC;AACzC,OAAO,EAAC,eAAe,EAAC,MAAM,mCAAmC,CAAC;AAClE,OAAO,EACL,gBAAgB,EAChB,YAAY,EACZ,kBAAkB,EAClB,aAAa,EACb,gBAAgB,GACjB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAC,sBAAsB,EAAC,MAAM,4BAA4B,CAAC;AAElE,8EAA8E;AAC9E,YAAY;AACZ,8EAA8E;AAE9E,MAAM,QAAQ,GAAG,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;AAC7B,MAAM,YAAY,GAAG,GAAG,CAAC,QAAQ,CAAC,EAAE,CA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,wBAAwB,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;AACjD,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,mBAAmB,CACjC,KAA4B,EAC5B,OAAuB;IAEvB,MAAM,IAAI,GAAG,oBAAoB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IAClD,OAAO,wBAAwB,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;AACjD,CAAC","sourcesContent":["import type {\n IRSelectQuery,\n IRAskQuery,\n IRCountQuery,\n IRCreateMutation,\n IRUpdateMutation,\n IRUpsertMutation,\n IRDeleteMutation,\n IRDeleteAllMutation,\n IRDeleteWhereMutation,\n IRUpdateWhereMutation,\n IRGraphPattern,\n IRExpression,\n IRFieldValue,\n IRNodeData,\n IRSetModificationValue,\n IRTraversePattern,\n} from '../queries/IntermediateRepresentation.js';\nimport {findPropertyShapeById, getPropertyShapes} from '../shapes/nodeShapeData.js';\nimport type {NodeReferenceValue} from '../utils/NodeReference.js';\nimport {pathExprToSparql, collectPathUris} from '../paths/pathExprToSparql.js';\nimport type {PathExpr} from '../paths/PropertyPathExpr.js';\nimport type {\n SparqlSelectPlan,\n SparqlAskPlan,\n SparqlInsertDataPlan,\n SparqlDeleteInsertPlan,\n SparqlAlgebraNode,\n SparqlBGP,\n SparqlTriple,\n SparqlTerm,\n SparqlExpression,\n SparqlProjectionItem,\n SparqlOrderCondition,\n SparqlAggregateBinding,\n SparqlAggregateExpr,\n SparqlLeftJoin,\n SparqlFilter,\n} from './SparqlAlgebra.js';\nimport {type SparqlOptions, generateEntityUri} from './sparqlUtils.js';\nimport {\n selectPlanToSparql,\n askPlanToSparql,\n insertDataPlanToSparql,\n deleteInsertPlanToSparql,\n} from './algebraToString.js';\nimport {rdf} from '../ontologies/rdf.js';\nimport {shacl} from '../ontologies/shacl.js';\nimport {xsd} from '../ontologies/xsd.js';\nimport {getSimplePathId} from '../paths/normalizePropertyPath.js';\nimport {\n getAllNodeShapes,\n getNodeShape,\n getRegistryVersion,\n getShapeClass,\n getTargetClassId,\n} from '../utils/ShapeClass.js';\nimport {UnresolvedContextError} from '../queries/QueryContext.js';\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst RDF_TYPE = rdf.type.id;\nconst XSD_DATETIME = xsd.dateTime.id;\nconst XSD_DATE = xsd.date.id;\nconst XSD_TIME = xsd.time.id;\nconst XSD_BOOLEAN = xsd.boolean.id;\nconst XSD_INTEGER = xsd.integer.id;\nconst XSD_DOUBLE = xsd.double.id;\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction iriTerm(value: string): SparqlTerm {\n return {kind: 'iri', value};\n}\n\nfunction varTerm(name: string): SparqlTerm {\n return {kind: 'variable', name};\n}\n\nfunction literalTerm(value: string, datatype?: string): SparqlTerm {\n if (datatype) {\n return {kind: 'literal', value, datatype};\n }\n return {kind: 'literal', value};\n}\n\nfunction tripleOf(\n subject: SparqlTerm,\n predicate: SparqlTerm,\n object: SparqlTerm,\n): SparqlTriple {\n return {subject, predicate, object};\n}\n\n/**\n * Resolve the shape a query scans to the IRI written and matched as its `rdf:type`.\n *\n * That IRI is the shape's declared `targetClass` — a node in its own right, which in\n * a real dataset carries `rdf:type rdfs:Class`. `targetClass` is read off the shape\n * *class*, so JavaScript static inheritance already walks the superclass chain: a\n * subclass that declares none inherits its parent's.\n *\n * A temporary (`linked://tmp/`) targetClass is honoured like any other. It is a real,\n * separate node — just one whose IRI has not been finalised — and it round-trips\n * consistently through both the scan and the create side.\n *\n * **A shape with no targetClass anywhere in its chain throws.** It used to fall back\n * to the shape's *own* IRI, which typed instances as the shape that describes them —\n * conflating a class with its description, and silently disagreeing with the declared\n * `targetClass` whenever that was still temporary.\n */\nfunction resolveShapeScanIri(shapeId: string): string {\n // `getTargetClassId` reads the METAMODEL registry as well as the class registry, and\n // walks `extends` for a data-only shape — reading only `getShapeClass(...)` here made\n // `SelectBuilder.from(dataOnlyIri)` resolve, build an IR, and then die at this line.\n const targetClassId = getTargetClassId(shapeId);\n if (!targetClassId) {\n throw new Error(\n `Cannot resolve an rdf:type for shape \"${shapeId}\": no targetClass is declared ` +\n 'on it or on any shape it extends. Declare one — `static targetClass = ' +\n \"{id: 'https://example.org/Person'}` — pointing at the class node instances are \" +\n 'typed with. The shape\\'s own IRI is not a substitute: it identifies the ' +\n 'description, not the class being described.',\n );\n }\n return targetClassId;\n}\n\n/**\n * Resolve a SHACL property-shape id to the predicate term used in a triple.\n *\n * - Simple single-IRI path → `{kind:'iri'}` (byte-for-byte unchanged behaviour).\n * - Structured path (sequence / inverse / alternative / …) → `{kind:'path'}` built from the property\n * shape's `sh:path`, reusing the same `pathExprToSparql` / `collectPathUris` machinery as the\n * inline-`pathExpr` branches. Without this, structured named-property paths collapsed to a shadow IRI\n * that matched nothing.\n * - No matching property shape at all → `{kind:'iri'}` of the id as given (nothing\n * better is knowable; the caller passed an id no registered shape declares).\n */\n// Memoizes resolved predicate terms across the many call sites that resolve the\n// same property. Guarded by the shape-registry size so it self-invalidates when\n// new shapes register (e.g. across test-file module instances). Only successful\n// resolutions are cached — a not-found fallback is never stored, so a predicate\n// resolved before its shape registers can still resolve correctly afterwards.\nconst predicateTermCache = new Map<string, SparqlTerm>();\nlet predicateTermCacheSize = -1;\n\n/**\n * The `sh:datatype` declared for a property, if any. Lets the serializer emit the\n * term the shape asks for rather than one inferred from the JavaScript value: a\n * numeric property gets the numeric type it declares, and an `xsd:date` /\n * `xsd:time` property its own lexical form instead of a full timestamp.\n */\nfunction resolvePropertyDatatype(propertyId: string): string | undefined {\n return findPropertyShapeById(propertyId)?.datatype?.id;\n}\n\nfunction resolvePropertyPredicateTerm(propertyId: string): SparqlTerm {\n const version = getRegistryVersion();\n if (version !== predicateTermCacheSize) {\n predicateTermCache.clear();\n predicateTermCacheSize = version;\n }\n const cached = predicateTermCache.get(propertyId);\n if (cached) return cached;\n\n const propertyShape = findPropertyShapeById(propertyId);\n if (propertyShape) {\n const simplePathId = getSimplePathId(propertyShape.path);\n let term: SparqlTerm;\n if (simplePathId !== null) {\n // Simple single-IRI path: the declared `sh:path` IS the predicate. There is\n // no fallback to the property shape's own IRI — that identifies the\n // *description* of the property, not the property itself.\n term = iriTerm(simplePathId);\n } else {\n // Structured sh:path — emit a property-path predicate instead of a shadow IRI.\n term = {\n kind: 'path',\n value: pathExprToSparql(propertyShape.path),\n uris: collectPathUris(propertyShape.path),\n };\n }\n predicateTermCache.set(propertyId, term);\n return term;\n }\n return iriTerm(propertyId);\n}\n\n/**\n * Resolve the predicate term for a traversal/property node: a structured\n * property-path when an explicit `pathExpr` is present, otherwise the\n * registry-resolved predicate for `property`. Centralizes the invariant that\n * these two branches stay in lockstep across every triple-building site.\n */\nfunction buildPredicateTerm(spec: {pathExpr?: PathExpr; property: string}): SparqlTerm {\n return spec.pathExpr\n ? {\n kind: 'path',\n value: pathExprToSparql(spec.pathExpr),\n uris: collectPathUris(spec.pathExpr),\n }\n : resolvePropertyPredicateTerm(spec.property);\n}\n\n/** Produce variable name suffix from the last segment of a property URI. */\nfunction propertySuffix(propertyUri: string): string {\n const hashIdx = propertyUri.lastIndexOf('#');\n if (hashIdx >= 0) return propertyUri.substring(hashIdx + 1);\n const slashIdx = propertyUri.lastIndexOf('/');\n return slashIdx >= 0 ? propertyUri.substring(slashIdx + 1) : propertyUri;\n}\n\n/**\n * Sanitize a string so it's valid in a SPARQL variable name.\n * Replaces any non-alphanumeric/underscore characters with underscores.\n */\nfunction sanitizeVarName(name: string): string {\n return name.replace(/[^A-Za-z0-9_]/g, '_');\n}\n\nconst IR_EXPRESSION_KINDS = new Set([\n 'literal_expr', 'property_expr', 'binary_expr', 'logical_expr',\n 'not_expr', 'function_expr', 'aggregate_expr', 'reference_expr',\n 'alias_expr', 'context_property_expr', 'exists_expr', 'in_expr',\n]);\n\nfunction isIRExpression(value: unknown): value is IRExpression {\n return !!value && typeof value === 'object' && 'kind' in value &&\n typeof (value as {kind: unknown}).kind === 'string' &&\n IR_EXPRESSION_KINDS.has((value as {kind: string}).kind);\n}\n\n/**\n * Wrap a single node in a LeftJoin, making `right` optional relative to `left`.\n */\nfunction wrapOptional(\n left: SparqlAlgebraNode,\n right: SparqlAlgebraNode,\n): SparqlLeftJoin {\n return {type: 'left_join', left, right};\n}\n\n/**\n * Join two algebra nodes. If left is null, returns right.\n */\nfunction joinNodes(\n left: SparqlAlgebraNode | null,\n right: SparqlAlgebraNode,\n): SparqlAlgebraNode {\n if (!left) return right;\n return {type: 'join', left, right};\n}\n\nfunction bindingKey(alias: string, property: string): string {\n return `${alias}::${property}`;\n}\n\nfunction contextAliasKey(contextIri: string): string {\n return `__ctx__${contextIri}`;\n}\n\n/**\n * Defense-in-depth: a `reference_expr`/`context_property_expr` must arrive here with its\n * IRI already resolved (lowering's `resolveContextRefs` fills it from `contextName`). If it\n * didn't — an unresolved `{@ctx}` reaching the algebra through some path that bypassed\n * resolution — fail with a clear `UnresolvedContextError` instead of an opaque\n * `undefined.substring` crash deeper in URI formatting.\n */\nfunction resolvedContextIri(iri: string | undefined, contextName?: string): string {\n if (iri === undefined) {\n throw new UnresolvedContextError(contextName ?? '<unknown>');\n }\n return iri;\n}\n\nfunction mergeKeySets(...sets: ReadonlySet<string>[]): Set<string> {\n const merged = new Set<string>();\n for (const set of sets) {\n for (const key of set) {\n merged.add(key);\n }\n }\n return merged;\n}\n\nfunction intersectKeySets(sets: ReadonlySet<string>[]): Set<string> {\n if (sets.length === 0) {\n return new Set<string>();\n }\n\n const [first, ...rest] = sets;\n const intersection = new Set(first);\n for (const value of intersection) {\n if (!rest.every((set) => set.has(value))) {\n intersection.delete(value);\n }\n }\n return intersection;\n}\n\n// ---------------------------------------------------------------------------\n// Pattern helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Recursively collects all traversal alias target variables from IR patterns.\n * Used to ensure traversal aliases appear in the SELECT projection for result grouping.\n */\nfunction collectTraversalAliases(patterns: IRGraphPattern[]): string[] {\n const aliases: string[] = [];\n for (const p of patterns) {\n if (p.kind === 'traverse') {\n aliases.push(p.to);\n } else if (p.kind === 'join') {\n aliases.push(...collectTraversalAliases(p.patterns));\n } else if (p.kind === 'optional') {\n aliases.push(...collectTraversalAliases([p.pattern]));\n } else if (p.kind === 'union') {\n for (const branch of p.branches) {\n aliases.push(...collectTraversalAliases([branch]));\n }\n }\n }\n return aliases;\n}\n\nfunction buildTraverseTriple(pattern: IRTraversePattern): SparqlTriple {\n const predicate = buildPredicateTerm(pattern);\n return tripleOf(\n varTerm(pattern.from),\n predicate,\n varTerm(pattern.to),\n );\n}\n\nfunction collectTraversePatternsInOrder(\n patterns: IRGraphPattern[],\n out: IRTraversePattern[] = [],\n): IRTraversePattern[] {\n for (const pattern of patterns) {\n switch (pattern.kind) {\n case 'traverse':\n out.push(pattern);\n break;\n case 'join':\n collectTraversePatternsInOrder(pattern.patterns, out);\n break;\n case 'optional':\n case 'exists':\n collectTraversePatternsInOrder([pattern.pattern], out);\n break;\n case 'union':\n for (const branch of pattern.branches) {\n collectTraversePatternsInOrder([branch], out);\n }\n break;\n case 'shape_scan':\n case 'minus':\n break;\n }\n }\n return out;\n}\n\nfunction collectDirectProjectionAliases(\n query: IRSelectQuery,\n rootAlias: string,\n): Set<string> {\n const aliases = new Set<string>();\n for (const item of query.projection) {\n if (item.expression.kind === 'property_expr') {\n if (item.expression.sourceAlias !== rootAlias) {\n aliases.add(item.expression.sourceAlias);\n }\n } else if (item.expression.kind === 'alias_expr') {\n if (item.expression.alias !== rootAlias) {\n aliases.add(item.expression.alias);\n }\n }\n }\n return aliases;\n}\n\nfunction collectExpressionAliases(\n expr: IRExpression,\n aliases: Set<string>,\n): void {\n switch (expr.kind) {\n case 'property_expr':\n aliases.add(expr.sourceAlias);\n break;\n case 'alias_expr':\n aliases.add(expr.alias);\n break;\n case 'binary_expr':\n collectExpressionAliases(expr.left, aliases);\n collectExpressionAliases(expr.right, aliases);\n break;\n case 'in_expr':\n collectExpressionAliases(expr.value, aliases);\n for (const el of expr.source.list) collectExpressionAliases(el, aliases);\n break;\n case 'logical_expr':\n for (const sub of expr.expressions) {\n collectExpressionAliases(sub, aliases);\n }\n break;\n case 'not_expr':\n collectExpressionAliases(expr.expression, aliases);\n break;\n case 'function_expr':\n case 'aggregate_expr':\n for (const arg of expr.args) {\n collectExpressionAliases(arg, aliases);\n }\n break;\n case 'exists_expr':\n if (expr.filter) {\n collectExpressionAliases(expr.filter, aliases);\n }\n break;\n case 'literal_expr':\n case 'reference_expr':\n case 'context_property_expr':\n break;\n }\n}\n\nfunction markAliasAndAncestors(\n alias: string,\n traversePatternMap: ReadonlyMap<string, IRTraversePattern>,\n target: Set<string>,\n): void {\n let currentAlias: string | undefined = alias;\n while (currentAlias && traversePatternMap.has(currentAlias)) {\n if (target.has(currentAlias)) {\n return;\n }\n target.add(currentAlias);\n currentAlias = traversePatternMap.get(currentAlias)?.from;\n }\n}\n\nfunction collectRequiredTraversalAliases(\n query: IRSelectQuery,\n traversePatternMap: ReadonlyMap<string, IRTraversePattern>,\n): Set<string> {\n const directAliases = new Set<string>();\n\n if (query.where) {\n collectExpressionAliases(query.where, directAliases);\n }\n\n if (query.orderBy) {\n for (const item of query.orderBy) {\n collectExpressionAliases(item.expression, directAliases);\n }\n }\n\n for (const pattern of traversePatternMap.values()) {\n if (pattern.filter) {\n directAliases.add(pattern.to);\n }\n }\n\n const requiredAliases = new Set<string>();\n for (const alias of directAliases) {\n markAliasAndAncestors(alias, traversePatternMap, requiredAliases);\n }\n return requiredAliases;\n}\n\nfunction buildOptionalTraversalSubtree(\n alias: string,\n traversePatternMap: ReadonlyMap<string, IRTraversePattern>,\n childOptionalAliasesByParent: ReadonlyMap<string, string[]>,\n propertyTriplesByAlias: ReadonlyMap<string, SparqlTriple[]>,\n): SparqlAlgebraNode {\n const pattern = traversePatternMap.get(alias);\n if (!pattern) {\n throw new Error(`Missing traverse pattern for alias \"${alias}\"`);\n }\n\n let subtree: SparqlAlgebraNode = {\n type: 'bgp',\n triples: [buildTraverseTriple(pattern)],\n };\n\n for (const propTriple of propertyTriplesByAlias.get(alias) ?? []) {\n subtree = wrapOptional(subtree, {\n type: 'bgp',\n triples: [propTriple],\n });\n }\n\n for (const childAlias of childOptionalAliasesByParent.get(alias) ?? []) {\n subtree = wrapOptional(\n subtree,\n buildOptionalTraversalSubtree(\n childAlias,\n traversePatternMap,\n childOptionalAliasesByParent,\n propertyTriplesByAlias,\n ),\n );\n }\n\n return subtree;\n}\n\n// ---------------------------------------------------------------------------\n// Variable Registry\n// ---------------------------------------------------------------------------\n\n/**\n * Maps (alias, property) → SPARQL variable name.\n * Used to deduplicate variables across traverse and property_expr nodes.\n */\nclass VariableRegistry {\n private map = new Map<string, string>();\n private usedVarNames = new Set<string>();\n\n private key(alias: string, property: string): string {\n return bindingKey(alias, property);\n }\n\n has(alias: string, property: string): boolean {\n return this.map.has(this.key(alias, property));\n }\n\n get(alias: string, property: string): string | undefined {\n return this.map.get(this.key(alias, property));\n }\n\n set(alias: string, property: string, variable: string): void {\n this.map.set(this.key(alias, property), variable);\n this.usedVarNames.add(variable);\n }\n\n getOrCreate(alias: string, property: string): string {\n const existing = this.get(alias, property);\n if (existing) return existing;\n const suffix = propertySuffix(property);\n let varName = `${sanitizeVarName(alias)}_${suffix}`;\n // Deduplicate: if varName is already used by a different (alias, property),\n // append a counter to ensure unique SPARQL variable names\n let counter = 2;\n while (this.usedVarNames.has(varName)) {\n varName = `${sanitizeVarName(alias)}_${suffix}_${counter}`;\n counter++;\n }\n this.set(alias, property, varName);\n return varName;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Aggregate detection\n// ---------------------------------------------------------------------------\n\n/**\n * Checks whether a SparqlExpression tree contains an aggregate sub-expression.\n * Used to route aggregate-containing filters to HAVING instead of FILTER.\n */\nfunction containsAggregate(expr: SparqlExpression): boolean {\n switch (expr.kind) {\n case 'aggregate_expr':\n return true;\n case 'in_expr':\n return containsAggregate(expr.value) || expr.list.some(containsAggregate);\n case 'binary_expr':\n return containsAggregate(expr.left) || containsAggregate(expr.right);\n case 'logical_expr':\n return expr.exprs.some(containsAggregate);\n case 'not_expr':\n return containsAggregate(expr.inner);\n case 'function_expr':\n return expr.args.some(containsAggregate);\n default:\n return false;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Select conversion\n// ---------------------------------------------------------------------------\n\n/**\n * Converts an IRSelectQuery to a SparqlSelectPlan.\n */\nexport function selectToAlgebra(\n query: IRSelectQuery,\n _options?: SparqlOptions,\n): SparqlSelectPlan {\n const registry = new VariableRegistry();\n\n // Promote bindings only when the top-level WHERE would reject rows without\n // them. This keeps human-like SPARQL for null-rejecting filters without\n // over-constraining OR cases that can still match through other branches.\n const requiredPropertyKeys = query.where\n ? collectRequiredBindingKeys(query.where)\n : new Set<string>();\n\n const requiredPropertyTriples: SparqlTriple[] = [];\n // Track property triples that need to be added as OPTIONAL\n const optionalPropertyTriples: SparqlTriple[] = [];\n\n // Track filtered traversals (inline where) — these get their own OPTIONAL blocks\n const filteredTraverseBlocks: Array<{\n traverseTriple: SparqlTriple;\n filter: IRExpression;\n toAlias: string;\n }> = [];\n\n // 1. Root shape scan → BGP with type triple\n if (!query?.root) {\n throw new Error(\n 'selectToAlgebra: query.root is undefined. The query IR is missing its root shape scan. ' +\n 'This usually means the query was built with a null/undefined subject (e.g. getQueryContext returned null).',\n );\n }\n const rootAlias = query.root.alias;\n const shapeUri = query.root.shape;\n const typeTriple = tripleOf(\n varTerm(rootAlias),\n iriTerm(RDF_TYPE),\n iriTerm(resolveShapeScanIri(shapeUri)),\n );\n const requiredTriples: SparqlTriple[] = [typeTriple];\n\n // Track traverse triples (required pattern)\n const traverseTriples: SparqlTriple[] = [];\n const traversePatternsInOrder = collectTraversePatternsInOrder(query.patterns);\n const traversePatternMap = new Map(\n traversePatternsInOrder.map((pattern) => [pattern.to, pattern] as const),\n );\n\n // ── Nested-select inner LIMIT/OFFSET (Option A: single-subject only) ──────\n // A nested select on a related collection may carry an inner LIMIT/OFFSET.\n // A plain SPARQL sub-SELECT is uncorrelated, so its LIMIT bounds GLOBALLY.\n // That only equals per-parent windowing when the outer query targets exactly\n // ONE root subject — then we inline that subject into the sub-SELECT.\n const paginatedTraversePatterns = traversePatternsInOrder.filter(\n (p) =>\n typeof p.innerLimit === 'number' ||\n typeof p.innerOffset === 'number' ||\n (p.innerOrderBy && p.innerOrderBy.length > 0),\n );\n const singleSubjectIri: string | undefined =\n query.subjectId ??\n (query.subjectIds && query.subjectIds.length === 1\n ? query.subjectIds[0]\n : undefined);\n if (paginatedTraversePatterns.length > 0 && !singleSubjectIri) {\n throw new Error(\n 'Inner LIMIT/OFFSET on a nested select is only supported when the outer ' +\n 'query targets a single subject; multi-parent per-group pagination is not ' +\n 'yet implemented.',\n );\n }\n // Only root→child traversals can be inlined against the single subject.\n // A paginated traversal deeper than root→child has a parent collection that is\n // itself multi-valued (effectively multi-parent), so a sub-SELECT LIMIT there\n // would bound globally, not per-parent. Reject it loudly rather than silently\n // dropping the inner limit.\n const deepPaginated = paginatedTraversePatterns.filter((p) => p.from !== rootAlias);\n if (deepPaginated.length > 0) {\n throw new Error(\n 'Inner LIMIT/OFFSET on a nested select is only supported on a direct nested ' +\n 'select of the single root subject; pagination on a deeper (grandchild) ' +\n 'collection is multi-parent and not yet implemented.',\n );\n }\n const subSelectAliases = new Set<string>(\n paginatedTraversePatterns.map((p) => p.to),\n );\n\n // 2. Process patterns → traverse triples, populate variable registry.\n // Skip sub-SELECT-wrapped traversals here — they are emitted separately\n // (their child variable is still registered so projection/optionals work).\n for (const pattern of query.patterns) {\n processPattern(\n pattern,\n registry,\n traverseTriples,\n optionalPropertyTriples,\n filteredTraverseBlocks,\n subSelectAliases,\n );\n }\n\n // 3. Pre-register filter property references BEFORE processing projections.\n // This ensures that property triples needed by inline where filters are\n // co-located inside the filtered OPTIONAL block, not in separate OPTIONALs.\n const filterPropertyTriplesMap = new Map<number, SparqlTriple[]>();\n filteredTraverseBlocks.forEach((block, idx) => {\n const filterPropertyTriples: SparqlTriple[] = [];\n processExpressionForProperties(block.filter, registry, filterPropertyTriples);\n filterPropertyTriplesMap.set(idx, filterPropertyTriples);\n });\n\n // 4. Process projection expressions, where clause, orderBy expressions\n // to discover any additional property_expr references.\n // Properties already registered by inline filters (above) will be skipped.\n for (const item of query.projection) {\n processExpressionForProperties(\n item.expression,\n registry,\n optionalPropertyTriples,\n requiredPropertyTriples,\n requiredPropertyKeys,\n );\n }\n\n if (query.where) {\n processExpressionForProperties(\n query.where,\n registry,\n optionalPropertyTriples,\n requiredPropertyTriples,\n requiredPropertyKeys,\n );\n }\n\n if (query.orderBy) {\n for (const orderItem of query.orderBy) {\n processExpressionForProperties(\n orderItem.expression,\n registry,\n optionalPropertyTriples,\n requiredPropertyTriples,\n requiredPropertyKeys,\n );\n }\n }\n\n const projectedTraversalAliases = new Set<string>();\n const directProjectionAliases = collectDirectProjectionAliases(query, rootAlias);\n for (const alias of directProjectionAliases) {\n markAliasAndAncestors(alias, traversePatternMap, projectedTraversalAliases);\n }\n\n const requiredTraversalAliases = collectRequiredTraversalAliases(\n query,\n traversePatternMap,\n );\n\n const optionalTraversalAliases = new Set(\n [...projectedTraversalAliases].filter((alias) => {\n const pattern = traversePatternMap.get(alias);\n // Lower projection-only traversals into OPTIONAL subtrees regardless of\n // cardinality, so a parent with an empty relationship is preserved (with\n // an empty array / null child) instead of being inner-joined away. The\n // result grouper already collects multiple child bindings into an array.\n //\n // Excluded:\n // - filtered traversals (`.where(...)`) — the filter makes the child required\n // - aliases otherwise required by the query (e.g. used in a top-level filter)\n // - paginated traversals — emitted separately as a sub-SELECT (section 5a),\n // so lowering them here too would double-emit the traverse triple\n return !!pattern &&\n !pattern.filter &&\n !subSelectAliases.has(alias) &&\n !requiredTraversalAliases.has(alias);\n }),\n );\n\n const requiredTraverseTriples = traverseTriples.filter((triple) =>\n !(triple.object.kind === 'variable' &&\n optionalTraversalAliases.has(triple.object.name))\n );\n\n const nestedOptionalPropertyTriplesByAlias = new Map<string, SparqlTriple[]>();\n const topLevelOptionalPropertyTriples: SparqlTriple[] = [];\n // Property triples whose subject is a sub-SELECT child alias must be nested\n // INSIDE the sub-SELECT's OPTIONAL block (keyed by alias), so that ?childVar\n // stays scoped — otherwise an empty window leaves ?childVar unbound and the\n // outer property OPTIONAL leaks across the whole graph.\n const subSelectChildPropertyTriplesByAlias = new Map<string, SparqlTriple[]>();\n // Same scoping rule for filtered traversals (`.where(...)`): anything anchored\n // on the filtered alias must live inside its filtered OPTIONAL block — when\n // the filter matches nothing, the alias is unbound and a top-level OPTIONAL\n // would range over the whole graph.\n const filteredTraverseAliases = new Set(filteredTraverseBlocks.map((b) => b.toAlias));\n const filteredChildPropertyTriplesByAlias = new Map<string, SparqlTriple[]>();\n for (const propTriple of optionalPropertyTriples) {\n if (propTriple.subject.kind === 'variable' &&\n subSelectAliases.has(propTriple.subject.name)) {\n const triples = subSelectChildPropertyTriplesByAlias.get(propTriple.subject.name) ?? [];\n triples.push(propTriple);\n subSelectChildPropertyTriplesByAlias.set(propTriple.subject.name, triples);\n } else if (propTriple.subject.kind === 'variable' &&\n filteredTraverseAliases.has(propTriple.subject.name)) {\n const triples = filteredChildPropertyTriplesByAlias.get(propTriple.subject.name) ?? [];\n triples.push(propTriple);\n filteredChildPropertyTriplesByAlias.set(propTriple.subject.name, triples);\n } else if (propTriple.subject.kind === 'variable' &&\n optionalTraversalAliases.has(propTriple.subject.name)) {\n const triples = nestedOptionalPropertyTriplesByAlias.get(propTriple.subject.name) ?? [];\n triples.push(propTriple);\n nestedOptionalPropertyTriplesByAlias.set(propTriple.subject.name, triples);\n } else {\n topLevelOptionalPropertyTriples.push(propTriple);\n }\n }\n\n const childOptionalAliasesByParent = new Map<string, string[]>();\n for (const pattern of traversePatternsInOrder) {\n if (!optionalTraversalAliases.has(pattern.to)) continue;\n const siblings = childOptionalAliasesByParent.get(pattern.from) ?? [];\n siblings.push(pattern.to);\n childOptionalAliasesByParent.set(pattern.from, siblings);\n }\n\n const rootOptionalTraversalAliases = traversePatternsInOrder\n .filter((pattern) =>\n optionalTraversalAliases.has(pattern.to) &&\n !optionalTraversalAliases.has(pattern.from) &&\n // Children of a filtered traversal nest inside its filtered block (5b)\n !filteredTraverseAliases.has(pattern.from),\n )\n .map((pattern) => pattern.to);\n\n // 5. Build the algebra tree\n // - Start with the required BGP (type triple + traverse triples)\n // - Wrap each optional property triple in a LeftJoin\n const requiredBgp: SparqlBGP = {\n type: 'bgp',\n triples: [...requiredTriples, ...requiredTraverseTriples, ...requiredPropertyTriples],\n };\n\n let algebra: SparqlAlgebraNode = requiredBgp;\n\n // 5a. Nested-select inner LIMIT/OFFSET → sub-SELECT (single-subject only).\n // Wrap each root→child paginated traversal in a sub-SELECT that inlines\n // the single subject, projecting only the child variable. The child's own\n // property triples stay OUTSIDE (as OPTIONALs), joined on the child var —\n // so the flat-row structure and result mapping are unchanged.\n // Every pattern here is a root→child paginated traversal (the deep-pagination\n // guard above rejected anything else), so each maps 1:1 to a sub-SELECT.\n for (const pattern of paginatedTraversePatterns) {\n const predicate = buildPredicateTerm(pattern);\n const innerTriple = tripleOf(\n iriTerm(singleSubjectIri!),\n predicate,\n varTerm(pattern.to),\n );\n // Default ORDER BY ?childVar for a deterministic window, unless the nested\n // select supplied its own ordering. When it did, each ordered property must\n // also be bound inside the sub-SELECT so the ORDER BY variable resolves.\n let orderBy: SparqlOrderCondition[];\n let innerNode: SparqlAlgebraNode = {type: 'bgp', triples: [innerTriple]};\n if (pattern.innerOrderBy && pattern.innerOrderBy.length > 0) {\n orderBy = pattern.innerOrderBy.map((o) => {\n const orderVar = registry.getOrCreate(pattern.to, o.property);\n innerNode = joinNodes(innerNode, {\n type: 'bgp',\n triples: [tripleOf(varTerm(pattern.to), resolvePropertyPredicateTerm(o.property), varTerm(orderVar))],\n });\n return {\n expression: {kind: 'variable_expr' as const, name: orderVar},\n direction: o.direction,\n };\n });\n } else {\n orderBy = [{\n expression: {kind: 'variable_expr', name: pattern.to},\n direction: 'ASC',\n }];\n }\n const subSelect: SparqlAlgebraNode = {\n type: 'subselect',\n projection: [pattern.to],\n inner: innerNode,\n orderBy,\n ...(typeof pattern.innerLimit === 'number' ? {limit: pattern.innerLimit} : {}),\n ...(typeof pattern.innerOffset === 'number' ? {offset: pattern.innerOffset} : {}),\n };\n // Nest the child's own property triples (e.g. ?a1 <name> ?a1_name) INSIDE\n // this block, each as its own OPTIONAL, so they only bind when the window\n // produced a ?childVar. This keeps the flat-row projection unchanged.\n let childBlock: SparqlAlgebraNode = subSelect;\n for (const propTriple of subSelectChildPropertyTriplesByAlias.get(pattern.to) ?? []) {\n childBlock = wrapOptional(childBlock, {type: 'bgp', triples: [propTriple]});\n }\n // OPTIONAL so a parent with an empty (or fully-windowed-out) child set is\n // still returned — the sub-SELECT yields no ?a1 binding, but the parent row\n // survives (mirrors the plain nested-traverse OPTIONAL behaviour).\n algebra = wrapOptional(algebra, childBlock);\n }\n\n // 5b. Build filtered OPTIONAL blocks for inline where traversals.\n // Each block contains: traverse triple + OPTIONAL property triples + FILTER.\n // Filter property triples are nested as OPTIONALs so that OR filters work\n // even when some entities lack certain properties.\n // First pass: build each filtered block's inner group and filter expression.\n const filteredBlockInners: SparqlAlgebraNode[] = [];\n const filteredBlockExprs: SparqlExpression[] = [];\n const filteredBlockIdxByAlias = new Map<string, number>(\n filteredTraverseBlocks.map((block, i) => [block.toAlias, i]),\n );\n for (let i = 0; i < filteredTraverseBlocks.length; i++) {\n const block = filteredTraverseBlocks[i];\n const filterPropertyTriples = filterPropertyTriplesMap.get(i) || [];\n const filterExpr = convertExpression(block.filter, registry, filterPropertyTriples);\n // Start with the traverse triple as the required BGP\n let blockInner: SparqlAlgebraNode = {type: 'bgp', triples: [block.traverseTriple]};\n // Wrap each filter property triple in its own nested OPTIONAL\n for (const propTriple of filterPropertyTriples) {\n blockInner = wrapOptional(blockInner, {type: 'bgp', triples: [propTriple]});\n }\n // Projected property triples on the filtered alias that aren't part of the\n // filter (e.g. `.where(name=...).select(pp => [pp.hobby])`)\n for (const propTriple of filteredChildPropertyTriplesByAlias.get(block.toAlias) ?? []) {\n blockInner = wrapOptional(blockInner, {type: 'bgp', triples: [propTriple]});\n }\n // Optional child traversal subtrees (nested sub-selects below the filtered\n // alias) — kept inside the block so an empty filter match leaves them unbound\n for (const childAlias of childOptionalAliasesByParent.get(block.toAlias) ?? []) {\n blockInner = wrapOptional(\n blockInner,\n buildOptionalTraversalSubtree(\n childAlias,\n traversePatternMap,\n childOptionalAliasesByParent,\n nestedOptionalPropertyTriplesByAlias,\n ),\n );\n }\n filteredBlockInners.push(blockInner);\n filteredBlockExprs.push(filterExpr);\n }\n // Second pass, children first (blocks are created parent-before-child):\n // finish each block and either nest it inside its parent's filtered block —\n // a filtered sub-select inside another filtered sub-select must stay scoped\n // to the parent alias, or an empty parent match leaves the alias unbound and\n // the block cross-products over the whole graph — or attach it at top level.\n const rootFilteredBlocks: SparqlAlgebraNode[] = [];\n for (let i = filteredTraverseBlocks.length - 1; i >= 0; i--) {\n const block = filteredTraverseBlocks[i];\n const finished: SparqlFilter = {\n type: 'filter',\n expression: filteredBlockExprs[i],\n inner: filteredBlockInners[i],\n };\n const subject = block.traverseTriple.subject;\n const parentIdx = subject.kind === 'variable'\n ? filteredBlockIdxByAlias.get(subject.name)\n : undefined;\n if (parentIdx !== undefined && parentIdx !== i) {\n filteredBlockInners[parentIdx] = wrapOptional(filteredBlockInners[parentIdx], finished);\n } else {\n rootFilteredBlocks.unshift(finished);\n }\n }\n for (const filteredBlock of rootFilteredBlocks) {\n algebra = wrapOptional(algebra, filteredBlock);\n }\n\n for (const alias of rootOptionalTraversalAliases) {\n algebra = wrapOptional(\n algebra,\n buildOptionalTraversalSubtree(\n alias,\n traversePatternMap,\n childOptionalAliasesByParent,\n nestedOptionalPropertyTriplesByAlias,\n ),\n );\n }\n\n // Wrap each optional property triple in its own OPTIONAL (LeftJoin)\n for (const propTriple of topLevelOptionalPropertyTriples) {\n algebra = wrapOptional(algebra, {\n type: 'bgp',\n triples: [propTriple],\n });\n }\n\n // 5. Where clause → Filter wrapping (or HAVING if aggregate-containing)\n let havingExpr: SparqlExpression | undefined;\n if (query.where) {\n const filterExpr = convertExpression(query.where, registry, optionalPropertyTriples);\n if (containsAggregate(filterExpr)) {\n havingExpr = filterExpr;\n } else {\n algebra = {\n type: 'filter',\n expression: filterExpr,\n inner: algebra,\n };\n }\n }\n\n // 5b. MINUS patterns — wrap algebra in SparqlMinus for each minus pattern\n for (const pattern of query.patterns) {\n if (pattern.kind === 'minus') {\n let minusAlgebra = convertExistsPattern(pattern.pattern, registry);\n if (pattern.filter) {\n const minusPropertyTriples: SparqlTriple[] = [];\n processExpressionForProperties(pattern.filter, registry, minusPropertyTriples);\n // Add property triples into the MINUS block\n if (minusPropertyTriples.length > 0) {\n minusAlgebra = joinNodes(minusAlgebra, {type: 'bgp', triples: minusPropertyTriples});\n }\n const filterExpr = convertExpression(pattern.filter, registry, minusPropertyTriples);\n minusAlgebra = {type: 'filter', expression: filterExpr, inner: minusAlgebra};\n }\n algebra = {type: 'minus', left: algebra, right: minusAlgebra};\n }\n }\n\n // 6. SubjectId → Filter / SubjectIds → VALUES\n if (query.subjectIds && query.subjectIds.length > 0) {\n // Multiple subjects: use VALUES clause for efficient filtering\n algebra = joinNodes(\n {type: 'values', variable: rootAlias, iris: query.subjectIds},\n algebra,\n );\n } else if (query.subjectId) {\n const subjectFilter: SparqlExpression = {\n kind: 'binary_expr',\n op: '=',\n left: {kind: 'variable_expr', name: rootAlias},\n right: {kind: 'iri_expr', value: query.subjectId},\n };\n algebra = {\n type: 'filter',\n expression: subjectFilter,\n inner: algebra,\n };\n }\n\n // 7. Build projection\n const projection: SparqlProjectionItem[] = [];\n const aggregates: SparqlAggregateBinding[] = [];\n let hasAggregates = false;\n\n // Always include root alias as first projection variable\n projection.push({kind: 'variable', name: rootAlias});\n\n // Collect traversal aliases upfront to detect aggregate alias collisions\n const traversalAliasSet = new Set(collectTraversalAliases(query.patterns));\n // Track traversal aliases consumed by aggregate renames (should not be\n // re-projected as plain variables, which would alter GROUP BY semantics)\n const aggregateRenamedAliases = new Set<string>();\n\n for (const item of query.projection) {\n const sparqlExpr = convertExpression(item.expression, registry, optionalPropertyTriples);\n\n if (sparqlExpr.kind === 'aggregate_expr') {\n hasAggregates = true;\n // Avoid collision: if aggregate alias matches a traversal alias,\n // rename it so SPARQL doesn't produce duplicate variable bindings\n let aggAlias = item.alias;\n if (traversalAliasSet.has(aggAlias)) {\n aggregateRenamedAliases.add(aggAlias);\n aggAlias = `${aggAlias}_agg`;\n // Update resultMap so result mapping uses the renamed alias\n for (const rm of query.resultMap) {\n if (rm.alias === item.alias) rm.alias = aggAlias;\n }\n }\n projection.push({\n kind: 'aggregate',\n expression: sparqlExpr,\n alias: aggAlias,\n });\n aggregates.push({\n variable: aggAlias,\n aggregate: sparqlExpr,\n });\n } else {\n // For property_expr, the variable is the resolved name from registry\n const varName = resolveExpressionVariable(item.expression, registry);\n if (varName && varName !== rootAlias) {\n projection.push({kind: 'variable', name: varName});\n } else if (!varName) {\n // Non-variable expression (binary_expr, function_expr, etc.)\n // → project as (expr AS ?alias)\n let exprAlias = item.alias;\n if (traversalAliasSet.has(exprAlias)) {\n // The output alias collides with a traversal target variable — e.g. a\n // computed expression over a traversed path lowers to\n // (UCASE(?a1_name) AS ?a1), and ?a1 is already bound by the traverse\n // triple. Rename the output so SPARQL doesn't reuse an in-scope var.\n exprAlias = `${exprAlias}_expr`;\n for (const rm of query.resultMap) {\n if (rm.alias === item.alias) rm.alias = exprAlias;\n }\n }\n projection.push({kind: 'expression', expression: sparqlExpr, alias: exprAlias});\n }\n }\n }\n\n // 7b. Include traversal aliases needed for result grouping\n // When nested results are projected (e.g. p.friends.name), the result\n // mapping needs the traversal alias variable (?a1) in the bindings to\n // group nested rows by entity. Without this, mapNestedRows() can't\n // identify which nested fields belong to which traversed entity.\n const projectedNames = new Set<string>();\n for (const p of projection) {\n if (p.kind === 'variable') projectedNames.add(p.name);\n else if (p.kind === 'aggregate' || p.kind === 'expression') projectedNames.add(p.alias);\n }\n for (const alias of collectTraversalAliases(query.patterns)) {\n if (!projectedNames.has(alias) && !aggregateRenamedAliases.has(alias)) {\n projection.push({kind: 'variable', name: alias});\n projectedNames.add(alias);\n }\n }\n\n // 8. GROUP BY inference\n let groupBy: string[] | undefined;\n if (havingExpr) {\n hasAggregates = true;\n }\n if (hasAggregates) {\n // All non-aggregate projected variables become GROUP BY targets\n groupBy = projection\n .filter((p): p is {kind: 'variable'; name: string} => p.kind === 'variable')\n .map((p) => p.name);\n }\n\n // 9. OrderBy\n let orderBy: SparqlOrderCondition[] | undefined;\n if (query.orderBy) {\n orderBy = query.orderBy.map((item) => ({\n expression: convertExpression(item.expression, registry, optionalPropertyTriples),\n direction: item.direction,\n }));\n }\n\n // `.one()` lowers to limit=1 + singleResult, but LIMIT bounds ROWS, not\n // entities. When the query yields multiple rows per root entity (traversals\n // or plural properties), a row-level LIMIT would truncate the entity's own\n // nested data — omit it and let the result mapper pick the single entity.\n const multiRowPerEntity =\n query.patterns.some((p) => p.kind === 'traverse') ||\n query.projection.some(\n (item) =>\n item.expression.kind === 'property_expr' &&\n !(typeof item.expression.maxCount === 'number' && item.expression.maxCount <= 1),\n );\n const limit =\n query.singleResult && query.limit === 1 && multiRowPerEntity\n ? undefined\n : query.limit;\n\n return {\n type: 'select',\n algebra,\n projection,\n distinct: !hasAggregates ? true : undefined,\n orderBy,\n limit,\n offset: query.offset,\n groupBy,\n having: havingExpr,\n aggregates: aggregates.length > 0 ? aggregates : undefined,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Pattern processing\n// ---------------------------------------------------------------------------\n\nfunction processPattern(\n pattern: IRGraphPattern,\n registry: VariableRegistry,\n traverseTriples: SparqlTriple[],\n optionalPropertyTriples: SparqlTriple[],\n filteredTraverseBlocks?: Array<{traverseTriple: SparqlTriple; filter: IRExpression; toAlias: string}>,\n subSelectAliases?: ReadonlySet<string>,\n): void {\n switch (pattern.kind) {\n case 'shape_scan':\n // Additional shape scans (non-root) are handled as type triples\n // but this case is rare — root is handled separately\n break;\n\n case 'traverse': {\n // Register the traverse variable: (from, property) → to\n registry.set(pattern.from, pattern.property, pattern.to);\n // Traversals wrapped in a sub-SELECT (inner LIMIT/OFFSET) are emitted\n // separately — don't add their triple to the required BGP here.\n if (subSelectAliases?.has(pattern.to)) {\n break;\n }\n // Add traverse triple to required pattern (or filtered block if inline where)\n const triple = buildTraverseTriple(pattern);\n if (pattern.filter && filteredTraverseBlocks) {\n filteredTraverseBlocks.push({\n traverseTriple: triple,\n filter: pattern.filter,\n toAlias: pattern.to,\n });\n } else {\n traverseTriples.push(triple);\n }\n break;\n }\n\n case 'join': {\n for (const sub of pattern.patterns) {\n processPattern(sub, registry, traverseTriples, optionalPropertyTriples, filteredTraverseBlocks, subSelectAliases);\n }\n break;\n }\n\n case 'optional': {\n // Optional patterns — process inner patterns but keep them optional\n processPattern(pattern.pattern, registry, traverseTriples, optionalPropertyTriples, filteredTraverseBlocks, subSelectAliases);\n break;\n }\n\n case 'union': {\n for (const branch of pattern.branches) {\n processPattern(branch, registry, traverseTriples, optionalPropertyTriples, filteredTraverseBlocks, subSelectAliases);\n }\n break;\n }\n\n case 'exists': {\n processPattern(pattern.pattern, registry, traverseTriples, optionalPropertyTriples, filteredTraverseBlocks, subSelectAliases);\n break;\n }\n\n case 'minus': {\n // MINUS patterns are handled separately in selectToAlgebra — skip in processPattern.\n break;\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Expression processing — discover property_expr references\n// ---------------------------------------------------------------------------\n\nfunction processExpressionForProperties(\n expr: IRExpression,\n registry: VariableRegistry,\n optionalPropertyTriples: SparqlTriple[],\n requiredPropertyTriples: SparqlTriple[] = [],\n requiredPropertyKeys = new Set<string>(),\n): void {\n switch (expr.kind) {\n case 'property_expr': {\n if (!registry.has(expr.sourceAlias, expr.property)) {\n const varName = registry.getOrCreate(expr.sourceAlias, expr.property);\n const predicate = buildPredicateTerm(expr);\n const triple = tripleOf(\n varTerm(expr.sourceAlias),\n predicate,\n varTerm(varName),\n );\n const triples = requiredPropertyKeys.has(bindingKey(expr.sourceAlias, expr.property))\n ? requiredPropertyTriples\n : optionalPropertyTriples;\n triples.push(triple);\n }\n break;\n }\n case 'binary_expr':\n processExpressionForProperties(\n expr.left,\n registry,\n optionalPropertyTriples,\n requiredPropertyTriples,\n requiredPropertyKeys,\n );\n processExpressionForProperties(\n expr.right,\n registry,\n optionalPropertyTriples,\n requiredPropertyTriples,\n requiredPropertyKeys,\n );\n break;\n case 'in_expr':\n // The tested value binds a property; list elements are constants.\n processExpressionForProperties(\n expr.value,\n registry,\n optionalPropertyTriples,\n requiredPropertyTriples,\n requiredPropertyKeys,\n );\n break;\n case 'logical_expr':\n for (const sub of expr.expressions) {\n processExpressionForProperties(\n sub,\n registry,\n optionalPropertyTriples,\n requiredPropertyTriples,\n requiredPropertyKeys,\n );\n }\n break;\n case 'not_expr':\n processExpressionForProperties(\n expr.expression,\n registry,\n optionalPropertyTriples,\n requiredPropertyTriples,\n requiredPropertyKeys,\n );\n break;\n case 'function_expr':\n for (const arg of expr.args) {\n processExpressionForProperties(\n arg,\n registry,\n optionalPropertyTriples,\n requiredPropertyTriples,\n requiredPropertyKeys,\n );\n }\n break;\n case 'aggregate_expr':\n for (const arg of expr.args) {\n processExpressionForProperties(\n arg,\n registry,\n optionalPropertyTriples,\n requiredPropertyTriples,\n requiredPropertyKeys,\n );\n }\n break;\n case 'exists_expr':\n // exists_expr filter properties belong INSIDE the EXISTS block, not in\n // the outer scope. Do NOT register them here — convertExpression's\n // exists_expr handler will collect and emit them locally.\n break;\n case 'context_property_expr': {\n // Context entity property — emit a triple with fixed IRI as subject.\n // Use raw IRI as registry key to avoid collision between IRIs that\n // sanitize to the same string (e.g. ctx-1 vs ctx_1).\n const contextIri = resolvedContextIri(expr.contextIri, expr.contextName);\n const ctxKey = contextAliasKey(contextIri);\n if (!registry.has(ctxKey, expr.property)) {\n const varName = registry.getOrCreate(ctxKey, expr.property);\n const triple = tripleOf(\n iriTerm(contextIri),\n resolvePropertyPredicateTerm(expr.property),\n varTerm(varName),\n );\n const triples = requiredPropertyKeys.has(bindingKey(ctxKey, expr.property))\n ? requiredPropertyTriples\n : optionalPropertyTriples;\n triples.push(triple);\n }\n break;\n }\n case 'literal_expr':\n case 'reference_expr':\n case 'alias_expr':\n // No property references to discover\n break;\n }\n}\n\n/**\n * Compute which bindings are mandatory for a top-level FILTER to keep a row.\n * AND makes either side required; OR only keeps bindings required by every branch.\n */\nfunction collectRequiredBindingKeys(expr: IRExpression): Set<string> {\n switch (expr.kind) {\n case 'property_expr':\n return new Set([bindingKey(expr.sourceAlias, expr.property)]);\n case 'context_property_expr':\n return new Set([bindingKey(contextAliasKey(resolvedContextIri(expr.contextIri, expr.contextName)), expr.property)]);\n case 'in_expr':\n // The tested value must be bound; list elements are constants.\n return collectRequiredBindingKeys(expr.value);\n case 'binary_expr':\n return mergeKeySets(\n collectRequiredBindingKeys(expr.left),\n collectRequiredBindingKeys(expr.right),\n );\n case 'function_expr': {\n const fn = expr.name.toUpperCase();\n // BOUND explicitly tests boundness — forcing its argument into a\n // required (inner-join) pattern would make !BOUND unsatisfiable.\n // COALESCE is unbound-tolerant by design — requiring its arguments\n // would make the fallback unreachable.\n if (fn === 'BOUND' || fn === 'COALESCE') {\n return new Set<string>();\n }\n // IF: an unbound variable in the condition errors the row out either\n // way, so the condition may keep its requirements — but the then/else\n // branches must stay optional (the untaken branch may reference a\n // property the entity doesn't have).\n if (fn === 'IF') {\n return expr.args.length > 0\n ? collectRequiredBindingKeys(expr.args[0])\n : new Set<string>();\n }\n return mergeKeySets(...expr.args.map((arg) => collectRequiredBindingKeys(arg)));\n }\n case 'not_expr':\n return collectRequiredBindingKeys(expr.expression);\n case 'logical_expr': {\n const childSets = expr.expressions.map((sub) => collectRequiredBindingKeys(sub));\n if (expr.operator === 'and') {\n return mergeKeySets(...childSets);\n }\n return intersectKeySets(childSets);\n }\n case 'aggregate_expr':\n case 'exists_expr':\n case 'literal_expr':\n case 'reference_expr':\n case 'alias_expr':\n return new Set<string>();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Expression conversion\n// ---------------------------------------------------------------------------\n\n/**\n * The `sh:datatype` of the property a literal is being compared AGAINST, when the\n * comparison has one. Only temporal values use it (see the `literal_expr` case):\n * it is what tells an `xsd:date` property's filter to render `\"2020-01-01\"^^xsd:date`\n * rather than a full timestamp that can never equal the stored term.\n */\nfunction siblingDatatype(expr: IRExpression | undefined): string | undefined {\n if (!expr) return undefined;\n if (expr.kind === 'property_expr' || expr.kind === 'context_property_expr') {\n return resolvePropertyDatatype(expr.property);\n }\n return undefined;\n}\n\nfunction convertExpression(\n expr: IRExpression,\n registry: VariableRegistry,\n optionalPropertyTriples: SparqlTriple[],\n datatypeHint?: string,\n): SparqlExpression {\n switch (expr.kind) {\n case 'literal_expr': {\n const value = expr.value;\n if (value === null || value === undefined) {\n return {kind: 'literal_expr', value: ''};\n }\n // A temporal literal must carry its datatype. SPARQL's `=` on a plain literal\n // and an `^^xsd:dateTime` one is a type error, so the row is dropped: an\n // untyped date filter matched NOTHING against data core itself wrote. The\n // lexical form follows the compared property's declared datatype, the same\n // rule `dateToTerm` applies on the mutation side.\n if (value instanceof Date) {\n const term = dateToTerm(value, datatypeHint);\n return {\n kind: 'literal_expr',\n value: term.kind === 'literal' ? term.value : String(value),\n datatype: term.kind === 'literal' ? term.datatype : XSD_DATETIME,\n };\n }\n if (typeof value === 'boolean') {\n return {\n kind: 'literal_expr',\n value: String(value),\n datatype: XSD_BOOLEAN,\n };\n }\n if (typeof value === 'number') {\n if (Number.isInteger(value)) {\n return {\n kind: 'literal_expr',\n value: String(value),\n datatype: XSD_INTEGER,\n };\n }\n return {\n kind: 'literal_expr',\n value: String(value),\n datatype: XSD_DOUBLE,\n };\n }\n return {kind: 'literal_expr', value: String(value)};\n }\n\n case 'reference_expr':\n return {kind: 'iri_expr', value: resolvedContextIri(expr.value, expr.contextName)};\n\n case 'alias_expr':\n return {kind: 'variable_expr', name: expr.alias};\n\n case 'context_property_expr': {\n const ctxKey = `__ctx__${resolvedContextIri(expr.contextIri, expr.contextName)}`;\n const ctxVarName = registry.getOrCreate(ctxKey, expr.property);\n return {kind: 'variable_expr', name: ctxVarName};\n }\n\n case 'property_expr': {\n const varName = registry.getOrCreate(expr.sourceAlias, expr.property);\n return {kind: 'variable_expr', name: varName};\n }\n\n case 'in_expr': {\n const listHint = siblingDatatype(expr.value);\n return {\n kind: 'in_expr',\n negated: expr.negated,\n value: convertExpression(expr.value, registry, optionalPropertyTriples),\n list: expr.source.list.map((e) =>\n convertExpression(e, registry, optionalPropertyTriples, listHint),\n ),\n };\n }\n\n case 'binary_expr':\n return {\n kind: 'binary_expr',\n op: expr.operator,\n left: convertExpression(\n expr.left, registry, optionalPropertyTriples, siblingDatatype(expr.right),\n ),\n right: convertExpression(\n expr.right, registry, optionalPropertyTriples, siblingDatatype(expr.left),\n ),\n };\n\n case 'logical_expr':\n return {\n kind: 'logical_expr',\n op: expr.operator,\n exprs: expr.expressions.map((e) =>\n convertExpression(e, registry, optionalPropertyTriples),\n ),\n };\n\n case 'not_expr':\n return {\n kind: 'not_expr',\n inner: convertExpression(expr.expression, registry, optionalPropertyTriples),\n };\n\n case 'function_expr':\n return {\n kind: 'function_expr',\n name: expr.name,\n args: expr.args.map((a) =>\n convertExpression(a, registry, optionalPropertyTriples),\n ),\n };\n\n case 'aggregate_expr':\n return {\n kind: 'aggregate_expr',\n name: expr.name,\n args: expr.args.map((a) =>\n convertExpression(a, registry, optionalPropertyTriples),\n ),\n };\n\n case 'exists_expr': {\n // Convert exists expression with inner pattern + filter.\n // Filter property triples must live INSIDE the EXISTS block\n // (not in the outer scope), so we collect them locally.\n let innerAlgebra = convertExistsPattern(\n expr.pattern,\n registry,\n );\n\n if (expr.filter) {\n // First, discover and register filter property references,\n // collecting their triples into a local array (NOT the outer scope).\n const existsPropertyTriples: SparqlTriple[] = [];\n processExpressionForProperties(expr.filter, registry, existsPropertyTriples);\n\n // Now convert the filter expression (variables are registered above).\n const filterExpr = convertExpression(\n expr.filter,\n registry,\n existsPropertyTriples, // unused — properties already registered\n );\n // Add filter property triples inside the EXISTS\n for (const propTriple of existsPropertyTriples) {\n innerAlgebra = joinNodes(innerAlgebra, {type: 'bgp', triples: [propTriple]})!;\n }\n // Wrap the inner pattern with a filter\n const filteredInner: SparqlFilter = {\n type: 'filter',\n expression: filterExpr,\n inner: innerAlgebra,\n };\n return {\n kind: 'exists_expr',\n pattern: filteredInner,\n negated: false,\n };\n }\n\n return {\n kind: 'exists_expr',\n pattern: innerAlgebra,\n negated: false,\n };\n }\n\n default:\n throw new Error(`Unknown IR expression kind: ${(expr as never as {kind: string}).kind}`);\n }\n}\n\n/**\n * Convert an exists pattern (from exists_expr) into an algebra node.\n * Recursively handles all IR graph pattern kinds.\n */\nfunction convertExistsPattern(\n pattern: IRGraphPattern,\n registry: VariableRegistry,\n): SparqlAlgebraNode {\n switch (pattern.kind) {\n case 'traverse': {\n const existsPredicate = buildPredicateTerm(pattern);\n const triple = tripleOf(\n varTerm(pattern.from),\n existsPredicate,\n varTerm(pattern.to),\n );\n return {type: 'bgp', triples: [triple]};\n }\n\n case 'join': {\n let result: SparqlAlgebraNode | null = null;\n for (const sub of pattern.patterns) {\n const subNode = convertExistsPattern(sub, registry);\n result = result ? joinNodes(result, subNode) : subNode;\n }\n return result || {type: 'bgp', triples: []};\n }\n\n case 'shape_scan': {\n return {\n type: 'bgp',\n triples: [\n tripleOf(\n varTerm(pattern.alias),\n iriTerm(RDF_TYPE),\n iriTerm(resolveShapeScanIri(pattern.shape)),\n ),\n ],\n };\n }\n\n case 'optional': {\n const inner = convertExistsPattern(pattern.pattern, registry);\n return wrapOptional({type: 'bgp', triples: []}, inner);\n }\n\n case 'union': {\n let result: SparqlAlgebraNode | null = null;\n for (const branch of pattern.branches) {\n const branchNode = convertExistsPattern(branch, registry);\n if (!result) {\n result = branchNode;\n } else {\n result = {type: 'union', left: result, right: branchNode};\n }\n }\n return result || {type: 'bgp', triples: []};\n }\n\n case 'exists': {\n return convertExistsPattern(pattern.pattern, registry);\n }\n\n case 'minus': {\n return convertExistsPattern(pattern.pattern, registry);\n }\n\n default:\n throw new Error(`Unsupported pattern kind in EXISTS: ${(pattern as never as {kind: string}).kind}`);\n }\n}\n\n/**\n * Resolve what variable name an IR expression ultimately refers to.\n */\nfunction resolveExpressionVariable(\n expr: IRExpression,\n registry: VariableRegistry,\n): string | null {\n switch (expr.kind) {\n case 'alias_expr':\n return expr.alias;\n case 'property_expr':\n return registry.getOrCreate(expr.sourceAlias, expr.property);\n default:\n return null;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Mutation conversions\n// ---------------------------------------------------------------------------\n\n/** The numeric datatypes a shape may declare, and the DSL accepts a number for. */\nconst NUMERIC_DATATYPES = new Set([\n XSD_INTEGER,\n XSD_DOUBLE,\n xsd.long.id,\n xsd.decimal.id,\n xsd.float.id,\n]);\n\n/**\n * The datatype to write a number as: the one its property declares, falling back\n * to the shape of the value itself. Without the declared datatype a property\n * typed `xsd:long` stored `xsd:integer` and one typed `xsd:decimal` stored\n * `xsd:double` — a value the store round-trips as a different term than the\n * shape says it holds.\n */\nfunction numericDatatype(value: number, datatype?: string): string {\n if (datatype && NUMERIC_DATATYPES.has(datatype)) return datatype;\n return Number.isInteger(value) ? XSD_INTEGER : XSD_DOUBLE;\n}\n\n/**\n * A `Date` in the lexical form its property asks for. `xsd:date` and `xsd:dateTime` take a `Date`\n * and only a `Date`, so the declared `sh:datatype` is what decides whether that instant is\n * written as a date or a full timestamp. With no declared datatype the term stays `xsd:dateTime`.\n *\n * `xsd:time` takes a STRING instead (see `STRING_LEXICAL_DATATYPES`): a `Date` cannot represent a\n * time of day without inventing a date alongside it, which then has to be discarded here and\n * makes two identical clock times on different days compare unequal. The `XSD_TIME` branch below\n * remains for a `Date` that reaches an `xsd:time` property some other way.\n */\nfunction dateToTerm(value: Date, datatype?: string): SparqlTerm {\n const iso = value.toISOString();\n if (datatype === XSD_DATE) return literalTerm(iso.slice(0, 10), XSD_DATE);\n if (datatype === XSD_TIME) return literalTerm(iso.slice(11), XSD_TIME);\n return literalTerm(iso, XSD_DATETIME);\n}\n\n/**\n * Datatypes whose lexical form IS a string, so a plain string value must be typed from the\n * DECLARED datatype rather than written as a plain literal.\n *\n * A deliberate allow-list rather than \"type every string from whatever is declared\". A string\n * reaching a numeric or boolean property is a mistake that `assertValid` rejects; typing it here\n * would instead write a well-formed-looking `\"abc\"^^xsd:integer` and hide the error in the data.\n * Only datatypes a string is a VALID lexical form for belong here.\n */\nconst STRING_LEXICAL_DATATYPES = new Set<string>([XSD_TIME]);\n\n/**\n * Convert a field value to one or more SparqlTerm objects for triple objects.\n *\n * `datatype` is the property's declared `sh:datatype`. It decides the term type for temporal\n * values and for the string-lexical datatypes above; every other literal is still typed from the\n * JavaScript value, because that is what makes a wrong JS type a visible failure rather than a\n * silently mistyped triple.\n */\nfunction fieldValueToTerms(\n value: IRFieldValue,\n options?: SparqlOptions,\n datatype?: string,\n): SparqlTerm[] {\n if (value === null || value === undefined) {\n return [];\n }\n\n if (typeof value === 'string') {\n // A plain literal is `xsd:string` in RDF 1.1, so a string for an `xsd:string` property needs\n // no explicit datatype. Anything else in the allow-list must carry one, or it is written\n // untyped and stops matching the property it was meant to fill.\n if (datatype && STRING_LEXICAL_DATATYPES.has(datatype)) {\n return [literalTerm(value, datatype)];\n }\n return [literalTerm(value)];\n }\n\n if (typeof value === 'number') {\n return [literalTerm(String(value), numericDatatype(value, datatype))];\n }\n\n if (typeof value === 'boolean') {\n return [literalTerm(String(value), XSD_BOOLEAN)];\n }\n\n if (value instanceof Date) {\n return [dateToTerm(value, datatype)];\n }\n\n // Computed/expression value in create: create lowers to INSERT DATA (ground\n // triples, no WHERE), so an expression can't be evaluated here. Fail loudly\n // instead of silently emitting no triple (report 021 §3, G4).\n if (\n value &&\n typeof value === 'object' &&\n (isIRExpression(value) || 'ir' in (value as object))\n ) {\n throw new Error(\n 'Computed/expression values are not supported in create (INSERT DATA has no WHERE clause to evaluate them). Use a literal value, or use update.',\n );\n }\n\n // NodeReferenceValue\n if (typeof value === 'object' && 'id' in value && !('shape' in value) && !('fields' in value)) {\n return [iriTerm((value as NodeReferenceValue).id)];\n }\n\n // IRNodeData — should not produce a term directly (handled by nested create)\n if (typeof value === 'object' && 'shape' in value && 'fields' in value) {\n return []; // Handled separately\n }\n\n // Array\n if (Array.isArray(value)) {\n const terms: SparqlTerm[] = [];\n for (const item of value) {\n terms.push(...fieldValueToTerms(item, options, datatype));\n }\n return terms;\n }\n\n return [];\n}\n\n/**\n * Recursively generate triples for an IRNodeData (used in create and nested creates).\n * Returns the URI used for this node and all generated triples.\n */\nfunction generateNodeDataTriples(\n data: IRNodeData,\n options?: SparqlOptions,\n): {uri: string; triples: SparqlTriple[]} {\n const uri = data.id || generateEntityUri(data.shape, options);\n const triples: SparqlTriple[] = [];\n const subjectTerm = iriTerm(uri);\n\n // Type triple — resolve the SHACL NodeShapeData id in the IR to the ontology\n // targetClass URI (sibling of PR #77's SELECT-side resolveShapeScanIri).\n // Mutations were not covered by #77; see mutation-uri-fidelity.test.ts.\n triples.push(tripleOf(subjectTerm, iriTerm(RDF_TYPE), iriTerm(resolveShapeScanIri(data.shape))));\n\n // Field triples\n for (const field of data.fields) {\n // Resolve the SHACL PropertyShapeData id to its declared `path` URI.\n const propertyTerm = resolvePropertyPredicateTerm(field.property);\n\n if (field.value === null || field.value === undefined) {\n continue;\n }\n\n // Handle arrays (including mixed arrays of references and nested creates)\n if (Array.isArray(field.value)) {\n for (const item of field.value) {\n if (item && typeof item === 'object' && 'shape' in item && 'fields' in item) {\n // Nested create\n const nested = generateNodeDataTriples(item as IRNodeData, options);\n triples.push(tripleOf(subjectTerm, propertyTerm, iriTerm(nested.uri)));\n triples.push(...nested.triples);\n } else {\n const terms = fieldValueToTerms(item, options, resolvePropertyDatatype(field.property));\n for (const term of terms) {\n triples.push(tripleOf(subjectTerm, propertyTerm, term));\n }\n }\n }\n continue;\n }\n\n // Handle nested IRNodeData\n if (typeof field.value === 'object' && 'shape' in field.value && 'fields' in field.value) {\n const nested = generateNodeDataTriples(field.value as IRNodeData, options);\n triples.push(tripleOf(subjectTerm, propertyTerm, iriTerm(nested.uri)));\n triples.push(...nested.triples);\n continue;\n }\n\n // Simple values\n const terms = fieldValueToTerms(field.value, options, resolvePropertyDatatype(field.property));\n for (const term of terms) {\n triples.push(tripleOf(subjectTerm, propertyTerm, term));\n }\n }\n\n return {uri, triples};\n}\n\n/**\n * Converts an IRCreateMutation to a SparqlInsertDataPlan.\n */\nexport function createToAlgebra(\n query: IRCreateMutation,\n options?: SparqlOptions,\n): SparqlInsertDataPlan {\n const {triples} = generateNodeDataTriples(query.data, options);\n return {\n type: 'insert_data',\n triples,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Shared update field processing\n// ---------------------------------------------------------------------------\n\n/**\n * Processes IRNodeData fields into DELETE/INSERT/WHERE triples.\n * Shared between updateToAlgebra (IRI subject) and updateWhereToAlgebra (variable subject).\n */\nfunction processUpdateFields(\n data: IRNodeData,\n subjectTerm: SparqlTerm,\n options?: SparqlOptions,\n): {\n deletePatterns: SparqlTriple[];\n insertPatterns: SparqlTriple[];\n oldValueTriples: SparqlTriple[];\n extends: Array<{variable: string; expression: SparqlExpression}>;\n cascadeOptionals: SparqlAlgebraNode[];\n} {\n const deletePatterns: SparqlTriple[] = [];\n const insertPatterns: SparqlTriple[] = [];\n const oldValueTriples: SparqlTriple[] = [];\n const extends_: Array<{variable: string; expression: SparqlExpression}> = [];\n // Owned cleanup on `contains` replace/remove: dropping a `contains` edge must delete\n // the old object itself (its own triples) AND its owned subtree, not just unlink the\n // one-hop edge — otherwise the old node orphans (backlog 032).\n const {containsPreds: updContainsPreds} = collectContainment();\n const containsOldVars: Array<{oldVar: string; propertyTerm: SparqlTerm}> = [];\n const cascadeOptionals: SparqlAlgebraNode[] = [];\n\n for (const field of data.fields) {\n const propertyTerm = resolvePropertyPredicateTerm(field.property);\n const suffix = propertySuffix(field.property);\n const isContainsField =\n propertyTerm.kind === 'iri' && updContainsPreds.includes(propertyTerm.value);\n\n // Check for set modification ({add, remove})\n if (\n field.value &&\n typeof field.value === 'object' &&\n !Array.isArray(field.value) &&\n !(field.value instanceof Date) &&\n !('id' in field.value) &&\n !('shape' in field.value) &&\n ('add' in field.value || 'remove' in field.value)\n ) {\n const setMod = field.value as IRSetModificationValue;\n\n if (setMod.remove) {\n setMod.remove.forEach((removeItem, ri) => {\n const removeTerm = iriTerm((removeItem as NodeReferenceValue).id);\n deletePatterns.push(tripleOf(subjectTerm, propertyTerm, removeTerm));\n oldValueTriples.push(tripleOf(subjectTerm, propertyTerm, removeTerm));\n // For a `contains` set, removing a value deletes the removed node itself\n // (its own triples) and its owned subtree — exclusive ownership via the edge.\n if (isContainsField) {\n const self = buildOwnedSelfDelete(\n subjectTerm,\n propertyTerm,\n removeTerm,\n `ucr_${suffix}_${ri}_`,\n );\n deletePatterns.push(...self.deletePatterns);\n cascadeOptionals.push(...self.whereOptionals);\n const cascade = buildOwnedCascade(removeTerm, `ucr_${suffix}_${ri}_`);\n deletePatterns.push(...cascade.deletePatterns);\n cascadeOptionals.push(...cascade.whereOptionals);\n }\n });\n }\n\n if (setMod.add) {\n for (const addItem of setMod.add) {\n if (addItem && typeof addItem === 'object' && 'shape' in addItem && 'fields' in addItem) {\n const nested = generateNodeDataTriples(addItem as IRNodeData, options);\n insertPatterns.push(tripleOf(subjectTerm, propertyTerm, iriTerm(nested.uri)));\n insertPatterns.push(...nested.triples);\n } else {\n const terms = fieldValueToTerms(addItem, options, resolvePropertyDatatype(field.property));\n for (const term of terms) {\n insertPatterns.push(tripleOf(subjectTerm, propertyTerm, term));\n }\n }\n }\n }\n\n continue;\n }\n\n // Non-set-modification replace of a `contains` property: cascade the old value's\n // subtree (every branch below binds `old_${suffix}` in the WHERE).\n if (isContainsField) {\n containsOldVars.push({oldVar: `old_${suffix}`, propertyTerm});\n }\n\n // Unset (undefined/null) — delete only\n if (field.value === undefined || field.value === null) {\n const oldVar = varTerm(`old_${suffix}`);\n deletePatterns.push(tripleOf(subjectTerm, propertyTerm, oldVar));\n oldValueTriples.push(tripleOf(subjectTerm, propertyTerm, oldVar));\n continue;\n }\n\n // Array overwrite — delete old values + insert new ones\n if (Array.isArray(field.value)) {\n const oldVar = varTerm(`old_${suffix}`);\n deletePatterns.push(tripleOf(subjectTerm, propertyTerm, oldVar));\n oldValueTriples.push(tripleOf(subjectTerm, propertyTerm, oldVar));\n\n for (const item of field.value) {\n if (item && typeof item === 'object' && 'shape' in item && 'fields' in item) {\n const nested = generateNodeDataTriples(item as IRNodeData, options);\n insertPatterns.push(tripleOf(subjectTerm, propertyTerm, iriTerm(nested.uri)));\n insertPatterns.push(...nested.triples);\n } else {\n const terms = fieldValueToTerms(item, options, resolvePropertyDatatype(field.property));\n for (const term of terms) {\n insertPatterns.push(tripleOf(subjectTerm, propertyTerm, term));\n }\n }\n }\n continue;\n }\n\n // Nested create (single object field)\n if (typeof field.value === 'object' && 'shape' in field.value && 'fields' in field.value) {\n const oldVar = varTerm(`old_${suffix}`);\n deletePatterns.push(tripleOf(subjectTerm, propertyTerm, oldVar));\n oldValueTriples.push(tripleOf(subjectTerm, propertyTerm, oldVar));\n\n const nested = generateNodeDataTriples(field.value as IRNodeData, options);\n insertPatterns.push(tripleOf(subjectTerm, propertyTerm, iriTerm(nested.uri)));\n insertPatterns.push(...nested.triples);\n continue;\n }\n\n // IRExpression — computed value update (e.g. p.age.plus(1))\n if (isIRExpression(field.value)) {\n const expr = field.value as IRExpression;\n const oldVar = varTerm(`old_${suffix}`);\n const computedVarName = `computed_${suffix}`;\n const computedVar = varTerm(computedVarName);\n\n // DELETE old value\n deletePatterns.push(tripleOf(subjectTerm, propertyTerm, oldVar));\n\n // WHERE: OPTIONAL for old value\n oldValueTriples.push(tripleOf(subjectTerm, propertyTerm, oldVar));\n\n // Discover additional property references in the expression and add OPTIONAL triples\n const registry = new VariableRegistry();\n const mutationSubjectAlias = '__mutation_subject__';\n // Pre-register the subject variable mapping for the field being updated\n registry.set(mutationSubjectAlias, field.property, `old_${suffix}`);\n\n const additionalOptionals: SparqlTriple[] = [];\n processExpressionForProperties(expr, registry, additionalOptionals);\n\n // Add any additional property OPTIONAL triples (for refs to other properties)\n for (const triple of additionalOptionals) {\n // Rewrite the subject from the placeholder variable to the actual subject term\n if (triple.subject.kind === 'variable' && triple.subject.name === mutationSubjectAlias) {\n oldValueTriples.push(tripleOf(subjectTerm, triple.predicate, triple.object));\n } else {\n oldValueTriples.push(triple);\n }\n }\n\n // Convert IRExpression to SparqlExpression\n const sparqlExpr = convertExpression(expr, registry, additionalOptionals);\n\n // BIND computed expression\n extends_.push({variable: computedVarName, expression: sparqlExpr});\n\n // INSERT computed value\n insertPatterns.push(tripleOf(subjectTerm, propertyTerm, computedVar));\n continue;\n }\n\n // Simple value update — delete old + insert new\n const oldVar = varTerm(`old_${suffix}`);\n deletePatterns.push(tripleOf(subjectTerm, propertyTerm, oldVar));\n oldValueTriples.push(tripleOf(subjectTerm, propertyTerm, oldVar));\n\n const terms = fieldValueToTerms(field.value, options, resolvePropertyDatatype(field.property));\n for (const term of terms) {\n insertPatterns.push(tripleOf(subjectTerm, propertyTerm, term));\n }\n }\n\n // For each replaced `contains` property: delete the old value's own triples\n // (exclusive ownership via the edge — backlog 032) then cascade any owned descendants.\n containsOldVars.forEach(({oldVar, propertyTerm}, n) => {\n const oldTerm = varTerm(oldVar);\n const self = buildOwnedSelfDelete(subjectTerm, propertyTerm, oldTerm, `uc${n}_`);\n deletePatterns.push(...self.deletePatterns);\n cascadeOptionals.push(...self.whereOptionals);\n const cascade = buildOwnedCascade(oldTerm, `uc${n}_`);\n deletePatterns.push(...cascade.deletePatterns);\n cascadeOptionals.push(...cascade.whereOptionals);\n });\n\n return {\n deletePatterns,\n insertPatterns,\n oldValueTriples,\n extends: extends_,\n cascadeOptionals,\n };\n}\n\n/**\n * Wraps old-value triples in OPTIONAL (LEFT JOIN) so UPDATE succeeds\n * even when the old value doesn't exist.\n */\nfunction wrapOldValueOptionals(\n base: SparqlAlgebraNode,\n oldValueTriples: SparqlTriple[],\n): SparqlAlgebraNode {\n let algebra = base;\n if (oldValueTriples.length === 0) {\n return algebra;\n }\n for (const triple of oldValueTriples) {\n algebra = {\n type: 'left_join',\n left: algebra,\n right: {type: 'bgp', triples: [triple]},\n };\n }\n return algebra;\n}\n\n/**\n * Converts an IRUpdateMutation to a SparqlDeleteInsertPlan.\n */\nexport function updateToAlgebra(\n query: IRUpdateMutation,\n options?: SparqlOptions,\n): SparqlDeleteInsertPlan {\n return buildDeleteInsertPlan(query, options);\n}\n\n/**\n * Converts an IRUpsertMutation to a SparqlDeleteInsertPlan.\n *\n * The same plan `update` produces, plus `<id> a <targetClass>` in the INSERT. Nothing else\n * differs: `update`'s WHERE is already a bare OPTIONAL, so it matches — and therefore\n * inserts — whether or not the node exists. The type triple is what turns that into a\n * create. Re-asserting it on an existing node is a no-op, RDF graphs being sets, so it\n * needs no guard.\n */\nexport function upsertToAlgebra(\n query: IRUpsertMutation,\n options?: SparqlOptions,\n): SparqlDeleteInsertPlan {\n return buildDeleteInsertPlan(query, options, {\n // Must match the IRI `create` asserts and `select` scans for; the raw shape id is\n // not the same thing, and a node typed with it would be invisible to queries.\n ensureType: resolveShapeScanIri(query.shape),\n });\n}\n\n/**\n * Shared body of the id-targeted DELETE/INSERT/WHERE plans. `ensureType` is the only\n * difference between `update` and `upsert`; when absent the output is exactly what the\n * update path has always emitted.\n */\nfunction buildDeleteInsertPlan(\n query: IRUpdateMutation | IRUpsertMutation,\n options?: SparqlOptions,\n opts?: {ensureType?: string},\n): SparqlDeleteInsertPlan {\n const subjectTerm = iriTerm(query.id);\n const result = processUpdateFields(query.data, subjectTerm, options);\n\n // Partition old-value/optional triples into subject-anchored ones and those\n // anchored on a traversal target variable (e.g. `?a1 <name> ?a1_name` from a\n // `p.bestFriend.name.ucase()` expression). Traversal-anchored triples MUST be\n // nested inside the same OPTIONAL group as their traversal edge — otherwise,\n // when the subject has no such edge, the leaf variable is unbound and the\n // property triple matches every entity in the graph (data-corruption bug).\n const travTos = new Set(\n (query.traversalPatterns ?? []).map((t) => t.to),\n );\n const travAnchoredByTo = new Map<string, SparqlTriple[]>();\n const subjectAnchored: SparqlTriple[] = [];\n for (const triple of result.oldValueTriples) {\n if (triple.subject.kind === 'variable' && travTos.has(triple.subject.name)) {\n const list = travAnchoredByTo.get(triple.subject.name) ?? [];\n list.push(triple);\n travAnchoredByTo.set(triple.subject.name, list);\n } else {\n subjectAnchored.push(triple);\n }\n }\n\n let whereAlgebra = wrapOldValueOptionals(\n {type: 'bgp', triples: []},\n subjectAnchored,\n );\n\n // Add traversal OPTIONAL patterns (for multi-segment expression refs). The\n // traversal edge and its dependent leaf property triples share one OPTIONAL\n // group so the leaf variable is scoped to the traversal target. These come\n // BEFORE expression BINDs since the BINDs reference the traversal variables.\n if (query.traversalPatterns) {\n for (const trav of query.traversalPatterns) {\n const fromTerm =\n trav.from === '__mutation_subject__' ? subjectTerm : varTerm(trav.from);\n const traversalTriple = tripleOf(\n fromTerm,\n // The declared `sh:path`, like every other predicate — not the property\n // shape's own IRI, which identifies the description of the property.\n resolvePropertyPredicateTerm(trav.property),\n varTerm(trav.to),\n );\n // The traversal edge binds the target var; each dependent leaf property is\n // a nested OPTIONAL *within* that scope, so a missing optional property\n // (e.g. a bestFriend with no hobby) doesn't drop the whole group, while an\n // absent edge still leaves every leaf var unbound (no cross-entity match).\n let travNode: SparqlAlgebraNode = {type: 'bgp', triples: [traversalTriple]};\n for (const leaf of travAnchoredByTo.get(trav.to) ?? []) {\n travNode = {\n type: 'left_join',\n left: travNode,\n right: {type: 'bgp', triples: [leaf]},\n };\n }\n whereAlgebra = {type: 'left_join', left: whereAlgebra, right: travNode};\n }\n }\n\n // Owned-subtree cascade OPTIONALs for replaced `contains` properties.\n for (const optional of result.cascadeOptionals) {\n whereAlgebra = {type: 'left_join', left: whereAlgebra, right: optional};\n }\n\n // Add BIND expressions for computed fields\n for (const ext of result.extends) {\n whereAlgebra = {\n type: 'extend',\n inner: whereAlgebra,\n variable: ext.variable,\n expression: ext.expression,\n };\n }\n\n // The type triple leads the INSERT, mirroring `create`'s triple order.\n const insertPatterns = opts?.ensureType\n ? [\n tripleOf(subjectTerm, iriTerm(RDF_TYPE), iriTerm(opts.ensureType)),\n ...result.insertPatterns,\n ]\n : result.insertPatterns;\n\n return {\n type: 'delete_insert',\n deletePatterns: result.deletePatterns,\n insertPatterns,\n whereAlgebra,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Owned-subtree cascade\n//\n// Composition cleanup driven by two declarative flags:\n// - a property marked `contains` → the cascade FOLLOWS that edge,\n// - a shape marked `dependent` → its instances may be DELETED when reached.\n// Both are read from the live registry, so no vocabulary is hardcoded. From a root\n// node we follow `(c1|c2|…)+` over all contains predicates and, for each dependent\n// targetClass, wildcard-delete the reached typed nodes. Requiring an asserted\n// `?owned a <dependentType>` naturally excludes shared predicate IRIs (e.g. a simple\n// `sh:path`) and `rdf:nil` (never typed), so only owned structural nodes are removed.\n// ---------------------------------------------------------------------------\n\n/** True when the shape (or an ancestor) declares at least one `contains` property. */\nfunction shapeHasContainsProperty(shapeId: string): boolean {\n const nodeShape = getShapeClass(shapeId)?.shape ?? getNodeShape(shapeId);\n if (!nodeShape) return false;\n return getPropertyShapes(nodeShape, true)\n .some((ps) => (ps as {contains?: boolean}).contains);\n}\n\n// Memoized registry scan for cascade lowering — called once per update/delete and\n// again per owned-cascade item inside loops. Guarded by registry size (same rationale\n// as predicateTermCache). Callers treat the result as read-only.\nlet containmentCache: {containsPreds: string[]; dependentTypes: string[]} | null = null;\nlet containmentCacheSize = -1;\n\n/** Gather contains-predicate IRIs and dependent targetClass IRIs from the registry. */\nfunction collectContainment(): {containsPreds: string[]; dependentTypes: string[]} {\n const version = getRegistryVersion();\n if (containmentCache && version === containmentCacheSize) {\n return containmentCache;\n }\n const containsPreds = new Set<string>();\n const dependentTypes = new Set<string>();\n for (const nodeShape of getAllNodeShapes().values()) {\n if (!nodeShape) continue;\n if ((nodeShape as {dependent?: boolean}).dependent && nodeShape.targetClass?.id) {\n dependentTypes.add(nodeShape.targetClass.id);\n }\n const propertyShapes = getPropertyShapes(nodeShape, false);\n for (const ps of propertyShapes) {\n if ((ps as {contains?: boolean}).contains) {\n const predId = getSimplePathId(ps.path);\n if (predId) containsPreds.add(predId);\n }\n }\n }\n containmentCache = {containsPreds: [...containsPreds], dependentTypes: [...dependentTypes]};\n containmentCacheSize = version;\n return containmentCache;\n}\n\n/**\n * Build DELETE patterns + WHERE OPTIONAL blocks that cascade-delete the owned subtree\n * reachable from `rootTerm` via `contains` edges. `varPrefix` keeps generated variables\n * unique across multiple roots in one query. Returns empty when nothing is owned.\n */\nexport function buildOwnedCascade(\n rootTerm: SparqlTerm,\n varPrefix: string,\n): {deletePatterns: SparqlTriple[]; whereOptionals: SparqlAlgebraNode[]} {\n const {containsPreds, dependentTypes} = collectContainment();\n if (containsPreds.length === 0 || dependentTypes.length === 0) {\n return {deletePatterns: [], whereOptionals: []};\n }\n // (c1|c2|…)+ — follow one-or-more contains edges from the root.\n const pathExpr: PathExpr =\n containsPreds.length === 1\n ? {oneOrMore: {id: containsPreds[0]}}\n : {oneOrMore: {alt: containsPreds.map((id) => ({id}))}};\n const pathTerm: SparqlTerm = {\n kind: 'path',\n value: pathExprToSparql(pathExpr),\n uris: collectPathUris(pathExpr),\n };\n\n const deletePatterns: SparqlTriple[] = [];\n const whereOptionals: SparqlAlgebraNode[] = [];\n dependentTypes.forEach((typeId, i) => {\n const owned = varTerm(`${varPrefix}own${i}`);\n const p = varTerm(`${varPrefix}op${i}`);\n const o = varTerm(`${varPrefix}ov${i}`);\n deletePatterns.push(tripleOf(owned, p, o));\n whereOptionals.push({\n type: 'bgp',\n triples: [\n tripleOf(rootTerm, pathTerm, owned),\n tripleOf(owned, iriTerm(RDF_TYPE), iriTerm(typeId)),\n tripleOf(owned, p, o),\n ],\n });\n });\n return {deletePatterns, whereOptionals};\n}\n\n/**\n * Build DELETE + WHERE OPTIONAL that removes the *old node's own* one-hop triples when a\n * `contains` edge is replaced, unset, or set-removed. A `contains` edge asserts exclusive\n * ownership, so overwriting it must delete the previously owned child fully — not merely\n * unlink it — or the child orphans (backlog 032). This is `contains`-driven and deliberately\n * does NOT require the child shape to be `dependent`: ownership via the edge is sufficient.\n * Owned descendants *below* the old node are cascaded separately by `buildOwnedCascade`.\n *\n * The owning edge `<subject> <prop> ?old` is re-asserted INSIDE the WHERE group so `?old`\n * is bound there: when no old value exists the group matches nothing and the DELETE is a\n * no-op, rather than an unbound `?old` matching (and deleting) the whole graph. When\n * `oldTerm` is a concrete IRI (set-remove), the guard just confirms the link still holds.\n */\nexport function buildOwnedSelfDelete(\n subjectTerm: SparqlTerm,\n propertyTerm: SparqlTerm,\n oldTerm: SparqlTerm,\n varPrefix: string,\n): {deletePatterns: SparqlTriple[]; whereOptionals: SparqlAlgebraNode[]} {\n const p = varTerm(`${varPrefix}sp`);\n const o = varTerm(`${varPrefix}so`);\n const wildcard = tripleOf(oldTerm, p, o);\n return {\n deletePatterns: [wildcard],\n whereOptionals: [\n {\n type: 'bgp',\n triples: [tripleOf(subjectTerm, propertyTerm, oldTerm), wildcard],\n },\n ],\n };\n}\n\n/**\n * Converts an IRDeleteMutation to a SparqlDeleteInsertPlan (DELETE + WHERE).\n *\n * The WHERE is the type guard of every id, joined with ONE UNION of independent\n * blocks: per id its own triples, its incoming references and, for a shape that\n * owns something, one block per dependent type of its owned subtree.\n *\n * The blocks must not be chained as OPTIONALs. A chain of OPTIONALs is a join, so\n * the solutions multiply: own triples x incoming references x owned triples of each\n * dependent type. Deleting one shape description with the shape sync's cascade\n * produced ~27,000 solutions for ~130 triples and took over 30 seconds on Fuseki,\n * which re-evaluates the cascade property path for every left-hand row. A UNION\n * yields each block's matches once, so the solutions add up instead, and it deletes\n * exactly the same triples: a DELETE template triple whose variables a solution\n * leaves unbound is skipped, as it was for an OPTIONAL that did not match.\n *\n * The guards stay required for every id, as before: when any id is not of the\n * shape, the WHERE has no solution and nothing is deleted.\n */\nexport function deleteToAlgebra(\n query: IRDeleteMutation,\n _options?: SparqlOptions,\n): SparqlDeleteInsertPlan {\n const deletePatterns: SparqlTriple[] = [];\n const guards: SparqlTriple[] = [];\n const blocks: SparqlAlgebraNode[] = [];\n\n for (let i = 0; i < query.ids.length; i++) {\n const subjectTerm = iriTerm(query.ids[i].id);\n const idx = query.ids.length > 1 ? `_${i}` : '';\n\n const subjWild = tripleOf(subjectTerm, varTerm(`p${idx}`), varTerm(`o${idx}`));\n const objWild = tripleOf(varTerm(`s${idx}`), varTerm(`p2${idx}`), subjectTerm);\n const typeGuard = tripleOf(subjectTerm, iriTerm(RDF_TYPE), iriTerm(resolveShapeScanIri(query.shape)));\n\n // DELETE block: all patterns (subject-wildcard, object-wildcard, type)\n deletePatterns.push(subjWild, objWild, typeGuard);\n\n // WHERE: the type guard is required; the subject's own triples and its\n // incoming references (the entity may have none) are separate UNION blocks.\n guards.push(typeGuard);\n blocks.push({type: 'bgp', triples: [subjWild]}, {type: 'bgp', triples: [objWild]});\n\n // Cascade-delete the owned subtree — only for shapes that actually own something\n // (have a `contains` property); a plain entity delete is left untouched.\n if (shapeHasContainsProperty(query.shape)) {\n const cascade = buildOwnedCascade(subjectTerm, `c${idx}_`);\n deletePatterns.push(...cascade.deletePatterns);\n blocks.push(...cascade.whereOptionals);\n }\n }\n\n let union: SparqlAlgebraNode = blocks[0];\n for (let i = 1; i < blocks.length; i++) {\n union = {type: 'union', left: union, right: blocks[i]};\n }\n const whereAlgebra: SparqlAlgebraNode = {\n type: 'join',\n left: {type: 'bgp', triples: guards},\n right: union,\n };\n\n return {\n type: 'delete_insert',\n deletePatterns,\n insertPatterns: [],\n whereAlgebra,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Blank node tree walking for schema-aware delete cleanup\n// ---------------------------------------------------------------------------\n\n/**\n * Checks whether a PropertyShapeData points to blank nodes (sh:BlankNode or\n * sh:BlankNodeOrIRI). Returns true when the property's range *may* include\n * blank node values that should be cleaned up on delete.\n */\nfunction isBlankNodeProperty(prop: {nodeKind?: {id?: string}}): boolean {\n const nk = prop.nodeKind?.id;\n if (!nk) return false;\n return nk === shacl.BlankNode.id || nk === shacl.BlankNodeOrIRI.id;\n}\n\n/**\n * Recursively builds DELETE + WHERE patterns for blank-node-typed properties.\n *\n * For each blank-node property on the shape:\n * - DELETE: `?bnVar ?pN ?oN .` (wildcard all triples on the blank node)\n * - WHERE: `OPTIONAL { ?parent <property> ?bnVar . FILTER(isBlank(?bnVar)) . ?bnVar ?pN ?oN . }`\n *\n * Recurses into the property's valueShape to handle nested blank nodes\n * (e.g. Person → Address (blank) → GeoPoint (blank)).\n */\nfunction walkBlankNodeTree(\n shapeId: string,\n parentVar: string,\n depth: number,\n deletePatterns: SparqlTriple[],\n): SparqlAlgebraNode | null {\n const nodeShape = getShapeClass(shapeId)?.shape ?? getNodeShape(shapeId);\n if (!nodeShape) return null;\n\n let optionals: SparqlAlgebraNode | null = null;\n\n const props = getPropertyShapes(nodeShape, true);\n for (const prop of props) {\n if (!isBlankNodeProperty(prop)) continue;\n\n const bnVar = `bn${depth}`;\n const pVar = `p${depth}`;\n const oVar = `o${depth}`;\n\n // DELETE pattern: wildcard all triples on the blank node\n deletePatterns.push(tripleOf(varTerm(bnVar), varTerm(pVar), varTerm(oVar)));\n\n // WHERE: parent --<property>--> ?bnVar\n const traverseTriple = tripleOf(\n varTerm(parentVar),\n resolvePropertyPredicateTerm(prop.id),\n varTerm(bnVar),\n );\n // FILTER(isBlank(?bnVar))\n const isBlankFilter: SparqlExpression = {\n kind: 'function_expr',\n name: 'isBlank',\n args: [{kind: 'variable_expr', name: bnVar}],\n };\n // ?bnVar ?pN ?oN\n const wildcardTriple = tripleOf(varTerm(bnVar), varTerm(pVar), varTerm(oVar));\n\n // Build inner pattern: traverse + filter + wildcard\n let innerPattern: SparqlAlgebraNode = {\n type: 'bgp',\n triples: [traverseTriple, wildcardTriple],\n };\n innerPattern = {type: 'filter', expression: isBlankFilter, inner: innerPattern};\n\n // Recurse into valueShape for nested blank nodes\n if (prop.valueShape?.id) {\n const nestedOptional = walkBlankNodeTree(\n prop.valueShape.id,\n bnVar,\n depth + 1,\n deletePatterns,\n );\n if (nestedOptional) {\n innerPattern = {type: 'left_join', left: innerPattern, right: nestedOptional};\n }\n }\n\n // Wrap in OPTIONAL (left_join)\n if (optionals) {\n optionals = {type: 'left_join', left: optionals, right: innerPattern};\n } else {\n optionals = innerPattern;\n }\n\n depth++;\n }\n\n return optionals;\n}\n\n/**\n * Converts an IRDeleteAllMutation to a SparqlDeleteInsertPlan.\n *\n * Generates DELETE { ?a0 ?p ?o . [blank node wildcards] }\n * WHERE { ?a0 a <Shape> . ?a0 ?p ?o . OPTIONAL { [blank node traversals] } }\n */\nexport function deleteAllToAlgebra(\n query: IRDeleteAllMutation,\n _options?: SparqlOptions,\n): SparqlDeleteInsertPlan {\n const subjectVar = 'a0';\n\n // DELETE patterns: root wildcard\n const deletePatterns: SparqlTriple[] = [\n tripleOf(varTerm(subjectVar), varTerm('p'), varTerm('o')),\n ];\n\n // WHERE: type triple + root wildcard\n const typeTriple = tripleOf(varTerm(subjectVar), iriTerm(RDF_TYPE), iriTerm(resolveShapeScanIri(query.shape)));\n const rootWildcard = tripleOf(varTerm(subjectVar), varTerm('p'), varTerm('o'));\n let whereAlgebra: SparqlAlgebraNode = {type: 'bgp', triples: [typeTriple, rootWildcard]};\n\n // Walk blank node tree for cleanup\n const blankNodeOptional = walkBlankNodeTree(query.shape, subjectVar, 1, deletePatterns);\n if (blankNodeOptional) {\n whereAlgebra = {type: 'left_join', left: whereAlgebra, right: blankNodeOptional};\n }\n\n return {\n type: 'delete_insert',\n deletePatterns,\n insertPatterns: [],\n whereAlgebra,\n };\n}\n\n/**\n * Converts an IRDeleteWhereMutation to a SparqlDeleteInsertPlan.\n *\n * Like deleteAllToAlgebra but adds filter conditions from the where clause.\n */\nexport function deleteWhereToAlgebra(\n query: IRDeleteWhereMutation,\n _options?: SparqlOptions,\n): SparqlDeleteInsertPlan {\n const subjectVar = 'a0';\n const registry = new VariableRegistry();\n\n // DELETE patterns: root wildcard\n const deletePatterns: SparqlTriple[] = [\n tripleOf(varTerm(subjectVar), varTerm('p'), varTerm('o')),\n ];\n\n // WHERE: type triple + root wildcard\n const typeTriple = tripleOf(varTerm(subjectVar), iriTerm(RDF_TYPE), iriTerm(resolveShapeScanIri(query.shape)));\n const rootWildcard = tripleOf(varTerm(subjectVar), varTerm('p'), varTerm('o'));\n let whereAlgebra: SparqlAlgebraNode = {type: 'bgp', triples: [typeTriple, rootWildcard]};\n\n // Process where patterns (traversals from the where clause)\n const traverseTriples: SparqlTriple[] = [];\n const optionalPropertyTriples: SparqlTriple[] = [];\n for (const pattern of query.wherePatterns) {\n processPattern(pattern, registry, traverseTriples, optionalPropertyTriples);\n }\n\n // Add traverse triples to required BGP\n if (traverseTriples.length > 0) {\n whereAlgebra = joinNodes(whereAlgebra, {type: 'bgp', triples: traverseTriples});\n }\n\n // Process expression to discover property triples\n processExpressionForProperties(query.where, registry, optionalPropertyTriples);\n\n // Add optional property triples\n for (const triple of optionalPropertyTriples) {\n whereAlgebra = joinNodes(whereAlgebra, {type: 'bgp', triples: [triple]});\n }\n\n // Convert and add filter expression\n const filterExpr = convertExpression(query.where, registry, []);\n whereAlgebra = {type: 'filter', expression: filterExpr, inner: whereAlgebra};\n\n // Walk blank node tree for cleanup\n const blankNodeOptional = walkBlankNodeTree(query.shape, subjectVar, 1, deletePatterns);\n if (blankNodeOptional) {\n whereAlgebra = {type: 'left_join', left: whereAlgebra, right: blankNodeOptional};\n }\n\n return {\n type: 'delete_insert',\n deletePatterns,\n insertPatterns: [],\n whereAlgebra,\n };\n}\n\n/**\n * Converts an IRUpdateWhereMutation to a SparqlDeleteInsertPlan.\n *\n * Like updateToAlgebra but uses a variable subject (?a0) instead of a\n * hardcoded entity IRI, adds a type triple, and optionally includes\n * filter conditions from the where clause.\n */\nexport function updateWhereToAlgebra(\n query: IRUpdateWhereMutation,\n options?: SparqlOptions,\n): SparqlDeleteInsertPlan {\n const subjectTerm = varTerm('a0');\n const result = processUpdateFields(query.data, subjectTerm, options);\n\n // WHERE: type triple is always required\n const typeTriple = tripleOf(subjectTerm, iriTerm(RDF_TYPE), iriTerm(resolveShapeScanIri(query.data.shape)));\n let whereAlgebra: SparqlAlgebraNode = {type: 'bgp', triples: [typeTriple]};\n\n // Process where filter conditions (if any)\n if (query.where && query.wherePatterns) {\n const registry = new VariableRegistry();\n const traverseTriples: SparqlTriple[] = [];\n const optionalPropertyTriples: SparqlTriple[] = [];\n\n for (const pattern of query.wherePatterns) {\n processPattern(pattern, registry, traverseTriples, optionalPropertyTriples);\n }\n\n if (traverseTriples.length > 0) {\n whereAlgebra = joinNodes(whereAlgebra, {type: 'bgp', triples: traverseTriples});\n }\n\n processExpressionForProperties(query.where, registry, optionalPropertyTriples);\n\n for (const triple of optionalPropertyTriples) {\n whereAlgebra = joinNodes(whereAlgebra, {type: 'bgp', triples: [triple]});\n }\n\n const filterExpr = convertExpression(query.where, registry, []);\n whereAlgebra = {type: 'filter', expression: filterExpr, inner: whereAlgebra};\n }\n\n // Old-value triples anchored on a traversal *target* belong INSIDE that\n // traversal's OPTIONAL group, not beside it. Emitted beside it, the leaf's\n // subject variable is introduced by an OPTIONAL that shares no variable with\n // anything to its left — a left join with no join condition, i.e. a cartesian\n // product over every node in the store carrying that predicate. The following\n // OPTIONAL cannot repair it: the variable is already bound, and OPTIONAL never\n // removes rows. `updateToAlgebra` performs the same split; this path did not.\n const travTos = new Set((query.traversalPatterns ?? []).map((t) => t.to));\n const travAnchoredByTo = new Map<string, SparqlTriple[]>();\n const subjectAnchored: SparqlTriple[] = [];\n for (const triple of result.oldValueTriples) {\n if (triple.subject.kind === 'variable' && travTos.has(triple.subject.name)) {\n const list = travAnchoredByTo.get(triple.subject.name) ?? [];\n list.push(triple);\n travAnchoredByTo.set(triple.subject.name, list);\n } else {\n subjectAnchored.push(triple);\n }\n }\n\n whereAlgebra = wrapOldValueOptionals(whereAlgebra, subjectAnchored);\n\n // Add traversal OPTIONAL patterns (for multi-segment expression refs)\n // These must come BEFORE expression BINDs since the BINDs reference traversal variables.\n if (query.traversalPatterns) {\n for (const trav of query.traversalPatterns) {\n const fromTerm =\n trav.from === '__mutation_subject__' ? varTerm('a0') : varTerm(trav.from);\n const traversalTriple = tripleOf(\n fromTerm,\n // The declared `sh:path`, like every other predicate — not the property\n // shape's own IRI, which identifies the description of the property.\n resolvePropertyPredicateTerm(trav.property),\n varTerm(trav.to),\n );\n // The edge binds the target variable; each dependent leaf property is a\n // nested OPTIONAL within that scope, so a missing leaf does not drop the\n // group while an absent edge leaves every leaf variable unbound.\n let travNode: SparqlAlgebraNode = {type: 'bgp', triples: [traversalTriple]};\n for (const leaf of travAnchoredByTo.get(trav.to) ?? []) {\n travNode = {\n type: 'left_join',\n left: travNode,\n right: {type: 'bgp', triples: [leaf]},\n };\n }\n whereAlgebra = {type: 'left_join', left: whereAlgebra, right: travNode};\n }\n }\n\n // Owned-subtree cascade OPTIONALs for replaced `contains` properties.\n for (const optional of result.cascadeOptionals) {\n whereAlgebra = {type: 'left_join', left: whereAlgebra, right: optional};\n }\n\n // Add BIND expressions for computed fields\n for (const ext of result.extends) {\n whereAlgebra = {\n type: 'extend',\n inner: whereAlgebra,\n variable: ext.variable,\n expression: ext.expression,\n };\n }\n\n return {\n type: 'delete_insert',\n deletePatterns: result.deletePatterns,\n insertPatterns: result.insertPatterns,\n whereAlgebra,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Ask conversion\n// ---------------------------------------------------------------------------\n\n/**\n * Converts an {@link IRAskQuery} to a {@link SparqlAskPlan}.\n *\n * Two cases:\n *\n * - **Rootless** (no shape scan) — a bare subject, emitted as `<iri> ?p ?o`. This\n * is \"does a node with this IRI exist at all\", with no `rdf:type` constraint.\n * - **Shaped** — the pattern is built by {@link selectToAlgebra}, so shape scans,\n * traversals, filters and `MINUS` have exactly one implementation. Only the\n * pattern is kept; the select plan's projection is discarded.\n *\n * `IRAskQuery` has no projection, `orderBy`, `limit` or `offset` to ignore or\n * reject — an `ASK` cannot express them, so the IR cannot carry them. The one\n * thing that *does* need guarding is an aggregate in the where clause, which\n * lowers to `GROUP BY` + `HAVING` rather than to a `FILTER`; see below.\n */\nexport function askToAlgebra(\n query: IRAskQuery,\n options?: SparqlOptions,\n): SparqlAskPlan {\n if (!query.root) {\n if (!query.subjectId) {\n throw new Error(\n 'askToAlgebra: a shapeless ask needs a subject — there is no shape to scan ' +\n 'and no subject to test, so the query matches every node in the store.',\n );\n }\n // ASK { <iri> ?p ?o } — existence of the node itself, under any type or none.\n const bgp: SparqlBGP = {\n type: 'bgp',\n triples: [\n tripleOf(iriTerm(query.subjectId), varTerm('p'), varTerm('o')),\n ],\n };\n return {type: 'ask', algebra: bgp};\n }\n const inner = selectToAlgebra(\n {\n kind: 'select',\n root: query.root,\n patterns: query.patterns,\n projection: [],\n where: query.where,\n subjectId: query.subjectId,\n subjectIds: query.subjectIds,\n },\n options,\n );\n if (inner.having) {\n // Same trap as in `countToAlgebra`: an aggregate in the WHERE clause (e.g.\n // `p.friends.size().gt(2)`) lowers to HAVING + GROUP BY on the select plan, and\n // only `algebra` is carried over here — so the HAVING would vanish and the ASK\n // would answer the UNFILTERED question, `true` for any store holding one\n // instance of the shape. A boolean of the right type for the wrong question is\n // worse than an error: nothing downstream can tell. Asking it properly needs\n // `ASK { SELECT ?a0 WHERE { … } GROUP BY ?a0 HAVING(…) }`, and `SparqlSubSelect`\n // carries no groupBy/having today. Refuse it rather than answer it wrongly.\n throw new Error(\n 'Cannot ask a query whose where clause contains an aggregate (e.g. ' +\n '`.where(p => p.friends.size().gt(2))`). That filter lowers to HAVING over a ' +\n 'per-subject group, and testing whether any group survives needs a nested ' +\n 'sub-SELECT that this layer does not emit yet. Filter without an aggregate, or ' +\n 'run the select and check for rows.',\n );\n }\n return {type: 'ask', algebra: inner.algebra};\n}\n\n/**\n * Converts an {@link IRCountQuery} to a {@link SparqlSelectPlan} shaped as a\n * root-level count:\n *\n * ```sparql\n * SELECT (COUNT(DISTINCT ?a0) AS ?count) WHERE { … }\n * ```\n *\n * The **pattern** is built by {@link selectToAlgebra}, so shape scans, traversals,\n * filters and `MINUS` have exactly one implementation; only the pattern is kept and\n * the select plan's projection is discarded. That discard is load-bearing:\n * `selectToAlgebra` unconditionally projects the root alias as a plain variable, and\n * then makes every plain projected variable a `GROUP BY` target once an aggregate is\n * present — so reusing its projection would yield `SELECT ?a0 (COUNT(…) AS ?count) …\n * GROUP BY ?a0`, one row per entity each counting 1.\n *\n * `DISTINCT` inside the aggregate is likewise load-bearing. A shape scan joined with\n * property triples yields one row per property-value combination (which is why the\n * plain select path emits `SELECT DISTINCT`), so `COUNT(?a0)` would count *rows* and\n * a filter on a multi-valued property would inflate the total. `COUNT(DISTINCT ?a0)`\n * counts subjects, which is what \"how many instances match\" means.\n *\n * There is no `groupBy`, `orderBy`, `limit` or `offset` on the returned plan — and\n * nothing to guard against, because {@link IRCountQuery} cannot carry them.\n */\nexport function countToAlgebra(\n query: IRCountQuery,\n options?: SparqlOptions,\n): SparqlSelectPlan {\n if (!query.root) {\n throw new Error(\n 'countToAlgebra: query.root is undefined. A count needs a shape to scan — a ' +\n 'shapeless count would count every node in the store.',\n );\n }\n const inner = selectToAlgebra(\n {\n kind: 'select',\n root: query.root,\n patterns: query.patterns,\n projection: [],\n where: query.where,\n subjectId: query.subjectId,\n subjectIds: query.subjectIds,\n },\n options,\n );\n if (inner.having) {\n // An aggregate in the WHERE clause (e.g. `p.friends.size().gt(2)`) lowers to\n // HAVING + GROUP BY on the select plan. Only `algebra` is carried over here, so\n // the HAVING would vanish and the count would be of the UNFILTERED match set —\n // a plausible-looking wrong number. Counting a HAVING-filtered group set needs\n // `SELECT (COUNT(DISTINCT ?a0) AS ?count) WHERE { SELECT ?a0 WHERE { … }\n // GROUP BY ?a0 HAVING(…) }`, and `SparqlSubSelect` carries no groupBy/having\n // today. Refuse it rather than answer it wrongly.\n throw new Error(\n 'Cannot count a query whose where clause contains an aggregate (e.g. ' +\n '`.where(p => p.friends.size().gt(2))`). That filter lowers to HAVING over a ' +\n 'per-subject group, and counting the surviving groups needs a nested ' +\n 'sub-SELECT that this layer does not emit yet. Filter without an aggregate, or ' +\n 'count the rows of the select.',\n );\n }\n const aggregate: SparqlAggregateExpr = {\n kind: 'aggregate_expr',\n name: 'count',\n args: [{kind: 'variable_expr', name: query.root.alias}],\n distinct: true,\n };\n return {\n type: 'select',\n algebra: inner.algebra,\n projection: [{kind: 'aggregate', expression: aggregate, alias: query.alias}],\n aggregates: [{variable: query.alias, aggregate}],\n };\n}\n\n// ---------------------------------------------------------------------------\n// Convenience wrappers: IR → algebra → SPARQL string in one call\n// ---------------------------------------------------------------------------\n\n/**\n * Converts an IRSelectQuery to a SPARQL string.\n */\nexport function selectToSparql(\n query: IRSelectQuery,\n options?: SparqlOptions,\n): string {\n const plan = selectToAlgebra(query, options);\n return selectPlanToSparql(plan, options);\n}\n\n/**\n * Converts an {@link IRAskQuery} to a SPARQL `ASK` string.\n */\nexport function askToSparql(\n query: IRAskQuery,\n options?: SparqlOptions,\n): string {\n const plan = askToAlgebra(query, options);\n return askPlanToSparql(plan, options);\n}\n\n/**\n * Converts an {@link IRCountQuery} to a SPARQL `SELECT (COUNT(DISTINCT …) AS …)`\n * string, through the same {@link selectPlanToSparql} every select uses.\n */\nexport function countToSparql(\n query: IRCountQuery,\n options?: SparqlOptions,\n): string {\n const plan = countToAlgebra(query, options);\n return selectPlanToSparql(plan, options);\n}\n\n/**\n * Converts an IRCreateMutation to a SPARQL string.\n * Stub: will be implemented when algebraToString is available.\n */\nexport function createToSparql(\n query: IRCreateMutation,\n options?: SparqlOptions,\n): string {\n const plan = createToAlgebra(query, options);\n return insertDataPlanToSparql(plan, options);\n}\n\n/**\n * Converts an IRUpdateMutation to a SPARQL string.\n * Stub: will be implemented when algebraToString is available.\n */\nexport function updateToSparql(\n query: IRUpdateMutation,\n options?: SparqlOptions,\n): string {\n const plan = updateToAlgebra(query, options);\n return deleteInsertPlanToSparql(plan, options);\n}\n\n/** Lowers an IRUpsertMutation all the way to a SPARQL update string. */\nexport function upsertToSparql(\n query: IRUpsertMutation,\n options?: SparqlOptions,\n): string {\n const plan = upsertToAlgebra(query, options);\n return deleteInsertPlanToSparql(plan, options);\n}\n\n/**\n * Converts an IRDeleteMutation to a SPARQL string.\n */\nexport function deleteToSparql(\n query: IRDeleteMutation,\n options?: SparqlOptions,\n): string {\n const plan = deleteToAlgebra(query, options);\n return deleteInsertPlanToSparql(plan, options);\n}\n\n/**\n * Converts an IRDeleteAllMutation to a SPARQL string.\n */\nexport function deleteAllToSparql(\n query: IRDeleteAllMutation,\n options?: SparqlOptions,\n): string {\n const plan = deleteAllToAlgebra(query, options);\n return deleteInsertPlanToSparql(plan, options);\n}\n\n/**\n * Converts an IRDeleteWhereMutation to a SPARQL string.\n */\nexport function deleteWhereToSparql(\n query: IRDeleteWhereMutation,\n options?: SparqlOptions,\n): string {\n const plan = deleteWhereToAlgebra(query, options);\n return deleteInsertPlanToSparql(plan, options);\n}\n\n/**\n * Converts an IRUpdateWhereMutation to a SPARQL string.\n */\nexport function updateWhereToSparql(\n query: IRUpdateWhereMutation,\n options?: SparqlOptions,\n): string {\n const plan = updateWhereToAlgebra(query, options);\n return deleteInsertPlanToSparql(plan, options);\n}\n"]}