Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/okikio/sparql-client. jsr.io/@okikio/sparql
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844/** * GraphTermType pattern matching inspired by Cypher. * * SPARQL's verbose syntax makes queries hard to read, especially when you're describing * complex graph structures. These pattern helpers let you think in terms of nodes and * relationships instead of raw triples. * * The core idea comes from Cypher (Neo4j's query language). Instead of repeating * `?person foaf:name ?name ; foaf:age ?age`, you describe the node once with all its * properties. Relationships work similarly - you define how nodes connect without * manually writing every triple. * * This is syntactic sugar that generates standard SPARQL triples under the hood. * The benefit is readability - your queries look more like the graph you're querying. * * @module */
import { isTerm as isRdfTerm, namedNode, RDF } from '@okikio/rdf'
import { type PatternValueType, raw, rawPattern, rawTerm, rdfTerm, SPARQL_PATTERN_BRAND, SPARQL_VALUE_BRAND, type SparqlTermType, type SparqlValueType, toPredicateName, toRawString, toVarToken, variable,} from '../sparql.ts'import { exprTermString } from '../utils.ts'
import { type PredicateObjectListType, triple, type TripleObjectType, type TriplePredicateType, triples,} from './triples.ts'
// ============================================================================// Design Philosophy// ============================================================================
/** * Best practice: Use explicit value constructors. * * When building patterns, always use str(), num(), v() etc. for values. * Don't rely on implicit conversion. This makes your intent clear and avoids * ambiguity about whether something is a literal value or a variable name. * * Good: node('person', Person).prop('name', str('Alice')) * Good: node('person', Person).prop('age', num(30)) * Bad: node('person', Person).prop('name', 'Alice') // Unclear intent * * The explicit style makes it obvious what's a value vs. a variable vs. an IRI. */
// ============================================================================// Node Patterns// ============================================================================
/** * Property value for a node. * * Can be a simple triple object (literal, IRI, variable) or another Node for * nested structures. Arrays let you specify multiple values for one property. */export type PropertyAtomicType = TripleObjectType | Node/** One object-pattern property value or a repeated set of property values. */export type PropertyValueType = PropertyAtomicType | PropertyAtomicType[]
/** * Map of property names to values. */export interface NodePropertyMapType { /** Additional keyed values accepted by this standards-compatible structural record. */ [predicate: string]: PropertyValueType}
/** Predicate-preserving property entry used internally by node and edge builders. */interface PropertyEntryType { /** RDF predicate IRI represented by this statement, pattern, or index entry. */ readonly predicate: TriplePredicateType /** Object value emitted for this predicate when the property pattern is serialized. */ value: PropertyValueType}
/** Creates a stable comparison key without changing the predicate's lexical form. */function predicateKey(predicate: TriplePredicateType): string { if (typeof predicate === 'string') return `string:${predicate}` if (isRdfTerm(predicate)) return `iri:${predicate.value}` return `term:${predicate.value}`}
/** * A node in your graph pattern. * * Nodes represent resources - people, places, things. Each node has a variable that will bind to * matching resources in your data. You can specify the node's type (what kind of resource it is) * and properties (facts about it). Properties can be simple values, variables, or other nodes for * nested structures. When you nest nodes, the library generates all necessary triples automatically. * * The pattern gets compiled to SPARQL triples, but you write it in a more intuitive nested structure. * This handles the bookkeeping of variable names and relationships between nodes. You can also nest * relationships within properties to create patterns that combine node and edge metadata. * * @example Basic node * ```ts * const person = node('person', 'foaf:Person') * // Generates: ?person a foaf:Person . * ``` * * @example Node with properties * ```ts * const person = node('person', 'foaf:Person', { * 'foaf:name': v('name'), * 'foaf:age': v('age') * }) * // Generates: * // ?person a foaf:Person . * // ?person foaf:name ?name . * // ?person foaf:age ?age . * ``` * * @example Nested nodes (one level) * ```ts * const product = node('product', 'schema:Product', { * 'schema:name': v('title'), * 'schema:publisher': node('publisher', 'schema:Organization', { * 'rdfs:label': str('Marvel Comics') * }) * }) * // Generates: * // ?product a schema:Product . * // ?product schema:name ?title . * // ?product schema:publisher ?publisher . * // ?publisher a schema:Organization . * // ?publisher rdfs:label "Marvel Comics" . * ``` * * @example Deeply nested nodes (multiple levels) * ```ts * const product = node('product', 'schema:Product', { * 'schema:name': v('title'), * 'schema:publisher': node('publisher', 'schema:Organization', { * 'schema:name': v('pubName'), * 'schema:location': node('location', 'schema:Place', { * 'schema:city': v('city'), * 'schema:country': v('country'), * 'schema:geo': node('geo', 'schema:GeoCoordinates', { * 'schema:latitude': v('lat'), * 'schema:longitude': v('lon') * }) * }) * }) * }) * // Generates all triples for product → publisher → location → geo * ``` * * @example Nesting relationships within properties * ```ts * const person = node('person', 'foaf:Person', { * 'foaf:name': v('name'), * 'foaf:knows': node('friend', 'foaf:Person', { * 'foaf:name': v('friendName') * }) * }) * // You can also use rel() for relationships with metadata: * const personWithRel = node('person', 'foaf:Person') * .prop('foaf:name', v('name')) * .prop('foaf:knows', * rel('person', 'foaf:knows', node('friend', 'foaf:Person')) * .prop('ex:since', date(new Date('2020-01-01'))) * ) * ``` * * @example Multiple nested nodes of the same type * ```ts * const book = node('book', 'schema:Book', { * 'schema:name': v('title'), * 'schema:author': [ * node('author1', 'schema:Person', { 'schema:name': str('Stan Lee') }), * node('author2', 'schema:Person', { 'schema:name': str('Jack Kirby') }) * ] * }) * // Generates triples for book with both authors * ``` * * @example Chain-style building with nested structures * ```ts * const query = select(['?productName', '?publisherName', '?city']) * .where( * node('product', 'schema:Product') * .prop('schema:name', v('productName')) * .prop('schema:publisher', * node('publisher', 'schema:Organization') * .prop('schema:name', v('publisherName')) * .prop('schema:location', * node('location', 'schema:Place') * .prop('schema:city', v('city')) * ) * ) * ) * ``` */export class Node implements PatternValueType { /** Compile-time brand that prevents unrelated values from satisfying the SPARQL value contract structurally. */ readonly [SPARQL_VALUE_BRAND] = true as const /** Compile-time brand that marks values that can be emitted as SPARQL graph patterns. */ readonly [SPARQL_PATTERN_BRAND] = true as const
/** Converts the supplied subject input into a validated SPARQL subject term. */ readonly subjectTerm: SparqlTermType /** Returns the variable name without its optional leading question mark. */ private readonly varName: string /** Builds the RDF type term or expression used by the object-pattern helpers. */ private readonly typesTerm: TriplePredicateType[] = [] /** Property records or property definitions owned by this model. */ private readonly properties: PropertyEntryType[] = []
// Fluent getters for natural chaining /** Fluent no-op alias that keeps natural-language Node chains on the same immutable pattern object. */ get is(): this { return this } /** Fluent no-op alias used to continue Node property/type chains without changing semantics. */ get with(): this { return this } /** Fluent no-op alias used to join consecutive Node clauses without allocating another wrapper. */ get and(): this { return this } /** Fluent no-op alias used by natural-language Node chains before a following predicate operation. */ get that(): this { return this } /** Fluent no-op alias used by natural-language Node chains before adding another property. */ get has(): this { return this }
/** Creates a variable-backed graph-pattern node and normalizes optional type/property seeds into predicate-preserving entries. */ constructor( subject: string | SparqlTermType, type?: TriplePredicateType | TriplePredicateType[], options?: NodePropertyMapType, ) { const subjectString = toVarToken(subject)
this.varName = subjectString this.subjectTerm = variable(subjectString)
if (type) { if (Array.isArray(type)) { this.typesTerm.push(...type) } else { this.typesTerm.push(type) } }
if (options) { for (const [key, value] of Object.entries(options)) { this.prop(key, value) } } }
/** Creates a variable-backed node using the fluent object-pattern API. */ static create( name: string, type?: TriplePredicateType | TriplePredicateType[], options?: NodePropertyMapType, ): Node { return new Node(name, type, options) }
/** * Get the variable term for this node. * * Use this when you need to reference the node as an object in another triple. * For example, when connecting two nodes with a relationship. */ term(): SparqlTermType { return this.subjectTerm }
/** * Add an rdf:type to this node. * * Types indicate what kind of resource this is. A node can have multiple types * (someone can be both a Person and an Author). * * @example * ```ts * node('person').a('foaf:Person').a('schema:Author') * ``` */ a(typeIri: TriplePredicateType): this { this.typesTerm.push(typeIri) return this }
/** Alias for {@link a} with more explicit naming. */ type(typeIri: TriplePredicateType): this { this.a(typeIri) return this }
/** * Add multiple types at once. * * @example * ```ts * node('item').types(['schema:Product', 'schema:CreativeWork']) * ``` */ types(typesIri: TriplePredicateType[]): this { for (const typeIri of typesIri) { this.a(typeIri) } return this }
/** * Add a property to this node. * * Properties describe facts about the resource. The value can be a literal, * variable, IRI, or even another node for nested structures. Arrays let you * specify multiple values for one property. * * If you call prop() multiple times with the same predicate, the values * accumulate - you'll get multiple triples with that predicate. * * @example Single value * ```ts * node('person').prop('foaf:name', v('name')) * ``` * * @example Multiple values * ```ts * node('person').prop('foaf:nick', ['Spidey', 'Web-Head']) * ``` * * @example Nested node * ```ts * node('product').prop('schema:publisher', node('publisher', 'schema:Organization')) * ``` */ prop(predicate: TriplePredicateType, value: PropertyValueType): this { const key = predicateKey(predicate) const entry = this.properties.find((item) => predicateKey(item.predicate) === key)
if (!entry) { this.properties.push({ predicate, value }) return this }
const existing = entry.value if (Array.isArray(existing)) { entry.value = Array.isArray(value) ? [...existing, ...value] : [...existing, value] } else { entry.value = Array.isArray(value) ? [existing, ...value] : [existing, value] } return this }
/** * Add multiple properties at once. * * Convenient when you have several properties to set. Just pass an object * where keys are predicates and values are objects. * * @example * ```ts * node('person').props({ * 'foaf:name': v('name'), * 'foaf:age': v('age'), * 'foaf:email': v('email') * }) * ``` */ props(map: NodePropertyMapType): this { for (const [key, value] of Object.entries(map)) { this.prop(key, value) } return this }
/** * Build the SPARQL pattern for this node. * * Recursively processes this node and any nested nodes, generating all the * necessary triples. The visited set prevents infinite recursion if there * are circular references. */ private buildPatternInternal(visited: Set<Node>): string { if (visited.has(this)) return '' visited.add(this)
const pairs: PredicateObjectListType = [] const nested: string[] = []
for (const type of this.typesTerm) { const object = typeof type === 'string' ? rawTerm(type) : type pairs.push([namedNode(RDF.type), object]) }
const push = (predicate: TriplePredicateType, atomic: PropertyAtomicType): void => { let object: TripleObjectType if (atomic instanceof Node) { object = atomic.term() const value = atomic.buildPatternInternal(visited) if (value.trim()) nested.push(value) } else { object = atomic } pairs.push([predicate, object]) }
for (const entry of this.properties) { const values = Array.isArray(entry.value) ? entry.value : [entry.value] for (const value of values) push(entry.predicate, value) }
const self = pairs.length === 0 ? '' : triples(this.subjectTerm, pairs).value return [self, ...nested].filter((value) => value.trim()).join('\n') }
/** * Get the full SPARQL pattern as a SparqlValueType. * * Call this to get the complete pattern including all nested nodes. */ pattern(): PatternValueType { const visited = new Set<Node>() const text = this.buildPatternInternal(visited) return rawPattern(text) }
/** * Get the SPARQL pattern string. * * This implements SparqlValueType.value, which means you can pass Node objects * directly to query builder methods that expect SparqlValueType. * * ⚠️ Warning: This returns the full pattern, not just the variable. If you * want to use this node as an object in a triple, call term() instead. */ get value(): string { return this.pattern().value }
/** Returns the canonical `?name` token used to reference this node in legacy/helper integrations. */ getVarName(): string { return this.varName }}
// ============================================================================// Relationship Patterns// ============================================================================
/** * Properties on a relationship. * * Like nodes, relationships can have properties too. This is called reification * in RDF - treating the edge itself as a resource with facts about it. */export interface RelationshipPropertyMapType { /** Additional keyed values accepted by this standards-compatible structural record. */ [predicate: string]: PropertyValueType}
/** * A relationship between two nodes. * * Relationships describe how nodes connect. In the simplest case, a relationship is just an edge * between two nodes with a predicate. But you can also add properties to the relationship itself * (metadata about the connection) and nest relationships with full node structures. When you pass * Node objects as the from/to arguments, the library automatically generates all necessary triples * for those nodes plus the connecting edge. * * When you add properties to a relationship, it uses RDF reification to represent the edge as a * resource. This lets you attach information like timestamps, confidence scores, or provenance data * to connections. You can also nest nodes within relationships to create patterns where both the * nodes and their connection have detailed structures. * * @example Simple relationship * ```ts * rel('person', 'foaf:knows', 'friend') * // Generates: ?person foaf:knows ?friend . * ``` * * @example Relationship with metadata * ```ts * rel('person', 'foaf:knows', 'friend') * .prop('rel:since', date(new Date('2020-01-01'))) * .prop('rel:confidence', num(0.95)) * // Generates: * // ?person foaf:knows ?friend . * // _:edge_xyz a rdf:Statement ; * // rdf:subject ?person ; * // rdf:predicate foaf:knows ; * // rdf:object ?friend ; * // rel:since "2020-01-01"^^xsd:date ; * // rel:confidence 0.95 . * ``` * * @example Relationship between nested nodes * ```ts * rel( * node('person', 'foaf:Person', { * 'foaf:name': v('personName'), * 'foaf:age': v('personAge') * }), * 'foaf:knows', * node('friend', 'foaf:Person', { * 'foaf:name': v('friendName'), * 'foaf:age': v('friendAge') * }) * ) * // Generates: * // ?person a foaf:Person . * // ?person foaf:name ?personName . * // ?person foaf:age ?personAge . * // ?friend a foaf:Person . * // ?friend foaf:name ?friendName . * // ?friend foaf:age ?friendAge . * // ?person foaf:knows ?friend . * ``` * * @example Relationship with nested nodes and metadata * ```ts * rel( * node('employee', 'org:Employee', { * 'foaf:name': v('empName'), * 'org:department': v('dept') * }), * 'org:reportsTo', * node('manager', 'org:Manager', { * 'foaf:name': v('mgrName'), * 'org:level': num(5) * }) * ) * .prop('org:since', date(new Date('2023-01-01'))) * .prop('org:directReport', bool(true)) * // Generates all node triples, the relationship triple, and reification with metadata * ``` * * @example Chain-style relationship building * ```ts * const pattern = select(['?person', '?friend', '?friendCity']) * .where( * rel( * node('person', 'foaf:Person') * .prop('foaf:name', v('personName')), * 'foaf:knows', * node('friend', 'foaf:Person') * .prop('foaf:name', v('friendName')) * .prop('schema:city', v('friendCity')) * ) * .prop('ex:closeness', v('score')) * .prop('ex:since', v('friendshipDate')) * ) * .filter(v('score').gte(0.8)) * ``` * * @example Multiple relationships from one node * ```ts * const person = node('person', 'foaf:Person', { * 'foaf:name': v('name') * }) * * const friend1Rel = rel(person, 'foaf:knows', node('friend1', 'foaf:Person')) * .prop('ex:closeness', num(0.9)) * * const friend2Rel = rel(person, 'foaf:knows', node('friend2', 'foaf:Person')) * .prop('ex:closeness', num(0.7)) * * select(['?name', '?friend1', '?friend2']) * .where(person) * .where(friend1Rel) * .where(friend2Rel) * ``` */export class Relationship implements PatternValueType { /** Compile-time brand that prevents unrelated values from satisfying the SPARQL value contract structurally. */ readonly [SPARQL_VALUE_BRAND] = true as const /** Compile-time brand that marks values that can be emitted as SPARQL graph patterns. */ readonly [SPARQL_PATTERN_BRAND] = true as const
/** Converts an RDF/JS term into the corresponding SPARQL value wrapper. */ private readonly fromTerm: SparqlTermType /** Converts a SPARQL term wrapper back to an RDF/JS term when representable. */ private readonly toTerm: SparqlTermType /** RDF predicate IRI represented by this statement, pattern, or index entry. */ private readonly predicate: TriplePredicateType /** Property records or property definitions owned by this model. */ private readonly properties: PropertyEntryType[] = []
/** Fluent no-op alias used to continue relationship metadata chains on the same pattern. */ get with(): this { return this } /** Fluent no-op alias used to join relationship metadata clauses without changing the RDF statement. */ get and(): this { return this } /** Fluent no-op alias retained for natural-language relationship chaining. */ get that(): this { return this } /** Fluent no-op alias used before attaching another reified relationship property. */ get has(): this { return this }
/** Captures caller endpoints as SPARQL terms and preserves the predicate term without flattening RDF IRIs to strings. */ constructor( from: Node | string | SparqlTermType, predicate: TriplePredicateType, to: Node | string | SparqlTermType, ) { if (from instanceof Node) { this.fromTerm = from.term() } else { this.fromTerm = variable(toVarToken(from)) }
if (to instanceof Node) { this.toTerm = to.term() } else { this.toTerm = variable(toVarToken(to)) }
this.predicate = predicate }
/** Creates a relationship between two variable-backed nodes using the supplied predicate term. */ static create( fromVar: string, predicate: TriplePredicateType, toVar: string, ): Relationship { return new Relationship(fromVar, predicate, toVar) }
/** * Add a property to this relationship. * * When you add properties, the relationship gets reified (represented as a * blank node with rdf:Statement type). This lets you attach metadata to * the connection itself. * * @example Timestamp on relationship * ```ts * rel('person', 'knows', 'friend').prop('timestamp', dateTime(new Date())) * ``` */ prop(predicate: TriplePredicateType, value: PropertyValueType): this { const key = predicateKey(predicate) const entry = this.properties.find((item) => predicateKey(item.predicate) === key) if (!entry) { this.properties.push({ predicate, value }) return this } const existing = entry.value entry.value = Array.isArray(existing) ? (Array.isArray(value) ? [...existing, ...value] : [...existing, value]) : (Array.isArray(value) ? [existing, ...value] : [existing, value]) return this }
/** * Add multiple properties at once. * * Convenient when you have several properties to set. Just pass an object * where keys are predicates and values are objects. */ props(map: RelationshipPropertyMapType): this { for (const [key, value] of Object.entries(map)) { this.prop(key, value) } return this }
/** * Generate deterministic ID for reified edge. * * Uses a simple hash of the subject-predicate-object to create a stable * blank node identifier. Same relationship always gets the same ID. */ private getEdgeId(): string { const predicate = isRdfTerm(this.predicate) ? rdfTerm(this.predicate) : toPredicateName(toRawString(this.predicate)) const hash = simpleHash( `${toVarToken(this.fromTerm)}|${predicate}|${exprTermString(this.toTerm)}`, ) return `_:edge_${hash}` }
/** * Build the triples for this relationship. * * If there are no properties, just generates the basic triple. If there are * properties, generates the triple plus a reification structure. */ private buildTriples(): SparqlValueType { const base = triple(this.fromTerm, this.predicate, this.toTerm)
if (this.properties.length === 0) { return base }
// Reify with properties const edgeId = this.getEdgeId() const poList: PredicateObjectListType = [ [namedNode(RDF.type), namedNode(RDF.statement)], [namedNode(RDF.subject), this.fromTerm], [ namedNode(RDF.predicate), typeof this.predicate === 'string' ? rawTerm(this.predicate) : this.predicate, ], [namedNode(RDF.object), this.toTerm], ] for (const entry of this.properties) { const values = Array.isArray(entry.value) ? entry.value : [entry.value] for (const value of values) { if (value instanceof Node) { throw new TypeError('Relationship metadata cannot contain a nested Node value.') } poList.push([entry.predicate, value]) } }
const edgeTriples = triples(rawTerm(edgeId), poList)
return rawPattern(`${base.value}\n ${edgeTriples.value}`) }
/** Serializes this relationship pattern using the same value contract consumed by SPARQL builders. */ get value(): string { return this.buildTriples().value }}
// ============================================================================// Convenience Functions// ============================================================================
/** * Create a node pattern. * * Convenience function for creating Node instances. Lets you quickly define * graph patterns without the `new` keyword. * * @param name Variable name for this node (without ? prefix) * @param type Optional RDF type(s) for the node * @param options Optional property map * * @example * ```ts * const person = node('person', 'foaf:Person') * .prop('foaf:name', v('name')) * .prop('foaf:age', v('age')) * ``` */export function node( name: string, type?: TriplePredicateType | TriplePredicateType[], options?: NodePropertyMapType,): Node { return Node.create(name, type, options)}
/** * Create a relationship pattern. * * Convenience function for creating Relationship instances. Describes how * two nodes connect. * * @param fromVar Source node variable name * @param predicate Relationship type/predicate * @param toVar Target node variable name * * @example * ```ts * const knows = rel('person', 'foaf:knows', 'friend') * ``` */export function rel( fromVar: string, predicate: TriplePredicateType, toVar: string,): Relationship { return Relationship.create(fromVar, predicate, toVar)}
/** * Combine multiple patterns into one. * * Takes several patterns (nodes, relationships, or raw SPARQL) and combines * them into a single pattern. Useful for building complex graph structures. * * @example * ```ts * const pattern = match( * node('person', 'foaf:Person').prop('name', v('name')), * rel('person', 'foaf:knows', 'friend'), * node('friend', 'foaf:Person') * ) * ``` */export function match( ...patterns: Array<Node | Relationship | SparqlValueType>): SparqlValueType { const built = patterns.map((p) => p.value) return raw(`${built.join('\n ')}`)}
/** * Simple string hash for generating IDs. * * Uses a basic hash algorithm to create deterministic IDs from strings. * Not cryptographically secure, but fine for generating blank node identifiers. */export function simpleHash(str: string): string { let hash = 0 for (let i = 0; i < str.length; i++) { const char = str.charCodeAt(i) hash = ((hash << 5) - hash) + char hash = hash & hash } return Math.abs(hash).toString(36)}