From 5362e9d1d34d56131c166492bc0e1ef18317d033 Mon Sep 17 00:00:00 2001 From: Gareth Johnson <75035963+garethj2@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:41:55 +0000 Subject: [PATCH] Handle different refs on target --- spec/filter/relativize.spec.ts | 287 +++++++++++++++++++++++++++++++++ src/filter/relativize.ts | 144 +++++++++++++---- 2 files changed, 398 insertions(+), 33 deletions(-) diff --git a/spec/filter/relativize.spec.ts b/spec/filter/relativize.spec.ts index 3aa9739..d11fded 100644 --- a/spec/filter/relativize.spec.ts +++ b/spec/filter/relativize.spec.ts @@ -948,6 +948,293 @@ describe('haystack', () => { }) }) // other refs + describe('anchor refs', () => { + let equip: HDict + let coordinator: HDict + let subEquip: HDict + let equipPoint: HDict + let coordinatorPoint: HDict + let subEquipPoint: HDict + let sitePoint: HDict + let otherEquip: HDict + let resolve: RelativizeResolveFunc + + beforeEach(() => { + equip = new HDict({ + id: HRef.make('equipId'), + dis: 'an equip', + equip: HMarker.make(), + siteRef: HRef.make('siteId'), + cooRef: HRef.make('cooId'), + }) + + coordinator = new HDict({ + id: HRef.make('cooId'), + dis: 'a coordinator', + equip: HMarker.make(), + siteRef: HRef.make('siteId'), + }) + + subEquip = new HDict({ + id: HRef.make('subEquipId'), + dis: 'a sub equip', + equip: HMarker.make(), + equipRef: HRef.make('cooId'), + siteRef: HRef.make('siteId'), + }) + + otherEquip = new HDict({ + id: HRef.make('otherEquipId'), + dis: 'another equip', + equip: HMarker.make(), + siteRef: HRef.make('siteId'), + }) + + equipPoint = new HDict({ + id: HRef.make('equipPointId'), + dis: 'equip point', + point: HMarker.make(), + equipRef: HRef.make('equipId'), + }) + + coordinatorPoint = new HDict({ + id: HRef.make('cooPointId'), + dis: 'coordinator point', + point: HMarker.make(), + equipRef: HRef.make('cooId'), + }) + + subEquipPoint = new HDict({ + id: HRef.make('subEquipPointId'), + dis: 'sub equip point', + point: HMarker.make(), + equipRef: HRef.make('subEquipId'), + }) + + sitePoint = new HDict({ + id: HRef.make('sitePointId'), + dis: 'site point', + point: HMarker.make(), + equipRef: HRef.make('otherEquipId'), + }) + + const dicts = [equip, coordinator, subEquip, otherEquip] + + resolve = async (ref: HRef) => + dicts.find((dict) => dict.get('id')?.equals(ref)) + }) + + it('relativizes to the target id', async () => { + const result = await makeRelativeHaystackFilterForTarget( + equip, + equipPoint, + { resolve } + ) + + expect(result).toBe( + 'equipRef == $id and dis == "equip point" and point' + ) + }) + + it('relativizes to a record contained under another ref on the target', async () => { + const result = await makeRelativeHaystackFilterForTarget( + equip, + coordinatorPoint, + { resolve } + ) + + expect(result).toBe( + 'equipRef == $cooRef and dis == "coordinator point" and point' + ) + }) + + it('relativizes to a record nested under another ref on the target', async () => { + const result = await makeRelativeHaystackFilterForTarget( + equip, + subEquipPoint, + { resolve } + ) + + expect(result).toBe( + 'equipRef->equipRef == $cooRef and dis == "sub equip point" and point and equipRef->dis == "a sub equip" and equipRef->equip' + ) + }) + + it('gives the target id precedence over other refs', async () => { + const target = new HDict({ + id: HRef.make('equipId'), + cooRef: HRef.make('equipId'), + }) + + const result = await makeRelativeHaystackFilterForTarget( + target, + equipPoint, + { resolve } + ) + + expect(result).toBe( + 'equipRef == $id and dis == "equip point" and point' + ) + }) + + it('throws for a contained record when includeOtherRefs is false', async () => { + await expect( + makeRelativeHaystackFilterForTarget( + equip, + coordinatorPoint, + { + resolve, + includeOtherRefs: false, + } + ) + ).rejects.toThrow() + }) + + it('never automatically uses containment refs on the target', async () => { + await expect( + makeRelativeHaystackFilterForTarget(equip, sitePoint, { + resolve, + }) + ).rejects.toThrow() + }) + + it('excludes containment refs defined in the namespace', async () => { + const target = new HDict({ + id: HRef.make('equipId'), + fooRef: HRef.make('cooId'), + }) + + const namespace = { + getContainmentRefs: () => [ + HDict.make({ def: HSymbol.make('fooRef') }), + ], + } as unknown as HNamespace + + await expect( + makeRelativeHaystackFilterForTarget( + target, + coordinatorPoint, + { + resolve, + namespace, + } + ) + ).rejects.toThrow() + }) + + it('skips anchor names that are not refs', async () => { + await expect( + makeRelativeHaystackFilterForTarget( + equip, + coordinatorPoint, + { + resolve, + targetRefNames: ['dis'], + } + ) + ).rejects.toThrow() + }) + + describe('targetRefNames', () => { + it('uses a single ref name', async () => { + const result = await makeRelativeHaystackFilterForTarget( + equip, + coordinatorPoint, + { resolve, targetRefNames: 'cooRef' } + ) + + expect(result).toBe( + 'equipRef == $cooRef and dis == "coordinator point" and point' + ) + }) + + it('replaces automatic discovery so id is not used unless listed', async () => { + await expect( + makeRelativeHaystackFilterForTarget(equip, equipPoint, { + resolve, + targetRefNames: 'cooRef', + }) + ).rejects.toThrow() + }) + + it('does not discover other refs that are not listed', async () => { + await expect( + makeRelativeHaystackFilterForTarget( + equip, + coordinatorPoint, + { resolve, targetRefNames: ['id'] } + ) + ).rejects.toThrow() + }) + + it('uses the list in priority order', async () => { + const target = new HDict({ + id: HRef.make('equipId'), + cooRef: HRef.make('equipId'), + }) + + const result = await makeRelativeHaystackFilterForTarget( + target, + equipPoint, + { resolve, targetRefNames: ['cooRef', 'id'] } + ) + + expect(result).toBe( + 'equipRef == $cooRef and dis == "equip point" and point' + ) + }) + + it('falls back to automatic discovery for an empty list', async () => { + for (const targetRefNames of [[], '']) { + expect( + await makeRelativeHaystackFilterForTarget( + equip, + equipPoint, + { resolve, targetRefNames } + ) + ).toBe( + 'equipRef == $id and dis == "equip point" and point' + ) + + expect( + await makeRelativeHaystackFilterForTarget( + equip, + coordinatorPoint, + { resolve, targetRefNames } + ) + ).toBe( + 'equipRef == $cooRef and dis == "coordinator point" and point' + ) + } + }) + + it('resolves both ids and other refs from a list', async () => { + const options = { + resolve, + targetRefNames: ['id', 'cooRef'], + } + + expect( + await makeRelativeHaystackFilterForTarget( + equip, + equipPoint, + options + ) + ).toBe('equipRef == $id and dis == "equip point" and point') + + expect( + await makeRelativeHaystackFilterForTarget( + equip, + coordinatorPoint, + options + ) + ).toBe( + 'equipRef == $cooRef and dis == "coordinator point" and point' + ) + }) + }) + }) // anchor refs + describe('options', () => { let equip: HDict let point: HDict diff --git a/src/filter/relativize.ts b/src/filter/relativize.ts index f7a138e..c46f970 100644 --- a/src/filter/relativize.ts +++ b/src/filter/relativize.ts @@ -116,57 +116,76 @@ export interface RelativizeForTargetOptions extends RelativizeOptions { includeTargetMacro?: boolean /** - * True (or undefined) if other references on the target record should be included when relativizing. + * True (or undefined) if other references on the target record should be automatically + * discovered and used as anchors when relativizing. * - * If this is false, only the containment references will be used to relativize the filter. - * If this is true, other references on the target record will be used to relativize the filter - * if they match the record being relativized. + * The target's `id` is always tried first. If this is true, any other references on the + * target that aren't containment references (i.e. `siteRef`, `equipRef` etc) are then + * tried in turn. A record matches one of these anchors if it either... + * + * - Has the same reference value as the target (i.e. `cooRef == $cooRef`). + * - Is contained under the referenced record (i.e. `equipRef == $cooRef`). + * + * If a namespace is specified, it's used to determine the containment references to exclude. + * + * This is ignored if `targetRefNames` is specified. */ includeOtherRefs?: boolean + + /** + * An optional explicit priority list of reference names on the target to use as + * anchors for relativization (i.e. `['id', 'cooRef']`). + * + * When specified, this replaces automatic discovery and the names are used exactly + * as given. If `id` should be used, it must be included in the list. An empty list + * falls back to automatic discovery. + */ + targetRefNames?: string | string[] } /** * Make a relative haystack filter for a target record. * - * The target record doesn't need to be the direct parent of - * the record, but it must be an ancestor in the containment hierarchy. + * The target record doesn't need to be the direct parent of the record. The record + * must either be contained under the target or be reachable through one of the target's + * anchor references (see `includeOtherRefs` and `targetRefNames`). * * @param target The target record to set the relative filter for. * @param record The child record to make the relative filter for. * @param options The options for relativizing the filter. * @returns A promise that resolves to the relative haystack filter. + * @throws An error if the record can't be relativized to the target. */ export async function makeRelativeHaystackFilterForTarget( target: HDict, record: HDict, options?: RelativizeForTargetOptions ): Promise { - let refMacroName = 'id' - - // 1. Resolve a path to the target record using containment. - let dictPathInfo = await resolveDictPathForId(target, record, options) - - const includeOtherRefs = options?.includeOtherRefs ?? true + const anchorRefNames = getAnchorRefNames(target, options) - // 2. If that can't be found then search through the target for other refs that could be used - // for relativization. - if (includeOtherRefs && !dictPathInfo) { - for (const refName of extractRefNamesFromTarget(target)) { - if (record.get(refName)?.equals(target.get(refName))) { - refMacroName = refName + let targetRefName = '' + let dictPathInfo: DictPathInfo | undefined - dictPathInfo = { - dicts: [record], - path: [refName], - } + for (const refName of anchorRefNames) { + dictPathInfo = await resolvePathForAnchor( + target, + refName, + record, + options + ) - break - } + if (dictPathInfo) { + targetRefName = refName + break } } if (!dictPathInfo) { - throw new Error('Could not resolve relative path for target record') + throw new Error( + `Could not resolve relative path for target record using refs: ${anchorRefNames.join( + ', ' + )}` + ) } const includeTargetMacro = options?.includeTargetMacro ?? true @@ -178,7 +197,7 @@ export async function makeRelativeHaystackFilterForTarget( const builder = new HFilterBuilder() const prefix = includeTargetMacro - ? dictPathInfo.path.join('->') + ` == $${refMacroName} and ` + ? dictPathInfo.path.join('->') + ` == $${targetRefName} and ` : '' for (let i = 0; i < dicts.length; ++i) { @@ -202,19 +221,65 @@ interface DictPathInfo { path: string[] } -async function resolveDictPathForId( +/** + * Return the ordered list of reference names on the target to use as anchors. + */ +function getAnchorRefNames( target: HDict, + options?: RelativizeForTargetOptions +): string[] { + const targetRefNames = [options?.targetRefNames ?? []] + .flat() + .filter((name) => !!name) + + // An explicit list replaces automatic discovery. + if (targetRefNames.length) { + return targetRefNames + } + + // Automatic discovery always gives the target's id precedence. + const includeOtherRefs = options?.includeOtherRefs ?? true + + return [ + 'id', + ...(includeOtherRefs + ? extractRefNamesFromTarget(target, options?.namespace) + : []), + ] +} + +/** + * Attempt to resolve a path from the record to the anchor reference on the target. + */ +async function resolvePathForAnchor( + target: HDict, + refName: string, record: HDict, options?: RelativizeForTargetOptions ): Promise { - // Follow the containment refs to build a tree of records - // with the target as the root. - const targetRef = target.get('id') + const anchorRef = target.get(refName) - if (!targetRef) { + if (!valueIsKind(anchorRef, Kind.Ref)) { return undefined } + // A record that shares the same reference as the target. + if (refName !== 'id' && record.get(refName)?.equals(anchorRef)) { + return { dicts: [record], path: [refName] } + } + + // A record that's contained under the referenced record. + return resolveContainedPath(anchorRef, record, options) +} + +/** + * Follow the containment refs from the record until the anchor reference is found. + */ +async function resolveContainedPath( + anchorRef: HRef, + record: HDict, + options?: RelativizeForTargetOptions +): Promise { let dictPathInfo: DictPathInfo | undefined = undefined let currentRecord: HDict | undefined = record let count = 0 @@ -239,7 +304,7 @@ async function resolveDictPathForId( dictPathInfo.path.push(parentRefTag) // If we're found the target ref we can stop traversing up the tree. - if (parentRef.equals(targetRef)) { + if (parentRef.equals(anchorRef)) { break } @@ -300,10 +365,23 @@ const IGNORE_REF_NAMES = new Set([ 'siteRef', ]) -function extractRefNamesFromTarget(target: HDict): string[] { +/** + * Return the names of the non-containment references on the target record. + * + * If a namespace is specified, any containment references it defines are also excluded. + */ +function extractRefNamesFromTarget( + target: HDict, + namespace?: HNamespace +): string[] { + const containmentRefNames = new Set( + namespace?.getContainmentRefs().map((def) => def.defName) ?? [] + ) + return target.keys.filter( (key) => !IGNORE_REF_NAMES.has(key) && + !containmentRefNames.has(key) && valueIsKind(target.get(key), Kind.Ref) ) }