@coasys/ad4m 0.13.0-test-model-layer → 0.13.0-test-flows-1
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/lib/index.cjs +817 -65
- package/lib/index.js +814 -66
- package/lib/src/ai/AIClient.d.ts +13 -0
- package/lib/src/ai/AIClient.js +15 -0
- package/lib/src/ai/AITypes.d.ts +5 -0
- package/lib/src/index.js +2 -0
- package/lib/src/model/Ad4mModel.d.ts +6 -1
- package/lib/src/model/Ad4mModel.js +41 -6
- package/lib/src/model/ModelQueryBuilder.d.ts +47 -3
- package/lib/src/model/ModelQueryBuilder.js +97 -6
- package/lib/src/model/query-common.d.ts +10 -1
- package/lib/src/model/query-common.js +16 -0
- package/lib/src/model/query-sparql.d.ts +11 -0
- package/lib/src/model/query-sparql.js +93 -1
- package/lib/src/model/query-utils.js +16 -0
- package/lib/src/model/shacl-gen.js +12 -0
- package/lib/src/model/types.d.ts +320 -3
- package/lib/src/model/types.js +9 -0
- package/lib/src/perspectives/AutoProcessor.d.ts +8 -0
- package/lib/src/perspectives/FlowInstance.d.ts +176 -12
- package/lib/src/perspectives/FlowInstance.js +77 -13
- package/lib/src/perspectives/FlowModels.d.ts +40 -9
- package/lib/src/perspectives/FlowModels.js +59 -13
- package/lib/src/perspectives/PerspectiveClient.d.ts +18 -0
- package/lib/src/perspectives/PerspectiveClient.js +30 -0
- package/lib/src/perspectives/PerspectiveProxy.d.ts +69 -2
- package/lib/src/perspectives/PerspectiveProxy.js +157 -7
- package/lib/src/perspectives/WakerSubscriptionManager.d.ts +55 -5
- package/lib/src/perspectives/WakerSubscriptionManager.js +183 -8
- package/lib/src/shacl/SHACLFlow.d.ts +43 -0
- package/package.json +1 -1
- package/src/ai/AIClient.ts +16 -0
- package/src/ai/AITypes.ts +5 -0
- package/src/index.ts +2 -0
- package/src/model/Ad4mModel.test.ts +442 -0
- package/src/model/Ad4mModel.ts +39 -7
- package/src/model/ModelQueryBuilder.ts +101 -10
- package/src/model/query-common.ts +20 -1
- package/src/model/query-sparql.test.ts +115 -0
- package/src/model/query-sparql.ts +97 -1
- package/src/model/query-utils.ts +18 -0
- package/src/model/relation-filtering.test.ts +7 -0
- package/src/model/shacl-gen.ts +12 -0
- package/src/model/shacl-roundtrip.test.ts +71 -0
- package/src/model/types-typed-query.test.ts +42 -0
- package/src/model/types.ts +316 -6
- package/src/perspectives/AutoProcessor.ts +8 -0
- package/src/perspectives/FlowInstance.ts +194 -13
- package/src/perspectives/FlowModels.ts +53 -13
- package/src/perspectives/PerspectiveClient.ts +62 -0
- package/src/perspectives/PerspectiveProxy.test.ts +272 -0
- package/src/perspectives/PerspectiveProxy.ts +163 -7
- package/src/perspectives/WakerSubscriptionManager.test.ts +199 -0
- package/src/perspectives/WakerSubscriptionManager.ts +197 -9
- package/src/shacl/SHACLFlow.ts +44 -0
|
@@ -6,11 +6,11 @@
|
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
import type { Ad4mModel } from "./Ad4mModel";
|
|
9
|
-
import type { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
|
|
9
|
+
import type { LinkStatus, PerspectiveProxy } from "../perspectives/PerspectiveProxy";
|
|
10
10
|
import type {
|
|
11
11
|
Where, Order, IncludeMap, Query,
|
|
12
12
|
ResultsWithTotalCount, PaginationResult,
|
|
13
|
-
|
|
13
|
+
TypedQueryWhere, TypedOrder, TypedIncludeMap, PropertyKeysOf,
|
|
14
14
|
} from "./types";
|
|
15
15
|
|
|
16
16
|
/** Query builder for Ad4mModel queries.
|
|
@@ -81,7 +81,7 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
81
81
|
* })
|
|
82
82
|
* ```
|
|
83
83
|
*/
|
|
84
|
-
where(conditions:
|
|
84
|
+
where(conditions: TypedQueryWhere<T>): ModelQueryBuilder<T> {
|
|
85
85
|
this.queryParams.where = conditions as Where;
|
|
86
86
|
return this;
|
|
87
87
|
}
|
|
@@ -224,6 +224,24 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
224
224
|
return this;
|
|
225
225
|
}
|
|
226
226
|
|
|
227
|
+
/**
|
|
228
|
+
* Asks for the individual links behind each instance — author, timestamp
|
|
229
|
+
* and proof per link — under `instance.__links`. See `Query.links`.
|
|
230
|
+
*
|
|
231
|
+
* @param keys - Property / relation names, or absolute predicate IRIs
|
|
232
|
+
* @returns The query builder for chaining
|
|
233
|
+
*
|
|
234
|
+
* @example
|
|
235
|
+
* ```typescript
|
|
236
|
+
* const [post] = await Post.query(perspective).links(["comments"]).get();
|
|
237
|
+
* post.__links!.comments.map((l) => l.timestamp); // when each comment was attached
|
|
238
|
+
* ```
|
|
239
|
+
*/
|
|
240
|
+
links(keys: string[]): ModelQueryBuilder<T> {
|
|
241
|
+
this.queryParams.links = keys;
|
|
242
|
+
return this;
|
|
243
|
+
}
|
|
244
|
+
|
|
227
245
|
/**
|
|
228
246
|
* Controls whether SPARQL property getters are evaluated during hydration.
|
|
229
247
|
*
|
|
@@ -247,6 +265,44 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
247
265
|
return this;
|
|
248
266
|
}
|
|
249
267
|
|
|
268
|
+
/**
|
|
269
|
+
* Reads instances as they exist in links of one status only.
|
|
270
|
+
*
|
|
271
|
+
* `'shared'` leaves out every Local link, both from the values returned and
|
|
272
|
+
* from what decides which instances are returned. Use it when the data is
|
|
273
|
+
* shown to another user. `'local'` is the converse: it returns only
|
|
274
|
+
* instances flagged in a Local link, so a Local note on a card flagged only
|
|
275
|
+
* in a Shared link is read without `linkStatus`, not under `'local'`.
|
|
276
|
+
* See {@link Query.linkStatus}.
|
|
277
|
+
*
|
|
278
|
+
* @param status - `'shared'` or `'local'`
|
|
279
|
+
* @returns The query builder for chaining
|
|
280
|
+
*
|
|
281
|
+
* @example
|
|
282
|
+
* ```typescript
|
|
283
|
+
* const cards = await Card.query(perspective).linkStatus('shared').get();
|
|
284
|
+
* ```
|
|
285
|
+
*/
|
|
286
|
+
linkStatus(status: LinkStatus): ModelQueryBuilder<T> {
|
|
287
|
+
this.queryParams.linkStatus = status;
|
|
288
|
+
return this;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* Also hydrate from links whose signature did not verify.
|
|
293
|
+
*
|
|
294
|
+
* Off by default: the executor withholds unverified links. Turn it on only
|
|
295
|
+
* to *display* an unverified claim, never for data you act on. See
|
|
296
|
+
* {@link Query.includeUnverified}.
|
|
297
|
+
*
|
|
298
|
+
* @param enabled - Whether to include unverified links (default: true)
|
|
299
|
+
* @returns The query builder for chaining
|
|
300
|
+
*/
|
|
301
|
+
includeUnverified(enabled: boolean = true): ModelQueryBuilder<T> {
|
|
302
|
+
this.queryParams.includeUnverified = enabled;
|
|
303
|
+
return this;
|
|
304
|
+
}
|
|
305
|
+
|
|
250
306
|
/**
|
|
251
307
|
* Specifies which relations to eager-load (hydrate into model instances).
|
|
252
308
|
*
|
|
@@ -407,13 +463,10 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
407
463
|
(rawResult: any) => {
|
|
408
464
|
try {
|
|
409
465
|
const results = parseResults(rawResult);
|
|
410
|
-
console.debug(`[ModelQueryBuilder.subscribe] Update received for ${subscriptionId}: ${results.length} instances`);
|
|
411
466
|
const fp = buildFingerprint(results);
|
|
412
467
|
if (fp === lastResultFingerprint) {
|
|
413
|
-
console.debug(`[ModelQueryBuilder.subscribe] Fingerprint unchanged, skipping callback`);
|
|
414
468
|
return;
|
|
415
469
|
}
|
|
416
|
-
console.debug(`[ModelQueryBuilder.subscribe] Fingerprint changed, calling callback with ${results.length} results`);
|
|
417
470
|
lastResultFingerprint = fp;
|
|
418
471
|
callback(results);
|
|
419
472
|
} catch (e) {
|
|
@@ -711,9 +764,48 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
711
764
|
count: true,
|
|
712
765
|
};
|
|
713
766
|
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
767
|
+
// One read in flight. A dispatch while a read is running sets `pending`
|
|
768
|
+
// so a fetch always completes after the last dispatch. The generation
|
|
769
|
+
// counter from #1020 dropped superseded fetches, but ordered them by
|
|
770
|
+
// start time rather than by how fresh the data they read was — two
|
|
771
|
+
// back-to-back dispatches could keep the fetch that saw 1 model and
|
|
772
|
+
// drop the one that saw 2, after which the server has nothing further
|
|
773
|
+
// to say (issue #1051 / CI: "Paginate callback did not see second model save").
|
|
774
|
+
// After dispose() no read starts and no result is delivered, including
|
|
775
|
+
// a read that was already in flight when dispose() ran.
|
|
776
|
+
let disposed = false;
|
|
777
|
+
let fetching = false;
|
|
778
|
+
let pending = false;
|
|
779
|
+
let coalesced = 0;
|
|
780
|
+
const processResults = async (): Promise<void> => {
|
|
781
|
+
if (disposed) return;
|
|
782
|
+
if (fetching) {
|
|
783
|
+
pending = true;
|
|
784
|
+
coalesced++;
|
|
785
|
+
return;
|
|
786
|
+
}
|
|
787
|
+
fetching = true;
|
|
788
|
+
try {
|
|
789
|
+
const { results, totalCount } = await (ctor as any).executeModelQuery(this.perspective, paginatedQuery, this.modelClassName);
|
|
790
|
+
if (!disposed) callback({ results, totalCount, pageSize, pageNumber });
|
|
791
|
+
} finally {
|
|
792
|
+
fetching = false;
|
|
793
|
+
if (pending) {
|
|
794
|
+
const dispatches = coalesced;
|
|
795
|
+
pending = false;
|
|
796
|
+
coalesced = 0;
|
|
797
|
+
// Whether a trailing fetch actually starts is decided by the entry
|
|
798
|
+
// guard at the top of processResults, which returns when disposed.
|
|
799
|
+
// Log only what that guard will let through, or the dispose path
|
|
800
|
+
// announces a fetch it then drops.
|
|
801
|
+
if (!disposed) {
|
|
802
|
+
console.debug(`[ModelQueryBuilder.paginateSubscribe] ${dispatches} dispatch(es) during read for ${subscriptionId}, coalesced into one trailing fetch`);
|
|
803
|
+
}
|
|
804
|
+
// Detached from the caller's promise: needs its own handler, or a
|
|
805
|
+
// rejection here is unhandled.
|
|
806
|
+
processResults().catch(e => console.error('Paginate subscription error:', e));
|
|
807
|
+
}
|
|
808
|
+
}
|
|
717
809
|
};
|
|
718
810
|
|
|
719
811
|
const unsubscribe = this.perspective.client.subscribeToQueryUpdates(
|
|
@@ -724,7 +816,6 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
724
816
|
},
|
|
725
817
|
);
|
|
726
818
|
|
|
727
|
-
let disposed = false;
|
|
728
819
|
let keepaliveTimer: ReturnType<typeof setTimeout> | undefined;
|
|
729
820
|
let resubscribeAttempts = 0;
|
|
730
821
|
const MAX_RESUBSCRIBE_ATTEMPTS = 5;
|
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
* Shared query helpers used by both the Prolog and SPARQL query pipelines.
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
-
import type { Scope } from "./types";
|
|
5
|
+
import type { Scope, TraverseScope } from "./types";
|
|
6
|
+
import { isTraverseScope } from "./types";
|
|
6
7
|
import { getRelationsMetadata } from "./decorators";
|
|
7
8
|
|
|
8
9
|
/**
|
|
@@ -14,6 +15,24 @@ import { getRelationsMetadata } from "./decorators";
|
|
|
14
15
|
* - With `field`: direct key lookup
|
|
15
16
|
* - Without `field`: scan for a relation whose `target()` matches `childCtor`
|
|
16
17
|
*/
|
|
18
|
+
/**
|
|
19
|
+
* Narrow a scope to the one-parent forms, for the paths that write a link.
|
|
20
|
+
*
|
|
21
|
+
* A traversal describes a read outward from several anchors. Creating a record
|
|
22
|
+
* "under" one would have to pick which, and nothing in the scope says — so this
|
|
23
|
+
* refuses rather than guessing at the first of the list. The executor's write
|
|
24
|
+
* scopes refuse it for the same reason.
|
|
25
|
+
*/
|
|
26
|
+
export function requireSingleParent(parent: Scope): Exclude<Scope, TraverseScope> {
|
|
27
|
+
if (isTraverseScope(parent)) {
|
|
28
|
+
throw new Error(
|
|
29
|
+
'parent(): a traverse scope describes a read and names no single parent to write under. ' +
|
|
30
|
+
'Use { id, predicate } or { model, id } when creating a record under a parent.',
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
return parent;
|
|
34
|
+
}
|
|
35
|
+
|
|
17
36
|
export function resolveParentPredicate(
|
|
18
37
|
parent: Scope,
|
|
19
38
|
childCtor: Function,
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { buildSPARQLQuery, buildPaginationSubquery, hasJsOnlyWhereFilters, looksLikeUri, valueToLiteralIri } from './query-sparql';
|
|
2
2
|
import { Literal } from '../Literal';
|
|
3
|
+
import { buildWhereCondition } from './query-utils';
|
|
3
4
|
|
|
4
5
|
// Minimal stubs for ModelMetadata
|
|
5
6
|
const emptyMetadata: any = { properties: {}, relations: {} };
|
|
@@ -623,3 +624,117 @@ describe('looksLikeUri', () => {
|
|
|
623
624
|
expect(looksLikeUri('1abc:foo')).toBe(false);
|
|
624
625
|
});
|
|
625
626
|
});
|
|
627
|
+
|
|
628
|
+
describe('buildSPARQLQuery — traverse scope', () => {
|
|
629
|
+
const modelClass: any = {};
|
|
630
|
+
|
|
631
|
+
it('binds every anchor and emits a path for transitive', () => {
|
|
632
|
+
const query = {
|
|
633
|
+
parent: {
|
|
634
|
+
ids: ['flux://a', 'flux://b'],
|
|
635
|
+
predicate: 'flux://has_message',
|
|
636
|
+
transitive: true,
|
|
637
|
+
},
|
|
638
|
+
};
|
|
639
|
+
const sparql = buildSPARQLQuery(richMetadata, emptyRelations, query, modelClass);
|
|
640
|
+
expect(sparql).toContain('VALUES ?_anchor { <flux://a> <flux://b> }');
|
|
641
|
+
expect(sparql).toContain('?_anchor <flux://has_message>+ ?source');
|
|
642
|
+
});
|
|
643
|
+
|
|
644
|
+
it('refuses limitPerAnchor, which only the executor can apply', () => {
|
|
645
|
+
const query = {
|
|
646
|
+
parent: {
|
|
647
|
+
ids: 'flux://a',
|
|
648
|
+
predicate: 'flux://has_message',
|
|
649
|
+
limitPerAnchor: 5,
|
|
650
|
+
},
|
|
651
|
+
};
|
|
652
|
+
expect(() => buildSPARQLQuery(richMetadata, emptyRelations, query, modelClass))
|
|
653
|
+
.toThrow('limitPerAnchor');
|
|
654
|
+
});
|
|
655
|
+
|
|
656
|
+
it('refuses levels, which only the executor can walk', () => {
|
|
657
|
+
const query = {
|
|
658
|
+
parent: {
|
|
659
|
+
ids: 'flux://a',
|
|
660
|
+
predicate: 'flux://has_message',
|
|
661
|
+
levels: [10, 5],
|
|
662
|
+
},
|
|
663
|
+
};
|
|
664
|
+
// Silently ignoring `levels` would return one unbounded level where a
|
|
665
|
+
// bounded walk was asked for — a wrong answer that looks like a right one.
|
|
666
|
+
expect(() => buildSPARQLQuery(richMetadata, emptyRelations, query, modelClass))
|
|
667
|
+
.toThrow('levels');
|
|
668
|
+
});
|
|
669
|
+
});
|
|
670
|
+
|
|
671
|
+
describe('where `eq` and per-link `author` (#1114)', () => {
|
|
672
|
+
const modelClass: any = {};
|
|
673
|
+
const roleMetadata: any = {
|
|
674
|
+
properties: {
|
|
675
|
+
agent: { name: 'agent', predicate: 'test://agent', required: false },
|
|
676
|
+
computed: { name: 'computed', predicate: '', getter: 'SELECT ?t WHERE { ?t ?p ?o }' },
|
|
677
|
+
},
|
|
678
|
+
relations: {
|
|
679
|
+
reviews: { name: 'reviews', predicate: 'test://review' },
|
|
680
|
+
derived: { name: 'derived', predicate: '', getter: 'SELECT ?t WHERE { ?t ?p ?o }' },
|
|
681
|
+
},
|
|
682
|
+
};
|
|
683
|
+
|
|
684
|
+
it('treats `{ eq: X }` as the bare value', () => {
|
|
685
|
+
const bare = buildSPARQLQuery(richMetadata, emptyRelations, { where: { name: 'Alice' } }, modelClass);
|
|
686
|
+
const eq = buildSPARQLQuery(richMetadata, emptyRelations, { where: { name: { eq: 'Alice' } } }, modelClass);
|
|
687
|
+
expect(eq).toBe(bare);
|
|
688
|
+
const bareIn = buildSPARQLQuery(richMetadata, emptyRelations, { where: { name: ['Alice', 'Bob'] } }, modelClass);
|
|
689
|
+
const eqIn = buildSPARQLQuery(richMetadata, emptyRelations, { where: { name: { eq: ['Alice', 'Bob'] } } }, modelClass);
|
|
690
|
+
expect(eqIn).toBe(bareIn);
|
|
691
|
+
});
|
|
692
|
+
|
|
693
|
+
it('refuses `eq` beside another operator', () => {
|
|
694
|
+
expect(() =>
|
|
695
|
+
buildSPARQLQuery(richMetadata, emptyRelations, { where: { name: { eq: 'a', not: 'b' } } as any }, modelClass),
|
|
696
|
+
).toThrow(/`eq` cannot be combined/);
|
|
697
|
+
});
|
|
698
|
+
|
|
699
|
+
it('refuses a nested author, at any depth', () => {
|
|
700
|
+
for (const where of [
|
|
701
|
+
{ agent: { eq: 'did:a', author: 'did:admin' } },
|
|
702
|
+
{ agent: { author: ['did:admin', 'did:lead'] } },
|
|
703
|
+
{ OR: [{ agent: { eq: 'did:a', author: { not: 'did:m' } } }] },
|
|
704
|
+
{ NOT: { agent: { eq: 'did:a', author: 'did:admin' } } },
|
|
705
|
+
]) {
|
|
706
|
+
expect(() => buildSPARQLQuery(roleMetadata, emptyRelations, { where } as any, modelClass)).toThrow(
|
|
707
|
+
/per-link `author`/,
|
|
708
|
+
);
|
|
709
|
+
}
|
|
710
|
+
});
|
|
711
|
+
|
|
712
|
+
it('refuses a side-by-side author beside a link-backed property', () => {
|
|
713
|
+
expect(() =>
|
|
714
|
+
buildSPARQLQuery(roleMetadata, emptyRelations, { where: { agent: 'did:a', author: 'did:admin' } }, modelClass),
|
|
715
|
+
).toThrow(/`author` beside `agent`/);
|
|
716
|
+
});
|
|
717
|
+
|
|
718
|
+
it('refuses a side-by-side author beside a relation, which is link-backed too', () => {
|
|
719
|
+
expect(() =>
|
|
720
|
+
buildSPARQLQuery(roleMetadata, emptyRelations, { where: { reviews: 'test://r1', author: 'did:admin' } } as any, modelClass),
|
|
721
|
+
).toThrow(/`author` beside `reviews`/);
|
|
722
|
+
});
|
|
723
|
+
|
|
724
|
+
it('keeps a bare author, including beside a getter or timestamp', () => {
|
|
725
|
+
for (const where of [
|
|
726
|
+
{ author: 'did:admin' },
|
|
727
|
+
{ author: { not: ['did:m'] } },
|
|
728
|
+
{ computed: 'x', author: 'did:admin' },
|
|
729
|
+
{ derived: 'x', author: 'did:admin' },
|
|
730
|
+
{ timestamp: { gt: 0 }, author: 'did:admin' },
|
|
731
|
+
]) {
|
|
732
|
+
expect(() => buildSPARQLQuery(roleMetadata, emptyRelations, { where } as any, modelClass)).not.toThrow();
|
|
733
|
+
}
|
|
734
|
+
});
|
|
735
|
+
|
|
736
|
+
it('getter where compilation unwraps `eq` and refuses a nested author', () => {
|
|
737
|
+
expect(buildWhereCondition('test://p', { eq: 'x' } as any)).toBe(buildWhereCondition('test://p', 'x'));
|
|
738
|
+
expect(() => buildWhereCondition('test://p', { eq: 'x', author: 'did:a' } as any)).toThrow(/per-link/);
|
|
739
|
+
});
|
|
740
|
+
});
|
|
@@ -15,6 +15,7 @@ import { Literal } from "../Literal";
|
|
|
15
15
|
import { resolveParentPredicate } from "./query-common";
|
|
16
16
|
import type { RelationMetadataEntry } from "./decorators";
|
|
17
17
|
import type { Where, Query, ModelMetadata, PropertyMetadata } from "./types";
|
|
18
|
+
import { isTraverseScope } from "./types";
|
|
18
19
|
|
|
19
20
|
/**
|
|
20
21
|
* Check whether a `where` clause contains filters that cannot be pushed down
|
|
@@ -80,6 +81,67 @@ export function hasJsOnlyWhereFilters(
|
|
|
80
81
|
return false;
|
|
81
82
|
}
|
|
82
83
|
|
|
84
|
+
/**
|
|
85
|
+
* Prepare a `where` for this client-side SPARQL builder: unwrap `{ eq: X }`
|
|
86
|
+
* to the bare `X`, and refuse a per-link `author`.
|
|
87
|
+
*
|
|
88
|
+
* A per-link `author` (nested, `{ agent: { eq: X, author: A } }`, or a
|
|
89
|
+
* top-level `author` beside link-backed property or relation conditions) is
|
|
90
|
+
* answered by the executor, which joins each matched link's reifier (#1114). This builder
|
|
91
|
+
* has no such join, and treating the author as instance-level here would
|
|
92
|
+
* answer a different, wider question. `findAll()`/`count()` answer it.
|
|
93
|
+
*/
|
|
94
|
+
export function normalizeWhereForSparql(metadata: ModelMetadata, where?: Where): Where | undefined {
|
|
95
|
+
if (!where) return where;
|
|
96
|
+
assertNoPerLinkAuthor(metadata, where);
|
|
97
|
+
const out: Where = {};
|
|
98
|
+
for (const [key, condition] of Object.entries(where)) {
|
|
99
|
+
out[key] = unwrapEq(key, condition);
|
|
100
|
+
}
|
|
101
|
+
return out;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function isOpsObject(condition: unknown): condition is Record<string, unknown> {
|
|
105
|
+
return typeof condition === "object" && condition !== null && !Array.isArray(condition);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function unwrapEq(key: string, condition: any): any {
|
|
109
|
+
if (key === "OR" || key === "AND" || key === "NOT" || !isOpsObject(condition) || condition.eq === undefined) {
|
|
110
|
+
return condition;
|
|
111
|
+
}
|
|
112
|
+
if (Object.keys(condition).some((k) => k !== "eq")) {
|
|
113
|
+
throw new Error(`where.${key}: \`eq\` cannot be combined with another operator`);
|
|
114
|
+
}
|
|
115
|
+
return condition.eq;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function assertNoPerLinkAuthor(metadata: ModelMetadata, where: Where): void {
|
|
119
|
+
const refuse = (what: string) => {
|
|
120
|
+
throw new Error(
|
|
121
|
+
`buildSPARQLQuery: ${what} is a per-link \`author\`, which the executor answers by ` +
|
|
122
|
+
"checking who wrote each matched link. This client-side SPARQL builder cannot express " +
|
|
123
|
+
"it. Use the model query path (findAll/count).",
|
|
124
|
+
);
|
|
125
|
+
};
|
|
126
|
+
// A property or a relation with a predicate, as the executor's `is_link_leaf`.
|
|
127
|
+
const linkBacked = (key: string) => {
|
|
128
|
+
const field = metadata.properties[key] ?? metadata.relations?.[key];
|
|
129
|
+
return !!field && !!field.predicate && !field.getter;
|
|
130
|
+
};
|
|
131
|
+
for (const [key, condition] of Object.entries(where)) {
|
|
132
|
+
if (key === "OR" || key === "AND") {
|
|
133
|
+
for (const branch of (condition as Where[]) ?? []) assertNoPerLinkAuthor(metadata, branch);
|
|
134
|
+
} else if (key === "NOT") {
|
|
135
|
+
if (condition) assertNoPerLinkAuthor(metadata, condition as Where);
|
|
136
|
+
} else if (key === "author") {
|
|
137
|
+
const sibling = Object.keys(where).find((k) => k !== "author" && linkBacked(k));
|
|
138
|
+
if (sibling) refuse(`\`author\` beside \`${sibling}\``);
|
|
139
|
+
} else if (isOpsObject(condition) && (condition as Record<string, unknown>).author !== undefined) {
|
|
140
|
+
refuse(`\`${key}.author\``);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
83
145
|
/**
|
|
84
146
|
* Check whether a string value is a well-formed absolute IRI that can be
|
|
85
147
|
* stored verbatim as a link target (raw `NamedNode`) instead of being
|
|
@@ -268,12 +330,46 @@ export function buildSPARQLQuery(
|
|
|
268
330
|
): string {
|
|
269
331
|
const joinPatterns: string[] = [];
|
|
270
332
|
const filterExpressions: string[] = [];
|
|
333
|
+
query = { ...query, where: normalizeWhereForSparql(metadata, query.where) };
|
|
271
334
|
|
|
272
335
|
// Parent filter — direct triple pattern
|
|
273
336
|
if (query.parent) {
|
|
274
337
|
const parentPredicate = resolveParentPredicate(query.parent, modelClass);
|
|
275
|
-
|
|
338
|
+
if (isTraverseScope(query.parent)) {
|
|
339
|
+
const { ids, transitive, direction, limitPerAnchor, levels } = query.parent;
|
|
340
|
+
// `limitPerAnchor` and `levels` are applied by the executor between
|
|
341
|
+
// selecting ids and hydrating them, which is a shape this path does not
|
|
342
|
+
// have — it builds one query and reads the rows. Refused rather than
|
|
343
|
+
// ignored: quietly returning every reply where five per parent were
|
|
344
|
+
// asked for — or one unbounded level where a walk was asked for — is a
|
|
345
|
+
// wrong answer that looks like a right one.
|
|
346
|
+
if (limitPerAnchor !== undefined) {
|
|
347
|
+
throw new Error(
|
|
348
|
+
'buildSPARQLQuery: limitPerAnchor is applied by the executor between query phases and ' +
|
|
349
|
+
'has no equivalent here. Use the model query path for per-anchor limits.',
|
|
350
|
+
);
|
|
351
|
+
}
|
|
352
|
+
if (levels !== undefined) {
|
|
353
|
+
throw new Error(
|
|
354
|
+
'buildSPARQLQuery: levels is walked by the executor between query phases and ' +
|
|
355
|
+
'has no equivalent here. Use the model query path for level walks.',
|
|
356
|
+
);
|
|
357
|
+
}
|
|
358
|
+
const anchors = (Array.isArray(ids) ? ids : [ids]).map(iri).join(' ');
|
|
359
|
+
const path = transitive ? '+' : '';
|
|
360
|
+
joinPatterns.push(`
|
|
361
|
+
VALUES ?_anchor { ${anchors} }`);
|
|
362
|
+
joinPatterns.push(
|
|
363
|
+
direction === 'in'
|
|
364
|
+
? `
|
|
365
|
+
?source ${iri(parentPredicate)}${path} ?_anchor .`
|
|
366
|
+
: `
|
|
367
|
+
?_anchor ${iri(parentPredicate)}${path} ?source .`,
|
|
368
|
+
);
|
|
369
|
+
} else {
|
|
370
|
+
joinPatterns.push(`
|
|
276
371
|
${iri(query.parent.id)} ${iri(parentPredicate)} ?source .`);
|
|
372
|
+
}
|
|
277
373
|
}
|
|
278
374
|
|
|
279
375
|
// Required property JOIN patterns — direct triple patterns
|
package/src/model/query-utils.ts
CHANGED
|
@@ -60,6 +60,24 @@ export function buildWhereCondition(
|
|
|
60
60
|
condition: WhereCondition,
|
|
61
61
|
opts?: { isDeterministicLiteral?: boolean; varIndex?: number },
|
|
62
62
|
): string {
|
|
63
|
+
// `{ eq: X }` is the bare `X`. A nested `author` is a per-link condition
|
|
64
|
+
// the executor answers in model queries; a getter's SPARQL has no reifier
|
|
65
|
+
// join to answer it with, so it is refused rather than dropped (#1114).
|
|
66
|
+
if (typeof condition === 'object' && condition !== null && !Array.isArray(condition)) {
|
|
67
|
+
const ops = condition as any;
|
|
68
|
+
if (ops.author !== undefined) {
|
|
69
|
+
throw new Error(
|
|
70
|
+
`buildWhereCondition: a nested \`author\` on <${predicate}> is a per-link condition ` +
|
|
71
|
+
'that only the model query path can answer',
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
if (ops.eq !== undefined) {
|
|
75
|
+
if (Object.keys(ops).some((k) => k !== 'eq')) {
|
|
76
|
+
throw new Error(`buildWhereCondition: \`eq\` on <${predicate}> cannot be combined with another operator`);
|
|
77
|
+
}
|
|
78
|
+
condition = ops.eq;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
63
81
|
const escapedPredicate = escapeQueryString(predicate);
|
|
64
82
|
// For deterministic-literal properties, values are stored as typed
|
|
65
83
|
// literals like `"X"^^xsd:string` (or the legacy `<literal:string:VALUE>`
|
|
@@ -99,6 +99,13 @@ describe("buildConformanceFilter()", () => {
|
|
|
99
99
|
expect(result!.getter).toContain("test://type");
|
|
100
100
|
expect(result!.getter).toContain("test://flagged_type");
|
|
101
101
|
expect(result!.getter).toContain("test://name");
|
|
102
|
+
// Exact form: the executor's `verify_relation_getter` (rust-executor
|
|
103
|
+
// model_query/getters.rs) matches this prefix to add the #1113 proof
|
|
104
|
+
// filter, and `verify_relation_getter_rewrites_the_sdk_conformance_getter`
|
|
105
|
+
// holds the same string. Change both together.
|
|
106
|
+
expect(result!.getter).toBe(
|
|
107
|
+
"SELECT ?target WHERE { <Base> <test://has_flagged> ?target . ?target <test://type> <test://flagged_type> . ?target <test://name> ?_v0 . }"
|
|
108
|
+
);
|
|
102
109
|
});
|
|
103
110
|
|
|
104
111
|
it("should return undefined for a target with no conformance conditions", () => {
|
package/src/model/shacl-gen.ts
CHANGED
|
@@ -124,6 +124,18 @@ export function buildSHACL(
|
|
|
124
124
|
|
|
125
125
|
if (!propMeta.through) continue; // Skip properties without predicates
|
|
126
126
|
|
|
127
|
+
// `@BelongsToOne`/`@BelongsToMany` register in both maps: the relation
|
|
128
|
+
// registry describes the edge, and `applyPropertyMetadata` marks the
|
|
129
|
+
// accessor read-only so the non-owning side gets no setter. Both loops
|
|
130
|
+
// then emitted a shape for it, so an inverse relation appeared twice in
|
|
131
|
+
// the generated SHACL — once thinly, from here, and once with its target
|
|
132
|
+
// class, polymorphism and ordering, from the relation loop below.
|
|
133
|
+
//
|
|
134
|
+
// The relation loop is the complete description, so this one stands
|
|
135
|
+
// aside. Skipping by presence in the relation map rather than by kind
|
|
136
|
+
// keeps it right for any future decorator that registers in both.
|
|
137
|
+
if (allRelationsMeta[propName]) continue;
|
|
138
|
+
|
|
127
139
|
const propShape: SHACLPropertyShape = {
|
|
128
140
|
name: propName,
|
|
129
141
|
path: propMeta.through,
|
|
@@ -403,3 +403,74 @@ describe("Decorators → SHACL writer round-trip", () => {
|
|
|
403
403
|
).toBeUndefined();
|
|
404
404
|
});
|
|
405
405
|
});
|
|
406
|
+
|
|
407
|
+
/**
|
|
408
|
+
* An inverse relation is registered twice by design: once in the relation
|
|
409
|
+
* registry, which describes the edge, and once as property metadata, which is
|
|
410
|
+
* what makes the accessor read-only. Both were then emitted into the shape, so
|
|
411
|
+
* `generateSHACL()` described the property twice — once thinly and once with
|
|
412
|
+
* its target class and options.
|
|
413
|
+
*
|
|
414
|
+
* A duplicate is not cosmetic. The executor reads the shape to decide what a
|
|
415
|
+
* class has; two entries for one name mean two conformance patterns and two
|
|
416
|
+
* hydration passes for the same predicate, and any consumer comparing a shape
|
|
417
|
+
* against a manifest sees a property the manifest cannot produce.
|
|
418
|
+
*/
|
|
419
|
+
describe("inverse relations appear once in the generated shape", () => {
|
|
420
|
+
@Model({ name: "RoundTripParent" })
|
|
421
|
+
class RoundTripParent extends Ad4mModel {
|
|
422
|
+
@HasMany({ through: "test://child" })
|
|
423
|
+
children: string[] = [];
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
@Model({ name: "RoundTripChild" })
|
|
427
|
+
class RoundTripChild extends Ad4mModel {
|
|
428
|
+
@BelongsToOne({ through: "test://child" })
|
|
429
|
+
parent?: string;
|
|
430
|
+
|
|
431
|
+
@BelongsToMany({ through: "test://tagged" })
|
|
432
|
+
taggedBy: string[] = [];
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
const propertiesOf = (cls: any): any[] =>
|
|
436
|
+
(cls.generateSHACL().shape?.properties ?? []) as any[];
|
|
437
|
+
|
|
438
|
+
it("emits one shape per inverse relation", () => {
|
|
439
|
+
const names = propertiesOf(RoundTripChild).map((p) => p.name);
|
|
440
|
+
expect(names.filter((n) => n === "parent")).toHaveLength(1);
|
|
441
|
+
expect(names.filter((n) => n === "taggedBy")).toHaveLength(1);
|
|
442
|
+
});
|
|
443
|
+
|
|
444
|
+
it("keeps the relation loop's description rather than the property loop's", () => {
|
|
445
|
+
const parent = propertiesOf(RoundTripChild).find((p) => p.name === "parent");
|
|
446
|
+
expect(parent.path).toBe("test://child");
|
|
447
|
+
// maxCount is the relation loop's contribution: belongsToOne is scalar.
|
|
448
|
+
expect(parent.maxCount).toBe(1);
|
|
449
|
+
});
|
|
450
|
+
|
|
451
|
+
it("leaves the owning side alone", () => {
|
|
452
|
+
const names = propertiesOf(RoundTripParent).map((p) => p.name);
|
|
453
|
+
expect(names.filter((n) => n === "children")).toHaveLength(1);
|
|
454
|
+
});
|
|
455
|
+
|
|
456
|
+
/**
|
|
457
|
+
* The forward and inverse of one link share a predicate, so a consumer
|
|
458
|
+
* keying shape properties by path finds two. That is correct and worth
|
|
459
|
+
* pinning: it is what made a downstream sort non-deterministic.
|
|
460
|
+
*/
|
|
461
|
+
it("lets a forward and inverse relation share one predicate", () => {
|
|
462
|
+
@Model({ name: "RoundTripBoth" })
|
|
463
|
+
class RoundTripBoth extends Ad4mModel {
|
|
464
|
+
@HasMany({ through: "test://comment" })
|
|
465
|
+
comments: string[] = [];
|
|
466
|
+
|
|
467
|
+
@BelongsToOne({ through: "test://comment" })
|
|
468
|
+
inReplyTo?: string;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
const props = propertiesOf(RoundTripBoth).filter(
|
|
472
|
+
(p) => p.path === "test://comment",
|
|
473
|
+
);
|
|
474
|
+
expect(props.map((p) => p.name).sort()).toEqual(["comments", "inReplyTo"]);
|
|
475
|
+
});
|
|
476
|
+
});
|
|
@@ -15,6 +15,7 @@ import type {
|
|
|
15
15
|
TypedQuery, TypedWhere, TypedOrder, TypedIncludeMap, TypedIncludeProjection,
|
|
16
16
|
IncludeExtras, Query,
|
|
17
17
|
} from "./types";
|
|
18
|
+
import type { ModelQueryBuilder } from "./ModelQueryBuilder";
|
|
18
19
|
|
|
19
20
|
// ---------------------------------------------------------------------------
|
|
20
21
|
// Fixtures
|
|
@@ -184,6 +185,31 @@ expectAssignable<TypedWhere<Post>>({ title: { gt: 5 } });
|
|
|
184
185
|
// @ts-expect-error
|
|
185
186
|
expectAssignable<TypedWhere<Post>>({ views: { contains: "x" } });
|
|
186
187
|
|
|
188
|
+
// producedByFlow — accepted at the top level of a typed query and by
|
|
189
|
+
// ModelQueryBuilder.where(), which is where the executor reads it
|
|
190
|
+
expectAssignable<TypedQuery<Post>>({ where: { producedByFlow: { flow: "coasys://F" } } });
|
|
191
|
+
expectAssignable<TypedQuery<Post>>({
|
|
192
|
+
where: { title: "x", producedByFlow: { flow: "coasys://F", state: "done" } },
|
|
193
|
+
});
|
|
194
|
+
expectAssignable<Parameters<ModelQueryBuilder<Post>["where"]>[0]>({
|
|
195
|
+
producedByFlow: { flow: "coasys://F" },
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
// ...and rejected everywhere the executor errors on it: nested under a
|
|
199
|
+
// combinator, or in an include sub-query's `where`
|
|
200
|
+
// @ts-expect-error
|
|
201
|
+
expectAssignable<TypedQuery<Post>>({ where: { OR: [{ producedByFlow: { flow: "coasys://F" } }] } });
|
|
202
|
+
// @ts-expect-error
|
|
203
|
+
expectAssignable<TypedQuery<Post>>({ where: { NOT: { producedByFlow: { flow: "coasys://F" } } } });
|
|
204
|
+
expectAssignable<TypedQuery<Post>>({
|
|
205
|
+
// @ts-expect-error
|
|
206
|
+
include: { comments: { where: { producedByFlow: { flow: "coasys://F" } } } },
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
// Malformed filter — must error
|
|
210
|
+
// @ts-expect-error
|
|
211
|
+
expectAssignable<TypedQuery<Post>>({ where: { producedByFlow: { state: "done" } } });
|
|
212
|
+
|
|
187
213
|
// ---------------------------------------------------------------------------
|
|
188
214
|
// TypedOrder
|
|
189
215
|
// ---------------------------------------------------------------------------
|
|
@@ -245,6 +271,22 @@ expectAssignable<TypedIncludeMap<Post>>({
|
|
|
245
271
|
void _bad1;
|
|
246
272
|
}
|
|
247
273
|
|
|
274
|
+
// A transitive projection: the whole conversation under each row rather than
|
|
275
|
+
// its direct replies. `IncludeProjection` has always accepted this; the typed
|
|
276
|
+
// form rejected it at compile time, so the option was unreachable from a typed
|
|
277
|
+
// query — the documented spelling for "42 replies" on a collapsed branch.
|
|
278
|
+
expectAssignable<TypedIncludeMap<Post>>({
|
|
279
|
+
$descendantCount: { from: "comments", count: true, transitive: true },
|
|
280
|
+
});
|
|
281
|
+
|
|
282
|
+
// And on the list-shaped variants, which the executor also walks transitively.
|
|
283
|
+
expectAssignable<TypedIncludeMap<Post>>({
|
|
284
|
+
$firstDescendant: { from: "comments", transitive: true, limit: 1 },
|
|
285
|
+
});
|
|
286
|
+
expectAssignable<TypedIncludeMap<Post>>({
|
|
287
|
+
$descendants: { from: "comments", transitive: true, limit: 10, where: { likes: { gt: 1 } } },
|
|
288
|
+
});
|
|
289
|
+
|
|
248
290
|
// Projection's nested where uses the *target's* property keys
|
|
249
291
|
expectAssignable<TypedIncludeMap<Post>>({
|
|
250
292
|
$popular: { from: "comments", where: { likes: { gt: 100 } }, limit: 10 },
|