@coasys/ad4m 0.12.0-dev-whisper-lang → 0.12.0-rc1-dev.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 +1746 -322
- package/lib/index.js +1745 -323
- package/lib/src/ai/AIClient.d.ts +1 -1
- package/lib/src/ai/AIClient.js +4 -5
- package/lib/src/ai/AIResolver.d.ts +1 -1
- package/lib/src/ai/AIResolver.js +2 -3
- package/lib/src/index.d.ts +2 -0
- package/lib/src/index.js +2 -0
- package/lib/src/model/Ad4mModel.js +21 -7
- package/lib/src/model/decorators.js +196 -6
- package/lib/src/model/util.d.ts +1 -1
- package/lib/src/model/util.js +15 -12
- package/lib/src/perspectives/PerspectiveClient.d.ts +11 -1
- package/lib/src/perspectives/PerspectiveClient.js +15 -4
- package/lib/src/perspectives/PerspectiveProxy.d.ts +124 -8
- package/lib/src/perspectives/PerspectiveProxy.js +573 -274
- package/lib/src/perspectives/PerspectiveResolver.d.ts +1 -1
- package/lib/src/perspectives/PerspectiveResolver.js +5 -4
- package/lib/src/schema.gql +2 -2
- package/lib/src/shacl/SHACLFlow.d.ts +171 -0
- package/lib/src/shacl/SHACLFlow.js +370 -0
- package/lib/src/shacl/SHACLFlow.test.d.ts +1 -0
- package/lib/src/shacl/SHACLFlow.test.js +205 -0
- package/lib/src/shacl/SHACLShape.d.ts +108 -0
- package/lib/src/shacl/SHACLShape.js +566 -0
- package/lib/src/shacl/SHACLShape.test.d.ts +1 -0
- package/lib/src/shacl/SHACLShape.test.js +336 -0
- package/lib/src/typeDefs.js +2 -2
- package/package.json +1 -2
- package/src/ai/AIClient.ts +4 -6
- package/src/ai/AIResolver.ts +1 -2
- package/src/index.ts +2 -0
- package/src/model/Ad4mModel.ts +23 -7
- package/src/model/decorators.ts +221 -5
- package/src/model/util.ts +15 -12
- package/src/perspectives/PerspectiveClient.ts +15 -4
- package/src/perspectives/PerspectiveProxy.ts +588 -304
- package/src/perspectives/PerspectiveResolver.ts +1 -1
- package/src/shacl/SHACLFlow.test.ts +237 -0
- package/src/shacl/SHACLFlow.ts +503 -0
- package/src/shacl/SHACLShape.test.ts +400 -0
- package/src/shacl/SHACLShape.ts +755 -0
|
@@ -6,7 +6,6 @@ import { Perspective } from "./Perspective";
|
|
|
6
6
|
import { Literal } from "../Literal";
|
|
7
7
|
import { Subject } from "../model/Subject";
|
|
8
8
|
import { ExpressionRendered } from "../expression/Expression";
|
|
9
|
-
import { collectionAdderToName, collectionRemoverToName, collectionSetterToName } from "../model/util";
|
|
10
9
|
import { NeighbourhoodProxy } from "../neighbourhood/NeighbourhoodProxy";
|
|
11
10
|
import { NeighbourhoodExpression } from "../neighbourhood/Neighbourhood";
|
|
12
11
|
import { AIClient } from "../ai/AIClient";
|
|
@@ -14,6 +13,8 @@ import { PERSPECTIVE_QUERY_SUBSCRIPTION } from "./PerspectiveResolver";
|
|
|
14
13
|
import { gql } from "@apollo/client/core";
|
|
15
14
|
import { AllInstancesResult } from "../model/Ad4mModel";
|
|
16
15
|
import { escapeSurrealString } from "../utils";
|
|
16
|
+
import { SHACLShape } from "../shacl/SHACLShape";
|
|
17
|
+
import { SHACLFlow, LinkPattern } from "../shacl/SHACLFlow";
|
|
17
18
|
|
|
18
19
|
type QueryCallback = (result: AllInstancesResult) => void;
|
|
19
20
|
|
|
@@ -856,48 +857,122 @@ export class PerspectiveProxy {
|
|
|
856
857
|
|
|
857
858
|
/** Returns all the Social DNA flows defined in this perspective */
|
|
858
859
|
async sdnaFlows(): Promise<string[]> {
|
|
859
|
-
|
|
860
|
-
|
|
860
|
+
// Query for all flow registration links
|
|
861
|
+
const flowLinks = await this.get(new LinkQuery({
|
|
862
|
+
source: "ad4m://self",
|
|
863
|
+
predicate: "ad4m://has_flow"
|
|
864
|
+
}));
|
|
865
|
+
return flowLinks.map(l => {
|
|
866
|
+
try {
|
|
867
|
+
return Literal.fromUrl(l.data.target).get() as string;
|
|
868
|
+
} catch {
|
|
869
|
+
return l.data.target;
|
|
870
|
+
}
|
|
871
|
+
});
|
|
861
872
|
}
|
|
862
873
|
|
|
863
874
|
/** Returns all Social DNA flows that can be started from the given expression */
|
|
864
875
|
async availableFlows(exprAddr: string): Promise<string[]> {
|
|
865
|
-
const
|
|
866
|
-
|
|
876
|
+
const allFlowNames = await this.sdnaFlows();
|
|
877
|
+
const available: string[] = [];
|
|
878
|
+
for (const name of allFlowNames) {
|
|
879
|
+
const flow = await this.getFlow(name);
|
|
880
|
+
if (!flow) continue;
|
|
881
|
+
if (flow.flowable === "any") {
|
|
882
|
+
available.push(name);
|
|
883
|
+
} else {
|
|
884
|
+
// Check if the expression matches the flowable link pattern
|
|
885
|
+
const pattern = flow.flowable as LinkPattern;
|
|
886
|
+
const source = pattern.source || exprAddr;
|
|
887
|
+
const links = await this.get(new LinkQuery({
|
|
888
|
+
source,
|
|
889
|
+
predicate: pattern.predicate,
|
|
890
|
+
target: pattern.target
|
|
891
|
+
}));
|
|
892
|
+
if (links.length > 0) {
|
|
893
|
+
available.push(name);
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
return available;
|
|
867
898
|
}
|
|
868
899
|
|
|
869
900
|
/** Starts the Social DNA flow @param flowName on the expression @param exprAddr */
|
|
870
901
|
async startFlow(flowName: string, exprAddr: string) {
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
startAction
|
|
874
|
-
await this.executeAction(startAction, exprAddr, undefined)
|
|
902
|
+
const flow = await this.getFlow(flowName);
|
|
903
|
+
if (!flow) throw `Flow "${flowName}" not found`;
|
|
904
|
+
if (flow.startAction.length === 0) throw `Flow "${flowName}" has no start action`;
|
|
905
|
+
await this.executeAction(flow.startAction, exprAddr, undefined)
|
|
875
906
|
}
|
|
876
907
|
|
|
877
908
|
/** Returns all expressions in the given state of given Social DNA flow */
|
|
878
909
|
async expressionsInFlowState(flowName: string, flowState: number): Promise<string[]> {
|
|
879
|
-
|
|
880
|
-
|
|
910
|
+
const flow = await this.getFlow(flowName);
|
|
911
|
+
if (!flow) return [];
|
|
912
|
+
// Find the state with the matching value
|
|
913
|
+
const state = flow.states.find(s => s.value === flowState);
|
|
914
|
+
if (!state) return [];
|
|
915
|
+
// Query for expressions matching this state's check pattern
|
|
916
|
+
const pattern = state.stateCheck;
|
|
917
|
+
const links = await this.get(new LinkQuery({
|
|
918
|
+
predicate: pattern.predicate,
|
|
919
|
+
target: pattern.target
|
|
920
|
+
}));
|
|
921
|
+
// Return the sources (expression addresses) - use source if pattern has no explicit source
|
|
922
|
+
return links.map(l => pattern.source ? l.data.target : l.data.source);
|
|
881
923
|
}
|
|
882
924
|
|
|
883
925
|
/** Returns the given expression's flow state with regard to given Social DNA flow */
|
|
884
926
|
async flowState(flowName: string, exprAddr: string): Promise<number> {
|
|
885
|
-
|
|
886
|
-
|
|
927
|
+
const flow = await this.getFlow(flowName);
|
|
928
|
+
if (!flow) throw `Flow "${flowName}" not found`;
|
|
929
|
+
// Check each state to find which one the expression is in
|
|
930
|
+
for (const state of flow.states) {
|
|
931
|
+
const pattern = state.stateCheck;
|
|
932
|
+
const source = pattern.source || exprAddr;
|
|
933
|
+
const links = await this.get(new LinkQuery({
|
|
934
|
+
source,
|
|
935
|
+
predicate: pattern.predicate,
|
|
936
|
+
target: pattern.target
|
|
937
|
+
}));
|
|
938
|
+
if (links.length > 0) return state.value;
|
|
939
|
+
}
|
|
940
|
+
throw `Expression "${exprAddr}" is not in any state of flow "${flowName}"`;
|
|
887
941
|
}
|
|
888
942
|
|
|
889
943
|
/** Returns available action names, with regard to Social DNA flow and expression's flow state */
|
|
890
944
|
async flowActions(flowName: string, exprAddr: string): Promise<string[]> {
|
|
891
|
-
|
|
892
|
-
|
|
945
|
+
const flow = await this.getFlow(flowName);
|
|
946
|
+
if (!flow) return [];
|
|
947
|
+
// Determine current state
|
|
948
|
+
let currentStateName: string | null = null;
|
|
949
|
+
for (const state of flow.states) {
|
|
950
|
+
const pattern = state.stateCheck;
|
|
951
|
+
const source = pattern.source || exprAddr;
|
|
952
|
+
const links = await this.get(new LinkQuery({
|
|
953
|
+
source,
|
|
954
|
+
predicate: pattern.predicate,
|
|
955
|
+
target: pattern.target
|
|
956
|
+
}));
|
|
957
|
+
if (links.length > 0) {
|
|
958
|
+
currentStateName = state.name;
|
|
959
|
+
break;
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
if (!currentStateName) return [];
|
|
963
|
+
// Return transitions available from current state
|
|
964
|
+
return flow.transitions
|
|
965
|
+
.filter(t => t.fromState === currentStateName)
|
|
966
|
+
.map(t => t.actionName);
|
|
893
967
|
}
|
|
894
968
|
|
|
895
969
|
/** Runs given Social DNA flow action */
|
|
896
970
|
async runFlowAction(flowName: string, exprAddr: string, actionName: string) {
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
971
|
+
const flow = await this.getFlow(flowName);
|
|
972
|
+
if (!flow) throw `Flow "${flowName}" not found`;
|
|
973
|
+
const transition = flow.transitions.find(t => t.actionName === actionName);
|
|
974
|
+
if (!transition) throw `Action "${actionName}" not found in flow "${flowName}"`;
|
|
975
|
+
await this.executeAction(transition.actions, exprAddr, undefined)
|
|
901
976
|
}
|
|
902
977
|
|
|
903
978
|
/** Returns the perspective's Social DNA code
|
|
@@ -975,17 +1050,280 @@ export class PerspectiveProxy {
|
|
|
975
1050
|
return typeof code === 'string' ? code : null;
|
|
976
1051
|
}
|
|
977
1052
|
|
|
978
|
-
/**
|
|
979
|
-
|
|
980
|
-
|
|
1053
|
+
/**
|
|
1054
|
+
* Adds Social DNA code to the perspective.
|
|
1055
|
+
*
|
|
1056
|
+
* **Recommended:** Use {@link addShacl} instead, which accepts the `SHACLShape` type directly.
|
|
1057
|
+
* This method is primarily for the GraphQL layer and legacy Prolog code.
|
|
1058
|
+
*
|
|
1059
|
+
* @param name - Unique name for this SDNA definition
|
|
1060
|
+
* @param sdnaCode - Prolog SDNA code (legacy, can be empty string if shaclJson provided)
|
|
1061
|
+
* @param sdnaType - Type of SDNA: "subject_class", "flow", or "custom"
|
|
1062
|
+
* @param shaclJson - SHACL JSON string (use addShacl() for type-safe alternative)
|
|
1063
|
+
*
|
|
1064
|
+
* @example
|
|
1065
|
+
* // Recommended: Use addShacl() with SHACLShape type
|
|
1066
|
+
* const shape = new SHACLShape('recipe://Recipe');
|
|
1067
|
+
* shape.addProperty({ name: 'title', path: 'recipe://title', datatype: 'xsd:string' });
|
|
1068
|
+
* await perspective.addShacl('Recipe', shape);
|
|
1069
|
+
*
|
|
1070
|
+
* // Legacy: Prolog code is auto-converted to SHACL
|
|
1071
|
+
* await perspective.addSdna('Recipe', prologCode, 'subject_class');
|
|
1072
|
+
*/
|
|
1073
|
+
async addSdna(name: string, sdnaCode: string, sdnaType: "subject_class" | "flow" | "custom", shaclJson?: string) {
|
|
1074
|
+
return this.#client.addSdna(this.#handle.uuid, name, sdnaCode, sdnaType, shaclJson)
|
|
981
1075
|
}
|
|
982
1076
|
|
|
983
|
-
/**
|
|
1077
|
+
/**
|
|
1078
|
+
* **Recommended way to add SDNA schemas.**
|
|
1079
|
+
*
|
|
1080
|
+
* Store a SHACL shape in this Perspective using the type-safe `SHACLShape` class.
|
|
1081
|
+
* The shape is serialized as RDF triples (links) for native AD4M storage and querying.
|
|
1082
|
+
*
|
|
1083
|
+
* @param name - Unique name for this schema (e.g., 'Recipe', 'Task')
|
|
1084
|
+
* @param shape - SHACLShape instance defining the schema
|
|
1085
|
+
*
|
|
1086
|
+
* @example
|
|
1087
|
+
* import { SHACLShape } from '@coasys/ad4m';
|
|
1088
|
+
*
|
|
1089
|
+
* const shape = new SHACLShape('recipe://Recipe');
|
|
1090
|
+
* shape.addProperty({
|
|
1091
|
+
* name: 'title',
|
|
1092
|
+
* path: 'recipe://title',
|
|
1093
|
+
* datatype: 'xsd:string',
|
|
1094
|
+
* minCount: 1
|
|
1095
|
+
* });
|
|
1096
|
+
* shape.addProperty({
|
|
1097
|
+
* name: 'ingredients',
|
|
1098
|
+
* path: 'recipe://has_ingredient',
|
|
1099
|
+
* // No maxCount = collection
|
|
1100
|
+
* });
|
|
1101
|
+
*
|
|
1102
|
+
* await perspective.addShacl('Recipe', shape);
|
|
1103
|
+
*/
|
|
1104
|
+
async addShacl(name: string, shape: SHACLShape): Promise<void> {
|
|
1105
|
+
// Serialize shape to links
|
|
1106
|
+
const shapeLinks = shape.toLinks();
|
|
1107
|
+
|
|
1108
|
+
// Create name -> shape mapping links
|
|
1109
|
+
const nameMapping = Literal.fromUrl(`literal://string:shacl://${name}`);
|
|
1110
|
+
const allLinks: Link[] = [
|
|
1111
|
+
...shapeLinks.map(l => new Link({
|
|
1112
|
+
source: l.source,
|
|
1113
|
+
predicate: l.predicate,
|
|
1114
|
+
target: l.target
|
|
1115
|
+
})),
|
|
1116
|
+
new Link({
|
|
1117
|
+
source: "ad4m://self",
|
|
1118
|
+
predicate: "ad4m://has_shacl",
|
|
1119
|
+
target: nameMapping.toUrl()
|
|
1120
|
+
}),
|
|
1121
|
+
new Link({
|
|
1122
|
+
source: nameMapping.toUrl(),
|
|
1123
|
+
predicate: "ad4m://shacl_shape_uri",
|
|
1124
|
+
target: shape.nodeShapeUri
|
|
1125
|
+
})
|
|
1126
|
+
];
|
|
1127
|
+
|
|
1128
|
+
// Batch add all links at once
|
|
1129
|
+
await this.addLinks(allLinks);
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
/**
|
|
1133
|
+
* Retrieve a SHACL shape by name from this Perspective
|
|
1134
|
+
*/
|
|
1135
|
+
async getShacl(name: string): Promise<SHACLShape | null> {
|
|
1136
|
+
// Find the shape URI from the name mapping
|
|
1137
|
+
const nameMapping = Literal.fromUrl(`literal://string:shacl://${name}`);
|
|
1138
|
+
const shapeUriLinks = await this.get(new LinkQuery({
|
|
1139
|
+
source: nameMapping.toUrl(),
|
|
1140
|
+
predicate: "ad4m://shacl_shape_uri"
|
|
1141
|
+
}));
|
|
1142
|
+
|
|
1143
|
+
if (shapeUriLinks.length === 0) {
|
|
1144
|
+
return null;
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1147
|
+
const shapeUri = shapeUriLinks[0].data.target;
|
|
1148
|
+
const escapedShapeUri = escapeSurrealString(shapeUri);
|
|
1149
|
+
|
|
1150
|
+
// First get property shape URIs so we can query everything in one go
|
|
1151
|
+
const propertyLinks = await this.get(new LinkQuery({
|
|
1152
|
+
source: shapeUri,
|
|
1153
|
+
predicate: "sh://property"
|
|
1154
|
+
}));
|
|
1155
|
+
|
|
1156
|
+
// Build a single surreal query that fetches all relevant links
|
|
1157
|
+
const sourceUris = [shapeUri, ...propertyLinks.map(l => l.data.target)];
|
|
1158
|
+
const escapedSources = sourceUris.map(u => `'${escapeSurrealString(u)}'`).join(', ');
|
|
1159
|
+
|
|
1160
|
+
const query = `SELECT in.uri AS source, predicate, out.uri AS target FROM link WHERE in.uri IN [${escapedSources}]`;
|
|
1161
|
+
const result = await this.querySurrealDB(query);
|
|
1162
|
+
|
|
1163
|
+
const shapeLinks = (result || []).map((r: any) => ({
|
|
1164
|
+
source: r.source,
|
|
1165
|
+
predicate: r.predicate,
|
|
1166
|
+
target: r.target
|
|
1167
|
+
}));
|
|
1168
|
+
|
|
1169
|
+
return SHACLShape.fromLinks(shapeLinks, shapeUri);
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
/**
|
|
1173
|
+
* Get all SHACL shapes stored in this Perspective
|
|
1174
|
+
*/
|
|
1175
|
+
async getAllShacl(): Promise<Array<{name: string, shape: SHACLShape}>> {
|
|
1176
|
+
const nameLinks = await this.get(new LinkQuery({
|
|
1177
|
+
source: "ad4m://self",
|
|
1178
|
+
predicate: "ad4m://has_shacl"
|
|
1179
|
+
}));
|
|
1180
|
+
|
|
1181
|
+
const shapes = [];
|
|
1182
|
+
for (const nameLink of nameLinks) {
|
|
1183
|
+
const nameUrl = nameLink.data.target;
|
|
1184
|
+
const name = Literal.fromUrl(nameUrl).get() as string;
|
|
1185
|
+
const shapeName = name.replace('shacl://', '');
|
|
1186
|
+
|
|
1187
|
+
const shape = await this.getShacl(shapeName);
|
|
1188
|
+
if (shape) {
|
|
1189
|
+
shapes.push({ name: shapeName, shape });
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
|
|
1193
|
+
return shapes;
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1196
|
+
/**
|
|
1197
|
+
* **Recommended way to add Flow definitions.**
|
|
1198
|
+
*
|
|
1199
|
+
* Store a SHACL Flow (state machine) in this Perspective using the type-safe `SHACLFlow` class.
|
|
1200
|
+
* The flow is serialized as RDF triples (links) for native AD4M storage and querying.
|
|
1201
|
+
*
|
|
1202
|
+
* @param name - Flow name (e.g., 'TODO', 'Approval')
|
|
1203
|
+
* @param flow - SHACLFlow instance defining the state machine
|
|
1204
|
+
*
|
|
1205
|
+
* @example
|
|
1206
|
+
* ```typescript
|
|
1207
|
+
* import { SHACLFlow } from '@coasys/ad4m';
|
|
1208
|
+
*
|
|
1209
|
+
* const todoFlow = new SHACLFlow('TODO', 'todo://');
|
|
1210
|
+
* todoFlow.flowable = 'any';
|
|
1211
|
+
*
|
|
1212
|
+
* // Define states
|
|
1213
|
+
* todoFlow.addState({ name: 'ready', value: 0, stateCheck: { predicate: 'todo://state', target: 'todo://ready' }});
|
|
1214
|
+
* todoFlow.addState({ name: 'done', value: 1, stateCheck: { predicate: 'todo://state', target: 'todo://done' }});
|
|
1215
|
+
*
|
|
1216
|
+
* // Define start action
|
|
1217
|
+
* todoFlow.startAction = [{ action: 'addLink', source: 'this', predicate: 'todo://state', target: 'todo://ready' }];
|
|
1218
|
+
*
|
|
1219
|
+
* // Define transitions
|
|
1220
|
+
* todoFlow.addTransition({
|
|
1221
|
+
* actionName: 'Complete',
|
|
1222
|
+
* fromState: 'ready',
|
|
1223
|
+
* toState: 'done',
|
|
1224
|
+
* actions: [
|
|
1225
|
+
* { action: 'addLink', source: 'this', predicate: 'todo://state', target: 'todo://done' },
|
|
1226
|
+
* { action: 'removeLink', source: 'this', predicate: 'todo://state', target: 'todo://ready' }
|
|
1227
|
+
* ]
|
|
1228
|
+
* });
|
|
1229
|
+
*
|
|
1230
|
+
* await perspective.addFlow('TODO', todoFlow);
|
|
1231
|
+
* ```
|
|
1232
|
+
*/
|
|
1233
|
+
async addFlow(name: string, flow: SHACLFlow): Promise<void> {
|
|
1234
|
+
// Serialize flow to links
|
|
1235
|
+
const flowLinks = flow.toLinks();
|
|
1236
|
+
|
|
1237
|
+
// Create registration and mapping links
|
|
1238
|
+
const flowNameLiteral = Literal.from(name).toUrl();
|
|
1239
|
+
const allLinks: Link[] = [
|
|
1240
|
+
...flowLinks.map(l => new Link({
|
|
1241
|
+
source: l.source,
|
|
1242
|
+
predicate: l.predicate,
|
|
1243
|
+
target: l.target
|
|
1244
|
+
})),
|
|
1245
|
+
new Link({
|
|
1246
|
+
source: "ad4m://self",
|
|
1247
|
+
predicate: "ad4m://has_flow",
|
|
1248
|
+
target: flowNameLiteral
|
|
1249
|
+
}),
|
|
1250
|
+
new Link({
|
|
1251
|
+
source: flowNameLiteral,
|
|
1252
|
+
predicate: "ad4m://flow_uri",
|
|
1253
|
+
target: flow.flowUri
|
|
1254
|
+
})
|
|
1255
|
+
];
|
|
1256
|
+
|
|
1257
|
+
// Batch add all links at once
|
|
1258
|
+
await this.addLinks(allLinks);
|
|
1259
|
+
}
|
|
1260
|
+
|
|
1261
|
+
/**
|
|
1262
|
+
* Retrieve a Flow definition by name from this Perspective
|
|
1263
|
+
*
|
|
1264
|
+
* @param name - Flow name to retrieve
|
|
1265
|
+
* @returns The SHACLFlow or null if not found
|
|
1266
|
+
*/
|
|
1267
|
+
async getFlow(name: string): Promise<SHACLFlow | null> {
|
|
1268
|
+
const flowNameLiteral = Literal.from(name).toUrl();
|
|
1269
|
+
|
|
1270
|
+
// Find flow URI from name mapping
|
|
1271
|
+
const flowUriLinks = await this.get(new LinkQuery({
|
|
1272
|
+
source: flowNameLiteral,
|
|
1273
|
+
predicate: "ad4m://flow_uri"
|
|
1274
|
+
}));
|
|
1275
|
+
|
|
1276
|
+
if (flowUriLinks.length === 0) {
|
|
1277
|
+
return null;
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
const flowUri = flowUriLinks[0].data.target;
|
|
1281
|
+
const escapedFlowUri = escapeSurrealString(flowUri);
|
|
1282
|
+
|
|
1283
|
+
// Compute alternate prefix for state/transition URIs
|
|
1284
|
+
const alternatePrefix = flowUri.endsWith('Flow')
|
|
1285
|
+
? flowUri.slice(0, -4) + '.'
|
|
1286
|
+
: flowUri + '.';
|
|
1287
|
+
const escapedAltPrefix = escapeSurrealString(alternatePrefix);
|
|
1288
|
+
|
|
1289
|
+
// Single surreal query to get all flow-related links
|
|
1290
|
+
const query = `SELECT in.uri AS source, predicate, out.uri AS target FROM link WHERE in.uri = '${escapedFlowUri}' OR string::starts_with(in.uri, '${escapedAltPrefix}')`;
|
|
1291
|
+
const result = await this.querySurrealDB(query);
|
|
1292
|
+
|
|
1293
|
+
const flowLinks = (result || []).map((r: any) => ({
|
|
1294
|
+
source: r.source,
|
|
1295
|
+
predicate: r.predicate,
|
|
1296
|
+
target: r.target
|
|
1297
|
+
}));
|
|
1298
|
+
|
|
1299
|
+
return SHACLFlow.fromLinks(flowLinks, flowUri);
|
|
1300
|
+
}
|
|
1301
|
+
|
|
1302
|
+
/** Returns all the Subject classes defined in this perspectives SDNA
|
|
1303
|
+
*
|
|
1304
|
+
* Uses SHACL-based lookup (Prolog-free implementation).
|
|
1305
|
+
*/
|
|
984
1306
|
async subjectClasses(): Promise<string[]> {
|
|
985
1307
|
try {
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
1308
|
+
// Query SHACL class links directly — no need for a separate GraphQL endpoint
|
|
1309
|
+
const classLinks = await this.get(new LinkQuery({
|
|
1310
|
+
predicate: "rdf://type",
|
|
1311
|
+
target: "ad4m://SubjectClass"
|
|
1312
|
+
}));
|
|
1313
|
+
const classNames = classLinks
|
|
1314
|
+
.map(l => {
|
|
1315
|
+
const source = l.data.source;
|
|
1316
|
+
// Extract class name from URI like "recipe://Recipe" or "flux://Channel"
|
|
1317
|
+
const parts = source.split("://");
|
|
1318
|
+
const lastPart = parts[parts.length - 1];
|
|
1319
|
+
return lastPart.split('/').pop() || '';
|
|
1320
|
+
})
|
|
1321
|
+
.filter(name => name.length > 0);
|
|
1322
|
+
// Deduplicate
|
|
1323
|
+
return [...new Set(classNames)];
|
|
1324
|
+
} catch (e) {
|
|
1325
|
+
console.warn('subjectClasses: SHACL lookup failed:', e);
|
|
1326
|
+
return [];
|
|
989
1327
|
}
|
|
990
1328
|
}
|
|
991
1329
|
|
|
@@ -1036,11 +1374,16 @@ export class PerspectiveProxy {
|
|
|
1036
1374
|
batchId
|
|
1037
1375
|
);
|
|
1038
1376
|
} else {
|
|
1039
|
-
|
|
1377
|
+
const obj = subjectClass as any;
|
|
1378
|
+
const resolvedClassName = obj.className || obj.constructor?.className || obj.constructor?.prototype?.className
|
|
1379
|
+
|| await this.findClassByProperties(obj);
|
|
1380
|
+
if (!resolvedClassName) {
|
|
1381
|
+
throw new Error("Could not resolve subject class name from object. Use a decorated class or pass a className string.");
|
|
1382
|
+
}
|
|
1040
1383
|
await this.#client.createSubject(
|
|
1041
1384
|
this.#handle.uuid,
|
|
1042
1385
|
JSON.stringify({
|
|
1043
|
-
|
|
1386
|
+
className: resolvedClassName,
|
|
1044
1387
|
initialValues
|
|
1045
1388
|
}),
|
|
1046
1389
|
exprAddr,
|
|
@@ -1061,8 +1404,46 @@ export class PerspectiveProxy {
|
|
|
1061
1404
|
if (typeof subjectClass === "string") {
|
|
1062
1405
|
return JSON.parse(await this.#client.getSubjectData(this.#handle.uuid, JSON.stringify({className: subjectClass}), exprAddr))
|
|
1063
1406
|
}
|
|
1064
|
-
|
|
1065
|
-
|
|
1407
|
+
const obj = subjectClass as any;
|
|
1408
|
+
const resolvedClassName = obj.className || obj.constructor?.className || obj.constructor?.prototype?.className
|
|
1409
|
+
|| await this.findClassByProperties(obj);
|
|
1410
|
+
if (!resolvedClassName) {
|
|
1411
|
+
throw new Error("Could not resolve subject class name from object. Use a decorated class or pass a className string.");
|
|
1412
|
+
}
|
|
1413
|
+
return JSON.parse(await this.#client.getSubjectData(this.#handle.uuid, JSON.stringify({className: resolvedClassName}), exprAddr))
|
|
1414
|
+
}
|
|
1415
|
+
|
|
1416
|
+
/**
|
|
1417
|
+
* Gets actions from SHACL links for a given predicate (e.g., ad4m://constructor, ad4m://destructor).
|
|
1418
|
+
* Returns the parsed action array if found, or null if not found.
|
|
1419
|
+
*/
|
|
1420
|
+
private async getActionsFromSHACL(className: string, predicate: string): Promise<any[] | null> {
|
|
1421
|
+
// Use regex to match exact class name followed by "Shape" at end of URI
|
|
1422
|
+
// This prevents "RecipeShape" from matching "MyRecipeShape"
|
|
1423
|
+
const escaped = this.escapeRegExp(className);
|
|
1424
|
+
const shapePattern = new RegExp(`[/:#]${escaped}Shape$`);
|
|
1425
|
+
const links = await this.get(new LinkQuery({ predicate }));
|
|
1426
|
+
|
|
1427
|
+
for (const link of links) {
|
|
1428
|
+
if (shapePattern.test(link.data.source)) {
|
|
1429
|
+
// Parse actions from literal://string:{json}
|
|
1430
|
+
const prefix = "literal://string:";
|
|
1431
|
+
if (link.data.target.startsWith(prefix)) {
|
|
1432
|
+
const jsonStr = link.data.target.slice(prefix.length);
|
|
1433
|
+
// Decode URL-encoded JSON if needed, with fallback for raw % characters
|
|
1434
|
+
let decoded = jsonStr;
|
|
1435
|
+
try { decoded = decodeURIComponent(jsonStr); } catch {}
|
|
1436
|
+
try {
|
|
1437
|
+
return JSON.parse(decoded);
|
|
1438
|
+
} catch (e) {
|
|
1439
|
+
console.warn(`Failed to parse SHACL actions JSON for ${className}:`, e);
|
|
1440
|
+
return null;
|
|
1441
|
+
}
|
|
1442
|
+
}
|
|
1443
|
+
}
|
|
1444
|
+
}
|
|
1445
|
+
|
|
1446
|
+
return null;
|
|
1066
1447
|
}
|
|
1067
1448
|
|
|
1068
1449
|
/** Removes a subject instance by running its (SDNA defined) destructor,
|
|
@@ -1077,13 +1458,15 @@ export class PerspectiveProxy {
|
|
|
1077
1458
|
*/
|
|
1078
1459
|
async removeSubject<T>(subjectClass: T, exprAddr: string, batchId?: string) {
|
|
1079
1460
|
let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass)
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1461
|
+
|
|
1462
|
+
// Get destructor actions from SHACL links (Prolog-free)
|
|
1463
|
+
let actions = await this.getActionsFromSHACL(className, "ad4m://destructor");
|
|
1464
|
+
|
|
1465
|
+
if (!actions) {
|
|
1466
|
+
throw `No destructor found for subject class: ${className}. Make sure the class was registered with SHACL.`;
|
|
1083
1467
|
}
|
|
1084
1468
|
|
|
1085
|
-
|
|
1086
|
-
await this.executeAction(actions[0], exprAddr, undefined, batchId)
|
|
1469
|
+
await this.executeAction(actions, exprAddr, undefined, batchId)
|
|
1087
1470
|
}
|
|
1088
1471
|
|
|
1089
1472
|
/** Checks if the given expression is a subject instance of the given subject class
|
|
@@ -1095,20 +1478,11 @@ export class PerspectiveProxy {
|
|
|
1095
1478
|
async isSubjectInstance<T>(expression: string, subjectClass: T): Promise<boolean> {
|
|
1096
1479
|
let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass)
|
|
1097
1480
|
|
|
1098
|
-
// Get metadata from
|
|
1481
|
+
// Get metadata from SHACL links
|
|
1099
1482
|
const metadata = await this.getSubjectClassMetadataFromSDNA(className);
|
|
1100
1483
|
if (!metadata) {
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
try {
|
|
1104
|
-
const escapedClassName = className.replace(/"/g, '\\"');
|
|
1105
|
-
const escapedExpression = expression.replace(/"/g, '\\"');
|
|
1106
|
-
const result = await this.infer(`subject_class("${escapedClassName}", C), instance(C, "${escapedExpression}")`);
|
|
1107
|
-
return result && result.length > 0;
|
|
1108
|
-
} catch (e) {
|
|
1109
|
-
console.warn(`Failed to check instance via Prolog for class ${className}:`, e);
|
|
1110
|
-
return false;
|
|
1111
|
-
}
|
|
1484
|
+
console.warn(`isSubjectInstance: No SHACL metadata found for class ${className}`);
|
|
1485
|
+
return false;
|
|
1112
1486
|
}
|
|
1113
1487
|
|
|
1114
1488
|
// If no required triples, any expression with links is an instance
|
|
@@ -1173,10 +1547,8 @@ export class PerspectiveProxy {
|
|
|
1173
1547
|
}
|
|
1174
1548
|
|
|
1175
1549
|
/**
|
|
1176
|
-
*
|
|
1177
|
-
*
|
|
1178
|
-
* Returns required predicates that define what makes something an instance,
|
|
1179
|
-
* plus a map of property/collection names to their predicates.
|
|
1550
|
+
* Gets subject class metadata from SHACL links using SHACLShape.fromLinks().
|
|
1551
|
+
* Retrieves the SHACL shape and extracts metadata for instance queries.
|
|
1180
1552
|
*/
|
|
1181
1553
|
async getSubjectClassMetadataFromSDNA(className: string): Promise<{
|
|
1182
1554
|
requiredPredicates: string[],
|
|
@@ -1185,182 +1557,59 @@ export class PerspectiveProxy {
|
|
|
1185
1557
|
collections: Map<string, { predicate: string, instanceFilter?: string, condition?: string }>
|
|
1186
1558
|
} | null> {
|
|
1187
1559
|
try {
|
|
1188
|
-
//
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
predicate: "ad4m://sdna"
|
|
1193
|
-
}));
|
|
1194
|
-
|
|
1195
|
-
//console.log(`getSubjectClassMetadataFromSDNA: sdnaLinks for ${className}:`, sdnaLinks);
|
|
1196
|
-
|
|
1197
|
-
if (!sdnaLinks || sdnaLinks.length === 0) {
|
|
1198
|
-
console.warn(`No SDNA found for class ${className}`);
|
|
1199
|
-
return null;
|
|
1200
|
-
}
|
|
1201
|
-
|
|
1202
|
-
if (!sdnaLinks[0].data.target) {
|
|
1203
|
-
console.error(`SDNA link for ${className} has no target:`, sdnaLinks[0]);
|
|
1560
|
+
// Use getShacl() to retrieve the shape via SHACLShape.fromLinks()
|
|
1561
|
+
const shape = await this.getShacl(className);
|
|
1562
|
+
if (!shape) {
|
|
1563
|
+
console.warn(`No SHACL metadata found for ${className}`);
|
|
1204
1564
|
return null;
|
|
1205
1565
|
}
|
|
1206
1566
|
|
|
1207
|
-
|
|
1208
|
-
const sdnaCode = Literal.fromUrl(sdnaLinks[0].data.target).get();
|
|
1209
|
-
//console.log("sdnaCode for", className, ":", sdnaCode.substring(0, 200));
|
|
1210
|
-
|
|
1211
|
-
// Store required triples as {predicate, target?}
|
|
1212
|
-
// target is only set for flags (exact matches), otherwise undefined
|
|
1567
|
+
const requiredPredicates: string[] = [];
|
|
1213
1568
|
const requiredTriples: Array<{predicate: string, target?: string}> = [];
|
|
1214
|
-
|
|
1215
|
-
// Parse the instance rule from the SDNA code
|
|
1216
|
-
// Format: instance(c, Base) :- triple(Base, "pred1", _), triple(Base, "pred2", "exact_value").
|
|
1217
|
-
// Use a more robust pattern that handles complex rule bodies
|
|
1218
|
-
// Match from "instance(" to the closing "." using non-greedy matching
|
|
1219
|
-
const instanceRulePattern = /instance\([^)]+\)\s*:-\s*([^.]+)\./g;
|
|
1220
|
-
let instanceRuleMatch;
|
|
1221
|
-
let foundInstanceRule = false;
|
|
1222
|
-
|
|
1223
|
-
while ((instanceRuleMatch = instanceRulePattern.exec(sdnaCode)) !== null) {
|
|
1224
|
-
foundInstanceRule = true;
|
|
1225
|
-
const ruleBody = instanceRuleMatch[1];
|
|
1226
|
-
|
|
1227
|
-
// Extract all triple(Base, "predicate", Target) patterns
|
|
1228
|
-
// Match both: triple(Base, "pred", _) and triple(Base, "pred", "value")
|
|
1229
|
-
const tripleRegex = /triple\([^,]+,\s*"([^"]+)",\s*(?:"([^"]+)"|_)\)/g;
|
|
1230
|
-
let match;
|
|
1231
|
-
|
|
1232
|
-
while ((match = tripleRegex.exec(ruleBody)) !== null) {
|
|
1233
|
-
const predicate = match[1];
|
|
1234
|
-
const target = match[2]; // undefined if matched "_"
|
|
1235
|
-
requiredTriples.push({ predicate, target });
|
|
1236
|
-
}
|
|
1237
|
-
}
|
|
1238
|
-
|
|
1239
|
-
if (!foundInstanceRule) {
|
|
1240
|
-
console.warn(`No instance rule found in SDNA for ${className}`);
|
|
1241
|
-
}
|
|
1242
|
-
|
|
1243
|
-
// For backward compatibility, also maintain requiredPredicates array
|
|
1244
|
-
const requiredPredicates = requiredTriples.map(t => t.predicate);
|
|
1245
|
-
|
|
1246
|
-
// Extract property metadata
|
|
1247
1569
|
const properties = new Map<string, { predicate: string, resolveLanguage?: string }>();
|
|
1248
|
-
const
|
|
1249
|
-
//console.log("propertyResults", propertyResults);
|
|
1250
|
-
|
|
1251
|
-
if (propertyResults) {
|
|
1252
|
-
for (const result of propertyResults) {
|
|
1253
|
-
const propName = result.P;
|
|
1254
|
-
let predicate: string | null = null;
|
|
1255
|
-
|
|
1256
|
-
// Try to extract predicate from property_setter first
|
|
1257
|
-
const setterResults = await this.infer(`subject_class("${className}", C), property_setter(C, "${propName}", Setter)`);
|
|
1258
|
-
if (setterResults && setterResults.length > 0) {
|
|
1259
|
-
const setterString = setterResults[0].Setter;
|
|
1260
|
-
const predicateMatch = setterString.match(/predicate:\s*"([^"]+)"|predicate:\s*([^,}\]]+)/);
|
|
1261
|
-
if (predicateMatch) {
|
|
1262
|
-
predicate = predicateMatch[1] || predicateMatch[2];
|
|
1263
|
-
}
|
|
1264
|
-
}
|
|
1570
|
+
const collections = new Map<string, { predicate: string, instanceFilter?: string }>();
|
|
1265
1571
|
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
const escapedPropName = this.escapeRegExp(propName);
|
|
1271
|
-
const getterMatch = sdnaCode.match(new RegExp(`property_getter\\([^,]+,\\s*[^,]+,\\s*"${escapedPropName}"[^)]*\\)\\s*:-\\s*triple\\([^,]+,\\s*"([^"]+)"`));
|
|
1272
|
-
if (getterMatch) {
|
|
1273
|
-
predicate = getterMatch[1];
|
|
1274
|
-
}
|
|
1275
|
-
}
|
|
1572
|
+
// Build property/collection maps and track writable predicates from shape properties
|
|
1573
|
+
const writablePredicates = new Set<string>();
|
|
1574
|
+
for (const prop of shape.properties) {
|
|
1575
|
+
if (!prop.path || !prop.name) continue;
|
|
1276
1576
|
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
const resolveLanguage = resolveResults && resolveResults.length > 0 ? resolveResults[0].Lang : undefined;
|
|
1577
|
+
if (prop.writable) {
|
|
1578
|
+
writablePredicates.add(prop.path);
|
|
1579
|
+
}
|
|
1281
1580
|
|
|
1282
|
-
|
|
1283
|
-
|
|
1581
|
+
const isCollection = prop.adder && prop.adder.length > 0;
|
|
1582
|
+
if (isCollection) {
|
|
1583
|
+
collections.set(prop.name, { predicate: prop.path });
|
|
1584
|
+
} else {
|
|
1585
|
+
properties.set(prop.name, {
|
|
1586
|
+
predicate: prop.path,
|
|
1587
|
+
resolveLanguage: prop.resolveLanguage
|
|
1588
|
+
});
|
|
1284
1589
|
}
|
|
1285
1590
|
}
|
|
1286
|
-
//console.log("properties", properties);
|
|
1287
|
-
|
|
1288
|
-
// Extract collection metadata
|
|
1289
|
-
const collections = new Map<string, { predicate: string, instanceFilter?: string, condition?: string }>();
|
|
1290
|
-
const collectionResults = await this.infer(`subject_class("${className}", C), collection(C, Coll)`);
|
|
1291
|
-
//console.log("collectionResults", collectionResults);
|
|
1292
|
-
if (collectionResults) {
|
|
1293
|
-
for (const result of collectionResults) {
|
|
1294
|
-
const collName = result.Coll;
|
|
1295
|
-
let predicate: string | null = null;
|
|
1296
|
-
let instanceFilter: string | undefined = undefined;
|
|
1297
|
-
let condition: string | undefined = undefined;
|
|
1298
|
-
|
|
1299
|
-
// Try to extract predicate from collection_adder first
|
|
1300
|
-
const adderResults = await this.infer(`subject_class("${className}", C), collection_adder(C, "${collName}", Adder)`);
|
|
1301
|
-
if (adderResults && adderResults.length > 0) {
|
|
1302
|
-
const adderString = adderResults[0].Adder;
|
|
1303
|
-
const predicateMatch = adderString.match(/predicate:\s*"([^"]+)"|predicate:\s*([^,}\]]+)/);
|
|
1304
|
-
if (predicateMatch) {
|
|
1305
|
-
predicate = predicateMatch[1] || predicateMatch[2];
|
|
1306
|
-
}
|
|
1307
|
-
}
|
|
1308
|
-
|
|
1309
|
-
// Note: condition is not stored in SDNA, it's read from class metadata
|
|
1310
|
-
// It will be populated by augmentMetadataWithCollectionOptions() when needed
|
|
1311
|
-
|
|
1312
|
-
// Parse collection_getter from SDNA to extract predicate and instanceFilter
|
|
1313
|
-
// Format 1 (findall): collection_getter(c, Base, "comments", List) :- findall(C, triple(Base, "todo://comment", C), List).
|
|
1314
|
-
// Format 2 (setof): collection_getter(c, Base, "messages", List) :- setof(Target, (triple(Base, "flux://entry_type", Target), ...), List).
|
|
1315
|
-
// Use a line-based match to avoid capturing multiple collections
|
|
1316
|
-
// Escape collName to prevent regex injection and ReDoS attacks
|
|
1317
|
-
const escapedCollName = this.escapeRegExp(collName);
|
|
1318
|
-
const getterLinePattern = new RegExp(`collection_getter\\([^,]+,\\s*[^,]+,\\s*"${escapedCollName}"[^)]*\\)\\s*:-[^.]+\\.`);
|
|
1319
|
-
const getterLineMatch = sdnaCode.match(getterLinePattern);
|
|
1320
|
-
|
|
1321
|
-
if (getterLineMatch) {
|
|
1322
|
-
const getterLine = getterLineMatch[0];
|
|
1323
|
-
// Extract the body between setof/findall and the final ).
|
|
1324
|
-
// Pattern: findall(Var, Body, List) or setof(Var, (Body), List)
|
|
1325
|
-
const bodyPattern = /(?:setof|findall)\([^,]+,\s*(.+),\s*\w+\)\./;
|
|
1326
|
-
const bodyMatch = getterLine.match(bodyPattern);
|
|
1327
|
-
|
|
1328
|
-
if (bodyMatch) {
|
|
1329
|
-
let getterBody = bodyMatch[1];
|
|
1330
|
-
// Remove outer parentheses if present (setof case)
|
|
1331
|
-
if (getterBody.startsWith('(') && getterBody.endsWith(')')) {
|
|
1332
|
-
getterBody = getterBody.substring(1, getterBody.length - 1);
|
|
1333
|
-
}
|
|
1334
|
-
|
|
1335
|
-
// Extract predicate from triple(Base, "predicate", Target)
|
|
1336
|
-
if (!predicate) {
|
|
1337
|
-
const tripleMatch = getterBody.match(/triple\([^,]+,\s*"([^"]+)"/);
|
|
1338
|
-
if (tripleMatch) {
|
|
1339
|
-
predicate = tripleMatch[1];
|
|
1340
|
-
}
|
|
1341
|
-
}
|
|
1342
|
-
|
|
1343
|
-
// Check for instance filter: subject_class("ClassName", OtherClass)
|
|
1344
|
-
const instanceMatch = getterBody.match(/subject_class\("([^"]+)"/);
|
|
1345
|
-
if (instanceMatch) {
|
|
1346
|
-
instanceFilter = instanceMatch[1];
|
|
1347
|
-
}
|
|
1348
|
-
}
|
|
1349
|
-
}
|
|
1350
1591
|
|
|
1351
|
-
|
|
1352
|
-
|
|
1592
|
+
// Extract required predicates/triples from constructor actions
|
|
1593
|
+
if (shape.constructor_actions) {
|
|
1594
|
+
for (const action of shape.constructor_actions) {
|
|
1595
|
+
if (action.predicate) {
|
|
1596
|
+
requiredPredicates.push(action.predicate);
|
|
1597
|
+
const isWritableProperty = writablePredicates.has(action.predicate);
|
|
1598
|
+
if (action.target && action.target !== 'value' && !isWritableProperty) {
|
|
1599
|
+
requiredTriples.push({ predicate: action.predicate, target: action.target });
|
|
1600
|
+
} else {
|
|
1601
|
+
requiredTriples.push({ predicate: action.predicate });
|
|
1602
|
+
}
|
|
1353
1603
|
}
|
|
1354
1604
|
}
|
|
1355
1605
|
}
|
|
1356
|
-
|
|
1606
|
+
|
|
1357
1607
|
return { requiredPredicates, requiredTriples, properties, collections };
|
|
1358
1608
|
} catch (e) {
|
|
1359
|
-
console.error(`Error getting metadata for ${className}:`, e);
|
|
1609
|
+
console.error(`Error getting SHACL metadata for ${className}:`, e);
|
|
1360
1610
|
return null;
|
|
1361
1611
|
}
|
|
1362
1612
|
}
|
|
1363
|
-
|
|
1364
1613
|
/**
|
|
1365
1614
|
* Generates a SurrealDB query to find instances based on class metadata.
|
|
1366
1615
|
*/
|
|
@@ -1596,8 +1845,13 @@ export class PerspectiveProxy {
|
|
|
1596
1845
|
*/
|
|
1597
1846
|
async getAllSubjectInstances<T>(subjectClass: T): Promise<T[]> {
|
|
1598
1847
|
let classes = []
|
|
1848
|
+
let isClassConstructor = typeof subjectClass === "function"
|
|
1599
1849
|
if(typeof subjectClass === "string") {
|
|
1600
1850
|
classes = [subjectClass]
|
|
1851
|
+
} else if (isClassConstructor) {
|
|
1852
|
+
// It's an Ad4mModel class constructor
|
|
1853
|
+
//@ts-ignore
|
|
1854
|
+
classes = [subjectClass.name]
|
|
1601
1855
|
} else {
|
|
1602
1856
|
classes = await this.subjectClassesByTemplate(subjectClass as object)
|
|
1603
1857
|
}
|
|
@@ -1616,9 +1870,19 @@ export class PerspectiveProxy {
|
|
|
1616
1870
|
for (const result of results || []) {
|
|
1617
1871
|
//console.log(`getAllSubjectInstances: Creating subject for base ${result.base}`);
|
|
1618
1872
|
try {
|
|
1619
|
-
let
|
|
1620
|
-
|
|
1621
|
-
|
|
1873
|
+
let instance;
|
|
1874
|
+
if (isClassConstructor) {
|
|
1875
|
+
// Create an instance of the actual Ad4mModel class
|
|
1876
|
+
//@ts-ignore
|
|
1877
|
+
instance = new subjectClass(this, result.base);
|
|
1878
|
+
// Load the instance data from links
|
|
1879
|
+
await instance.get();
|
|
1880
|
+
} else {
|
|
1881
|
+
// Legacy: Create a Subject proxy
|
|
1882
|
+
instance = new Subject(this, result.base, className);
|
|
1883
|
+
await instance.init();
|
|
1884
|
+
}
|
|
1885
|
+
instances.push(instance as unknown as T);
|
|
1622
1886
|
//console.log(`getAllSubjectInstances: Successfully created subject for ${result.base}`);
|
|
1623
1887
|
} catch (e) {
|
|
1624
1888
|
//console.warn(`Failed to create subject for ${result.base}:`, e);
|
|
@@ -1668,97 +1932,88 @@ export class PerspectiveProxy {
|
|
|
1668
1932
|
}
|
|
1669
1933
|
|
|
1670
1934
|
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
// Collect all collections of the object in a list
|
|
1689
|
-
if (Object.getPrototypeOf(obj).__collections) {
|
|
1690
|
-
Object.keys(Object.getPrototypeOf(obj).__collections).filter(key => key !== 'isSubjectInstance').forEach(c => {
|
|
1691
|
-
if (!collections.includes(c)) {
|
|
1692
|
-
collections.push(c);
|
|
1693
|
-
}
|
|
1694
|
-
});
|
|
1695
|
-
} else {
|
|
1696
|
-
collections.push(...Object.keys(obj).filter(key => Array.isArray(obj[key])).filter(key => key !== 'isSubjectInstance'))
|
|
1697
|
-
}
|
|
1698
|
-
|
|
1699
|
-
// Collect all set functions of the object in a list
|
|
1700
|
-
let setFunctions = Object.getOwnPropertyNames(obj).filter(key => (typeof obj[key] === "function") && key.startsWith("set") && !key.startsWith("setCollection"))
|
|
1701
|
-
// Add all set functions of the object's prototype to that list
|
|
1702
|
-
setFunctions = setFunctions.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).filter(key => {
|
|
1703
|
-
const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), key);
|
|
1704
|
-
return descriptor && typeof descriptor.value === "function" && key.startsWith("set") && !key.startsWith("setCollection");
|
|
1705
|
-
}));
|
|
1706
|
-
|
|
1707
|
-
// Collect all add functions of the object in a list
|
|
1708
|
-
let addFunctions = Object.getOwnPropertyNames(obj).filter(key => (Object.prototype.hasOwnProperty.call(obj, key) && typeof obj[key] === "function") && key.startsWith("add"))
|
|
1709
|
-
// Add all add functions of the object's prototype to that list
|
|
1710
|
-
addFunctions = addFunctions.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).filter(key => {
|
|
1711
|
-
const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), key);
|
|
1712
|
-
return descriptor && typeof descriptor.value === "function" && key.startsWith("add");
|
|
1713
|
-
}));
|
|
1714
|
-
|
|
1715
|
-
// Collect all remove functions of the object in a list
|
|
1716
|
-
let removeFunctions = Object.getOwnPropertyNames(obj).filter(key => (Object.prototype.hasOwnProperty.call(obj, key) && typeof obj[key] === "function") && key.startsWith("remove"))
|
|
1717
|
-
// Add all remove functions of the object's prototype to that list
|
|
1718
|
-
removeFunctions = removeFunctions.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).filter(key => {
|
|
1719
|
-
const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), key);
|
|
1720
|
-
return descriptor && typeof descriptor.value === "function" && key.startsWith("remove");
|
|
1721
|
-
}));
|
|
1935
|
+
/**
|
|
1936
|
+
* Find a subject class by matching an object's properties/collections against SHACL shapes.
|
|
1937
|
+
* Queries SHACL links client-side to find a class whose properties contain all required ones.
|
|
1938
|
+
* @returns The matching class name, or null if no match found.
|
|
1939
|
+
*/
|
|
1940
|
+
private async findClassByProperties(obj: object): Promise<string | null> {
|
|
1941
|
+
// Extract properties and collections from the object
|
|
1942
|
+
let properties: string[] = [];
|
|
1943
|
+
let collections: string[] = [];
|
|
1944
|
+
const proto = Object.getPrototypeOf(obj);
|
|
1945
|
+
|
|
1946
|
+
if (proto?.__properties) {
|
|
1947
|
+
properties = Object.keys(proto.__properties);
|
|
1948
|
+
} else {
|
|
1949
|
+
properties = Object.keys(obj).filter(key => !Array.isArray((obj as any)[key]));
|
|
1950
|
+
}
|
|
1722
1951
|
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
return descriptor && typeof descriptor.value === "function" && key.startsWith("setCollection");
|
|
1729
|
-
}));
|
|
1730
|
-
// Construct query to find all subject classes that have the given properties and collections
|
|
1731
|
-
let query = `subject_class(Class, C)`
|
|
1952
|
+
if (proto?.__collections) {
|
|
1953
|
+
collections = Object.keys(proto.__collections).filter(key => key !== 'isSubjectInstance');
|
|
1954
|
+
} else {
|
|
1955
|
+
collections = Object.keys(obj).filter(key => Array.isArray((obj as any)[key]) && key !== 'isSubjectInstance');
|
|
1956
|
+
}
|
|
1732
1957
|
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
for(let collection of collections) {
|
|
1737
|
-
query += `, collection(C, "${collection}")`
|
|
1738
|
-
}
|
|
1958
|
+
if (properties.length === 0 && collections.length === 0) {
|
|
1959
|
+
return null;
|
|
1960
|
+
}
|
|
1739
1961
|
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1962
|
+
// Single SurrealDB query to find all classes and their properties/collections
|
|
1963
|
+
const query = `SELECT
|
|
1964
|
+
in.uri AS shape_source,
|
|
1965
|
+
predicate,
|
|
1966
|
+
out.uri AS target
|
|
1967
|
+
FROM link
|
|
1968
|
+
WHERE predicate IN ['rdf://type', 'sh://property', 'sh://collection']`;
|
|
1969
|
+
|
|
1970
|
+
const results = await this.querySurrealDB(query);
|
|
1971
|
+
if (!results || results.length === 0) return null;
|
|
1972
|
+
|
|
1973
|
+
// Build a map of className -> { properties, collections }
|
|
1974
|
+
const classShapes: Map<string, { shapeUri: string, properties: string[], collections: string[] }> = new Map();
|
|
1975
|
+
|
|
1976
|
+
// First pass: find all subject classes
|
|
1977
|
+
for (const r of results) {
|
|
1978
|
+
if (r.predicate === 'rdf://type' && r.target === 'ad4m://SubjectClass') {
|
|
1979
|
+
const source = r.shape_source;
|
|
1980
|
+
const sepIdx = source.indexOf('://');
|
|
1981
|
+
if (sepIdx < 0) continue;
|
|
1982
|
+
const className = source.substring(sepIdx + 3).split('/').pop();
|
|
1983
|
+
if (!className) continue;
|
|
1984
|
+
classShapes.set(className, { shapeUri: source, properties: [], collections: [] });
|
|
1748
1985
|
}
|
|
1986
|
+
}
|
|
1749
1987
|
|
|
1750
|
-
|
|
1751
|
-
|
|
1988
|
+
// Second pass: collect properties and collections for each class
|
|
1989
|
+
for (const r of results) {
|
|
1990
|
+
if (r.predicate === 'sh://property' || r.predicate === 'sh://collection') {
|
|
1991
|
+
// Match shape source to class (e.g., "recipe://RecipeShape" -> "Recipe")
|
|
1992
|
+
for (const [className, shape] of classShapes) {
|
|
1993
|
+
if (r.shape_source.endsWith(`${className}Shape`)) {
|
|
1994
|
+
const dotIdx = r.target.lastIndexOf('.');
|
|
1995
|
+
if (dotIdx < 0) continue;
|
|
1996
|
+
const name = r.target.substring(dotIdx + 1);
|
|
1997
|
+
if (r.predicate === 'sh://property') {
|
|
1998
|
+
shape.properties.push(name);
|
|
1999
|
+
} else {
|
|
2000
|
+
shape.collections.push(name);
|
|
2001
|
+
}
|
|
2002
|
+
}
|
|
2003
|
+
}
|
|
1752
2004
|
}
|
|
2005
|
+
}
|
|
1753
2006
|
|
|
1754
|
-
|
|
1755
|
-
|
|
2007
|
+
// Find a class that has all required properties and collections
|
|
2008
|
+
for (const [className, shape] of classShapes) {
|
|
2009
|
+
const hasAllProps = properties.every(p => shape.properties.includes(p));
|
|
2010
|
+
const hasAllCols = collections.every(c => shape.collections.includes(c));
|
|
2011
|
+
if (hasAllProps && hasAllCols) {
|
|
2012
|
+
return className;
|
|
1756
2013
|
}
|
|
2014
|
+
}
|
|
1757
2015
|
|
|
1758
|
-
|
|
1759
|
-
result = query
|
|
1760
|
-
}(obj))
|
|
1761
|
-
return result
|
|
2016
|
+
return null;
|
|
1762
2017
|
}
|
|
1763
2018
|
|
|
1764
2019
|
/** Returns all subject classes that match the given template object.
|
|
@@ -1773,13 +2028,31 @@ export class PerspectiveProxy {
|
|
|
1773
2028
|
* @param obj The template object
|
|
1774
2029
|
*/
|
|
1775
2030
|
async subjectClassesByTemplate(obj: object): Promise<string[]> {
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
2031
|
+
// SHACL-based lookup: try property matching first (more precise), fall back to className
|
|
2032
|
+
try {
|
|
2033
|
+
const match = await this.findClassByProperties(obj);
|
|
2034
|
+
if (match) {
|
|
2035
|
+
return [match];
|
|
2036
|
+
}
|
|
2037
|
+
} catch (e) {
|
|
2038
|
+
console.warn('subjectClassesByTemplate: property matching failed:', e);
|
|
2039
|
+
}
|
|
2040
|
+
|
|
2041
|
+
// Fall back to className lookup
|
|
2042
|
+
try {
|
|
2043
|
+
// @ts-ignore - className is added dynamically by decorators
|
|
2044
|
+
const className = obj.className || obj.constructor?.className || obj.constructor?.prototype?.className;
|
|
2045
|
+
if (className) {
|
|
2046
|
+
const existingClasses = await this.subjectClasses();
|
|
2047
|
+
if (existingClasses.includes(className)) {
|
|
2048
|
+
return [className];
|
|
2049
|
+
}
|
|
2050
|
+
}
|
|
2051
|
+
} catch (e) {
|
|
2052
|
+
console.warn('subjectClassesByTemplate: className lookup failed:', e);
|
|
1782
2053
|
}
|
|
2054
|
+
|
|
2055
|
+
return [];
|
|
1783
2056
|
}
|
|
1784
2057
|
|
|
1785
2058
|
/** Takes a JS class (its constructor) and assumes that it was decorated by
|
|
@@ -1789,14 +2062,25 @@ export class PerspectiveProxy {
|
|
|
1789
2062
|
* static generateSDNA() function and adds it to the perspective's SDNA.
|
|
1790
2063
|
*/
|
|
1791
2064
|
async ensureSDNASubjectClass(jsClass: any): Promise<void> {
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
2065
|
+
// Get the class name from the JS class
|
|
2066
|
+
const className = jsClass.className || jsClass.prototype?.className || jsClass.name;
|
|
2067
|
+
|
|
2068
|
+
// Note: Duplicate checking is handled on the Rust side in add_sdna
|
|
2069
|
+
|
|
2070
|
+
// Generate SHACL SDNA (Prolog-free)
|
|
2071
|
+
if (!jsClass.generateSHACL) {
|
|
2072
|
+
throw new Error(`Class ${jsClass.name} must have generateSHACL(). Use @ModelOptions decorator.`);
|
|
1795
2073
|
}
|
|
1796
2074
|
|
|
1797
|
-
|
|
2075
|
+
// Get SHACL shape (W3C standard + AD4M action definitions)
|
|
2076
|
+
const { shape } = jsClass.generateSHACL();
|
|
2077
|
+
|
|
2078
|
+
// Serialize SHACL shape to JSON for Rust backend using SHACLShape.toJSON()
|
|
2079
|
+
const shaclJson = JSON.stringify(shape.toJSON());
|
|
1798
2080
|
|
|
1799
|
-
|
|
2081
|
+
// Pass SHACL JSON to backend (Prolog-free)
|
|
2082
|
+
// Backend stores SHACL links directly
|
|
2083
|
+
await this.addSdna(className, '', 'subject_class', shaclJson);
|
|
1800
2084
|
}
|
|
1801
2085
|
|
|
1802
2086
|
getNeighbourhoodProxy(): NeighbourhoodProxy {
|