@_linked/core 2.36.1 → 2.36.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -0
- package/README.md +19 -0
- package/lib/esm/collections/CoreSet.js +2 -0
- package/lib/esm/collections/CoreSet.js.map +1 -1
- package/lib/esm/collections/ShapeSet.js +2 -0
- package/lib/esm/collections/ShapeSet.js.map +1 -1
- package/lib/esm/expressions/Expr.js +3 -2
- package/lib/esm/expressions/Expr.js.map +1 -1
- package/lib/esm/expressions/ExpressionNode.js +10 -7
- package/lib/esm/expressions/ExpressionNode.js.map +1 -1
- package/lib/esm/index.d.ts +1 -1
- package/lib/esm/index.js +1 -1
- package/lib/esm/index.js.map +1 -1
- package/lib/esm/queries/AskBuilder.js +5 -3
- package/lib/esm/queries/AskBuilder.js.map +1 -1
- package/lib/esm/queries/CountBuilder.js +4 -2
- package/lib/esm/queries/CountBuilder.js.map +1 -1
- package/lib/esm/queries/CreateBuilder.js +2 -0
- package/lib/esm/queries/CreateBuilder.js.map +1 -1
- package/lib/esm/queries/DeleteBuilder.js +3 -1
- package/lib/esm/queries/DeleteBuilder.js.map +1 -1
- package/lib/esm/queries/DslJsonExpression.js +7 -6
- package/lib/esm/queries/DslJsonExpression.js.map +1 -1
- package/lib/esm/queries/FieldSet.js +10 -8
- package/lib/esm/queries/FieldSet.js.map +1 -1
- package/lib/esm/queries/IRLower.js +2 -1
- package/lib/esm/queries/IRLower.js.map +1 -1
- package/lib/esm/queries/MutationSerialization.js +2 -1
- package/lib/esm/queries/MutationSerialization.js.map +1 -1
- package/lib/esm/queries/PropertyPath.js +2 -0
- package/lib/esm/queries/PropertyPath.js.map +1 -1
- package/lib/esm/queries/ProxiedPathBuilder.js +2 -1
- package/lib/esm/queries/ProxiedPathBuilder.js.map +1 -1
- package/lib/esm/queries/QueryBuilder.js +5 -4
- package/lib/esm/queries/QueryBuilder.js.map +1 -1
- package/lib/esm/queries/QueryContext.js +17 -6
- package/lib/esm/queries/QueryContext.js.map +1 -1
- package/lib/esm/queries/SelectQuery.js +18 -12
- package/lib/esm/queries/SelectQuery.js.map +1 -1
- package/lib/esm/queries/UpdateBuilder.js +3 -1
- package/lib/esm/queries/UpdateBuilder.js.map +1 -1
- package/lib/esm/queries/lower.js +5 -4
- package/lib/esm/queries/lower.js.map +1 -1
- package/lib/esm/shapes/SHACL.js +6 -3
- package/lib/esm/shapes/SHACL.js.map +1 -1
- package/lib/esm/shapes/Shape.d.ts +3 -1
- package/lib/esm/shapes/Shape.js +20 -2
- package/lib/esm/shapes/Shape.js.map +1 -1
- package/lib/esm/utils/LinkedErrorLogging.d.ts +2 -1
- package/lib/esm/utils/LinkedErrorLogging.js +11 -0
- package/lib/esm/utils/LinkedErrorLogging.js.map +1 -1
- package/lib/esm/utils/LinkedFileStorage.d.ts +6 -4
- package/lib/esm/utils/LinkedFileStorage.js +34 -4
- package/lib/esm/utils/LinkedFileStorage.js.map +1 -1
- package/lib/esm/utils/Package.d.ts +6 -0
- package/lib/esm/utils/Package.js +35 -7
- package/lib/esm/utils/Package.js.map +1 -1
- package/lib/esm/utils/Prefix.d.ts +4 -2
- package/lib/esm/utils/Prefix.js +18 -2
- package/lib/esm/utils/Prefix.js.map +1 -1
- package/lib/esm/utils/ShapeClass.js +11 -6
- package/lib/esm/utils/ShapeClass.js.map +1 -1
- package/lib/esm/utils/cached.js +2 -1
- package/lib/esm/utils/cached.js.map +1 -1
- package/lib/esm/utils/linkedError.d.ts +32 -0
- package/lib/esm/utils/linkedError.js +63 -0
- package/lib/esm/utils/linkedError.js.map +1 -1
- package/lib/esm/utils/unresolvedShape.d.ts +3 -1
- package/lib/esm/utils/unresolvedShape.js +5 -1
- package/lib/esm/utils/unresolvedShape.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MutationSerialization.js","sourceRoot":"","sources":["../../../src/queries/MutationSerialization.ts"],"names":[],"mappings":"AAAA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CAAC,CAAC,gBAAgB,CAAC,SAAS,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QACtE,GAAG,CAAC,GAAG,CAAC,GAAG,gBAAgB,CAAC,GAAwB,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;IACzE,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["/*\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\n\n/**\n * Lossless JSON (de)serialization for mutations (create / update / delete) — the\n * **IR-free wire codec**. The companion IR side (`decodeNodeData` / `lowerMutationJSON`)\n * lives in `lowerMutationJSON.ts` so this module never pulls the canonical-IR pipeline.\n *\n * The serialization unit is the normalized `NodeDescriptionValue` produced by the\n * IR-free factory base (`MutationQueryFactory.describe()`) — i.e. after `.set()` and\n * after any update-expression callback has been evaluated, but before canonical IR.\n * Property keys are serialized as **labels** (shape-relative, lightweight); decoding\n * resolves them back via the registered shape.\n *\n * Values use the DSL-JSON grammar (documentation/dsl-json.md): a bare scalar is a\n * literal; objects tag the kinds `JSON.stringify` can't represent natively\n * (`{@date}`, `{@id}`, `{@ctx}`, `{@list}`, `{@add,@remove}`, `{@unset}`); and a\n * computed value is an S-expr array via the shared `DslJsonExpression` codec —\n * so the wire carries no IR.\n */\nimport {\n type NodeDescriptionValue,\n type NodeReferenceValue,\n type PropUpdateValue,\n type SetModificationValue,\n type SinglePropertyUpdateValue,\n isSetModificationValue,\n} from './QueryFactory.js';\nimport {getPropertyShape} from '../shapes/nodeShapeData.js';\nimport {ExpressionNode, isExpressionNode} from '../expressions/ExpressionNode.js';\nimport type {WherePathJSON} from './QueryBuilderSerialization.js';\nimport type {ContextRefJSON} from './ContextRef.js';\nimport {PendingQueryContext} from './QueryContext.js';\nimport {resolveShapeConstructor, getQueryShapeClass} from '../utils/ShapeClass.js';\nimport type {ShapeConstructor} from '../shapes/Shape.js';\nimport type {NodeShapeData, PropertyShapeData} from '../shapes/SHACL.js';\nimport {\n encodeValueExpr,\n decodeValueExpr,\n type DslJsonValue,\n} from './DslJsonExpression.js';\n\n// =============================================================================\n// JSON types\n// =============================================================================\n\n/**\n * A mutation field value in the DSL-JSON grammar. A bare scalar is a literal; objects\n * tag the non-JSON-native kinds (`@`-sigiled); a computed value is an S-expr array (no IR); a\n * nested-node create is a bare path-keyed object ({@link MutationNodeDataJSON}),\n * disambiguated from the tagged forms by having no reserved value-key.\n */\nexport type MutationValueJSON =\n | string\n | number\n | boolean\n | null\n | {'@date': string}\n | {'@id': string}\n | {'@ctx': string}\n | {'@list': MutationValueJSON[]}\n | {'@add'?: MutationValueJSON[]; '@remove'?: string[]}\n | {'@unset': true}\n | MutationNodeDataJSON // nested-node create (bare, path-keyed)\n | DslJsonValue; // computed expression (S-expr) / {@path}\n\n/**\n * A node description in **path-keyed** form: `label → value`, plus two reserved\n * keys — `__id` (a fixed/predefined id) and `__shape` (the concrete shape IRI,\n * emitted only when it differs from the shape inferred from context, e.g. a\n * subclass instance under a superclass-typed relation). Whether a nested node is\n * written as a blank node is not on the wire: the lowering decides it from the\n * property's `sh:nodeKind`.\n */\nexport type MutationNodeDataJSON = {\n [key: string]: MutationValueJSON | undefined;\n};\n\n/** Reserved node-data keys (not property labels). */\nconst NODE_ID_KEY = '__id';\nconst NODE_SHAPE_KEY = '__shape';\n\nexport type CreateMutationJSON = {\n v?: string;\n op: 'create';\n shape: string;\n data: MutationNodeDataJSON;\n};\n\nexport type UpdateMutationJSON = {\n v?: string;\n op: 'update';\n shape: string;\n mode: 'for' | 'forAll' | 'where';\n /** A node id, or a `{@ctx: name}` context reference resolved at lowering. */\n targetId?: string | ContextRefJSON;\n where?: WherePathJSON;\n data: MutationNodeDataJSON;\n};\n\n/**\n * Create-or-replace against a known id.\n *\n * A distinct `op` rather than `op: 'update'` with a new `mode`. An unaware consumer that\n * received `{op: 'update', mode: 'upsert'}` would fall past its `mode === 'for'` and\n * `mode === 'where'` branches into the update-where path with no where clause — an update\n * applied to *every instance of the shape*. A distinct op instead hits `fromJSON`'s\n * existing `default:` and throws \"Unknown query op\": loud, and safe.\n */\nexport type UpsertMutationJSON = {\n v?: string;\n op: 'upsert';\n shape: string;\n /** Upsert targets one known id; there is no `forAll`/`where` form. */\n mode: 'for';\n /** A node id, or a `{@ctx: name}` context reference resolved at lowering. */\n targetId?: string | ContextRefJSON;\n data: MutationNodeDataJSON;\n};\n\nexport type DeleteMutationJSON =\n | {v?: string; op: 'delete'; shape: string; mode: 'ids'; ids: (string | ContextRefJSON)[]}\n | {v?: string; op: 'delete'; shape: string; mode: 'all'}\n | {v?: string; op: 'delete'; shape: string; mode: 'where'; where: WherePathJSON};\n\nexport type MutationJSON =\n | CreateMutationJSON\n | UpdateMutationJSON\n | UpsertMutationJSON\n | DeleteMutationJSON;\n\n// =============================================================================\n// Value codec\n// =============================================================================\n\n/** The shape a nested node is expected to have (a property's value shape), if resolvable. */\nexport function valueShapeOf(prop?: PropertyShapeData): NodeShapeData | undefined {\n const id = (prop as unknown as {valueShape?: {id: string}})?.valueShape?.id;\n return id ? getQueryShapeClass(id)?.shape : undefined;\n}\n\n/** Encode a single (non-array, non-setMod) property value. `prop` gives the nested-node shape. */\nfunction encodeSingleValue(\n value: SinglePropertyUpdateValue,\n prop?: PropertyShapeData,\n): MutationValueJSON {\n if (value === undefined) return {'@unset': true};\n if (isExpressionNode(value)) {\n // A computed value is an S-expr (or {@path}) via the shared codec — no IR.\n return encodeValueExpr(value.ir, value._refs) as MutationValueJSON;\n }\n if (value instanceof Date) return {'@date': value.toISOString()};\n if (\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ) {\n return value;\n }\n if (value && typeof value === 'object') {\n // Query-context reference — carry the name, resolve at lowering (checked\n // before the generic `.id` branch since a PendingQueryContext has an `.id` getter).\n if (value instanceof PendingQueryContext) {\n return {'@ctx': value.contextName};\n }\n if ('fields' in value) {\n // Nested-node create — bare path-keyed; expected shape = the relation's value shape.\n return encodeNodeData(value as NodeDescriptionValue, valueShapeOf(prop));\n }\n if ('id' in value) return {'@id': (value as NodeReferenceValue).id};\n }\n throw new Error(`Cannot serialize mutation value: ${JSON.stringify(value)}`);\n}\n\n/** Encode any property value, including arrays and set modifications. */\nexport function encodeValue(\n value: PropUpdateValue,\n prop?: PropertyShapeData,\n): MutationValueJSON {\n if (value === undefined) return {'@unset': true};\n if (Array.isArray(value)) {\n return {'@list': value.map((v) => encodeSingleValue(v, prop))};\n }\n if (isSetModificationValue(value)) {\n const mod = value as SetModificationValue;\n const json: {'@add'?: MutationValueJSON[]; '@remove'?: string[]} = {};\n if (mod.$add) json['@add'] = mod.$add.map((v) => encodeValue(v as PropUpdateValue, prop));\n if (mod.$remove) json['@remove'] = mod.$remove.map((r) => r.id);\n return json;\n }\n return encodeSingleValue(value as SinglePropertyUpdateValue, prop);\n}\n\n/**\n * Encode a normalized node description to path-keyed form. `expectedShape` is the\n * shape inferable from context (the envelope, or the parent relation's value shape);\n * `__shape` is emitted only when the concrete shape differs (a subclass instance).\n */\nexport function encodeNodeData(\n desc: NodeDescriptionValue,\n expectedShape?: NodeShapeData,\n): MutationNodeDataJSON {\n const json: MutationNodeDataJSON = {};\n if (desc.__id) json[NODE_ID_KEY] = desc.__id;\n if (!expectedShape || desc.shape.id !== expectedShape.id) {\n json[NODE_SHAPE_KEY] = desc.shape.id;\n }\n for (const f of desc.fields) {\n json[f.prop.label] = encodeValue(f.val, f.prop);\n }\n return json;\n}\n\n// =============================================================================\n// JSON → raw UpdatePartial (for builder rehydration / fromJSON)\n// =============================================================================\n\n// Bound the DSL-JSON decode recursion (rehydration path) against a deeply-nested\n// payload exhausting the stack. Mirrors the cap in lowerMutationJSON.\nconst MAX_DECODE_DEPTH = 128;\nlet _decodeDepth = 0;\n\n/**\n * Decode a DSL-JSON value back to a raw DSL value (the form `.set()` accepts).\n * `currentShape` resolves computed `{@path}`/S-expr; `prop` gives a nested node's shape.\n * Depth-guarded wrapper around {@link decodeValueToRawInner}.\n */\nfunction decodeValueToRaw(\n json: MutationValueJSON,\n currentShape: NodeShapeData | undefined,\n prop?: PropertyShapeData,\n): unknown {\n if (++_decodeDepth > MAX_DECODE_DEPTH) {\n _decodeDepth = 0;\n throw new Error('DSL-JSON value nested too deeply');\n }\n try {\n return decodeValueToRawInner(json, currentShape, prop);\n } finally {\n _decodeDepth--;\n }\n}\n\nfunction decodeValueToRawInner(\n json: MutationValueJSON,\n currentShape: NodeShapeData | undefined,\n prop?: PropertyShapeData,\n): unknown {\n // S-expr computed value\n if (Array.isArray(json)) {\n const {ir, refs} = decodeValueExpr(json as DslJsonValue, requireShapeForExpr(currentShape));\n return new ExpressionNode(ir, refs);\n }\n if (json === null) return null;\n if (typeof json !== 'object') return json; // bare scalar literal\n const o = json as Record<string, unknown>;\n if ('@unset' in o) return undefined;\n if ('@date' in o) return new Date(o['@date'] as string);\n // Rehydration path: preserve the live reference so it re-serializes as a\n // `{@ctx}` marker and resolves at the rebuilt builder's own lowering.\n if ('@ctx' in o) return new PendingQueryContext(o['@ctx'] as string);\n if ('@id' in o) return {id: o['@id']};\n if ('@list' in o) {\n return (o['@list'] as MutationValueJSON[]).map((i) => decodeValueToRaw(i, currentShape, prop));\n }\n if ('@add' in o || '@remove' in o) {\n // Raw DSL set-modifications use `@add`/`@remove` on the wire.\n const mod: {add?: unknown[]; remove?: {id: string}[]} = {};\n if (o['@add']) mod.add = (o['@add'] as MutationValueJSON[]).map((i) => decodeValueToRaw(i, currentShape, prop));\n if (o['@remove']) mod.remove = (o['@remove'] as string[]).map((id) => ({id}));\n return mod;\n }\n // A computed-path value (`{@path}`) used as a value.\n if ('@path' in o) {\n const {ir, refs} = decodeValueExpr(json as DslJsonValue, requireShapeForExpr(currentShape));\n return new ExpressionNode(ir, refs);\n }\n // Otherwise: a bare path-keyed nested-node create.\n return decodeNestedNodeDataToRaw(o as MutationNodeDataJSON, valueShapeOf(prop) ?? currentShape);\n}\n\n/**\n * Decode a nested node and, when it names its concrete shape (`__shape`), carry that\n * shape as the reserved `shape` key `.set()` accepts on a nested value. Without it the\n * builders validate and lower the value against the property's declared value shape —\n * or none, for a polymorphic slot like `PropertyShape.path` — and reject the fields\n * only the concrete shape has.\n */\n/**\n * The class for a node's `__shape`. Either registry — a project-authored shape exists only\n * as metadata. Throws like `lowerMutationJSON` does, so both decode paths reject an\n * unregistered shape instead of one of them silently validating against another.\n */\nfunction requireNodeShapeClass(shapeId: string): ShapeConstructor {\n const shapeClass = resolveShapeConstructor(shapeId);\n if (!shapeClass) {\n throw new Error(\n `Shape '${shapeId}' is not registered. The receiving side must have the shape registered to decode mutation DSL-JSON.`,\n );\n }\n return shapeClass;\n}\n\nfunction decodeNestedNodeDataToRaw(\n json: MutationNodeDataJSON,\n shape: NodeShapeData | undefined,\n): Record<string, unknown> {\n const obj = decodeNodeDataToRaw(json, shape);\n const shapeId = json[NODE_SHAPE_KEY];\n if (typeof shapeId === 'string') obj.shape = requireNodeShapeClass(shapeId);\n return obj;\n}\n\nfunction requireShapeForExpr(shape: NodeShapeData | undefined): NodeShapeData {\n if (!shape) {\n throw new Error('A shape is required to decode a computed mutation value');\n }\n return shape;\n}\n\n/**\n * Decode path-keyed node data into a raw object the mutation builders' `.set()` accepts.\n * `__id` becomes `id`; `__shape` (if present) overrides the inferred `shape`. Mirrors\n * {@link encodeNodeData}.\n */\nexport function decodeNodeDataToRaw(\n json: MutationNodeDataJSON,\n shape?: NodeShapeData,\n): Record<string, unknown> {\n const nodeShape =\n typeof json[NODE_SHAPE_KEY] === 'string'\n ? requireNodeShapeClass(json[NODE_SHAPE_KEY] as string).shape\n : shape;\n const obj: Record<string, unknown> = {};\n if (typeof json[NODE_ID_KEY] === 'string') obj.id = json[NODE_ID_KEY];\n for (const [key, val] of Object.entries(json)) {\n if (key === NODE_ID_KEY || key === NODE_SHAPE_KEY || val === undefined) continue;\n // Skip prototype-polluting keys from untrusted DSL-JSON input.\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;\n const prop = nodeShape ? getPropertyShape(nodeShape, key) : undefined;\n obj[key] = decodeValueToRaw(val as MutationValueJSON, nodeShape, prop);\n }\n return obj;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"MutationSerialization.js","sourceRoot":"","sources":["../../../src/queries/MutationSerialization.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,EAML,sBAAsB,GACvB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAC,gBAAgB,EAAC,MAAM,4BAA4B,CAAC;AAC5D,OAAO,EAAC,cAAc,EAAE,gBAAgB,EAAC,MAAM,kCAAkC,CAAC;AAGlF,OAAO,EAAC,mBAAmB,EAAC,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAC,uBAAuB,EAAE,kBAAkB,EAAC,MAAM,wBAAwB,CAAC;AAGnF,OAAO,EACL,eAAe,EACf,eAAe,GAEhB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAC,gBAAgB,EAAC,MAAM,yBAAyB,CAAC;AAsCzD,qDAAqD;AACrD,MAAM,WAAW,GAAG,MAAM,CAAC;AAC3B,MAAM,cAAc,GAAG,SAAS,CAAC;AAmDjC,gFAAgF;AAChF,cAAc;AACd,gFAAgF;AAEhF,6FAA6F;AAC7F,MAAM,UAAU,YAAY,CAAC,IAAwB;;IACnD,MAAM,EAAE,GAAG,MAAC,IAA+C,aAA/C,IAAI,uBAAJ,IAAI,CAA6C,UAAU,0CAAE,EAAE,CAAC;IAC5E,OAAO,EAAE,CAAC,CAAC,CAAC,MAAA,kBAAkB,CAAC,EAAE,CAAC,0CAAE,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AACxD,CAAC;AAED,kGAAkG;AAClG,SAAS,iBAAiB,CACxB,KAAgC,EAChC,IAAwB;IAExB,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,EAAC,QAAQ,EAAE,IAAI,EAAC,CAAC;IACj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AE,GAAG,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;QAC9C,IAAI,GAAG,KAAK,WAAW,IAAI,GAAG,KAAK,cAAc,IAAI,GAAG,KAAK,SAAS;YAAE,SAAS;QACjF,+DAA+D;QAC/D,IAAI,GAAG,KAAK,WAAW,IAAI,GAAG,KAAK,aAAa,IAAI,GAAG,KAAK,WAAW;YAAE,SAAS;QAClF,MAAM,IAAI,GAAG,SAAS,CAAC,CAAC,CAAC,gBAAgB,CAAC,SAAS,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QACtE,GAAG,CAAC,GAAG,CAAC,GAAG,gBAAgB,CAAC,GAAwB,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;IACzE,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["/*\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\n\n/**\n * Lossless JSON (de)serialization for mutations (create / update / delete) — the\n * **IR-free wire codec**. The companion IR side (`decodeNodeData` / `lowerMutationJSON`)\n * lives in `lowerMutationJSON.ts` so this module never pulls the canonical-IR pipeline.\n *\n * The serialization unit is the normalized `NodeDescriptionValue` produced by the\n * IR-free factory base (`MutationQueryFactory.describe()`) — i.e. after `.set()` and\n * after any update-expression callback has been evaluated, but before canonical IR.\n * Property keys are serialized as **labels** (shape-relative, lightweight); decoding\n * resolves them back via the registered shape.\n *\n * Values use the DSL-JSON grammar (documentation/dsl-json.md): a bare scalar is a\n * literal; objects tag the kinds `JSON.stringify` can't represent natively\n * (`{@date}`, `{@id}`, `{@ctx}`, `{@list}`, `{@add,@remove}`, `{@unset}`); and a\n * computed value is an S-expr array via the shared `DslJsonExpression` codec —\n * so the wire carries no IR.\n */\nimport {\n type NodeDescriptionValue,\n type NodeReferenceValue,\n type PropUpdateValue,\n type SetModificationValue,\n type SinglePropertyUpdateValue,\n isSetModificationValue,\n} from './QueryFactory.js';\nimport {getPropertyShape} from '../shapes/nodeShapeData.js';\nimport {ExpressionNode, isExpressionNode} from '../expressions/ExpressionNode.js';\nimport type {WherePathJSON} from './QueryBuilderSerialization.js';\nimport type {ContextRefJSON} from './ContextRef.js';\nimport {PendingQueryContext} from './QueryContext.js';\nimport {resolveShapeConstructor, getQueryShapeClass} from '../utils/ShapeClass.js';\nimport type {ShapeConstructor} from '../shapes/Shape.js';\nimport type {NodeShapeData, PropertyShapeData} from '../shapes/SHACL.js';\nimport {\n encodeValueExpr,\n decodeValueExpr,\n type DslJsonValue,\n} from './DslJsonExpression.js';\nimport {isLinkedInstance} from '../utils/linkedError.js';\n\n// =============================================================================\n// JSON types\n// =============================================================================\n\n/**\n * A mutation field value in the DSL-JSON grammar. A bare scalar is a literal; objects\n * tag the non-JSON-native kinds (`@`-sigiled); a computed value is an S-expr array (no IR); a\n * nested-node create is a bare path-keyed object ({@link MutationNodeDataJSON}),\n * disambiguated from the tagged forms by having no reserved value-key.\n */\nexport type MutationValueJSON =\n | string\n | number\n | boolean\n | null\n | {'@date': string}\n | {'@id': string}\n | {'@ctx': string}\n | {'@list': MutationValueJSON[]}\n | {'@add'?: MutationValueJSON[]; '@remove'?: string[]}\n | {'@unset': true}\n | MutationNodeDataJSON // nested-node create (bare, path-keyed)\n | DslJsonValue; // computed expression (S-expr) / {@path}\n\n/**\n * A node description in **path-keyed** form: `label → value`, plus two reserved\n * keys — `__id` (a fixed/predefined id) and `__shape` (the concrete shape IRI,\n * emitted only when it differs from the shape inferred from context, e.g. a\n * subclass instance under a superclass-typed relation). Whether a nested node is\n * written as a blank node is not on the wire: the lowering decides it from the\n * property's `sh:nodeKind`.\n */\nexport type MutationNodeDataJSON = {\n [key: string]: MutationValueJSON | undefined;\n};\n\n/** Reserved node-data keys (not property labels). */\nconst NODE_ID_KEY = '__id';\nconst NODE_SHAPE_KEY = '__shape';\n\nexport type CreateMutationJSON = {\n v?: string;\n op: 'create';\n shape: string;\n data: MutationNodeDataJSON;\n};\n\nexport type UpdateMutationJSON = {\n v?: string;\n op: 'update';\n shape: string;\n mode: 'for' | 'forAll' | 'where';\n /** A node id, or a `{@ctx: name}` context reference resolved at lowering. */\n targetId?: string | ContextRefJSON;\n where?: WherePathJSON;\n data: MutationNodeDataJSON;\n};\n\n/**\n * Create-or-replace against a known id.\n *\n * A distinct `op` rather than `op: 'update'` with a new `mode`. An unaware consumer that\n * received `{op: 'update', mode: 'upsert'}` would fall past its `mode === 'for'` and\n * `mode === 'where'` branches into the update-where path with no where clause — an update\n * applied to *every instance of the shape*. A distinct op instead hits `fromJSON`'s\n * existing `default:` and throws \"Unknown query op\": loud, and safe.\n */\nexport type UpsertMutationJSON = {\n v?: string;\n op: 'upsert';\n shape: string;\n /** Upsert targets one known id; there is no `forAll`/`where` form. */\n mode: 'for';\n /** A node id, or a `{@ctx: name}` context reference resolved at lowering. */\n targetId?: string | ContextRefJSON;\n data: MutationNodeDataJSON;\n};\n\nexport type DeleteMutationJSON =\n | {v?: string; op: 'delete'; shape: string; mode: 'ids'; ids: (string | ContextRefJSON)[]}\n | {v?: string; op: 'delete'; shape: string; mode: 'all'}\n | {v?: string; op: 'delete'; shape: string; mode: 'where'; where: WherePathJSON};\n\nexport type MutationJSON =\n | CreateMutationJSON\n | UpdateMutationJSON\n | UpsertMutationJSON\n | DeleteMutationJSON;\n\n// =============================================================================\n// Value codec\n// =============================================================================\n\n/** The shape a nested node is expected to have (a property's value shape), if resolvable. */\nexport function valueShapeOf(prop?: PropertyShapeData): NodeShapeData | undefined {\n const id = (prop as unknown as {valueShape?: {id: string}})?.valueShape?.id;\n return id ? getQueryShapeClass(id)?.shape : undefined;\n}\n\n/** Encode a single (non-array, non-setMod) property value. `prop` gives the nested-node shape. */\nfunction encodeSingleValue(\n value: SinglePropertyUpdateValue,\n prop?: PropertyShapeData,\n): MutationValueJSON {\n if (value === undefined) return {'@unset': true};\n if (isExpressionNode(value)) {\n // A computed value is an S-expr (or {@path}) via the shared codec — no IR.\n return encodeValueExpr(value.ir, value._refs) as MutationValueJSON;\n }\n if (value instanceof Date) return {'@date': value.toISOString()};\n if (\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ) {\n return value;\n }\n if (value && typeof value === 'object') {\n // Query-context reference — carry the name, resolve at lowering (checked\n // before the generic `.id` branch since a PendingQueryContext has an `.id` getter).\n if (isLinkedInstance(value, PendingQueryContext)) {\n return {'@ctx': value.contextName};\n }\n if ('fields' in value) {\n // Nested-node create — bare path-keyed; expected shape = the relation's value shape.\n return encodeNodeData(value as NodeDescriptionValue, valueShapeOf(prop));\n }\n if ('id' in value) return {'@id': (value as NodeReferenceValue).id};\n }\n throw new Error(`Cannot serialize mutation value: ${JSON.stringify(value)}`);\n}\n\n/** Encode any property value, including arrays and set modifications. */\nexport function encodeValue(\n value: PropUpdateValue,\n prop?: PropertyShapeData,\n): MutationValueJSON {\n if (value === undefined) return {'@unset': true};\n if (Array.isArray(value)) {\n return {'@list': value.map((v) => encodeSingleValue(v, prop))};\n }\n if (isSetModificationValue(value)) {\n const mod = value as SetModificationValue;\n const json: {'@add'?: MutationValueJSON[]; '@remove'?: string[]} = {};\n if (mod.$add) json['@add'] = mod.$add.map((v) => encodeValue(v as PropUpdateValue, prop));\n if (mod.$remove) json['@remove'] = mod.$remove.map((r) => r.id);\n return json;\n }\n return encodeSingleValue(value as SinglePropertyUpdateValue, prop);\n}\n\n/**\n * Encode a normalized node description to path-keyed form. `expectedShape` is the\n * shape inferable from context (the envelope, or the parent relation's value shape);\n * `__shape` is emitted only when the concrete shape differs (a subclass instance).\n */\nexport function encodeNodeData(\n desc: NodeDescriptionValue,\n expectedShape?: NodeShapeData,\n): MutationNodeDataJSON {\n const json: MutationNodeDataJSON = {};\n if (desc.__id) json[NODE_ID_KEY] = desc.__id;\n if (!expectedShape || desc.shape.id !== expectedShape.id) {\n json[NODE_SHAPE_KEY] = desc.shape.id;\n }\n for (const f of desc.fields) {\n json[f.prop.label] = encodeValue(f.val, f.prop);\n }\n return json;\n}\n\n// =============================================================================\n// JSON → raw UpdatePartial (for builder rehydration / fromJSON)\n// =============================================================================\n\n// Bound the DSL-JSON decode recursion (rehydration path) against a deeply-nested\n// payload exhausting the stack. Mirrors the cap in lowerMutationJSON.\nconst MAX_DECODE_DEPTH = 128;\nlet _decodeDepth = 0;\n\n/**\n * Decode a DSL-JSON value back to a raw DSL value (the form `.set()` accepts).\n * `currentShape` resolves computed `{@path}`/S-expr; `prop` gives a nested node's shape.\n * Depth-guarded wrapper around {@link decodeValueToRawInner}.\n */\nfunction decodeValueToRaw(\n json: MutationValueJSON,\n currentShape: NodeShapeData | undefined,\n prop?: PropertyShapeData,\n): unknown {\n if (++_decodeDepth > MAX_DECODE_DEPTH) {\n _decodeDepth = 0;\n throw new Error('DSL-JSON value nested too deeply');\n }\n try {\n return decodeValueToRawInner(json, currentShape, prop);\n } finally {\n _decodeDepth--;\n }\n}\n\nfunction decodeValueToRawInner(\n json: MutationValueJSON,\n currentShape: NodeShapeData | undefined,\n prop?: PropertyShapeData,\n): unknown {\n // S-expr computed value\n if (Array.isArray(json)) {\n const {ir, refs} = decodeValueExpr(json as DslJsonValue, requireShapeForExpr(currentShape));\n return new ExpressionNode(ir, refs);\n }\n if (json === null) return null;\n if (typeof json !== 'object') return json; // bare scalar literal\n const o = json as Record<string, unknown>;\n if ('@unset' in o) return undefined;\n if ('@date' in o) return new Date(o['@date'] as string);\n // Rehydration path: preserve the live reference so it re-serializes as a\n // `{@ctx}` marker and resolves at the rebuilt builder's own lowering.\n if ('@ctx' in o) return new PendingQueryContext(o['@ctx'] as string);\n if ('@id' in o) return {id: o['@id']};\n if ('@list' in o) {\n return (o['@list'] as MutationValueJSON[]).map((i) => decodeValueToRaw(i, currentShape, prop));\n }\n if ('@add' in o || '@remove' in o) {\n // Raw DSL set-modifications use `@add`/`@remove` on the wire.\n const mod: {add?: unknown[]; remove?: {id: string}[]} = {};\n if (o['@add']) mod.add = (o['@add'] as MutationValueJSON[]).map((i) => decodeValueToRaw(i, currentShape, prop));\n if (o['@remove']) mod.remove = (o['@remove'] as string[]).map((id) => ({id}));\n return mod;\n }\n // A computed-path value (`{@path}`) used as a value.\n if ('@path' in o) {\n const {ir, refs} = decodeValueExpr(json as DslJsonValue, requireShapeForExpr(currentShape));\n return new ExpressionNode(ir, refs);\n }\n // Otherwise: a bare path-keyed nested-node create.\n return decodeNestedNodeDataToRaw(o as MutationNodeDataJSON, valueShapeOf(prop) ?? currentShape);\n}\n\n/**\n * Decode a nested node and, when it names its concrete shape (`__shape`), carry that\n * shape as the reserved `shape` key `.set()` accepts on a nested value. Without it the\n * builders validate and lower the value against the property's declared value shape —\n * or none, for a polymorphic slot like `PropertyShape.path` — and reject the fields\n * only the concrete shape has.\n */\n/**\n * The class for a node's `__shape`. Either registry — a project-authored shape exists only\n * as metadata. Throws like `lowerMutationJSON` does, so both decode paths reject an\n * unregistered shape instead of one of them silently validating against another.\n */\nfunction requireNodeShapeClass(shapeId: string): ShapeConstructor {\n const shapeClass = resolveShapeConstructor(shapeId);\n if (!shapeClass) {\n throw new Error(\n `Shape '${shapeId}' is not registered. The receiving side must have the shape registered to decode mutation DSL-JSON.`,\n );\n }\n return shapeClass;\n}\n\nfunction decodeNestedNodeDataToRaw(\n json: MutationNodeDataJSON,\n shape: NodeShapeData | undefined,\n): Record<string, unknown> {\n const obj = decodeNodeDataToRaw(json, shape);\n const shapeId = json[NODE_SHAPE_KEY];\n if (typeof shapeId === 'string') obj.shape = requireNodeShapeClass(shapeId);\n return obj;\n}\n\nfunction requireShapeForExpr(shape: NodeShapeData | undefined): NodeShapeData {\n if (!shape) {\n throw new Error('A shape is required to decode a computed mutation value');\n }\n return shape;\n}\n\n/**\n * Decode path-keyed node data into a raw object the mutation builders' `.set()` accepts.\n * `__id` becomes `id`; `__shape` (if present) overrides the inferred `shape`. Mirrors\n * {@link encodeNodeData}.\n */\nexport function decodeNodeDataToRaw(\n json: MutationNodeDataJSON,\n shape?: NodeShapeData,\n): Record<string, unknown> {\n const nodeShape =\n typeof json[NODE_SHAPE_KEY] === 'string'\n ? requireNodeShapeClass(json[NODE_SHAPE_KEY] as string).shape\n : shape;\n const obj: Record<string, unknown> = {};\n if (typeof json[NODE_ID_KEY] === 'string') obj.id = json[NODE_ID_KEY];\n for (const [key, val] of Object.entries(json)) {\n if (key === NODE_ID_KEY || key === NODE_SHAPE_KEY || val === undefined) continue;\n // Skip prototype-polluting keys from untrusted DSL-JSON input.\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;\n const prop = nodeShape ? getPropertyShape(nodeShape, key) : undefined;\n obj[key] = decodeValueToRaw(val as MutationValueJSON, nodeShape, prop);\n }\n return obj;\n}\n"]}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { getPropertyShape } from '../shapes/nodeShapeData.js';
|
|
2
2
|
import { getQueryShapeClass } from '../utils/ShapeClass.js';
|
|
3
3
|
import { unresolvedValueShapeError } from '../utils/unresolvedShape.js';
|
|
4
|
+
import { brandLinkedClass } from '../utils/linkedError.js';
|
|
4
5
|
/**
|
|
5
6
|
* A value object representing a sequence of property traversals from a root shape.
|
|
6
7
|
*
|
|
@@ -41,6 +42,7 @@ export class PropertyPath {
|
|
|
41
42
|
return this.segments.every((s, i) => s.id === other.segments[i].id);
|
|
42
43
|
}
|
|
43
44
|
}
|
|
45
|
+
brandLinkedClass(PropertyPath, '@_linked/core', 'PropertyPath');
|
|
44
46
|
/**
|
|
45
47
|
* Resolve a dot-separated property path string into a PropertyPath.
|
|
46
48
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PropertyPath.js","sourceRoot":"","sources":["../../../src/queries/PropertyPath.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,gBAAgB,EAAC,MAAM,4BAA4B,CAAC;AAC5D,OAAO,EAAC,kBAAkB,EAAC,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAC,yBAAy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AI,CAAC,UAAU,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;gBACrC,MAAM,yBAAyB,CAC7B,8BAA8B,aAAa,CAAC,UAAU,CAAC,EAAE,mBAAmB,KAAK,cAAc,IAAI,GAAG,EACtG,aAAa,EACb,YAAY,CACb,CAAC;YACJ,CAAC;YACD,YAAY,GAAG,UAAU,CAAC,KAAK,CAAC;QAClC,CAAC;IACH,CAAC;IAED,OAAO,IAAI,YAAY,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;AAC3C,CAAC","sourcesContent":["import type {PropertyShapeData, NodeShapeData} from '../shapes/SHACL.js';\nimport {getPropertyShape} from '../shapes/nodeShapeData.js';\nimport {getQueryShapeClass} from '../utils/ShapeClass.js';\nimport {unresolvedValueShapeError} from '../utils/unresolvedShape.js';\nimport {brandLinkedClass} from '../utils/linkedError.js';\n\n/**\n * A value object representing a sequence of property traversals from a root shape.\n *\n * Each segment is a PropertyShapeData representing one hop in the traversal.\n * For example, `friends.name` on PersonShape produces a PropertyPath with\n * two segments: [friendsPropertyShape, namePropertyShape].\n *\n * This is used by FieldSet and QueryBuilder to describe which properties\n * to select/filter, independent of proxy tracing.\n */\nexport class PropertyPath {\n constructor(\n readonly rootShape: NodeShapeData,\n readonly segments: readonly PropertyShapeData[],\n ) {}\n\n /** Append a property traversal hop, returning a new PropertyPath. */\n prop(property: PropertyShapeData): PropertyPath {\n return new PropertyPath(this.rootShape, [...this.segments, property]);\n }\n\n /** The terminal (leaf) property of this path. */\n get terminal(): PropertyShapeData | undefined {\n return this.segments[this.segments.length - 1];\n }\n\n /** The depth (number of hops) of this path. */\n get depth(): number {\n return this.segments.length;\n }\n\n /** String representation using property labels joined by dots. */\n toString(): string {\n return this.segments.map((s) => s.label).join('.');\n }\n\n /** Two PropertyPaths are equal if they have the same root shape and same segment sequence. */\n equals(other: PropertyPath): boolean {\n if (this.rootShape.id !== other.rootShape.id) return false;\n if (this.segments.length !== other.segments.length) return false;\n return this.segments.every((s, i) => s.id === other.segments[i].id);\n }\n}\nbrandLinkedClass(PropertyPath, '@_linked/core', 'PropertyPath');\n\n\n/**\n * Resolve a dot-separated property path string into a PropertyPath.\n *\n * Walks the shape's property shapes by label, following valueShape references\n * to traverse into nested shapes.\n *\n * Example: `walkPropertyPath(PersonShape, 'friends.name')` resolves\n * [friendsPropertyShape, namePropertyShape].\n *\n * @throws If any segment cannot be resolved.\n */\nexport function walkPropertyPath(shape: NodeShapeData, path: string): PropertyPath {\n const labels = path.split('.');\n const segments: PropertyShapeData[] = [];\n let currentShape = shape;\n\n for (const label of labels) {\n const propertyShape = getPropertyShape(currentShape, label);\n if (!propertyShape) {\n throw new Error(\n `Property '${label}' not found on shape '${currentShape.label || currentShape.id}' while resolving path '${path}'`,\n );\n }\n segments.push(propertyShape);\n\n // If there are more segments to resolve, follow the valueShape\n if (segments.length < labels.length) {\n if (!propertyShape.valueShape) {\n throw new Error(\n `Property '${label}' on shape '${currentShape.label || currentShape.id}' has no valueShape; cannot traverse further in path '${path}'`,\n );\n }\n const shapeClass = getQueryShapeClass(propertyShape.valueShape);\n if (!shapeClass || !shapeClass.shape) {\n throw unresolvedValueShapeError(\n `Cannot resolve valueShape '${propertyShape.valueShape.id}' for property '${label}' in path '${path}'`,\n propertyShape,\n currentShape,\n );\n }\n currentShape = shapeClass.shape;\n }\n }\n\n return new PropertyPath(shape, segments);\n}\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createShapeTarget } from '../shapes/Shape.js';
|
|
2
2
|
import { QueryBuilderObject, QueryShape } from './SelectQuery.js';
|
|
3
|
+
import { isLinkedInstance } from '../utils/linkedError.js';
|
|
3
4
|
/**
|
|
4
5
|
* Creates the proxy object used as the `p` parameter in query callbacks.
|
|
5
6
|
*
|
|
@@ -12,7 +13,7 @@ import { QueryBuilderObject, QueryShape } from './SelectQuery.js';
|
|
|
12
13
|
* across the DSL and dynamic query building.
|
|
13
14
|
*/
|
|
14
15
|
export function createProxiedPathBuilder(shape) {
|
|
15
|
-
if (shape
|
|
16
|
+
if (isLinkedInstance(shape, QueryBuilderObject)) {
|
|
16
17
|
// When a QueryBuilderObject is passed directly (e.g. QueryPrimitives
|
|
17
18
|
// used as the shape for where-clause evaluation), use it as-is.
|
|
18
19
|
return shape;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ProxiedPathBuilder.js","sourceRoot":"","sources":["../../../src/queries/ProxiedPathBuilder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAQ,iBAAiB,EAAwB,MAAM,oBAAoB,CAAC;AACnF,OAAO,EAAC,kBAAkB,EAAE,UAAU,EAAC,MAAM,kBAAkB,CAAC;
|
|
1
|
+
{"version":3,"file":"ProxiedPathBuilder.js","sourceRoot":"","sources":["../../../src/queries/ProxiedPathBuilder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAQ,iBAAiB,EAAwB,MAAM,oBAAoB,CAAC;AACnF,OAAO,EAAC,kBAAkB,EAAE,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAChE,OAAO,EAAC,gBAAgB,EAAC,MAAM,yBAAyB,CAAC;AAEzD;;;;;;;;;;GAUG;AACH,MAAM,UAAU,wBAAwB,CACtC,KAA+C;IAE/C,IAAI,gBAAgB,CAAC,KAAK,EAAE,kBAAkB,CAAC,EAAE,CAAC;QAChD,qEAAqE;QACrE,gEAAgE;QAChE,OAAO,KAAK,CAAC;IACf,CAAC;IACD,2EAA2E;IAC3E,8EAA8E;IAC9E,yEAAyE;IACzE,oCAAoC;IACpC,MAAM,UAAU,GAAG,iBAAiB,CAAC,KAAK,CAAC,CAAC;IAC5C,OAAO,UAAU,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;AACvC,CAAC","sourcesContent":["import {Shape, createShapeTarget, type ShapeConstructor} from '../shapes/Shape.js';\nimport {QueryBuilderObject, QueryShape} from './SelectQuery.js';\nimport {isLinkedInstance} from '../utils/linkedError.js';\n\n/**\n * Creates the proxy object used as the `p` parameter in query callbacks.\n *\n * Property access on the returned proxy (e.g., `p.name`, `p.friends.name`)\n * creates QueryBuilderObject chains that trace the path of requested properties.\n * This is the shared foundation for both the DSL (`Person.select(p => p.name)`)\n * and the future QueryBuilder API.\n *\n * Originally extracted from SelectQueryFactory.getQueryShape() to enable reuse\n * across the DSL and dynamic query building.\n */\nexport function createProxiedPathBuilder<S extends Shape>(\n shape: ShapeConstructor<S> | QueryBuilderObject,\n): QueryBuilderObject {\n if (isLinkedInstance(shape, QueryBuilderObject)) {\n // When a QueryBuilderObject is passed directly (e.g. QueryPrimitives\n // used as the shape for where-clause evaluation), use it as-is.\n return shape;\n }\n // Create a constructor-less dummy shape target and wrap it in a QueryShape\n // proxy. The proxy intercepts property access and resolves each property name\n // to its PropertyShapeData, building a chain of QueryBuilderObjects that\n // records which path was traversed.\n const dummyShape = createShapeTarget(shape);\n return QueryShape.create(dummyShape);\n}\n"]}
|
|
@@ -22,7 +22,7 @@ import { createProxiedPathBuilder } from './ProxiedPathBuilder.js';
|
|
|
22
22
|
import { serializeWherePath, serializeSortByPath, serializeRawMinusEntry, deserializeWherePath, deserializeSortByPath, deserializeRawMinusEntry, } from './QueryBuilderSerialization.js';
|
|
23
23
|
import { requireLiveQueryStore } from '../live/registry.js';
|
|
24
24
|
import { captureCatalog, getActiveShapeCatalog, withShapeCatalog } from '../utils/ShapeClass.js';
|
|
25
|
-
import { isLinkedError } from '../utils/linkedError.js';
|
|
25
|
+
import { brandLinkedClass, isLinkedError, isLinkedInstance } from '../utils/linkedError.js';
|
|
26
26
|
/**
|
|
27
27
|
* An immutable, fluent query builder for select queries.
|
|
28
28
|
*
|
|
@@ -80,7 +80,7 @@ export class SelectBuilder {
|
|
|
80
80
|
return new SelectBuilder({ shape: resolved });
|
|
81
81
|
}
|
|
82
82
|
select(fnOrLabelsOrFieldSet) {
|
|
83
|
-
if (fnOrLabelsOrFieldSet
|
|
83
|
+
if (isLinkedInstance(fnOrLabelsOrFieldSet, FieldSet)) {
|
|
84
84
|
const labels = fnOrLabelsOrFieldSet.labels();
|
|
85
85
|
const selectFn = ((p) => labels.map((label) => p[label]));
|
|
86
86
|
return this.clone({ selectFn, selectAllLabels: undefined, fieldSet: fnOrLabelsOrFieldSet });
|
|
@@ -152,7 +152,7 @@ export class SelectBuilder {
|
|
|
152
152
|
}
|
|
153
153
|
/** Target a single entity by ID. Implies singleResult; unwraps array Result type. */
|
|
154
154
|
for(id) {
|
|
155
|
-
if (id
|
|
155
|
+
if (isLinkedInstance(id, PendingQueryContext)) {
|
|
156
156
|
// Store the pending context as subject — its .id getter resolves lazily
|
|
157
157
|
// from the global context map when the query is lowered/serialized.
|
|
158
158
|
return this.clone({ subject: id, subjects: undefined, singleResult: true, _nullSubject: false, _pendingContextName: id.contextName });
|
|
@@ -345,7 +345,7 @@ export class SelectBuilder {
|
|
|
345
345
|
// narrowing it to `{id}` here would silently resolve it against THIS process's
|
|
346
346
|
// context map — and the query would then travel as a concrete IRI where the
|
|
347
347
|
// equivalent select travels as `{"@ctx": name}` for the receiver to resolve.
|
|
348
|
-
const subject = this._subject
|
|
348
|
+
const subject = isLinkedInstance(this._subject, PendingQueryContext)
|
|
349
349
|
? this._subject
|
|
350
350
|
: this._subject && typeof this._subject === 'object' && 'id' in this._subject
|
|
351
351
|
? { id: this._subject.id }
|
|
@@ -770,6 +770,7 @@ export class SelectBuilder {
|
|
|
770
770
|
return 'SelectBuilder';
|
|
771
771
|
}
|
|
772
772
|
}
|
|
773
|
+
brandLinkedClass(SelectBuilder, '@_linked/core', 'SelectBuilder');
|
|
773
774
|
/** @deprecated Renamed to `SelectBuilder`. This alias will be removed in a future major. */
|
|
774
775
|
export { SelectBuilder as QueryBuilder };
|
|
775
776
|
//# sourceMappingURL=QueryBuilder.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"QueryBuilder.js","sourceRoot":"","sources":["../../../src/queries/QueryBuilder.ts"],"names":[],"mappings":";;;;;;;;;AACA,OAAO,EAAC,uBAAuB,EAAC,M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IAAI,EAAE,CAAC,IAAI,CAAC,WAAW,EAAE,UAAU,CAAC,CAAC;IACnD,CAAC;IAED,2EAA2E;IAC3E,KAAK,CACH,UAAqE;QAErE,OAAO,IAAI,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IACvC,CAAC;IAED,+EAA+E;IAC/E,OAAO,CAAC,SAA+B;QACrC,OAAO,IAAI,CAAC,IAAI,EAAE,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IACxC,CAAC;IAED,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC;QACtB,OAAO,eAAe,CAAC;IACzB,CAAC;CACF;AAED,4FAA4F;AAC5F,OAAO,EAAC,aAAa,IAAI,YAAY,EAAC,CAAC","sourcesContent":["import {Shape, type ShapeConstructor} from '../shapes/Shape.js';\nimport {getUniquePropertyShapes} from '../shapes/nodeShapeData.js';\nimport {resolveShape} from './resolveShape.js';\nimport {\n type QueryBuildFn,\n type WhereClause,\n type QResult,\n type QueryResponseToResultType,\n type SelectAllQueryResponse,\n type QueryComponentLike,\n processWhereClause,\n evaluateSortCallback,\n} from './SelectQuery.js';\nimport type {SortByPath, WherePath} from './SelectQuery.js';\nimport type {PropertyPathSegment, RawMinusEntry, RawSelectInput} from './IRDesugar.js';\nimport {WIRE_VERSION, assertWireVersion} from './wireVersion.js';\nimport {getQueryDispatch} from './queryDispatch.js';\nimport {AskBuilder} from './AskBuilder.js';\nimport {CountBuilder} from './CountBuilder.js';\nimport type {IDataset} from '../interfaces/IDataset.js';\nimport type {NodeShapeData} from '../shapes/SHACL.js';\nimport type {NodeReferenceValue} from './QueryFactory.js';\nimport {resolveUriOrThrow} from '../utils/NodeReference.js';\nimport {FieldSet, type FieldSetFieldJSON, type FieldSetEntry} from './FieldSet.js';\nimport {PendingQueryContext, UnresolvedContextError} from './QueryContext.js';\nimport {encodeContextRef, isContextRefJSON, type ContextRefJSON} from './ContextRef.js';\nimport {createProxiedPathBuilder} from './ProxiedPathBuilder.js';\nimport {\n serializeWherePath,\n serializeSortByPath,\n serializeRawMinusEntry,\n deserializeWherePath,\n deserializeSortByPath,\n deserializeRawMinusEntry,\n type WherePathJSON,\n type SortByPathJSON,\n type RawMinusEntryJSON,\n} from './QueryBuilderSerialization.js';\nimport {requireLiveQueryStore} from '../live/registry.js';\nimport {captureCatalog, getActiveShapeCatalog, withShapeCatalog} from '../utils/ShapeClass.js';\nimport type {ShapeCatalog} from '../utils/ShapeCatalog.js';\nimport {isLinkedError} from '../utils/linkedError.js';\nimport type {LiveListener, LiveQuery, LiveQueryOptions} from '../live/LiveQueryStore.js';\n\n/** JSON representation of a SelectBuilder. */\nexport type QueryBuilderJSON = {\n /** DSL-JSON wire-format version. */\n v?: string;\n shape: string;\n fields?: FieldSetFieldJSON[];\n limit?: number;\n offset?: number;\n /** A node id, or a `{@ctx: name}` context reference resolved at lowering. */\n subject?: string | ContextRefJSON;\n subjects?: string[];\n /** `.one()` — unwrap a single result. */\n one?: boolean;\n where?: WherePathJSON;\n sortBy?: SortByPathJSON;\n minusEntries?: RawMinusEntryJSON[];\n nullSubject?: boolean;\n};\n\n/** A preload entry binding a property path to a component's query. */\ninterface PreloadEntry {\n path: string;\n component: QueryComponentLike<any, any>;\n}\n\n/** A MINUS entry — either a shape type exclusion or a WHERE-clause condition. */\ninterface MinusEntry<S extends Shape> {\n shapeId?: string;\n whereFn?: WhereClause<S>;\n}\n\n/** Internal state bag for SelectBuilder. */\ninterface QueryBuilderInit<S extends Shape, R> {\n shape: ShapeConstructor<S>;\n /** The catalog the builder resolves in; absent = captured from the active one. */\n catalog?: ShapeCatalog;\n selectFn?: QueryBuildFn<S, R>;\n whereFn?: WhereClause<S>;\n sortByFn?: QueryBuildFn<S, any>;\n sortDirection?: 'ASC' | 'DESC';\n limit?: number;\n offset?: number;\n subject?: S | QResult<S> | NodeReferenceValue;\n subjects?: NodeReferenceValue[];\n singleResult?: boolean;\n selectAllLabels?: string[];\n fieldSet?: FieldSet;\n preloads?: PreloadEntry[];\n minusEntries?: MinusEntry<S>[];\n _nullSubject?: boolean;\n _pendingContextName?: string;\n // Pre-evaluated data (restored from JSON; used when callbacks are not available)\n _where?: WherePath;\n _sortBy?: SortByPath;\n _rawMinusEntries?: RawMinusEntry[];\n}\n\n/**\n * An immutable, fluent query builder for select queries.\n *\n * Every mutation method (`.select()`, `.where()`, `.limit()`, etc.) returns\n * a **new** SelectBuilder instance — the original is never modified.\n *\n * Implements `PromiseLike` so queries execute on `await`:\n * ```ts\n * const results = await SelectBuilder.from(Person).select(p => p.name);\n * ```\n *\n * Produces a raw select input (`toRawInput()`) that the free `lower()` function\n * turns into IR; the builder itself carries no dependency on the IR pipeline.\n */\nexport class SelectBuilder<S extends Shape = Shape, R = any, Result = any>\n implements PromiseLike<Result>, Promise<Result>\n{\n private readonly _shape: ShapeConstructor<S>;\n private readonly _selectFn?: QueryBuildFn<S, R>;\n private readonly _whereFn?: WhereClause<S>;\n private readonly _sortByFn?: QueryBuildFn<S, any>;\n private readonly _sortDirection?: 'ASC' | 'DESC';\n private readonly _limit?: number;\n private readonly _offset?: number;\n private readonly _subject?: S | QResult<S> | NodeReferenceValue;\n private readonly _subjects?: NodeReferenceValue[];\n private readonly _singleResult?: boolean;\n private readonly _selectAllLabels?: string[];\n private readonly _fieldSet?: FieldSet;\n private readonly _preloads?: PreloadEntry[];\n private readonly _minusEntries?: MinusEntry<S>[];\n private readonly _nullSubject?: boolean;\n private readonly _pendingContextName?: string;\n // Pre-evaluated data (restored from JSON; used when callbacks are not available)\n private readonly _where?: WherePath;\n private readonly _sortBy?: SortByPath;\n private readonly _rawMinusEntries?: RawMinusEntry[];\n private readonly _catalog: ShapeCatalog | undefined;\n\n private constructor(init: QueryBuilderInit<S, R>) {\n this._shape = init.shape;\n this._catalog = 'catalog' in init ? init.catalog : captureCatalog(init.shape);\n this._selectFn = init.selectFn;\n this._whereFn = init.whereFn;\n this._sortByFn = init.sortByFn;\n this._sortDirection = init.sortDirection;\n this._limit = init.limit;\n this._offset = init.offset;\n this._subject = init.subject;\n this._subjects = init.subjects;\n this._singleResult = init.singleResult;\n this._selectAllLabels = init.selectAllLabels;\n this._fieldSet = init.fieldSet;\n this._preloads = init.preloads;\n this._minusEntries = init.minusEntries;\n this._nullSubject = init._nullSubject;\n this._pendingContextName = init._pendingContextName;\n this._where = init._where;\n this._sortBy = init._sortBy;\n this._rawMinusEntries = init._rawMinusEntries;\n }\n\n /** Create a shallow clone with overrides. */\n private clone<NR = R, NResult = Result>(overrides: Partial<QueryBuilderInit<S, any>> = {}): SelectBuilder<S, NR, NResult> {\n return new SelectBuilder<S, NR, NResult>({\n shape: this._shape,\n selectFn: this._selectFn as any,\n whereFn: this._whereFn,\n sortByFn: this._sortByFn,\n sortDirection: this._sortDirection,\n limit: this._limit,\n offset: this._offset,\n subject: this._subject,\n subjects: this._subjects,\n singleResult: this._singleResult,\n selectAllLabels: this._selectAllLabels,\n fieldSet: this._fieldSet,\n preloads: this._preloads,\n minusEntries: this._minusEntries,\n _nullSubject: this._nullSubject,\n _pendingContextName: this._pendingContextName,\n _where: this._where,\n _sortBy: this._sortBy,\n _rawMinusEntries: this._rawMinusEntries,\n catalog: this._catalog,\n ...overrides,\n });\n }\n\n // ---------------------------------------------------------------------------\n // Static constructors\n // ---------------------------------------------------------------------------\n\n /**\n * Create a SelectBuilder for the given shape.\n *\n * Accepts a shape class (e.g. `Person`), a NodeShapeData instance,\n * or a shape IRI string (resolved via the shape registry).\n */\n static from<S extends Shape>(\n shape: ShapeConstructor<S> | string,\n ): SelectBuilder<S> {\n const resolved = resolveShape<S>(shape);\n return new SelectBuilder<S>({shape: resolved});\n }\n\n // ---------------------------------------------------------------------------\n // Fluent API — each returns a new instance\n // ---------------------------------------------------------------------------\n\n /** Set the select projection via a callback, labels, or FieldSet. */\n select<NewR>(fn: QueryBuildFn<S, NewR>): SelectBuilder<S, NewR, QueryResponseToResultType<NewR, S>[]>;\n select(labels: string[]): SelectBuilder<S>;\n select<NewR>(fieldSet: FieldSet<NewR>): SelectBuilder<S, NewR, QueryResponseToResultType<NewR, S>[]>;\n select<NewR = R>(fnOrLabelsOrFieldSet: QueryBuildFn<S, NewR> | string[] | FieldSet<any>): SelectBuilder<S, NewR, any> {\n if (fnOrLabelsOrFieldSet instanceof FieldSet) {\n const labels = fnOrLabelsOrFieldSet.labels();\n const selectFn = ((p: any) =>\n labels.map((label) => p[label])) as unknown as QueryBuildFn<S, any>;\n return this.clone<NewR, any>({selectFn, selectAllLabels: undefined, fieldSet: fnOrLabelsOrFieldSet});\n }\n if (Array.isArray(fnOrLabelsOrFieldSet)) {\n const labels = fnOrLabelsOrFieldSet;\n const selectFn = ((p: any) =>\n labels.map((label) => p[label])) as unknown as QueryBuildFn<S, any>;\n return this.clone<NewR, any>({selectFn, selectAllLabels: undefined, fieldSet: undefined});\n }\n return this.clone<NewR, any>({selectFn: fnOrLabelsOrFieldSet as any, selectAllLabels: undefined, fieldSet: undefined});\n }\n\n /** Select all decorated properties of the shape. */\n selectAll(): SelectBuilder<S, any, QueryResponseToResultType<SelectAllQueryResponse<S>, S>[]> {\n const catalog = this._catalog;\n if (catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(catalog, () => this.selectAll());\n }\n const propertyLabels = getUniquePropertyShapes(this._shape.shape)\n .map((ps) => ps.label);\n const selectFn = ((p: any) =>\n propertyLabels.map((label) => p[label])) as unknown as QueryBuildFn<S, any>;\n return this.clone({selectFn, selectAllLabels: propertyLabels});\n }\n\n /** Add a where clause. */\n where(fn: WhereClause<S>): SelectBuilder<S, R, Result> {\n return this.clone({whereFn: fn});\n }\n\n /**\n * Exclude results matching a MINUS pattern.\n *\n * Accepts:\n * - A shape constructor to exclude by type: `.minus(Employee)`\n * - A WHERE callback to exclude by condition: `.minus(p => p.hobby.equals('Chess'))`\n * - A callback returning a property or array of properties for existence exclusion:\n * `.minus(p => p.hobby)` or `.minus(p => [p.hobby, p.bestFriend.name])`\n *\n * Chainable: `.minus(A).minus(B)` produces two separate `MINUS { }` blocks.\n */\n minus(shapeOrFn: ShapeConstructor<any> | WhereClause<S> | ((s: any) => any)): SelectBuilder<S, R, Result> {\n const entry: MinusEntry<S> = {};\n if (typeof shapeOrFn === 'function' && 'shape' in shapeOrFn) {\n // ShapeConstructor — has a static .shape property\n entry.shapeId = (shapeOrFn as ShapeConstructor<any>).shape?.id;\n } else {\n // WhereClause callback\n entry.whereFn = shapeOrFn as WhereClause<S>;\n }\n const existing = this._minusEntries || [];\n return this.clone({minusEntries: [...existing, entry]});\n }\n\n /** Set sort order. */\n orderBy<OR>(fn: QueryBuildFn<S, OR>, direction: 'ASC' | 'DESC' = 'ASC'): SelectBuilder<S, R, Result> {\n return this.clone({sortByFn: fn as any, sortDirection: direction});\n }\n\n /**\n * @deprecated Use `orderBy()` instead.\n */\n sortBy<OR>(fn: QueryBuildFn<S, OR>, direction: 'ASC' | 'DESC' = 'ASC'): SelectBuilder<S, R, Result> {\n return this.orderBy(fn, direction);\n }\n\n /** Set result limit. */\n limit(n: number): SelectBuilder<S, R, Result> {\n return this.clone({limit: n});\n }\n\n /** Set result offset. */\n offset(n: number): SelectBuilder<S, R, Result> {\n return this.clone({offset: n});\n }\n\n /** Target a single entity by ID. Implies singleResult; unwraps array Result type. */\n for(id: string | NodeReferenceValue | PendingQueryContext | null | undefined): SelectBuilder<S, R, Result extends (infer E)[] ? E : Result> {\n if (id instanceof PendingQueryContext) {\n // Store the pending context as subject — its .id getter resolves lazily\n // from the global context map when the query is lowered/serialized.\n return this.clone({subject: id as any, subjects: undefined, singleResult: true, _nullSubject: false, _pendingContextName: id.contextName}) as any;\n }\n if (id == null) {\n // Return a builder that resolves to null when executed (no subject = no query).\n // This commonly happens when getQueryContext() returns null before the user is authenticated.\n return this.clone({subject: undefined, subjects: undefined, singleResult: true, _nullSubject: true, _pendingContextName: undefined}) as any;\n }\n const subject: NodeReferenceValue = typeof id === 'string' ? {id: resolveUriOrThrow(id)} : id;\n return this.clone({subject, subjects: undefined, singleResult: true, _pendingContextName: undefined}) as any;\n }\n\n /**\n * Whether the query has a pending (lazy) context that hasn't resolved yet.\n * Returns true when .for() received a PendingQueryContext whose value isn't available yet.\n */\n hasPendingContext(): boolean {\n return !!(this._pendingContextName && !this._subject?.id);\n }\n\n /** Target multiple entities by ID, or all if no ids given. */\n forAll(ids?: (string | NodeReferenceValue)[]): SelectBuilder<S, R, Result> {\n if (!ids) {\n return this.clone({subject: undefined, subjects: undefined, singleResult: false, _pendingContextName: undefined});\n }\n const subjects = ids.map((id) => typeof id === 'string' ? {id: resolveUriOrThrow(id)} : id);\n return this.clone({subject: undefined, subjects, singleResult: false, _pendingContextName: undefined});\n }\n\n /** Limit to one result. Unwraps array Result type to single element. */\n one(): SelectBuilder<S, R, Result extends (infer E)[] ? E : Result> {\n return this.clone<R, Result extends (infer E)[] ? E : Result>({limit: 1, singleResult: true});\n }\n\n /**\n * Whether **any** row matches this query. Executes immediately and resolves to a\n * real `boolean` — never a row, never `null`, never an array the caller has to\n * interpret.\n *\n * ```ts\n * await Person.select().where(p => p.name.equals('Semmy')).exists(); // boolean\n * await Person.exists({id}); // the common case\n * ```\n *\n * ### The query is normalised to its cheapest correct form first\n *\n * **Dropped** — the projection, preloads, sorting *and pagination* (`limit`/`offset`).\n * **Kept** — filters, `minus` entries and the subject: those decide whether a match\n * exists. `LIMIT 1` is then applied.\n *\n * So `.select(…).orderBy(…).offset(10).exists()` costs, and answers, exactly the\n * same as a bare `.exists()`. Against a SPARQL store that goes out as:\n *\n * ```sparql\n * ASK WHERE { ?a0 rdf:type <…> . FILTER(?a0 = <…>) }\n * ```\n *\n * Pagination does not survive, and cannot: `OFFSET` skips rows of a *solution\n * sequence*, and an ask has none. (Nor is it merely dropped — an\n * {@link AskBuilder} has nowhere to hold it.) `exists()` answers a question about\n * the **match set**, not about a page of it.\n *\n * ### Errors are not swallowed\n *\n * A store, transport or lowering failure rejects the returned promise; it is never\n * reported as `false`. That includes an unresolved query-context reference in a\n * where clause, which `exec()` deliberately reports as `null` (\"not ready\") but\n * which `exists()` must not flatten into a boolean — and a store whose `askQuery`\n * resolves to something that is not a boolean, which rejects rather than being\n * coerced into one.\n *\n * The one case that does resolve `false` without querying is a query with **no\n * subject to ask about** — `.for(null)`, `.for(undefined)`, or an unresolved\n * `PendingQueryContext` *as the subject*. \"Does the node with no id exist?\" has a\n * correct total answer, and it is `false`.\n *\n * @param target Optional explicit dataset, as for {@link exec}.\n */\n async exists(target?: IDataset): Promise<boolean> {\n return this._toAsk().exec(target);\n }\n\n /**\n * **How many** rows match this query — the total of the match set, as a real\n * `number`.\n *\n * ```ts\n * await Person.select().where(p => p.name.equals('Semmy')).count(); // number\n * await SelectBuilder.from(shapeIri).where(…).count(); // from an IRI alone\n * ```\n *\n * ### The query is normalised to its cheapest correct form first\n *\n * **Dropped** — the projection, preloads, sorting *and pagination*\n * (`limit`/`offset`). **Kept** — filters, `minus` entries and the subject: those\n * decide membership of the match set. Against a SPARQL store that goes out as:\n *\n * ```sparql\n * SELECT (COUNT(DISTINCT ?a0) AS ?count)\n * WHERE { ?a0 rdf:type <…> . ?a0 <…name> ?a0_name . FILTER(?a0_name = \"Semmy\") }\n * ```\n *\n * ### `limit`/`offset` are dropped, not rejected\n *\n * A count of a windowed query is meaningless — `OFFSET` skips rows of a *solution\n * sequence*, and the number a count answers is a property of the whole match set,\n * not of a page of it. So `.limit(20).offset(40).count()` costs, and answers,\n * exactly the same as a bare `.count()`.\n *\n * Dropping rather than throwing is deliberate: the paging caller holds **one**\n * builder and wants the page *and* its total from the same filter, so rejecting\n * the combination would force it to rebuild the builder by hand for no\n * correctness gain. There is exactly one sensible reading, and it is this one.\n * `.exists()` already made the same call, so the DSL has one rule — *a\n * scalar-answering query drops the solution-sequence modifiers* — not two.\n *\n * Nor is the drop merely a convention: a {@link CountBuilder} has nowhere to hold\n * a window, so it cannot be forgotten or half-applied downstream.\n *\n * `DISTINCT` is likewise not optional. A filter on a multi-valued property yields\n * several rows per subject, so the count is of distinct subjects — \"how many\n * instances match\", which is the question asked.\n *\n * ### Errors are not swallowed\n *\n * A store, transport or lowering failure **rejects**; it is never reported as `0`.\n * `0` is a plausible count: it renders an empty table and looks like data. Do not\n * wrap this in `.catch(() => 0)`.\n *\n * The one case that resolves `0` without querying is a query with no subject to\n * count — `.for(null)`, `.for(undefined)`, or an unresolved `PendingQueryContext`\n * *as the subject*.\n *\n * @param target Optional explicit dataset, as for {@link exec}.\n */\n async count(target?: IDataset): Promise<number> {\n return this.toCount().exec(target);\n }\n\n /**\n * Reduce this select to the count query that answers \"how many match?\".\n *\n * Public, unlike the ask equivalent, because a caller may want to **forward**\n * rather than execute: `builder.toCount().toJSON()` is the `{op: 'count'}` wire\n * envelope a router or RPC boundary sends on, and `fromJSON` turns it back into a\n * `CountBuilder` on the other side.\n *\n * Only the pattern survives — shape, subject(s), filters, `minus`. The projection,\n * preloads, sorting and pagination are not so much \"dropped\" as unrepresentable:\n * {@link CountBuilder} has nowhere to put them. That is the point of it being a\n * separate builder rather than a mode of this one.\n */\n toCount(): CountBuilder {\n const catalog = this._catalog;\n if (catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(catalog, () => this.toCount());\n }\n return CountBuilder.of({\n shapeClass: this._shape,\n catalog: this._catalog,\n // `.for(null)` rides along in the spec. An unresolved pending context is\n // handled by CountBuilder.exec, which answers `0` without querying.\n ...this._patternSpec(),\n });\n }\n\n /**\n * The pattern-bearing part of this select: shape-membership, subject(s), filters\n * and `minus` — everything that decides which nodes are in the match set, and\n * nothing that shapes or windows the rows describing them.\n *\n * Shared by {@link _toAsk} and {@link toCount} rather than written twice. That is\n * not only about duplication: if the two normalisations drifted, `.exists()` and\n * `.count()` would disagree about what the match set *is* — a count of 0 next to\n * an `exists` of `true`, from the same builder.\n */\n private _patternSpec(): {\n subject?: NodeReferenceValue | PendingQueryContext;\n subjects?: NodeReferenceValue[];\n where?: WherePath;\n minusEntries?: RawMinusEntry[];\n nullSubject?: boolean;\n } {\n const catalog = this._catalog;\n if (catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(catalog, () => this._patternSpec());\n }\n let where: WherePath | undefined;\n if (this._whereFn) {\n where = processWhereClause(this._whereFn, this._shape);\n } else if (this._where) {\n where = this._where;\n }\n\n let minusEntries: RawMinusEntry[] | undefined;\n if (this._minusEntries && this._minusEntries.length > 0) {\n minusEntries = this._evaluateMinusEntries();\n } else if (this._rawMinusEntries && this._rawMinusEntries.length > 0) {\n minusEntries = this._rawMinusEntries;\n }\n\n // A PendingQueryContext must survive as itself. It has an `id` *getter*, so\n // narrowing it to `{id}` here would silently resolve it against THIS process's\n // context map — and the query would then travel as a concrete IRI where the\n // equivalent select travels as `{\"@ctx\": name}` for the receiver to resolve.\n const subject =\n this._subject instanceof PendingQueryContext\n ? this._subject\n : this._subject && typeof this._subject === 'object' && 'id' in this._subject\n ? {id: (this._subject as NodeReferenceValue).id}\n : undefined;\n\n return {\n subject,\n subjects: this._subjects,\n where,\n minusEntries,\n nullSubject: this._nullSubject,\n };\n }\n\n /**\n * Reduce this select to the ask query that answers the same existence question.\n *\n * Only the pattern survives — shape, subject(s), filters, `minus`. The\n * projection, preloads, sorting and pagination are not \"dropped\" so much as\n * unrepresentable: {@link AskBuilder} has nowhere to put them. That is the point\n * of it being a separate builder rather than a mode of this one — the\n * normalisation cannot be forgotten or half-applied.\n */\n private _toAsk(): AskBuilder {\n const catalog = this._catalog;\n if (catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(catalog, () => this._toAsk());\n }\n return AskBuilder.of({\n shapeClass: this._shape,\n catalog: this._catalog,\n // `.for(null)` rides along in the spec. An unresolved pending context is\n // handled by AskBuilder.exec, which sees the live context and answers `false`\n // without querying.\n ...this._patternSpec(),\n });\n }\n\n /**\n * Preload a component's query fields at the given property path.\n *\n * This merges the component's query paths into this query's selection,\n * wrapping them in an OPTIONAL block (handled by the IR pipeline).\n *\n * Equivalent to the DSL's `.preloadFor()`:\n * ```ts\n * // DSL style\n * Person.select(p => p.bestFriend.preloadFor(PersonCard))\n * // SelectBuilder style\n * SelectBuilder.from(Person).select(p => [p.name]).preload('bestFriend', PersonCard)\n * ```\n *\n * NOTE: Preloads hold live component references and are not serializable.\n * They are merged into the selection when the field set is evaluated\n * (`_fieldsWithPreloads()`), so changes to preload handling must account for\n * the selectFn wrapping logic.\n */\n preload<CS extends Shape, CR>(\n path: string,\n component: QueryComponentLike<CS, CR>,\n ): SelectBuilder<S, R, Result> {\n const newPreloads = [...(this._preloads || []), {path, component}];\n return this.clone({preloads: newPreloads});\n }\n\n /**\n * Returns the current selection as a FieldSet.\n * If the selection was set via a FieldSet, returns that directly.\n * If set via selectAll labels, constructs a FieldSet from them.\n * If set via a callback, eagerly evaluates it through the proxy to produce a FieldSet.\n */\n fields(): FieldSet | undefined {\n const catalog = this._catalog;\n if (catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(catalog, () => this.fields());\n }\n if (this._fieldSet) {\n return this._fieldSet;\n }\n if (this._selectAllLabels) {\n return FieldSet.for(this._shape.shape, this._selectAllLabels);\n }\n if (this._selectFn) {\n // Eagerly evaluate the callback through FieldSet.for(ShapeClass, callback)\n // The callback is pure — same proxy always produces same paths.\n return FieldSet.for(this._shape, this._selectFn as unknown as (p: any) => any[]);\n }\n return undefined;\n }\n\n // ---------------------------------------------------------------------------\n // Internal helpers\n // ---------------------------------------------------------------------------\n\n /** Return the FieldSet with preload entries merged in (if any). */\n private _fieldsWithPreloads(): FieldSet | undefined {\n let fs = this.fields();\n if (this._preloads && this._preloads.length > 0) {\n const preloadFn = (p: any) => {\n return this._preloads!.map((entry) => p[entry.path].preloadFor(entry.component));\n };\n const preloadFs = FieldSet.for(this._shape, preloadFn);\n if (fs) {\n fs = FieldSet.createFromEntries(fs.shape, [\n ...(fs.entries as FieldSetEntry[]),\n ...(preloadFs.entries as FieldSetEntry[]),\n ]);\n } else {\n fs = preloadFs;\n }\n }\n return fs;\n }\n\n /** Evaluate minus entry callbacks into RawMinusEntry[] (plain data). */\n private _evaluateMinusEntries(): RawMinusEntry[] {\n const proxy = createProxiedPathBuilder(this._shape);\n return this._minusEntries!.map((entry) => {\n if (entry.shapeId) {\n return {shapeId: entry.shapeId};\n }\n if (entry.whereFn) {\n const result = (entry.whereFn as Function)(proxy);\n\n if (Array.isArray(result)) {\n const propertyPaths = result.map((item: any) => {\n const segments = FieldSet.collectPropertySegments(item);\n return segments.map((seg): PropertyPathSegment => ({propertyShapeId: seg.id}));\n });\n return {propertyPaths};\n }\n\n if (result && typeof result === 'object' && 'property' in result && 'subject' in result) {\n const segments = FieldSet.collectPropertySegments(result);\n return {propertyPaths: [segments.map((seg): PropertyPathSegment => ({propertyShapeId: seg.id}))]};\n }\n\n // WHERE-based exclusion\n return {where: processWhereClause(entry.whereFn, this._shape)};\n }\n return {};\n });\n }\n\n // ---------------------------------------------------------------------------\n // Serialization\n // ---------------------------------------------------------------------------\n\n /**\n * Serialize this SelectBuilder to a plain JSON object.\n *\n * Selections are serializable regardless of how they were set (FieldSet,\n * string[], selectAll, or callback). Callback-based selections are eagerly\n * evaluated through the proxy to produce a FieldSet.\n *\n * Where, orderBy, and minus clauses are evaluated through the proxy and\n * serialized as plain data structures. Preloads are merged into the FieldSet\n * as subSelect entries, producing identical IR on deserialization.\n */\n toJSON(): QueryBuilderJSON {\n const catalog = this._catalog;\n if (catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(catalog, () => this.toJSON());\n }\n const shapeId = this._shape.shape?.id || '';\n const json: QueryBuilderJSON = {\n v: WIRE_VERSION,\n shape: shapeId,\n };\n\n const fs = this._fieldsWithPreloads();\n if (fs) {\n json.fields = fs.toJSON().fields;\n }\n\n if (this._limit !== undefined) {\n json.limit = this._limit;\n }\n if (this._offset !== undefined) {\n json.offset = this._offset;\n }\n if (this._pendingContextName) {\n // Carry the context reference, not its (possibly unresolved) id, so the\n // receiver resolves it against its own context map at lowering time.\n json.subject = encodeContextRef(this._pendingContextName);\n } else if (this._subject && typeof this._subject === 'object' && 'id' in this._subject) {\n json.subject = (this._subject as NodeReferenceValue).id;\n }\n if (this._subjects && this._subjects.length > 0) {\n json.subjects = this._subjects.map((s) => s.id);\n }\n if (this._singleResult) {\n json.one = true;\n }\n\n if (this._whereFn) {\n json.where = serializeWherePath(processWhereClause(this._whereFn, this._shape), this._shape.shape);\n } else if (this._where) {\n json.where = serializeWherePath(this._where, this._shape.shape);\n }\n\n if (this._sortByFn) {\n json.sortBy = serializeSortByPath(\n evaluateSortCallback(this._shape, this._sortByFn as unknown as (p: any) => any, this._sortDirection || 'ASC'),\n );\n } else if (this._sortBy) {\n json.sortBy = serializeSortByPath(this._sortBy);\n }\n\n if (this._minusEntries && this._minusEntries.length > 0) {\n json.minusEntries = this._evaluateMinusEntries().map((e) =>\n serializeRawMinusEntry(e, this._shape.shape),\n );\n } else if (this._rawMinusEntries && this._rawMinusEntries.length > 0) {\n json.minusEntries = this._rawMinusEntries.map((e) =>\n serializeRawMinusEntry(e, this._shape.shape),\n );\n }\n\n if (this._nullSubject) {\n json.nullSubject = true;\n }\n\n return json;\n }\n\n /**\n * Reconstruct a SelectBuilder from a JSON object.\n * Resolves shape IRI via getShapeClass() and field paths as label selections.\n */\n static fromJSON<S extends Shape = Shape>(json: QueryBuilderJSON): SelectBuilder<S> {\n assertWireVersion(json.v);\n let builder = SelectBuilder.from<S>(json.shape as any);\n\n if (json.fields && json.fields.length > 0) {\n const fieldSet = FieldSet.fromJSON({\n shape: json.shape,\n fields: json.fields,\n });\n builder = builder.select(fieldSet) as SelectBuilder<S>;\n }\n\n if (json.limit !== undefined) {\n builder = builder.limit(json.limit) as SelectBuilder<S>;\n }\n if (json.offset !== undefined) {\n builder = builder.offset(json.offset) as SelectBuilder<S>;\n }\n if (json.subject) {\n // A `{@ctx}` subject rehydrates as a pending context (preserving the name\n // so it re-serializes as a context reference and resolves live).\n const subject = isContextRefJSON(json.subject)\n ? new PendingQueryContext(json.subject['@ctx'])\n : json.subject;\n builder = builder.for(subject) as SelectBuilder<S>;\n }\n if (json.subjects && json.subjects.length > 0) {\n builder = builder.forAll(json.subjects) as SelectBuilder<S>;\n }\n if (json.one && !json.subject) {\n builder = builder.one() as SelectBuilder<S>;\n }\n\n // Restore pre-evaluated data via clone — safe because fromJSON is in the same class.\n const overrides: Partial<QueryBuilderInit<S, any>> = {};\n const nodeShape = builder._shape.shape;\n\n // Restore where clause\n if (json.where && nodeShape) {\n overrides._where = deserializeWherePath(nodeShape, json.where);\n }\n\n // Restore sort key + direction (direction rides on the ordered sortBy array)\n if (json.sortBy && json.sortBy.length > 0 && nodeShape) {\n const sortBy = deserializeSortByPath(nodeShape, json.sortBy);\n overrides._sortBy = sortBy;\n overrides.sortDirection = sortBy.directions[0];\n }\n\n // Restore minus entries\n if (json.minusEntries && json.minusEntries.length > 0 && nodeShape) {\n overrides._rawMinusEntries = json.minusEntries.map((e) =>\n deserializeRawMinusEntry(nodeShape, e),\n );\n }\n\n // Restore nullSubject flag\n if (json.nullSubject) {\n overrides._nullSubject = true;\n }\n\n if (Object.keys(overrides).length > 0) {\n builder = (builder as any).clone(overrides) as SelectBuilder<S>;\n }\n\n return builder;\n }\n\n // ---------------------------------------------------------------------------\n // Build & execute\n // ---------------------------------------------------------------------------\n\n /**\n * Get the raw pipeline input.\n *\n * Constructs RawSelectInput directly from FieldSet entries.\n */\n toRawInput(): RawSelectInput {\n const catalog = this._catalog;\n if (catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(catalog, () => this.toRawInput());\n }\n return this._buildDirectRawInput();\n }\n\n /** Build RawSelectInput directly from FieldSet entries. */\n private _buildDirectRawInput(): RawSelectInput {\n const fs = this._fieldsWithPreloads();\n const entries = fs ? fs.entries : [];\n\n let where: WherePath | undefined;\n if (this._whereFn) {\n where = processWhereClause(this._whereFn, this._shape);\n } else if (this._where) {\n where = this._where;\n }\n\n let sortBy: SortByPath | undefined;\n if (this._sortByFn) {\n sortBy = evaluateSortCallback(\n this._shape,\n this._sortByFn as unknown as (p: any) => any,\n this._sortDirection || 'ASC',\n );\n } else if (this._sortBy) {\n sortBy = this._sortBy;\n }\n\n const input: RawSelectInput = {\n entries,\n subject: this._subject,\n limit: this._limit,\n offset: this._offset,\n shape: this._shape,\n sortBy,\n singleResult:\n this._singleResult ||\n !!(\n this._subject &&\n typeof this._subject === 'object' &&\n 'id' in this._subject\n ),\n };\n\n if (where) {\n input.where = where;\n }\n if (this._subjects && this._subjects.length > 0) {\n input.subjects = this._subjects;\n }\n if (this._minusEntries && this._minusEntries.length > 0) {\n input.minusEntries = this._evaluateMinusEntries();\n } else if (this._rawMinusEntries && this._rawMinusEntries.length > 0) {\n input.minusEntries = this._rawMinusEntries;\n }\n\n return input;\n }\n\n /** Discriminator for the free `lower()` function and dataset routing. */\n readonly __queryKind = 'select' as const;\n\n /** The shape this query targets — the routing key datasets/`LinkedStorage` use. */\n get shape(): NodeShapeData {\n return this._shape.shape;\n }\n\n /**\n * The catalog this builder resolves shapes in — captured when it was built, kept by\n * every derived builder. Undefined = the global registry. Never serialized.\n */\n get catalog(): ShapeCatalog | undefined {\n return this._catalog;\n }\n\n /**\n * Execute the query and return results.\n *\n * @param target Optional explicit dataset (a store or a router — a router *is* an\n * `IDataset`) to run against. Omitted → the global query dispatch (the router's\n * shape-based default). A `target` runs on that dataset only; the global router is\n * untouched. `await`ing the builder (the PromiseLike path) always uses the global\n * dispatch — only `.exec(target)` overrides.\n */\n async exec(target?: IDataset): Promise<Result> {\n return this._run(target, true) as Promise<Result>;\n }\n\n /**\n * Shared execution path for {@link exec} and {@link exists}.\n *\n * @param swallowUnresolvedContext When true (the `exec` path), a where-clause\n * context reference that has not resolved yet surfaces as `null` — \"not ready\",\n * which a reactive layer re-runs once the context lands. `exists()` passes\n * false: it must not turn \"could not ask\" into a boolean.\n */\n private async _run(\n target: IDataset | undefined,\n swallowUnresolvedContext: boolean,\n ): Promise<unknown> {\n if (this._nullSubject) {\n // .for(null/undefined) was called — return null instead of executing a broken query.\n return null;\n }\n if (this._pendingContextName && !this._subject?.id) {\n // Pending context hasn't resolved yet — return null rather than querying without a subject.\n return null;\n }\n // Dispatch the live (closed) query; the dataset decides whether to lower it.\n // `async` ensures a missing global dispatch surfaces as a rejected promise, not a sync throw.\n const dispatch = target ?? getQueryDispatch();\n try {\n return await dispatch.selectQuery(this);\n } catch (err) {\n // A where-clause context reference that hasn't resolved yet surfaces as\n // UnresolvedContextError when the dataset lowers the query. For SELECT this\n // means \"not ready\" — return null (a reactive layer re-runs once it lands),\n // mirroring the pending-subject behavior. Mutations still throw.\n if (swallowUnresolvedContext && isLinkedError(err, UnresolvedContextError)) {\n return null;\n }\n // The message names the query, which is what a human needs. `cause` keeps\n // the ORIGINAL error reachable as an object, which is what code needs: a\n // store error's status/endpoint/class is how a caller tells \"this dataset\n // does not exist\" from \"this query is wrong\", and without the chain the\n // only way left is to pattern-match this string. Written with\n // defineProperty rather than `new Error(msg, {cause})` because this\n // package targets es6, where that overload is not typed; the property\n // shape (own, non-enumerable) is identical.\n const wrapped = Error(`Error while executing query: ${(err as Error).stack}.\\n\\nQuery related to this error: ${JSON.stringify(this.toJSON())}`);\n Object.defineProperty(wrapped, 'cause', {\n value: err,\n writable: true,\n configurable: true,\n enumerable: false,\n });\n throw wrapped;\n }\n }\n\n\n /**\n * Go live: subscribe to this query and keep its result current.\n *\n * Returns a {@link LiveQuery} handle. `await` it for the first result,\n * `subscribe()` for every later one, `close()` when done. A listener may be\n * passed directly as the first argument. Requires the live-query store to be\n * loaded, which importing `@_linked/core` (the package root) does.\n */\n live<R = Result>(listenerOrOptions?: LiveListener<R> | LiveQueryOptions, options?: LiveQueryOptions): LiveQuery<R> {\n const listener = typeof listenerOrOptions === 'function' ? listenerOrOptions : undefined;\n const opts = typeof listenerOrOptions === 'function' ? options : listenerOrOptions;\n return requireLiveQueryStore().subscribe<R>(this as any, listener, opts);\n }\n\n // ---------------------------------------------------------------------------\n // Promise-compatible interface\n // ---------------------------------------------------------------------------\n\n /** `await` triggers execution. */\n then<TResult1 = Result, TResult2 = never>(\n onfulfilled?: ((value: Result) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null,\n ): Promise<TResult1 | TResult2> {\n return this.exec().then(onfulfilled, onrejected);\n }\n\n /** Catch errors from execution. Chain off then() to avoid re-executing. */\n catch<TResult = never>(\n onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null,\n ): Promise<Result | TResult> {\n return this.then().catch(onrejected);\n }\n\n /** Finally handler after execution. Chain off then() to avoid re-executing. */\n finally(onfinally?: (() => void) | null): Promise<Result> {\n return this.then().finally(onfinally);\n }\n\n get [Symbol.toStringTag](): string {\n return 'SelectBuilder';\n }\n}\n\n/** @deprecated Renamed to `SelectBuilder`. This alias will be removed in a future major. */\nexport {SelectBuilder as QueryBuilder};\n"]}
|
|
1
|
+
{"version":3,"file":"QueryBuilder.js","sourceRoot":"","sources":["../../../src/queries/QueryBuilder.ts"],"names":[],"mappings":";;;;;;;;;AACA,OAAO,EAAC,uBAAuB,EAAC,MAAM,4BAA4B,CAAC;AACnE,OAAO,EAAC,YAAY,EAAC,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAOL,kBAAkB,EAClB,oBAAoB,GACrB,MAAM,kBAAkB,CAAC;AAG1B,OAAO,EAAC,YAAY,EAAE,iBAAiB,EAAC,MAAM,kBAAkB,CAAC;AACjE,OAAO,EAAC,gBAAgB,EAAC,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAC,UAAU,EAAC,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAC,YAAY,EAAC,MAAM,mBAAmB,CAAC;AAI/C,OAAO,EAAC,iBAAiB,EAAC,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAC,QAAQ,EAA6C,MAAM,eAAe,CAAC;AACnF,OAAO,EAAC,mBAAmB,EAAE,sBAAsB,EAAC,MAAM,mBAAmB,CAAC;AAC9E,OAAO,EAAC,gBAAgB,EAAE,gBAAgB,EAAsB,MAAM,iBAAiB,CAAC;AACxF,OAAO,E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sourcesContent":["import {Shape, type ShapeConstructor} from '../shapes/Shape.js';\nimport {getUniquePropertyShapes} from '../shapes/nodeShapeData.js';\nimport {resolveShape} from './resolveShape.js';\nimport {\n type QueryBuildFn,\n type WhereClause,\n type QResult,\n type QueryResponseToResultType,\n type SelectAllQueryResponse,\n type QueryComponentLike,\n processWhereClause,\n evaluateSortCallback,\n} from './SelectQuery.js';\nimport type {SortByPath, WherePath} from './SelectQuery.js';\nimport type {PropertyPathSegment, RawMinusEntry, RawSelectInput} from './IRDesugar.js';\nimport {WIRE_VERSION, assertWireVersion} from './wireVersion.js';\nimport {getQueryDispatch} from './queryDispatch.js';\nimport {AskBuilder} from './AskBuilder.js';\nimport {CountBuilder} from './CountBuilder.js';\nimport type {IDataset} from '../interfaces/IDataset.js';\nimport type {NodeShapeData} from '../shapes/SHACL.js';\nimport type {NodeReferenceValue} from './QueryFactory.js';\nimport {resolveUriOrThrow} from '../utils/NodeReference.js';\nimport {FieldSet, type FieldSetFieldJSON, type FieldSetEntry} from './FieldSet.js';\nimport {PendingQueryContext, UnresolvedContextError} from './QueryContext.js';\nimport {encodeContextRef, isContextRefJSON, type ContextRefJSON} from './ContextRef.js';\nimport {createProxiedPathBuilder} from './ProxiedPathBuilder.js';\nimport {\n serializeWherePath,\n serializeSortByPath,\n serializeRawMinusEntry,\n deserializeWherePath,\n deserializeSortByPath,\n deserializeRawMinusEntry,\n type WherePathJSON,\n type SortByPathJSON,\n type RawMinusEntryJSON,\n} from './QueryBuilderSerialization.js';\nimport {requireLiveQueryStore} from '../live/registry.js';\nimport {captureCatalog, getActiveShapeCatalog, withShapeCatalog} from '../utils/ShapeClass.js';\nimport type {ShapeCatalog} from '../utils/ShapeCatalog.js';\nimport {brandLinkedClass, isLinkedError, isLinkedInstance} from '../utils/linkedError.js';\nimport type {LiveListener, LiveQuery, LiveQueryOptions} from '../live/LiveQueryStore.js';\n\n/** JSON representation of a SelectBuilder. */\nexport type QueryBuilderJSON = {\n /** DSL-JSON wire-format version. */\n v?: string;\n shape: string;\n fields?: FieldSetFieldJSON[];\n limit?: number;\n offset?: number;\n /** A node id, or a `{@ctx: name}` context reference resolved at lowering. */\n subject?: string | ContextRefJSON;\n subjects?: string[];\n /** `.one()` — unwrap a single result. */\n one?: boolean;\n where?: WherePathJSON;\n sortBy?: SortByPathJSON;\n minusEntries?: RawMinusEntryJSON[];\n nullSubject?: boolean;\n};\n\n/** A preload entry binding a property path to a component's query. */\ninterface PreloadEntry {\n path: string;\n component: QueryComponentLike<any, any>;\n}\n\n/** A MINUS entry — either a shape type exclusion or a WHERE-clause condition. */\ninterface MinusEntry<S extends Shape> {\n shapeId?: string;\n whereFn?: WhereClause<S>;\n}\n\n/** Internal state bag for SelectBuilder. */\ninterface QueryBuilderInit<S extends Shape, R> {\n shape: ShapeConstructor<S>;\n /** The catalog the builder resolves in; absent = captured from the active one. */\n catalog?: ShapeCatalog;\n selectFn?: QueryBuildFn<S, R>;\n whereFn?: WhereClause<S>;\n sortByFn?: QueryBuildFn<S, any>;\n sortDirection?: 'ASC' | 'DESC';\n limit?: number;\n offset?: number;\n subject?: S | QResult<S> | NodeReferenceValue;\n subjects?: NodeReferenceValue[];\n singleResult?: boolean;\n selectAllLabels?: string[];\n fieldSet?: FieldSet;\n preloads?: PreloadEntry[];\n minusEntries?: MinusEntry<S>[];\n _nullSubject?: boolean;\n _pendingContextName?: string;\n // Pre-evaluated data (restored from JSON; used when callbacks are not available)\n _where?: WherePath;\n _sortBy?: SortByPath;\n _rawMinusEntries?: RawMinusEntry[];\n}\n\n/**\n * An immutable, fluent query builder for select queries.\n *\n * Every mutation method (`.select()`, `.where()`, `.limit()`, etc.) returns\n * a **new** SelectBuilder instance — the original is never modified.\n *\n * Implements `PromiseLike` so queries execute on `await`:\n * ```ts\n * const results = await SelectBuilder.from(Person).select(p => p.name);\n * ```\n *\n * Produces a raw select input (`toRawInput()`) that the free `lower()` function\n * turns into IR; the builder itself carries no dependency on the IR pipeline.\n */\nexport class SelectBuilder<S extends Shape = Shape, R = any, Result = any>\n implements PromiseLike<Result>, Promise<Result>\n{\n private readonly _shape: ShapeConstructor<S>;\n private readonly _selectFn?: QueryBuildFn<S, R>;\n private readonly _whereFn?: WhereClause<S>;\n private readonly _sortByFn?: QueryBuildFn<S, any>;\n private readonly _sortDirection?: 'ASC' | 'DESC';\n private readonly _limit?: number;\n private readonly _offset?: number;\n private readonly _subject?: S | QResult<S> | NodeReferenceValue;\n private readonly _subjects?: NodeReferenceValue[];\n private readonly _singleResult?: boolean;\n private readonly _selectAllLabels?: string[];\n private readonly _fieldSet?: FieldSet;\n private readonly _preloads?: PreloadEntry[];\n private readonly _minusEntries?: MinusEntry<S>[];\n private readonly _nullSubject?: boolean;\n private readonly _pendingContextName?: string;\n // Pre-evaluated data (restored from JSON; used when callbacks are not available)\n private readonly _where?: WherePath;\n private readonly _sortBy?: SortByPath;\n private readonly _rawMinusEntries?: RawMinusEntry[];\n private readonly _catalog: ShapeCatalog | undefined;\n\n private constructor(init: QueryBuilderInit<S, R>) {\n this._shape = init.shape;\n this._catalog = 'catalog' in init ? init.catalog : captureCatalog(init.shape);\n this._selectFn = init.selectFn;\n this._whereFn = init.whereFn;\n this._sortByFn = init.sortByFn;\n this._sortDirection = init.sortDirection;\n this._limit = init.limit;\n this._offset = init.offset;\n this._subject = init.subject;\n this._subjects = init.subjects;\n this._singleResult = init.singleResult;\n this._selectAllLabels = init.selectAllLabels;\n this._fieldSet = init.fieldSet;\n this._preloads = init.preloads;\n this._minusEntries = init.minusEntries;\n this._nullSubject = init._nullSubject;\n this._pendingContextName = init._pendingContextName;\n this._where = init._where;\n this._sortBy = init._sortBy;\n this._rawMinusEntries = init._rawMinusEntries;\n }\n\n /** Create a shallow clone with overrides. */\n private clone<NR = R, NResult = Result>(overrides: Partial<QueryBuilderInit<S, any>> = {}): SelectBuilder<S, NR, NResult> {\n return new SelectBuilder<S, NR, NResult>({\n shape: this._shape,\n selectFn: this._selectFn as any,\n whereFn: this._whereFn,\n sortByFn: this._sortByFn,\n sortDirection: this._sortDirection,\n limit: this._limit,\n offset: this._offset,\n subject: this._subject,\n subjects: this._subjects,\n singleResult: this._singleResult,\n selectAllLabels: this._selectAllLabels,\n fieldSet: this._fieldSet,\n preloads: this._preloads,\n minusEntries: this._minusEntries,\n _nullSubject: this._nullSubject,\n _pendingContextName: this._pendingContextName,\n _where: this._where,\n _sortBy: this._sortBy,\n _rawMinusEntries: this._rawMinusEntries,\n catalog: this._catalog,\n ...overrides,\n });\n }\n\n // ---------------------------------------------------------------------------\n // Static constructors\n // ---------------------------------------------------------------------------\n\n /**\n * Create a SelectBuilder for the given shape.\n *\n * Accepts a shape class (e.g. `Person`), a NodeShapeData instance,\n * or a shape IRI string (resolved via the shape registry).\n */\n static from<S extends Shape>(\n shape: ShapeConstructor<S> | string,\n ): SelectBuilder<S> {\n const resolved = resolveShape<S>(shape);\n return new SelectBuilder<S>({shape: resolved});\n }\n\n // ---------------------------------------------------------------------------\n // Fluent API — each returns a new instance\n // ---------------------------------------------------------------------------\n\n /** Set the select projection via a callback, labels, or FieldSet. */\n select<NewR>(fn: QueryBuildFn<S, NewR>): SelectBuilder<S, NewR, QueryResponseToResultType<NewR, S>[]>;\n select(labels: string[]): SelectBuilder<S>;\n select<NewR>(fieldSet: FieldSet<NewR>): SelectBuilder<S, NewR, QueryResponseToResultType<NewR, S>[]>;\n select<NewR = R>(fnOrLabelsOrFieldSet: QueryBuildFn<S, NewR> | string[] | FieldSet<any>): SelectBuilder<S, NewR, any> {\n if (isLinkedInstance(fnOrLabelsOrFieldSet, FieldSet)) {\n const labels = fnOrLabelsOrFieldSet.labels();\n const selectFn = ((p: any) =>\n labels.map((label) => p[label])) as unknown as QueryBuildFn<S, any>;\n return this.clone<NewR, any>({selectFn, selectAllLabels: undefined, fieldSet: fnOrLabelsOrFieldSet});\n }\n if (Array.isArray(fnOrLabelsOrFieldSet)) {\n const labels = fnOrLabelsOrFieldSet;\n const selectFn = ((p: any) =>\n labels.map((label) => p[label])) as unknown as QueryBuildFn<S, any>;\n return this.clone<NewR, any>({selectFn, selectAllLabels: undefined, fieldSet: undefined});\n }\n return this.clone<NewR, any>({selectFn: fnOrLabelsOrFieldSet as any, selectAllLabels: undefined, fieldSet: undefined});\n }\n\n /** Select all decorated properties of the shape. */\n selectAll(): SelectBuilder<S, any, QueryResponseToResultType<SelectAllQueryResponse<S>, S>[]> {\n const catalog = this._catalog;\n if (catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(catalog, () => this.selectAll());\n }\n const propertyLabels = getUniquePropertyShapes(this._shape.shape)\n .map((ps) => ps.label);\n const selectFn = ((p: any) =>\n propertyLabels.map((label) => p[label])) as unknown as QueryBuildFn<S, any>;\n return this.clone({selectFn, selectAllLabels: propertyLabels});\n }\n\n /** Add a where clause. */\n where(fn: WhereClause<S>): SelectBuilder<S, R, Result> {\n return this.clone({whereFn: fn});\n }\n\n /**\n * Exclude results matching a MINUS pattern.\n *\n * Accepts:\n * - A shape constructor to exclude by type: `.minus(Employee)`\n * - A WHERE callback to exclude by condition: `.minus(p => p.hobby.equals('Chess'))`\n * - A callback returning a property or array of properties for existence exclusion:\n * `.minus(p => p.hobby)` or `.minus(p => [p.hobby, p.bestFriend.name])`\n *\n * Chainable: `.minus(A).minus(B)` produces two separate `MINUS { }` blocks.\n */\n minus(shapeOrFn: ShapeConstructor<any> | WhereClause<S> | ((s: any) => any)): SelectBuilder<S, R, Result> {\n const entry: MinusEntry<S> = {};\n if (typeof shapeOrFn === 'function' && 'shape' in shapeOrFn) {\n // ShapeConstructor — has a static .shape property\n entry.shapeId = (shapeOrFn as ShapeConstructor<any>).shape?.id;\n } else {\n // WhereClause callback\n entry.whereFn = shapeOrFn as WhereClause<S>;\n }\n const existing = this._minusEntries || [];\n return this.clone({minusEntries: [...existing, entry]});\n }\n\n /** Set sort order. */\n orderBy<OR>(fn: QueryBuildFn<S, OR>, direction: 'ASC' | 'DESC' = 'ASC'): SelectBuilder<S, R, Result> {\n return this.clone({sortByFn: fn as any, sortDirection: direction});\n }\n\n /**\n * @deprecated Use `orderBy()` instead.\n */\n sortBy<OR>(fn: QueryBuildFn<S, OR>, direction: 'ASC' | 'DESC' = 'ASC'): SelectBuilder<S, R, Result> {\n return this.orderBy(fn, direction);\n }\n\n /** Set result limit. */\n limit(n: number): SelectBuilder<S, R, Result> {\n return this.clone({limit: n});\n }\n\n /** Set result offset. */\n offset(n: number): SelectBuilder<S, R, Result> {\n return this.clone({offset: n});\n }\n\n /** Target a single entity by ID. Implies singleResult; unwraps array Result type. */\n for(id: string | NodeReferenceValue | PendingQueryContext | null | undefined): SelectBuilder<S, R, Result extends (infer E)[] ? E : Result> {\n if (isLinkedInstance(id, PendingQueryContext)) {\n // Store the pending context as subject — its .id getter resolves lazily\n // from the global context map when the query is lowered/serialized.\n return this.clone({subject: id as any, subjects: undefined, singleResult: true, _nullSubject: false, _pendingContextName: id.contextName}) as any;\n }\n if (id == null) {\n // Return a builder that resolves to null when executed (no subject = no query).\n // This commonly happens when getQueryContext() returns null before the user is authenticated.\n return this.clone({subject: undefined, subjects: undefined, singleResult: true, _nullSubject: true, _pendingContextName: undefined}) as any;\n }\n const subject: NodeReferenceValue = typeof id === 'string' ? {id: resolveUriOrThrow(id)} : id;\n return this.clone({subject, subjects: undefined, singleResult: true, _pendingContextName: undefined}) as any;\n }\n\n /**\n * Whether the query has a pending (lazy) context that hasn't resolved yet.\n * Returns true when .for() received a PendingQueryContext whose value isn't available yet.\n */\n hasPendingContext(): boolean {\n return !!(this._pendingContextName && !this._subject?.id);\n }\n\n /** Target multiple entities by ID, or all if no ids given. */\n forAll(ids?: (string | NodeReferenceValue)[]): SelectBuilder<S, R, Result> {\n if (!ids) {\n return this.clone({subject: undefined, subjects: undefined, singleResult: false, _pendingContextName: undefined});\n }\n const subjects = ids.map((id) => typeof id === 'string' ? {id: resolveUriOrThrow(id)} : id);\n return this.clone({subject: undefined, subjects, singleResult: false, _pendingContextName: undefined});\n }\n\n /** Limit to one result. Unwraps array Result type to single element. */\n one(): SelectBuilder<S, R, Result extends (infer E)[] ? E : Result> {\n return this.clone<R, Result extends (infer E)[] ? E : Result>({limit: 1, singleResult: true});\n }\n\n /**\n * Whether **any** row matches this query. Executes immediately and resolves to a\n * real `boolean` — never a row, never `null`, never an array the caller has to\n * interpret.\n *\n * ```ts\n * await Person.select().where(p => p.name.equals('Semmy')).exists(); // boolean\n * await Person.exists({id}); // the common case\n * ```\n *\n * ### The query is normalised to its cheapest correct form first\n *\n * **Dropped** — the projection, preloads, sorting *and pagination* (`limit`/`offset`).\n * **Kept** — filters, `minus` entries and the subject: those decide whether a match\n * exists. `LIMIT 1` is then applied.\n *\n * So `.select(…).orderBy(…).offset(10).exists()` costs, and answers, exactly the\n * same as a bare `.exists()`. Against a SPARQL store that goes out as:\n *\n * ```sparql\n * ASK WHERE { ?a0 rdf:type <…> . FILTER(?a0 = <…>) }\n * ```\n *\n * Pagination does not survive, and cannot: `OFFSET` skips rows of a *solution\n * sequence*, and an ask has none. (Nor is it merely dropped — an\n * {@link AskBuilder} has nowhere to hold it.) `exists()` answers a question about\n * the **match set**, not about a page of it.\n *\n * ### Errors are not swallowed\n *\n * A store, transport or lowering failure rejects the returned promise; it is never\n * reported as `false`. That includes an unresolved query-context reference in a\n * where clause, which `exec()` deliberately reports as `null` (\"not ready\") but\n * which `exists()` must not flatten into a boolean — and a store whose `askQuery`\n * resolves to something that is not a boolean, which rejects rather than being\n * coerced into one.\n *\n * The one case that does resolve `false` without querying is a query with **no\n * subject to ask about** — `.for(null)`, `.for(undefined)`, or an unresolved\n * `PendingQueryContext` *as the subject*. \"Does the node with no id exist?\" has a\n * correct total answer, and it is `false`.\n *\n * @param target Optional explicit dataset, as for {@link exec}.\n */\n async exists(target?: IDataset): Promise<boolean> {\n return this._toAsk().exec(target);\n }\n\n /**\n * **How many** rows match this query — the total of the match set, as a real\n * `number`.\n *\n * ```ts\n * await Person.select().where(p => p.name.equals('Semmy')).count(); // number\n * await SelectBuilder.from(shapeIri).where(…).count(); // from an IRI alone\n * ```\n *\n * ### The query is normalised to its cheapest correct form first\n *\n * **Dropped** — the projection, preloads, sorting *and pagination*\n * (`limit`/`offset`). **Kept** — filters, `minus` entries and the subject: those\n * decide membership of the match set. Against a SPARQL store that goes out as:\n *\n * ```sparql\n * SELECT (COUNT(DISTINCT ?a0) AS ?count)\n * WHERE { ?a0 rdf:type <…> . ?a0 <…name> ?a0_name . FILTER(?a0_name = \"Semmy\") }\n * ```\n *\n * ### `limit`/`offset` are dropped, not rejected\n *\n * A count of a windowed query is meaningless — `OFFSET` skips rows of a *solution\n * sequence*, and the number a count answers is a property of the whole match set,\n * not of a page of it. So `.limit(20).offset(40).count()` costs, and answers,\n * exactly the same as a bare `.count()`.\n *\n * Dropping rather than throwing is deliberate: the paging caller holds **one**\n * builder and wants the page *and* its total from the same filter, so rejecting\n * the combination would force it to rebuild the builder by hand for no\n * correctness gain. There is exactly one sensible reading, and it is this one.\n * `.exists()` already made the same call, so the DSL has one rule — *a\n * scalar-answering query drops the solution-sequence modifiers* — not two.\n *\n * Nor is the drop merely a convention: a {@link CountBuilder} has nowhere to hold\n * a window, so it cannot be forgotten or half-applied downstream.\n *\n * `DISTINCT` is likewise not optional. A filter on a multi-valued property yields\n * several rows per subject, so the count is of distinct subjects — \"how many\n * instances match\", which is the question asked.\n *\n * ### Errors are not swallowed\n *\n * A store, transport or lowering failure **rejects**; it is never reported as `0`.\n * `0` is a plausible count: it renders an empty table and looks like data. Do not\n * wrap this in `.catch(() => 0)`.\n *\n * The one case that resolves `0` without querying is a query with no subject to\n * count — `.for(null)`, `.for(undefined)`, or an unresolved `PendingQueryContext`\n * *as the subject*.\n *\n * @param target Optional explicit dataset, as for {@link exec}.\n */\n async count(target?: IDataset): Promise<number> {\n return this.toCount().exec(target);\n }\n\n /**\n * Reduce this select to the count query that answers \"how many match?\".\n *\n * Public, unlike the ask equivalent, because a caller may want to **forward**\n * rather than execute: `builder.toCount().toJSON()` is the `{op: 'count'}` wire\n * envelope a router or RPC boundary sends on, and `fromJSON` turns it back into a\n * `CountBuilder` on the other side.\n *\n * Only the pattern survives — shape, subject(s), filters, `minus`. The projection,\n * preloads, sorting and pagination are not so much \"dropped\" as unrepresentable:\n * {@link CountBuilder} has nowhere to put them. That is the point of it being a\n * separate builder rather than a mode of this one.\n */\n toCount(): CountBuilder {\n const catalog = this._catalog;\n if (catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(catalog, () => this.toCount());\n }\n return CountBuilder.of({\n shapeClass: this._shape,\n catalog: this._catalog,\n // `.for(null)` rides along in the spec. An unresolved pending context is\n // handled by CountBuilder.exec, which answers `0` without querying.\n ...this._patternSpec(),\n });\n }\n\n /**\n * The pattern-bearing part of this select: shape-membership, subject(s), filters\n * and `minus` — everything that decides which nodes are in the match set, and\n * nothing that shapes or windows the rows describing them.\n *\n * Shared by {@link _toAsk} and {@link toCount} rather than written twice. That is\n * not only about duplication: if the two normalisations drifted, `.exists()` and\n * `.count()` would disagree about what the match set *is* — a count of 0 next to\n * an `exists` of `true`, from the same builder.\n */\n private _patternSpec(): {\n subject?: NodeReferenceValue | PendingQueryContext;\n subjects?: NodeReferenceValue[];\n where?: WherePath;\n minusEntries?: RawMinusEntry[];\n nullSubject?: boolean;\n } {\n const catalog = this._catalog;\n if (catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(catalog, () => this._patternSpec());\n }\n let where: WherePath | undefined;\n if (this._whereFn) {\n where = processWhereClause(this._whereFn, this._shape);\n } else if (this._where) {\n where = this._where;\n }\n\n let minusEntries: RawMinusEntry[] | undefined;\n if (this._minusEntries && this._minusEntries.length > 0) {\n minusEntries = this._evaluateMinusEntries();\n } else if (this._rawMinusEntries && this._rawMinusEntries.length > 0) {\n minusEntries = this._rawMinusEntries;\n }\n\n // A PendingQueryContext must survive as itself. It has an `id` *getter*, so\n // narrowing it to `{id}` here would silently resolve it against THIS process's\n // context map — and the query would then travel as a concrete IRI where the\n // equivalent select travels as `{\"@ctx\": name}` for the receiver to resolve.\n const subject =\n isLinkedInstance(this._subject, PendingQueryContext)\n ? this._subject\n : this._subject && typeof this._subject === 'object' && 'id' in this._subject\n ? {id: (this._subject as NodeReferenceValue).id}\n : undefined;\n\n return {\n subject,\n subjects: this._subjects,\n where,\n minusEntries,\n nullSubject: this._nullSubject,\n };\n }\n\n /**\n * Reduce this select to the ask query that answers the same existence question.\n *\n * Only the pattern survives — shape, subject(s), filters, `minus`. The\n * projection, preloads, sorting and pagination are not \"dropped\" so much as\n * unrepresentable: {@link AskBuilder} has nowhere to put them. That is the point\n * of it being a separate builder rather than a mode of this one — the\n * normalisation cannot be forgotten or half-applied.\n */\n private _toAsk(): AskBuilder {\n const catalog = this._catalog;\n if (catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(catalog, () => this._toAsk());\n }\n return AskBuilder.of({\n shapeClass: this._shape,\n catalog: this._catalog,\n // `.for(null)` rides along in the spec. An unresolved pending context is\n // handled by AskBuilder.exec, which sees the live context and answers `false`\n // without querying.\n ...this._patternSpec(),\n });\n }\n\n /**\n * Preload a component's query fields at the given property path.\n *\n * This merges the component's query paths into this query's selection,\n * wrapping them in an OPTIONAL block (handled by the IR pipeline).\n *\n * Equivalent to the DSL's `.preloadFor()`:\n * ```ts\n * // DSL style\n * Person.select(p => p.bestFriend.preloadFor(PersonCard))\n * // SelectBuilder style\n * SelectBuilder.from(Person).select(p => [p.name]).preload('bestFriend', PersonCard)\n * ```\n *\n * NOTE: Preloads hold live component references and are not serializable.\n * They are merged into the selection when the field set is evaluated\n * (`_fieldsWithPreloads()`), so changes to preload handling must account for\n * the selectFn wrapping logic.\n */\n preload<CS extends Shape, CR>(\n path: string,\n component: QueryComponentLike<CS, CR>,\n ): SelectBuilder<S, R, Result> {\n const newPreloads = [...(this._preloads || []), {path, component}];\n return this.clone({preloads: newPreloads});\n }\n\n /**\n * Returns the current selection as a FieldSet.\n * If the selection was set via a FieldSet, returns that directly.\n * If set via selectAll labels, constructs a FieldSet from them.\n * If set via a callback, eagerly evaluates it through the proxy to produce a FieldSet.\n */\n fields(): FieldSet | undefined {\n const catalog = this._catalog;\n if (catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(catalog, () => this.fields());\n }\n if (this._fieldSet) {\n return this._fieldSet;\n }\n if (this._selectAllLabels) {\n return FieldSet.for(this._shape.shape, this._selectAllLabels);\n }\n if (this._selectFn) {\n // Eagerly evaluate the callback through FieldSet.for(ShapeClass, callback)\n // The callback is pure — same proxy always produces same paths.\n return FieldSet.for(this._shape, this._selectFn as unknown as (p: any) => any[]);\n }\n return undefined;\n }\n\n // ---------------------------------------------------------------------------\n // Internal helpers\n // ---------------------------------------------------------------------------\n\n /** Return the FieldSet with preload entries merged in (if any). */\n private _fieldsWithPreloads(): FieldSet | undefined {\n let fs = this.fields();\n if (this._preloads && this._preloads.length > 0) {\n const preloadFn = (p: any) => {\n return this._preloads!.map((entry) => p[entry.path].preloadFor(entry.component));\n };\n const preloadFs = FieldSet.for(this._shape, preloadFn);\n if (fs) {\n fs = FieldSet.createFromEntries(fs.shape, [\n ...(fs.entries as FieldSetEntry[]),\n ...(preloadFs.entries as FieldSetEntry[]),\n ]);\n } else {\n fs = preloadFs;\n }\n }\n return fs;\n }\n\n /** Evaluate minus entry callbacks into RawMinusEntry[] (plain data). */\n private _evaluateMinusEntries(): RawMinusEntry[] {\n const proxy = createProxiedPathBuilder(this._shape);\n return this._minusEntries!.map((entry) => {\n if (entry.shapeId) {\n return {shapeId: entry.shapeId};\n }\n if (entry.whereFn) {\n const result = (entry.whereFn as Function)(proxy);\n\n if (Array.isArray(result)) {\n const propertyPaths = result.map((item: any) => {\n const segments = FieldSet.collectPropertySegments(item);\n return segments.map((seg): PropertyPathSegment => ({propertyShapeId: seg.id}));\n });\n return {propertyPaths};\n }\n\n if (result && typeof result === 'object' && 'property' in result && 'subject' in result) {\n const segments = FieldSet.collectPropertySegments(result);\n return {propertyPaths: [segments.map((seg): PropertyPathSegment => ({propertyShapeId: seg.id}))]};\n }\n\n // WHERE-based exclusion\n return {where: processWhereClause(entry.whereFn, this._shape)};\n }\n return {};\n });\n }\n\n // ---------------------------------------------------------------------------\n // Serialization\n // ---------------------------------------------------------------------------\n\n /**\n * Serialize this SelectBuilder to a plain JSON object.\n *\n * Selections are serializable regardless of how they were set (FieldSet,\n * string[], selectAll, or callback). Callback-based selections are eagerly\n * evaluated through the proxy to produce a FieldSet.\n *\n * Where, orderBy, and minus clauses are evaluated through the proxy and\n * serialized as plain data structures. Preloads are merged into the FieldSet\n * as subSelect entries, producing identical IR on deserialization.\n */\n toJSON(): QueryBuilderJSON {\n const catalog = this._catalog;\n if (catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(catalog, () => this.toJSON());\n }\n const shapeId = this._shape.shape?.id || '';\n const json: QueryBuilderJSON = {\n v: WIRE_VERSION,\n shape: shapeId,\n };\n\n const fs = this._fieldsWithPreloads();\n if (fs) {\n json.fields = fs.toJSON().fields;\n }\n\n if (this._limit !== undefined) {\n json.limit = this._limit;\n }\n if (this._offset !== undefined) {\n json.offset = this._offset;\n }\n if (this._pendingContextName) {\n // Carry the context reference, not its (possibly unresolved) id, so the\n // receiver resolves it against its own context map at lowering time.\n json.subject = encodeContextRef(this._pendingContextName);\n } else if (this._subject && typeof this._subject === 'object' && 'id' in this._subject) {\n json.subject = (this._subject as NodeReferenceValue).id;\n }\n if (this._subjects && this._subjects.length > 0) {\n json.subjects = this._subjects.map((s) => s.id);\n }\n if (this._singleResult) {\n json.one = true;\n }\n\n if (this._whereFn) {\n json.where = serializeWherePath(processWhereClause(this._whereFn, this._shape), this._shape.shape);\n } else if (this._where) {\n json.where = serializeWherePath(this._where, this._shape.shape);\n }\n\n if (this._sortByFn) {\n json.sortBy = serializeSortByPath(\n evaluateSortCallback(this._shape, this._sortByFn as unknown as (p: any) => any, this._sortDirection || 'ASC'),\n );\n } else if (this._sortBy) {\n json.sortBy = serializeSortByPath(this._sortBy);\n }\n\n if (this._minusEntries && this._minusEntries.length > 0) {\n json.minusEntries = this._evaluateMinusEntries().map((e) =>\n serializeRawMinusEntry(e, this._shape.shape),\n );\n } else if (this._rawMinusEntries && this._rawMinusEntries.length > 0) {\n json.minusEntries = this._rawMinusEntries.map((e) =>\n serializeRawMinusEntry(e, this._shape.shape),\n );\n }\n\n if (this._nullSubject) {\n json.nullSubject = true;\n }\n\n return json;\n }\n\n /**\n * Reconstruct a SelectBuilder from a JSON object.\n * Resolves shape IRI via getShapeClass() and field paths as label selections.\n */\n static fromJSON<S extends Shape = Shape>(json: QueryBuilderJSON): SelectBuilder<S> {\n assertWireVersion(json.v);\n let builder = SelectBuilder.from<S>(json.shape as any);\n\n if (json.fields && json.fields.length > 0) {\n const fieldSet = FieldSet.fromJSON({\n shape: json.shape,\n fields: json.fields,\n });\n builder = builder.select(fieldSet) as SelectBuilder<S>;\n }\n\n if (json.limit !== undefined) {\n builder = builder.limit(json.limit) as SelectBuilder<S>;\n }\n if (json.offset !== undefined) {\n builder = builder.offset(json.offset) as SelectBuilder<S>;\n }\n if (json.subject) {\n // A `{@ctx}` subject rehydrates as a pending context (preserving the name\n // so it re-serializes as a context reference and resolves live).\n const subject = isContextRefJSON(json.subject)\n ? new PendingQueryContext(json.subject['@ctx'])\n : json.subject;\n builder = builder.for(subject) as SelectBuilder<S>;\n }\n if (json.subjects && json.subjects.length > 0) {\n builder = builder.forAll(json.subjects) as SelectBuilder<S>;\n }\n if (json.one && !json.subject) {\n builder = builder.one() as SelectBuilder<S>;\n }\n\n // Restore pre-evaluated data via clone — safe because fromJSON is in the same class.\n const overrides: Partial<QueryBuilderInit<S, any>> = {};\n const nodeShape = builder._shape.shape;\n\n // Restore where clause\n if (json.where && nodeShape) {\n overrides._where = deserializeWherePath(nodeShape, json.where);\n }\n\n // Restore sort key + direction (direction rides on the ordered sortBy array)\n if (json.sortBy && json.sortBy.length > 0 && nodeShape) {\n const sortBy = deserializeSortByPath(nodeShape, json.sortBy);\n overrides._sortBy = sortBy;\n overrides.sortDirection = sortBy.directions[0];\n }\n\n // Restore minus entries\n if (json.minusEntries && json.minusEntries.length > 0 && nodeShape) {\n overrides._rawMinusEntries = json.minusEntries.map((e) =>\n deserializeRawMinusEntry(nodeShape, e),\n );\n }\n\n // Restore nullSubject flag\n if (json.nullSubject) {\n overrides._nullSubject = true;\n }\n\n if (Object.keys(overrides).length > 0) {\n builder = (builder as any).clone(overrides) as SelectBuilder<S>;\n }\n\n return builder;\n }\n\n // ---------------------------------------------------------------------------\n // Build & execute\n // ---------------------------------------------------------------------------\n\n /**\n * Get the raw pipeline input.\n *\n * Constructs RawSelectInput directly from FieldSet entries.\n */\n toRawInput(): RawSelectInput {\n const catalog = this._catalog;\n if (catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(catalog, () => this.toRawInput());\n }\n return this._buildDirectRawInput();\n }\n\n /** Build RawSelectInput directly from FieldSet entries. */\n private _buildDirectRawInput(): RawSelectInput {\n const fs = this._fieldsWithPreloads();\n const entries = fs ? fs.entries : [];\n\n let where: WherePath | undefined;\n if (this._whereFn) {\n where = processWhereClause(this._whereFn, this._shape);\n } else if (this._where) {\n where = this._where;\n }\n\n let sortBy: SortByPath | undefined;\n if (this._sortByFn) {\n sortBy = evaluateSortCallback(\n this._shape,\n this._sortByFn as unknown as (p: any) => any,\n this._sortDirection || 'ASC',\n );\n } else if (this._sortBy) {\n sortBy = this._sortBy;\n }\n\n const input: RawSelectInput = {\n entries,\n subject: this._subject,\n limit: this._limit,\n offset: this._offset,\n shape: this._shape,\n sortBy,\n singleResult:\n this._singleResult ||\n !!(\n this._subject &&\n typeof this._subject === 'object' &&\n 'id' in this._subject\n ),\n };\n\n if (where) {\n input.where = where;\n }\n if (this._subjects && this._subjects.length > 0) {\n input.subjects = this._subjects;\n }\n if (this._minusEntries && this._minusEntries.length > 0) {\n input.minusEntries = this._evaluateMinusEntries();\n } else if (this._rawMinusEntries && this._rawMinusEntries.length > 0) {\n input.minusEntries = this._rawMinusEntries;\n }\n\n return input;\n }\n\n /** Discriminator for the free `lower()` function and dataset routing. */\n readonly __queryKind = 'select' as const;\n\n /** The shape this query targets — the routing key datasets/`LinkedStorage` use. */\n get shape(): NodeShapeData {\n return this._shape.shape;\n }\n\n /**\n * The catalog this builder resolves shapes in — captured when it was built, kept by\n * every derived builder. Undefined = the global registry. Never serialized.\n */\n get catalog(): ShapeCatalog | undefined {\n return this._catalog;\n }\n\n /**\n * Execute the query and return results.\n *\n * @param target Optional explicit dataset (a store or a router — a router *is* an\n * `IDataset`) to run against. Omitted → the global query dispatch (the router's\n * shape-based default). A `target` runs on that dataset only; the global router is\n * untouched. `await`ing the builder (the PromiseLike path) always uses the global\n * dispatch — only `.exec(target)` overrides.\n */\n async exec(target?: IDataset): Promise<Result> {\n return this._run(target, true) as Promise<Result>;\n }\n\n /**\n * Shared execution path for {@link exec} and {@link exists}.\n *\n * @param swallowUnresolvedContext When true (the `exec` path), a where-clause\n * context reference that has not resolved yet surfaces as `null` — \"not ready\",\n * which a reactive layer re-runs once the context lands. `exists()` passes\n * false: it must not turn \"could not ask\" into a boolean.\n */\n private async _run(\n target: IDataset | undefined,\n swallowUnresolvedContext: boolean,\n ): Promise<unknown> {\n if (this._nullSubject) {\n // .for(null/undefined) was called — return null instead of executing a broken query.\n return null;\n }\n if (this._pendingContextName && !this._subject?.id) {\n // Pending context hasn't resolved yet — return null rather than querying without a subject.\n return null;\n }\n // Dispatch the live (closed) query; the dataset decides whether to lower it.\n // `async` ensures a missing global dispatch surfaces as a rejected promise, not a sync throw.\n const dispatch = target ?? getQueryDispatch();\n try {\n return await dispatch.selectQuery(this);\n } catch (err) {\n // A where-clause context reference that hasn't resolved yet surfaces as\n // UnresolvedContextError when the dataset lowers the query. For SELECT this\n // means \"not ready\" — return null (a reactive layer re-runs once it lands),\n // mirroring the pending-subject behavior. Mutations still throw.\n if (swallowUnresolvedContext && isLinkedError(err, UnresolvedContextError)) {\n return null;\n }\n // The message names the query, which is what a human needs. `cause` keeps\n // the ORIGINAL error reachable as an object, which is what code needs: a\n // store error's status/endpoint/class is how a caller tells \"this dataset\n // does not exist\" from \"this query is wrong\", and without the chain the\n // only way left is to pattern-match this string. Written with\n // defineProperty rather than `new Error(msg, {cause})` because this\n // package targets es6, where that overload is not typed; the property\n // shape (own, non-enumerable) is identical.\n const wrapped = Error(`Error while executing query: ${(err as Error).stack}.\\n\\nQuery related to this error: ${JSON.stringify(this.toJSON())}`);\n Object.defineProperty(wrapped, 'cause', {\n value: err,\n writable: true,\n configurable: true,\n enumerable: false,\n });\n throw wrapped;\n }\n }\n\n\n /**\n * Go live: subscribe to this query and keep its result current.\n *\n * Returns a {@link LiveQuery} handle. `await` it for the first result,\n * `subscribe()` for every later one, `close()` when done. A listener may be\n * passed directly as the first argument. Requires the live-query store to be\n * loaded, which importing `@_linked/core` (the package root) does.\n */\n live<R = Result>(listenerOrOptions?: LiveListener<R> | LiveQueryOptions, options?: LiveQueryOptions): LiveQuery<R> {\n const listener = typeof listenerOrOptions === 'function' ? listenerOrOptions : undefined;\n const opts = typeof listenerOrOptions === 'function' ? options : listenerOrOptions;\n return requireLiveQueryStore().subscribe<R>(this as any, listener, opts);\n }\n\n // ---------------------------------------------------------------------------\n // Promise-compatible interface\n // ---------------------------------------------------------------------------\n\n /** `await` triggers execution. */\n then<TResult1 = Result, TResult2 = never>(\n onfulfilled?: ((value: Result) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null,\n ): Promise<TResult1 | TResult2> {\n return this.exec().then(onfulfilled, onrejected);\n }\n\n /** Catch errors from execution. Chain off then() to avoid re-executing. */\n catch<TResult = never>(\n onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null,\n ): Promise<Result | TResult> {\n return this.then().catch(onrejected);\n }\n\n /** Finally handler after execution. Chain off then() to avoid re-executing. */\n finally(onfinally?: (() => void) | null): Promise<Result> {\n return this.then().finally(onfinally);\n }\n\n get [Symbol.toStringTag](): string {\n return 'SelectBuilder';\n }\n}\nbrandLinkedClass(SelectBuilder, '@_linked/core', 'SelectBuilder');\n\n\n/** @deprecated Renamed to `SelectBuilder`. This alias will be removed in a future major. */\nexport {SelectBuilder as QueryBuilder};\n"]}
|
|
@@ -1,7 +1,17 @@
|
|
|
1
1
|
import { QueryShape } from './SelectQuery.js';
|
|
2
2
|
import { Shape, createShapeTarget } from '../shapes/Shape.js';
|
|
3
|
-
import { brandLinkedError } from '../utils/linkedError.js';
|
|
4
|
-
|
|
3
|
+
import { brandLinkedClass, brandLinkedError, isLinkedInstance } from '../utils/linkedError.js';
|
|
4
|
+
import { sharedState } from '../utils/sharedState.js';
|
|
5
|
+
/**
|
|
6
|
+
* The context map and its listeners, shared by every copy of core in the runtime: a context
|
|
7
|
+
* the app sets through one copy must resolve for a query lowered by the other, and a React
|
|
8
|
+
* layer subscribed through one copy must hear a change made through the other.
|
|
9
|
+
*/
|
|
10
|
+
const contextState = sharedState('@_linked/core', 'QueryContext', () => ({
|
|
11
|
+
contexts: new Map(),
|
|
12
|
+
listeners: new Set(),
|
|
13
|
+
}));
|
|
14
|
+
const queryContext = contextState.contexts;
|
|
5
15
|
/**
|
|
6
16
|
* A live reference returned by getQueryContext when the context hasn't been set yet.
|
|
7
17
|
* Its `id` getter resolves lazily from the global context map, so queries built with
|
|
@@ -16,6 +26,7 @@ export class PendingQueryContext {
|
|
|
16
26
|
return (_a = queryContext.get(this.contextName)) === null || _a === void 0 ? void 0 : _a.id;
|
|
17
27
|
}
|
|
18
28
|
}
|
|
29
|
+
brandLinkedClass(PendingQueryContext, '@_linked/core', 'PendingQueryContext');
|
|
19
30
|
/**
|
|
20
31
|
* Thrown when a query carrying a context reference is lowered but the context
|
|
21
32
|
* isn't set in the current process. A context ref is carried in DSL-JSON and
|
|
@@ -31,7 +42,7 @@ export class UnresolvedContextError extends Error {
|
|
|
31
42
|
}
|
|
32
43
|
}
|
|
33
44
|
brandLinkedError(UnresolvedContextError, '@_linked/core', 'UnresolvedContextError');
|
|
34
|
-
const contextListeners =
|
|
45
|
+
const contextListeners = contextState.listeners;
|
|
35
46
|
/**
|
|
36
47
|
* Subscribe to query-context changes. Returns an unsubscribe function.
|
|
37
48
|
*
|
|
@@ -72,7 +83,7 @@ function notifyContextChange(name) {
|
|
|
72
83
|
*/
|
|
73
84
|
export function asContextRef(value) {
|
|
74
85
|
var _a;
|
|
75
|
-
if (value
|
|
86
|
+
if (isLinkedInstance(value, PendingQueryContext))
|
|
76
87
|
return value;
|
|
77
88
|
if (!value || typeof value !== 'object')
|
|
78
89
|
return undefined;
|
|
@@ -107,7 +118,7 @@ export function setQueryContext(name, value, shapeType) {
|
|
|
107
118
|
// Already a QShape — stamp the underlying shape and store as-is. (Checked before
|
|
108
119
|
// the plain-`{id}` branch below: a QueryShape's `.id` getter is also a string, so
|
|
109
120
|
// testing for `{id}` first would wrongly require a shapeType and no-op.)
|
|
110
|
-
if (value
|
|
121
|
+
if (isLinkedInstance(value, QueryShape)) {
|
|
111
122
|
const orig = value.originalValue;
|
|
112
123
|
if (orig) {
|
|
113
124
|
orig.__queryContextName = name;
|
|
@@ -120,7 +131,7 @@ export function setQueryContext(name, value, shapeType) {
|
|
|
120
131
|
}
|
|
121
132
|
// A Shape-shaped value (e.g. a `createShapeTarget` proxy target) — stamp it and
|
|
122
133
|
// wrap as a QShape. Needs no shapeType (it already carries its shape class).
|
|
123
|
-
if (value
|
|
134
|
+
if (isLinkedInstance(value, Shape)) {
|
|
124
135
|
value.__queryContextName = name;
|
|
125
136
|
if (typeof value.id === 'string')
|
|
126
137
|
value.__queryContextId = value.id;
|