@coasys/ad4m 0.13.0-test-2 → 0.13.0-test-4
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/README.md +2 -25
- package/jest-setup.ts +1 -1
- package/lib/index.cjs +2805 -10556
- package/lib/index.js +2513 -10322
- package/lib/src/Ad4mClient.d.ts +7 -3
- package/lib/src/Ad4mClient.js +29 -13
- package/lib/src/agent/Agent.js +26 -272
- package/lib/src/agent/AgentClient.d.ts +10 -21
- package/lib/src/agent/AgentClient.js +75 -427
- package/lib/src/agent/AgentStatus.js +2 -37
- package/lib/src/ai/AIClient.d.ts +12 -4
- package/lib/src/ai/AIClient.js +81 -285
- package/lib/src/ai/AITypes.d.ts +55 -0
- package/lib/src/ai/AITypes.js +18 -0
- package/lib/src/ai/Tasks.js +10 -133
- package/lib/src/apiClient.d.ts +52 -0
- package/lib/src/apiClient.js +231 -0
- package/lib/src/expression/Expression.d.ts +1 -1
- package/lib/src/expression/Expression.js +13 -122
- package/lib/src/expression/ExpressionClient.d.ts +3 -3
- package/lib/src/expression/ExpressionClient.js +13 -76
- package/lib/src/expression/ExpressionRef.js +2 -25
- package/lib/src/generated/api/AIModelLoadingStatus.d.ts +7 -0
- package/lib/src/generated/api/AIModelLoadingStatus.js +2 -0
- package/lib/src/generated/api/AddLinkExpressionRequest.d.ts +6 -0
- package/lib/src/generated/api/AddLinkExpressionRequest.js +1 -0
- package/lib/src/generated/api/AddLinkRequest.d.ts +6 -0
- package/lib/src/generated/api/AddLinkRequest.js +1 -0
- package/lib/src/generated/api/AddLinksBulkRequest.d.ts +6 -0
- package/lib/src/generated/api/AddLinksBulkRequest.js +1 -0
- package/lib/src/generated/api/AddSdnaRequest.d.ts +6 -0
- package/lib/src/generated/api/AddSdnaRequest.js +2 -0
- package/lib/src/generated/api/ApplyTemplateRequest.d.ts +4 -0
- package/lib/src/generated/api/ApplyTemplateRequest.js +2 -0
- package/lib/src/generated/api/AuthInfoInput.d.ts +10 -0
- package/lib/src/generated/api/AuthInfoInput.js +1 -0
- package/lib/src/generated/api/CapabilityInput.d.ts +5 -0
- package/lib/src/generated/api/CapabilityInput.js +1 -0
- package/lib/src/generated/api/CommitBatchRequest.d.ts +3 -0
- package/lib/src/generated/api/CommitBatchRequest.js +2 -0
- package/lib/src/generated/api/ComputeLogEntry.d.ts +9 -0
- package/lib/src/generated/api/ComputeLogEntry.js +2 -0
- package/lib/src/generated/api/CreateExpressionRequest.d.ts +4 -0
- package/lib/src/generated/api/CreateExpressionRequest.js +2 -0
- package/lib/src/generated/api/CreatePerspectiveRequest.d.ts +3 -0
- package/lib/src/generated/api/CreatePerspectiveRequest.js +2 -0
- package/lib/src/generated/api/CreateSubjectRequest.d.ts +6 -0
- package/lib/src/generated/api/CreateSubjectRequest.js +2 -0
- package/lib/src/generated/api/EmbedRequest.d.ts +4 -0
- package/lib/src/generated/api/EmbedRequest.js +2 -0
- package/lib/src/generated/api/EntanglementProofInput.d.ts +6 -0
- package/lib/src/generated/api/EntanglementProofInput.js +2 -0
- package/lib/src/generated/api/ExecuteCommandsRequest.d.ts +4 -0
- package/lib/src/generated/api/ExecuteCommandsRequest.js +2 -0
- package/lib/src/generated/api/ExportRequest.d.ts +5 -0
- package/lib/src/generated/api/ExportRequest.js +2 -0
- package/lib/src/generated/api/ExpressionManyRequest.d.ts +3 -0
- package/lib/src/generated/api/ExpressionManyRequest.js +2 -0
- package/lib/src/generated/api/ExpressionProof.d.ts +4 -0
- package/lib/src/generated/api/ExpressionProof.js +2 -0
- package/lib/src/generated/api/ExpressionProofInput.d.ts +6 -0
- package/lib/src/generated/api/ExpressionProofInput.js +2 -0
- package/lib/src/generated/api/FriendSendMessageRequest.d.ts +3 -0
- package/lib/src/generated/api/FriendSendMessageRequest.js +2 -0
- package/lib/src/generated/api/FriendsListRequest.d.ts +3 -0
- package/lib/src/generated/api/FriendsListRequest.js +2 -0
- package/lib/src/generated/api/GenerateAgentRequest.d.ts +3 -0
- package/lib/src/generated/api/GenerateAgentRequest.js +2 -0
- package/lib/src/generated/api/GenerateJwtRequest.d.ts +4 -0
- package/lib/src/generated/api/GenerateJwtRequest.js +2 -0
- package/lib/src/generated/api/GetSubjectDataRequest.d.ts +4 -0
- package/lib/src/generated/api/GetSubjectDataRequest.js +2 -0
- package/lib/src/generated/api/ImportAgentRequest.d.ts +6 -0
- package/lib/src/generated/api/ImportAgentRequest.js +2 -0
- package/lib/src/generated/api/ImportRequest.d.ts +4 -0
- package/lib/src/generated/api/ImportRequest.js +2 -0
- package/lib/src/generated/api/JoinNeighbourhoodRequest.d.ts +3 -0
- package/lib/src/generated/api/JoinNeighbourhoodRequest.js +2 -0
- package/lib/src/generated/api/LanguageMetaInput.d.ts +6 -0
- package/lib/src/generated/api/LanguageMetaInput.js +2 -0
- package/lib/src/generated/api/Link.d.ts +5 -0
- package/lib/src/generated/api/Link.js +2 -0
- package/lib/src/generated/api/LinkExpression.d.ts +10 -0
- package/lib/src/generated/api/LinkExpression.js +1 -0
- package/lib/src/generated/api/LinkExpressionInput.d.ts +10 -0
- package/lib/src/generated/api/LinkExpressionInput.js +1 -0
- package/lib/src/generated/api/LinkInput.d.ts +5 -0
- package/lib/src/generated/api/LinkInput.js +2 -0
- package/lib/src/generated/api/LinkLanguageTemplatesRequest.d.ts +3 -0
- package/lib/src/generated/api/LinkLanguageTemplatesRequest.js +2 -0
- package/lib/src/generated/api/LinkMutations.d.ts +6 -0
- package/lib/src/generated/api/LinkMutations.js +1 -0
- package/lib/src/generated/api/LinkStatus.d.ts +1 -0
- package/lib/src/generated/api/LinkStatus.js +2 -0
- package/lib/src/generated/api/LockAgentRequest.d.ts +3 -0
- package/lib/src/generated/api/LockAgentRequest.js +2 -0
- package/lib/src/generated/api/ModelType.d.ts +1 -0
- package/lib/src/generated/api/ModelType.js +2 -0
- package/lib/src/generated/api/NotificationInput.d.ts +10 -0
- package/lib/src/generated/api/NotificationInput.js +2 -0
- package/lib/src/generated/api/OpenLinkRequest.d.ts +3 -0
- package/lib/src/generated/api/OpenLinkRequest.js +2 -0
- package/lib/src/generated/api/PermitCapabilityRequest.d.ts +3 -0
- package/lib/src/generated/api/PermitCapabilityRequest.js +2 -0
- package/lib/src/generated/api/PerspectiveInput.d.ts +4 -0
- package/lib/src/generated/api/PerspectiveInput.js +1 -0
- package/lib/src/generated/api/PromptRequest.d.ts +4 -0
- package/lib/src/generated/api/PromptRequest.js +2 -0
- package/lib/src/generated/api/PublishLanguageRequest.d.ts +5 -0
- package/lib/src/generated/api/PublishLanguageRequest.js +1 -0
- package/lib/src/generated/api/PublishNeighbourhoodRequest.d.ts +6 -0
- package/lib/src/generated/api/PublishNeighbourhoodRequest.js +1 -0
- package/lib/src/generated/api/QueryRequest.d.ts +7 -0
- package/lib/src/generated/api/QueryRequest.js +2 -0
- package/lib/src/generated/api/RemoveLinkRequest.d.ts +5 -0
- package/lib/src/generated/api/RemoveLinkRequest.js +1 -0
- package/lib/src/generated/api/RemoveLinksBulkRequest.d.ts +5 -0
- package/lib/src/generated/api/RemoveLinksBulkRequest.js +1 -0
- package/lib/src/generated/api/ResourceInput.d.ts +4 -0
- package/lib/src/generated/api/ResourceInput.js +2 -0
- package/lib/src/generated/api/SetDefaultModelRequest.d.ts +4 -0
- package/lib/src/generated/api/SetDefaultModelRequest.js +1 -0
- package/lib/src/generated/api/SetFreeHostingEnabledRequest.d.ts +3 -0
- package/lib/src/generated/api/SetFreeHostingEnabledRequest.js +2 -0
- package/lib/src/generated/api/SetMultiUserRequest.d.ts +3 -0
- package/lib/src/generated/api/SetMultiUserRequest.js +2 -0
- package/lib/src/generated/api/SetStatusRequest.d.ts +3 -0
- package/lib/src/generated/api/SetStatusRequest.js +2 -0
- package/lib/src/generated/api/SignMessageRequest.d.ts +3 -0
- package/lib/src/generated/api/SignMessageRequest.js +2 -0
- package/lib/src/generated/api/TrustedAgentsRequest.d.ts +3 -0
- package/lib/src/generated/api/TrustedAgentsRequest.js +2 -0
- package/lib/src/generated/api/UnlockAgentRequest.d.ts +4 -0
- package/lib/src/generated/api/UnlockAgentRequest.js +2 -0
- package/lib/src/generated/api/UpdateLinkRequest.d.ts +7 -0
- package/lib/src/generated/api/UpdateLinkRequest.js +1 -0
- package/lib/src/generated/api/UpdatePerspectiveRequest.d.ts +3 -0
- package/lib/src/generated/api/UpdatePerspectiveRequest.js +2 -0
- package/lib/src/generated/api/UserStatistics.d.ts +9 -0
- package/lib/src/generated/api/UserStatistics.js +2 -0
- package/lib/src/generated/api/VerificationRequestResult.d.ts +6 -0
- package/lib/src/generated/api/VerificationRequestResult.js +2 -0
- package/lib/src/generated/api/VerifySignatureRequest.d.ts +5 -0
- package/lib/src/generated/api/VerifySignatureRequest.js +2 -0
- package/lib/src/generated/api/WriteSettingsRequest.d.ts +3 -0
- package/lib/src/generated/api/WriteSettingsRequest.js +2 -0
- package/lib/src/generated/api/index.d.ts +42 -0
- package/lib/src/generated/api/index.js +7 -0
- package/lib/src/index.d.ts +6 -2
- package/lib/src/index.js +6 -2
- package/lib/src/jestSetup.d.ts +0 -1
- package/lib/src/jestSetup.js +1 -1
- package/lib/src/language/Icon.js +2 -21
- package/lib/src/language/Language.d.ts +26 -214
- package/lib/src/language/Language.js +32 -72
- package/lib/src/language/LanguageClient.d.ts +2 -2
- package/lib/src/language/LanguageClient.js +15 -105
- package/lib/src/language/LanguageHandle.js +2 -41
- package/lib/src/language/LanguageMeta.js +4 -75
- package/lib/src/language/LanguageRef.js +2 -25
- package/lib/src/links/Links.js +14 -111
- package/lib/src/model/Ad4mModel.d.ts +81 -38
- package/lib/src/model/Ad4mModel.js +651 -408
- package/lib/src/model/Ad4mModel.test.js +488 -750
- package/lib/src/model/ModelQueryBuilder.d.ts +28 -21
- package/lib/src/model/ModelQueryBuilder.js +160 -195
- package/lib/src/model/decorators.d.ts +22 -0
- package/lib/src/model/decorators.js +7 -0
- package/lib/src/model/hydration-batching.test.d.ts +7 -0
- package/lib/src/model/hydration-batching.test.js +456 -0
- package/lib/src/model/hydration.d.ts +8 -60
- package/lib/src/model/hydration.js +41 -541
- package/lib/src/model/index.d.ts +0 -4
- package/lib/src/model/index.js +0 -4
- package/lib/src/model/model-manifest.d.ts +41 -0
- package/lib/src/model/model-manifest.js +11 -0
- package/lib/src/model/query-sparql.d.ts +36 -22
- package/lib/src/model/query-sparql.js +188 -53
- package/lib/src/model/query-sparql.test.d.ts +1 -0
- package/lib/src/model/query-sparql.test.js +312 -0
- package/lib/src/model/query-utils.js +4 -0
- package/lib/src/model/shacl-gen.js +4 -0
- package/lib/src/model/subscription-delta.test.d.ts +24 -0
- package/lib/src/model/subscription-delta.test.js +180 -0
- package/lib/src/model/subscription-pool.js +48 -2
- package/lib/src/model/types.d.ts +58 -1
- package/lib/src/model/types.js +4 -1
- package/lib/src/neighbourhood/Neighbourhood.js +4 -32
- package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +3 -3
- package/lib/src/neighbourhood/NeighbourhoodClient.js +40 -203
- package/lib/src/perspectives/LinkQuery.js +2 -42
- package/lib/src/perspectives/Perspective.d.ts +1 -1
- package/lib/src/perspectives/Perspective.js +10 -52
- package/lib/src/perspectives/PerspectiveClient.d.ts +12 -15
- package/lib/src/perspectives/PerspectiveClient.js +168 -400
- package/lib/src/perspectives/PerspectiveClient.test.d.ts +1 -0
- package/lib/src/perspectives/PerspectiveClient.test.js +224 -0
- package/lib/src/perspectives/PerspectiveDiff.js +4 -31
- package/lib/src/perspectives/PerspectiveHandle.js +3 -43
- package/lib/src/perspectives/PerspectiveProxy.d.ts +95 -71
- package/lib/src/perspectives/PerspectiveProxy.js +288 -310
- package/lib/src/runtime/RuntimeClient.d.ts +6 -6
- package/lib/src/runtime/RuntimeClient.js +93 -467
- package/lib/src/runtime/RuntimeTypes.d.ts +101 -0
- package/lib/src/runtime/RuntimeTypes.js +45 -0
- package/lib/src/shacl/SHACLShape.d.ts +7 -0
- package/lib/src/shacl/SHACLShape.js +19 -0
- package/lib/src/shacl/SHACLShape.test.js +82 -0
- package/lib/src/typeDefs.js +3 -628
- package/package.json +9 -24
- package/rollup.config.js +0 -7
- package/src/Ad4mClient.test.ts +1182 -1288
- package/src/Ad4mClient.ts +30 -15
- package/src/agent/Agent.ts +0 -99
- package/src/agent/AgentClient.ts +112 -526
- package/src/agent/AgentStatus.ts +0 -12
- package/src/ai/AIClient.ts +96 -296
- package/src/ai/AITypes.ts +66 -0
- package/src/ai/Tasks.ts +0 -52
- package/src/apiClient.ts +283 -0
- package/src/expression/Expression.ts +3 -43
- package/src/expression/ExpressionClient.ts +14 -77
- package/src/expression/ExpressionRef.ts +0 -6
- package/src/generated/api/AIModelLoadingStatus.ts +3 -0
- package/src/generated/api/AddLinkExpressionRequest.ts +4 -0
- package/src/generated/api/AddLinkRequest.ts +4 -0
- package/src/generated/api/AddLinksBulkRequest.ts +4 -0
- package/src/generated/api/AddSdnaRequest.ts +3 -0
- package/src/generated/api/ApplyTemplateRequest.ts +3 -0
- package/src/generated/api/AuthInfoInput.ts +4 -0
- package/src/generated/api/CapabilityInput.ts +4 -0
- package/src/generated/api/CommitBatchRequest.ts +3 -0
- package/src/generated/api/ComputeLogEntry.ts +3 -0
- package/src/generated/api/CreateExpressionRequest.ts +3 -0
- package/src/generated/api/CreatePerspectiveRequest.ts +3 -0
- package/src/generated/api/CreateSubjectRequest.ts +3 -0
- package/src/generated/api/EmbedRequest.ts +3 -0
- package/src/generated/api/EntanglementProofInput.ts +3 -0
- package/src/generated/api/ExecuteCommandsRequest.ts +3 -0
- package/src/generated/api/ExportRequest.ts +3 -0
- package/src/generated/api/ExpressionManyRequest.ts +3 -0
- package/src/generated/api/ExpressionProof.ts +3 -0
- package/src/generated/api/ExpressionProofInput.ts +3 -0
- package/src/generated/api/FriendSendMessageRequest.ts +3 -0
- package/src/generated/api/FriendsListRequest.ts +3 -0
- package/src/generated/api/GenerateAgentRequest.ts +3 -0
- package/src/generated/api/GenerateJwtRequest.ts +3 -0
- package/src/generated/api/GetSubjectDataRequest.ts +3 -0
- package/src/generated/api/ImportAgentRequest.ts +3 -0
- package/src/generated/api/ImportRequest.ts +3 -0
- package/src/generated/api/JoinNeighbourhoodRequest.ts +3 -0
- package/src/generated/api/LanguageMetaInput.ts +3 -0
- package/src/generated/api/Link.ts +3 -0
- package/src/generated/api/LinkExpression.ts +6 -0
- package/src/generated/api/LinkExpressionInput.ts +6 -0
- package/src/generated/api/LinkInput.ts +3 -0
- package/src/generated/api/LinkLanguageTemplatesRequest.ts +3 -0
- package/src/generated/api/LinkMutations.ts +5 -0
- package/src/generated/api/LinkStatus.ts +3 -0
- package/src/generated/api/LockAgentRequest.ts +3 -0
- package/src/generated/api/ModelType.ts +3 -0
- package/src/generated/api/NotificationInput.ts +3 -0
- package/src/generated/api/OpenLinkRequest.ts +3 -0
- package/src/generated/api/PermitCapabilityRequest.ts +3 -0
- package/src/generated/api/PerspectiveInput.ts +4 -0
- package/src/generated/api/PromptRequest.ts +3 -0
- package/src/generated/api/PublishLanguageRequest.ts +4 -0
- package/src/generated/api/PublishNeighbourhoodRequest.ts +4 -0
- package/src/generated/api/QueryRequest.ts +6 -0
- package/src/generated/api/RemoveLinkRequest.ts +4 -0
- package/src/generated/api/RemoveLinksBulkRequest.ts +4 -0
- package/src/generated/api/ResourceInput.ts +3 -0
- package/src/generated/api/SetDefaultModelRequest.ts +4 -0
- package/src/generated/api/SetFreeHostingEnabledRequest.ts +3 -0
- package/src/generated/api/SetMultiUserRequest.ts +3 -0
- package/src/generated/api/SetStatusRequest.ts +3 -0
- package/src/generated/api/SignMessageRequest.ts +3 -0
- package/src/generated/api/TrustedAgentsRequest.ts +3 -0
- package/src/generated/api/UnlockAgentRequest.ts +3 -0
- package/src/generated/api/UpdateLinkRequest.ts +5 -0
- package/src/generated/api/UpdatePerspectiveRequest.ts +3 -0
- package/src/generated/api/UserStatistics.ts +3 -0
- package/src/generated/api/VerificationRequestResult.ts +3 -0
- package/src/generated/api/VerifySignatureRequest.ts +3 -0
- package/src/generated/api/WriteSettingsRequest.ts +3 -0
- package/src/generated/api/index.ts +49 -0
- package/src/index.ts +6 -2
- package/src/jestSetup.ts +1 -1
- package/src/language/Icon.ts +0 -4
- package/src/language/Language.ts +50 -292
- package/src/language/LanguageClient.ts +21 -132
- package/src/language/LanguageHandle.ts +0 -14
- package/src/language/LanguageMeta.ts +0 -29
- package/src/language/LanguageRef.ts +0 -7
- package/src/links/Links.ts +0 -37
- package/src/model/Ad4mModel.test.ts +827 -808
- package/src/model/Ad4mModel.ts +676 -457
- package/src/model/ModelQueryBuilder.ts +199 -217
- package/src/model/decorators.ts +29 -0
- package/src/model/hydration.ts +17 -572
- package/src/model/index.ts +0 -4
- package/src/model/query-sparql.test.ts +360 -0
- package/src/model/query-sparql.ts +203 -56
- package/src/model/query-utils.ts +4 -0
- package/src/model/shacl-gen.ts +5 -0
- package/src/model/types.ts +62 -1
- package/src/neighbourhood/Neighbourhood.ts +0 -9
- package/src/neighbourhood/NeighbourhoodClient.ts +42 -207
- package/src/neighbourhood/NeighbourhoodProxy.test.ts +34 -36
- package/src/perspectives/LinkQuery.ts +0 -15
- package/src/perspectives/Perspective.ts +1 -12
- package/src/perspectives/PerspectiveClient.test.ts +262 -0
- package/src/perspectives/PerspectiveClient.ts +227 -412
- package/src/perspectives/PerspectiveDiff.ts +0 -8
- package/src/perspectives/PerspectiveHandle.ts +1 -12
- package/src/perspectives/PerspectiveProxy.test.ts +41 -0
- package/src/perspectives/PerspectiveProxy.ts +325 -348
- package/src/runtime/RuntimeClient.ts +112 -474
- package/src/runtime/RuntimeTypes.ts +144 -0
- package/src/shacl/SHACLShape.test.ts +94 -0
- package/src/shacl/SHACLShape.ts +27 -0
- package/src/typeDefs.ts +3 -5
- package/tsconfig.json +3 -7
- package/lib/src/model/query-surreal.d.ts +0 -44
- package/lib/src/model/query-surreal.js +0 -249
- package/lib/src/model/surreal-utils.d.ts +0 -42
- package/lib/src/model/surreal-utils.js +0 -128
- package/shims/reflect-metadata.ts +0 -0
- package/shims/type-graphql.ts +0 -75
- package/src/PubSub.ts +0 -17
- package/src/agent/AgentResolver.ts +0 -263
- package/src/ai/AIResolver.ts +0 -372
- package/src/buildSchema.ts +0 -43
- package/src/expression/ExpressionResolver.ts +0 -64
- package/src/language/LanguageContext.ts +0 -37
- package/src/language/LanguageResolver.ts +0 -98
- package/src/model/Subject.ts +0 -159
- package/src/model/hydration-batch.ts +0 -205
- package/src/model/prolog-facts.ts +0 -145
- package/src/model/query-prolog.ts +0 -148
- package/src/model/query-sparql-batch.ts +0 -301
- package/src/model/subscription-pool.ts +0 -163
- package/src/neighbourhood/NeighbourhoodResolver.ts +0 -100
- package/src/perspectives/PerspectiveResolver.ts +0 -364
- package/src/runtime/RuntimeResolver.ts +0 -749
- package/src/unwrapApolloResult.ts +0 -16
- package/tsconfig-browser.json +0 -82
|
@@ -2,13 +2,148 @@ import { Literal } from "../Literal";
|
|
|
2
2
|
import { Link } from "../links/Links";
|
|
3
3
|
import { LinkQuery } from "../perspectives/LinkQuery";
|
|
4
4
|
import { makeRandomId } from "./util";
|
|
5
|
-
import { getPropertiesMetadata, getRelationsMetadata } from "./decorators";
|
|
5
|
+
import { getPropertiesMetadata, getRelationsMetadata, buildConformanceFilter, setPropertyRegistryEntry, setRelationRegistryEntry, Model } from "./decorators";
|
|
6
|
+
import { compileWhereClause } from "./query-utils";
|
|
6
7
|
import { resolveParentPredicate } from "./query-common";
|
|
7
|
-
import { buildParentQuery, buildAuthorAndTimestampQuery, buildPropertiesQuery, buildWhereQuery, buildCountQuery, buildOrderQuery, buildOffsetQuery, buildLimitQuery } from "./query-prolog";
|
|
8
8
|
import { isArrayType, determinePredicate, determineNamespace, buildModelFromJSONSchema } from "./json-schema";
|
|
9
|
-
import { buildSPARQLQuery
|
|
9
|
+
import { buildSPARQLQuery } from "./query-sparql";
|
|
10
10
|
import { ModelQueryBuilder } from "./ModelQueryBuilder";
|
|
11
|
-
import { normalizeValue,
|
|
11
|
+
import { normalizeValue, evaluateCustomGettersForInstance, } from "./hydration";
|
|
12
|
+
// ---------------------------------------------------------------------------
|
|
13
|
+
// Helpers for Rust-side include resolution
|
|
14
|
+
// ---------------------------------------------------------------------------
|
|
15
|
+
/**
|
|
16
|
+
* Recursively enrich relation metadata in the shape with target class shapes
|
|
17
|
+
* so the Rust endpoint can resolve includes in-process (no extra GraphQL
|
|
18
|
+
* round-trips per relation).
|
|
19
|
+
*/
|
|
20
|
+
function enrichShapeForIncludes(metadata, include, allRelMeta) {
|
|
21
|
+
for (const [relName, includeVal] of Object.entries(include)) {
|
|
22
|
+
if (!includeVal)
|
|
23
|
+
continue;
|
|
24
|
+
const meta = allRelMeta[relName];
|
|
25
|
+
if (!meta?.target)
|
|
26
|
+
continue;
|
|
27
|
+
const TargetClass = meta.target();
|
|
28
|
+
// Deep-copy so we don't mutate the cached metadata
|
|
29
|
+
const targetMeta = JSON.parse(JSON.stringify(TargetClass.getModelMetadata()));
|
|
30
|
+
// Ensure the relation is in metadata.relations (fallback for edge cases)
|
|
31
|
+
if (!metadata.relations[relName]) {
|
|
32
|
+
metadata.relations[relName] = {
|
|
33
|
+
name: relName,
|
|
34
|
+
predicate: meta.predicate,
|
|
35
|
+
direction: meta.kind === 'belongsToMany' || meta.kind === 'belongsToOne'
|
|
36
|
+
? 'reverse'
|
|
37
|
+
: 'forward',
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
const rel = metadata.relations[relName];
|
|
41
|
+
rel.kind = meta.kind;
|
|
42
|
+
rel.maxCount = meta.maxCount;
|
|
43
|
+
rel.targetShape = targetMeta;
|
|
44
|
+
rel.targetClassName = targetMeta.className;
|
|
45
|
+
// Recurse for nested includes
|
|
46
|
+
const nested = typeof includeVal === 'object' && includeVal !== null
|
|
47
|
+
? includeVal.include
|
|
48
|
+
: undefined;
|
|
49
|
+
if (nested) {
|
|
50
|
+
const targetRelMeta = getRelationsMetadata(TargetClass);
|
|
51
|
+
enrichShapeForIncludes(targetMeta, nested, targetRelMeta);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Construct a model class instance from a plain JSON object returned by the
|
|
57
|
+
* Rust endpoint. Recursively converts included relation values (which come
|
|
58
|
+
* back as plain JSON objects) into proper model class instances.
|
|
59
|
+
*/
|
|
60
|
+
function jsonToModelInstance(ModelClass, perspective, json, include, properties) {
|
|
61
|
+
const instance = new ModelClass(perspective, json.id || json.baseExpression);
|
|
62
|
+
// When a properties projection is active, remove own properties set by the
|
|
63
|
+
// constructor that are not in the projected JSON. This ensures assertions
|
|
64
|
+
// like `expect(r).to.not.have.own.property("body")` pass.
|
|
65
|
+
if (properties) {
|
|
66
|
+
const jsonKeys = new Set(Object.keys(json));
|
|
67
|
+
for (const key of Object.getOwnPropertyNames(instance)) {
|
|
68
|
+
// Keep internal fields (backing store for getters), id, baseExpression, perspective
|
|
69
|
+
if (key === 'id' || key === 'baseExpression' || key === 'perspective' || key.startsWith('_'))
|
|
70
|
+
continue;
|
|
71
|
+
if (!jsonKeys.has(key)) {
|
|
72
|
+
delete instance[key];
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
for (const [key, value] of Object.entries(json)) {
|
|
77
|
+
if (key === 'baseExpression' || key === 'id')
|
|
78
|
+
continue;
|
|
79
|
+
// Skip getter-only properties anywhere in the prototype chain
|
|
80
|
+
let isReadonly = false;
|
|
81
|
+
let proto = Object.getPrototypeOf(instance);
|
|
82
|
+
while (proto) {
|
|
83
|
+
const desc = Object.getOwnPropertyDescriptor(proto, key);
|
|
84
|
+
if (desc) {
|
|
85
|
+
isReadonly = !!(desc.get && !desc.set);
|
|
86
|
+
break;
|
|
87
|
+
}
|
|
88
|
+
proto = Object.getPrototypeOf(proto);
|
|
89
|
+
}
|
|
90
|
+
if (isReadonly)
|
|
91
|
+
continue;
|
|
92
|
+
// Parse ISO timestamps to epoch milliseconds (matches hydrateFromLinks behaviour)
|
|
93
|
+
if ((key === 'createdAt' || key === 'updatedAt') && typeof value === 'string' && value.includes('T')) {
|
|
94
|
+
instance[key] = new Date(value).getTime();
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
instance[key] = value;
|
|
98
|
+
}
|
|
99
|
+
// Apply property transform functions from decorators (only for literal-resolved
|
|
100
|
+
// or no-resolveLanguage properties; non-literal properties are resolved + transformed
|
|
101
|
+
// asynchronously in executeModelQuery).
|
|
102
|
+
try {
|
|
103
|
+
const propsMeta = getPropertiesMetadata(ModelClass);
|
|
104
|
+
for (const [propName, opts] of Object.entries(propsMeta)) {
|
|
105
|
+
const o = opts;
|
|
106
|
+
if (typeof o.transform !== 'function' || !(propName in json))
|
|
107
|
+
continue;
|
|
108
|
+
// Skip non-literal resolveLanguage props — they need async expression resolution first
|
|
109
|
+
if (o.resolveLanguage != null && o.resolveLanguage !== 'literal')
|
|
110
|
+
continue;
|
|
111
|
+
instance[propName] = o.transform(instance[propName]);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
catch (_) { /* no metadata available */ }
|
|
115
|
+
// Recursively convert included relation values to class instances
|
|
116
|
+
if (include) {
|
|
117
|
+
const relMeta = getRelationsMetadata(ModelClass);
|
|
118
|
+
for (const [relName, includeVal] of Object.entries(include)) {
|
|
119
|
+
if (!includeVal)
|
|
120
|
+
continue;
|
|
121
|
+
const meta = relMeta[relName];
|
|
122
|
+
if (!meta?.target)
|
|
123
|
+
continue;
|
|
124
|
+
const TargetClass = meta.target();
|
|
125
|
+
const nestedInclude = typeof includeVal === 'object' && includeVal !== null
|
|
126
|
+
? includeVal.include
|
|
127
|
+
: undefined;
|
|
128
|
+
const nestedProperties = typeof includeVal === 'object' && includeVal !== null
|
|
129
|
+
? includeVal.properties
|
|
130
|
+
: undefined;
|
|
131
|
+
const raw = instance[relName];
|
|
132
|
+
if (Array.isArray(raw)) {
|
|
133
|
+
instance[relName] = raw.map((item) => {
|
|
134
|
+
if (typeof item === 'object' && item !== null && item.id) {
|
|
135
|
+
return jsonToModelInstance(TargetClass, perspective, item, nestedInclude, nestedProperties);
|
|
136
|
+
}
|
|
137
|
+
return item;
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
else if (typeof raw === 'object' && raw !== null && raw.id) {
|
|
141
|
+
instance[relName] = jsonToModelInstance(TargetClass, perspective, raw, nestedInclude, nestedProperties);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return instance;
|
|
146
|
+
}
|
|
12
147
|
/**
|
|
13
148
|
* Base class for defining data models in AD4M.
|
|
14
149
|
*
|
|
@@ -106,6 +241,13 @@ import { normalizeValue, matchesCondition, hydrateFromLinks, assignValuesToInsta
|
|
|
106
241
|
* ```
|
|
107
242
|
*/
|
|
108
243
|
export class Ad4mModel {
|
|
244
|
+
/**
|
|
245
|
+
* Backwards compatibility alias for createdAt.
|
|
246
|
+
* @deprecated Use createdAt instead. This will be removed in a future version.
|
|
247
|
+
*/
|
|
248
|
+
get timestamp() {
|
|
249
|
+
return this.createdAt;
|
|
250
|
+
}
|
|
109
251
|
/**
|
|
110
252
|
* Generates the SDNA (Subject DNA) Prolog rules for this model class.
|
|
111
253
|
* Injected at class-definition time by the `@Model` decorator.
|
|
@@ -143,13 +285,6 @@ export class Ad4mModel {
|
|
|
143
285
|
}
|
|
144
286
|
return classCache[perspectiveID];
|
|
145
287
|
}
|
|
146
|
-
/**
|
|
147
|
-
* Backwards compatibility alias for createdAt.
|
|
148
|
-
* @deprecated Use createdAt instead. This will be removed in a future version.
|
|
149
|
-
*/
|
|
150
|
-
get timestamp() {
|
|
151
|
-
return this.createdAt;
|
|
152
|
-
}
|
|
153
288
|
/**
|
|
154
289
|
* Extracts metadata from decorators for query building.
|
|
155
290
|
*
|
|
@@ -221,7 +356,7 @@ export class Ad4mModel {
|
|
|
221
356
|
// Extract relations (relations) from WeakMap registry
|
|
222
357
|
const relationsMetadata = {};
|
|
223
358
|
const allRelationsMeta = getRelationsMetadata(this);
|
|
224
|
-
const prototypeRelations =
|
|
359
|
+
const prototypeRelations = allRelationsMeta;
|
|
225
360
|
for (const [relationName, opts] of Object.entries(prototypeRelations)) {
|
|
226
361
|
const options = opts;
|
|
227
362
|
relationsMetadata[relationName] = {
|
|
@@ -230,6 +365,8 @@ export class Ad4mModel {
|
|
|
230
365
|
...(options.local !== undefined && { local: options.local }),
|
|
231
366
|
...(options.getter !== undefined && { getter: options.getter }),
|
|
232
367
|
direction: (options.kind === 'belongsToMany' || options.kind === 'belongsToOne') ? 'reverse' : 'forward',
|
|
368
|
+
...(options.kind !== undefined && { kind: options.kind }),
|
|
369
|
+
...(options.maxCount !== undefined && { maxCount: options.maxCount }),
|
|
233
370
|
...(options.target !== undefined && { target: options.target }),
|
|
234
371
|
...(options.filter !== undefined && { filter: options.filter }),
|
|
235
372
|
...(options.where !== undefined && { where: options.where }),
|
|
@@ -304,12 +441,6 @@ export class Ad4mModel {
|
|
|
304
441
|
get id() {
|
|
305
442
|
return this._baseExpression;
|
|
306
443
|
}
|
|
307
|
-
/**
|
|
308
|
-
* @deprecated Use `.id` instead. Will be removed in a future version.
|
|
309
|
-
*/
|
|
310
|
-
get baseExpression() {
|
|
311
|
-
return this._baseExpression;
|
|
312
|
-
}
|
|
313
444
|
/**
|
|
314
445
|
* Protected getter for the perspective.
|
|
315
446
|
* Allows subclasses to access the perspective while keeping it private from external code.
|
|
@@ -390,13 +521,6 @@ export class Ad4mModel {
|
|
|
390
521
|
...(metadata.local && { local: true })
|
|
391
522
|
}];
|
|
392
523
|
}
|
|
393
|
-
/**
|
|
394
|
-
* Assigns decoded Prolog property values to an instance.
|
|
395
|
-
* Delegates to the standalone function in hydration.ts.
|
|
396
|
-
*/
|
|
397
|
-
static async assignValuesToInstance(perspective, instance, values) {
|
|
398
|
-
return _assignValuesToInstance(perspective, instance, values);
|
|
399
|
-
}
|
|
400
524
|
// ──────────────────────────────────────────────────────────
|
|
401
525
|
// Snapshot / dirty tracking
|
|
402
526
|
// ──────────────────────────────────────────────────────────
|
|
@@ -516,78 +640,52 @@ export class Ad4mModel {
|
|
|
516
640
|
return changed;
|
|
517
641
|
}
|
|
518
642
|
async getData(opts) {
|
|
519
|
-
//
|
|
520
|
-
//
|
|
643
|
+
// Route through the Rust model query endpoint — same pipeline as executeModelQuery
|
|
644
|
+
// but for a single instance by ID.
|
|
521
645
|
try {
|
|
522
646
|
const ctor = this.constructor;
|
|
523
|
-
const
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
if (
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
}
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
647
|
+
const query = {
|
|
648
|
+
where: { id: this._baseExpression },
|
|
649
|
+
limit: 1,
|
|
650
|
+
};
|
|
651
|
+
if (opts?.properties)
|
|
652
|
+
query.properties = opts.properties;
|
|
653
|
+
if (opts?.include)
|
|
654
|
+
query.include = opts.include;
|
|
655
|
+
const { results } = await ctor.executeModelQuery(this._perspective, query, null);
|
|
656
|
+
if (results.length > 0) {
|
|
657
|
+
const hydrated = results[0];
|
|
658
|
+
// Copy all hydrated values from the Rust-side result onto this instance
|
|
659
|
+
for (const [key, value] of Object.entries(hydrated)) {
|
|
660
|
+
if (key === '_baseExpression' || key === '_perspective' || key === '_snapshot')
|
|
661
|
+
continue;
|
|
662
|
+
if (key.startsWith('_'))
|
|
663
|
+
continue;
|
|
664
|
+
// Check for readonly getters
|
|
665
|
+
let isReadonly = false;
|
|
666
|
+
let proto = Object.getPrototypeOf(this);
|
|
667
|
+
while (proto) {
|
|
668
|
+
const desc = Object.getOwnPropertyDescriptor(proto, key);
|
|
669
|
+
if (desc) {
|
|
670
|
+
isReadonly = !!(desc.get && !desc.set);
|
|
671
|
+
break;
|
|
672
|
+
}
|
|
673
|
+
proto = Object.getPrototypeOf(proto);
|
|
674
|
+
}
|
|
675
|
+
if (isReadonly)
|
|
676
|
+
continue;
|
|
677
|
+
this[key] = value;
|
|
549
678
|
}
|
|
550
679
|
}
|
|
551
|
-
//
|
|
552
|
-
|
|
553
|
-
? { requestedProperties: opts?.properties, include: opts?.include }
|
|
554
|
-
: undefined;
|
|
555
|
-
await evaluateCustomGettersForInstance(this, this._perspective, metadata, getterOpts);
|
|
556
|
-
// Eager-load relations if requested
|
|
557
|
-
if (opts?.include) {
|
|
558
|
-
await hydrateRelations(ctor, [this], this._perspective, opts.include);
|
|
559
|
-
}
|
|
680
|
+
// Property getters and relation conformance getters are now evaluated
|
|
681
|
+
// Rust-side via evaluate_getters() in model_query.rs.
|
|
560
682
|
}
|
|
561
683
|
catch (e) {
|
|
562
|
-
console.error(`
|
|
684
|
+
console.error(`getData via Rust model query failed for ${this._baseExpression}:`, e);
|
|
563
685
|
}
|
|
564
|
-
this.takeSnapshot();
|
|
686
|
+
this.takeSnapshot(opts?.include);
|
|
565
687
|
return this;
|
|
566
688
|
}
|
|
567
|
-
static async queryToProlog(perspective, query, modelClassName) {
|
|
568
|
-
const { properties, where, order, offset, limit, count } = query;
|
|
569
|
-
const className = modelClassName || (await this.getClassName(perspective));
|
|
570
|
-
// Resolve parent predicate from model metadata if needed
|
|
571
|
-
const resolvedParentPredicate = query.parent
|
|
572
|
-
? resolveParentPredicate(query.parent, this)
|
|
573
|
-
: undefined;
|
|
574
|
-
const instanceQueries = [
|
|
575
|
-
buildAuthorAndTimestampQuery(),
|
|
576
|
-
buildParentQuery(query.parent, resolvedParentPredicate),
|
|
577
|
-
buildPropertiesQuery(properties),
|
|
578
|
-
buildWhereQuery(where),
|
|
579
|
-
];
|
|
580
|
-
const resultSetQueries = [buildCountQuery(count), buildOrderQuery(order), buildOffsetQuery(offset), buildLimitQuery(limit)];
|
|
581
|
-
const fullQuery = `
|
|
582
|
-
findall([Base, Properties, Collections, Timestamp, Author], (
|
|
583
|
-
subject_class("${className}", SubjectClass),
|
|
584
|
-
instance(SubjectClass, Base),
|
|
585
|
-
${instanceQueries.filter((q) => q).join(", ")}
|
|
586
|
-
), UnsortedInstances),
|
|
587
|
-
${resultSetQueries.filter((q) => q).join(", ")}
|
|
588
|
-
`;
|
|
589
|
-
return fullQuery;
|
|
590
|
-
}
|
|
591
689
|
/**
|
|
592
690
|
* Generates a SPARQL query from a Query object.
|
|
593
691
|
*
|
|
@@ -629,255 +727,353 @@ export class Ad4mModel {
|
|
|
629
727
|
const allRelMeta = getRelationsMetadata(this);
|
|
630
728
|
return buildSPARQLQuery(metadata, allRelMeta, query, this);
|
|
631
729
|
}
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
730
|
+
/**
|
|
731
|
+
* Build the JSON parameters needed for a model query/subscription endpoint.
|
|
732
|
+
* Returns the className, queryJson, and shapeJson that the Rust executor expects.
|
|
733
|
+
* @internal
|
|
734
|
+
*/
|
|
735
|
+
static prepareModelQueryParams(query = {}, classNameOverride) {
|
|
736
|
+
const metadata = this.getModelMetadata();
|
|
737
|
+
const className = classNameOverride || metadata.className;
|
|
738
|
+
const queryInput = {};
|
|
739
|
+
if (query.parent) {
|
|
740
|
+
const parentPredicate = resolveParentPredicate(query.parent, this);
|
|
741
|
+
queryInput.parent = { id: query.parent.id, predicate: parentPredicate };
|
|
742
|
+
}
|
|
743
|
+
if (query.properties)
|
|
744
|
+
queryInput.properties = query.properties;
|
|
745
|
+
if (query.include)
|
|
746
|
+
queryInput.include = query.include;
|
|
747
|
+
if (query.where)
|
|
748
|
+
queryInput.where = query.where;
|
|
749
|
+
if (query.order) {
|
|
750
|
+
queryInput.order = Object.entries(query.order).map(([k, v]) => [k, v]);
|
|
751
|
+
}
|
|
752
|
+
if (query.offset !== undefined)
|
|
753
|
+
queryInput.offset = query.offset;
|
|
754
|
+
if (query.limit !== undefined)
|
|
755
|
+
queryInput.limit = query.limit;
|
|
756
|
+
if (query.count !== undefined)
|
|
757
|
+
queryInput.count = query.count;
|
|
758
|
+
if (query.include) {
|
|
759
|
+
const allRelMeta = getRelationsMetadata(this);
|
|
760
|
+
enrichShapeForIncludes(metadata, query.include, allRelMeta);
|
|
761
|
+
}
|
|
762
|
+
// Pre-compute conformance getters (with where-clause support)
|
|
763
|
+
{
|
|
764
|
+
const allRelMeta = getRelationsMetadata(this);
|
|
765
|
+
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
766
|
+
const rel = relMeta;
|
|
767
|
+
if (rel.getter || rel.direction === 'reverse' || rel.filter === false)
|
|
768
|
+
continue;
|
|
769
|
+
const meta = allRelMeta[relName];
|
|
770
|
+
if (!meta?.target)
|
|
771
|
+
continue;
|
|
772
|
+
try {
|
|
773
|
+
const TargetClass = meta.target();
|
|
774
|
+
const filter = buildConformanceFilter(meta.predicate, TargetClass);
|
|
775
|
+
// Only compile where clauses to SPARQL when the target properties
|
|
776
|
+
// are stored as plain IRIs (not signed expressions). Properties
|
|
777
|
+
// without resolveLanguage or with resolveLanguage='literal' store
|
|
778
|
+
// values as signed JSON envelopes, so SPARQL exact-match fails.
|
|
779
|
+
let whereConditions = [];
|
|
780
|
+
if (rel.where) {
|
|
781
|
+
try {
|
|
782
|
+
const targetMetadata = TargetClass.getModelMetadata?.() ?? null;
|
|
783
|
+
let allSparqlFilterable = true;
|
|
784
|
+
if (targetMetadata) {
|
|
785
|
+
for (const propName of Object.keys(rel.where)) {
|
|
786
|
+
if (['id', 'author', 'timestamp'].includes(propName))
|
|
787
|
+
continue;
|
|
788
|
+
const propMeta = targetMetadata.properties[propName];
|
|
789
|
+
if (propMeta && (!propMeta.resolveLanguage || propMeta.resolveLanguage === 'literal')) {
|
|
790
|
+
allSparqlFilterable = false;
|
|
791
|
+
break;
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
else {
|
|
796
|
+
allSparqlFilterable = false;
|
|
797
|
+
}
|
|
798
|
+
if (allSparqlFilterable) {
|
|
799
|
+
whereConditions = compileWhereClause(rel.where, targetMetadata);
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
catch (_) { }
|
|
803
|
+
}
|
|
804
|
+
if (filter) {
|
|
805
|
+
let getter = filter.getter;
|
|
806
|
+
if (whereConditions.length > 0) {
|
|
807
|
+
getter = getter.replace(/ \}$/, ` ${whereConditions.join(' ')} }`);
|
|
808
|
+
}
|
|
809
|
+
rel.getter = getter;
|
|
810
|
+
}
|
|
811
|
+
else if (whereConditions.length > 0) {
|
|
812
|
+
const escapedPred = meta.predicate.replace(/[<>"{}|\\^`\u0000-\u0020]/g, '');
|
|
813
|
+
rel.getter = `SELECT ?target WHERE { <Base> <${escapedPred}> ?target . ${whereConditions.join(' ')} }`;
|
|
814
|
+
}
|
|
646
815
|
}
|
|
647
|
-
|
|
648
|
-
const values = [...Properties, ...Collections, ["createdAt", Timestamp], ["author", Author]];
|
|
649
|
-
await Ad4mModel.assignValuesToInstance(perspective, instance, values);
|
|
650
|
-
return instance;
|
|
651
|
-
}
|
|
652
|
-
catch (error) {
|
|
653
|
-
console.error(`Failed to process instance ${Base}:`, error);
|
|
654
|
-
// Return null for failed instances - we'll filter these out below
|
|
655
|
-
return null;
|
|
816
|
+
catch (_) { }
|
|
656
817
|
}
|
|
657
|
-
}));
|
|
658
|
-
const instances = allInstances.filter((instance) => instance !== null);
|
|
659
|
-
// Eager-load relations if requested (BEFORE snapshot so dirty tracking is accurate)
|
|
660
|
-
if (query.include && instances.length > 0) {
|
|
661
|
-
await hydrateRelations(this, instances, perspective, query.include);
|
|
662
|
-
}
|
|
663
|
-
// Take snapshots for dirty tracking after ALL hydration is complete
|
|
664
|
-
// (including eager-loaded relations).
|
|
665
|
-
// When `include` is specified, only snapshot those relations.
|
|
666
|
-
// Otherwise snapshot ALL fields (properties + relations) since
|
|
667
|
-
// hydrateFromLinks populates relations with stable raw IDs.
|
|
668
|
-
const snapshotRelations = query.include;
|
|
669
|
-
for (const inst of instances) {
|
|
670
|
-
inst.takeSnapshot(snapshotRelations);
|
|
671
818
|
}
|
|
672
|
-
return {
|
|
819
|
+
return {
|
|
820
|
+
className,
|
|
821
|
+
queryJson: JSON.stringify(queryInput),
|
|
822
|
+
shapeJson: JSON.stringify(metadata),
|
|
823
|
+
};
|
|
673
824
|
}
|
|
674
825
|
/**
|
|
675
|
-
*
|
|
826
|
+
* Parse raw model query/subscription result JSON into typed model instances.
|
|
827
|
+
* Used by ModelQueryBuilder to convert subscription updates without circular imports.
|
|
828
|
+
* @internal
|
|
829
|
+
*/
|
|
830
|
+
static parseModelResult(perspective, raw, include, properties) {
|
|
831
|
+
const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
|
|
832
|
+
const arr = data.instances || data;
|
|
833
|
+
if (!Array.isArray(arr))
|
|
834
|
+
return [];
|
|
835
|
+
return arr.map((json) => jsonToModelInstance(this, perspective, json, include, properties));
|
|
836
|
+
}
|
|
837
|
+
// instancesFromQueryResult — removed (superseded by Rust executeModelQuery pipeline)
|
|
838
|
+
/**
|
|
839
|
+
* Execute a model query via the executor-side endpoint.
|
|
676
840
|
*
|
|
677
|
-
*
|
|
678
|
-
*
|
|
679
|
-
* @param result - Array of result objects from SPARQL
|
|
680
|
-
* @returns Promise resolving to results with total count
|
|
841
|
+
* This replaces the old SPARQL-build → hydrate → JS-filter → JS-sort → JS-paginate pipeline
|
|
842
|
+
* with a single RPC to the executor that handles everything in Rust.
|
|
681
843
|
*
|
|
682
844
|
* @internal
|
|
683
845
|
*/
|
|
684
|
-
static async
|
|
685
|
-
if (!result || result.length === 0)
|
|
686
|
-
return { results: [], totalCount: 0 };
|
|
846
|
+
static async executeModelQuery(perspective, query = {}, classNameOverride) {
|
|
687
847
|
const metadata = this.getModelMetadata();
|
|
688
|
-
const
|
|
689
|
-
//
|
|
690
|
-
//
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
// Use source_uri as the base (the actual URI), not the node ID
|
|
698
|
-
base = row.source_uri;
|
|
699
|
-
// Skip rows without a source_uri field
|
|
700
|
-
if (!base) {
|
|
701
|
-
continue;
|
|
848
|
+
const className = classNameOverride || metadata.className;
|
|
849
|
+
// Expand includeAll: true to a full IncludeMap covering every forward relation.
|
|
850
|
+
// Done before queryInput is built so all downstream uses of query.include see the expansion.
|
|
851
|
+
if (query.includeAll) {
|
|
852
|
+
const allRelMeta = getRelationsMetadata(this);
|
|
853
|
+
const expanded = {};
|
|
854
|
+
for (const [relName, relMeta] of Object.entries(allRelMeta)) {
|
|
855
|
+
if (relMeta.direction !== 'reverse') {
|
|
856
|
+
expanded[relName] = true;
|
|
702
857
|
}
|
|
703
|
-
const links = row.links || [];
|
|
704
|
-
const instance = new this(perspective, base);
|
|
705
|
-
// Core hydration via unified helper (pass requestedProperties for sparse fieldset).
|
|
706
|
-
// Also hydrate any properties referenced in `where` so the JS post-filter can match them,
|
|
707
|
-
// even if they're not in the user's `properties` projection.
|
|
708
|
-
let hydrationProps = requestedProperties.length > 0 ? [...requestedProperties] : undefined;
|
|
709
|
-
if (hydrationProps && query.where) {
|
|
710
|
-
for (const key of Object.keys(query.where)) {
|
|
711
|
-
if (!hydrationProps.includes(key)) {
|
|
712
|
-
hydrationProps.push(key);
|
|
713
|
-
}
|
|
714
|
-
}
|
|
715
|
-
}
|
|
716
|
-
await hydrateFromLinks(instance, links, metadata, perspective, hydrationProps);
|
|
717
|
-
// NOTE: Property deletion for sparse fieldsets is deferred until AFTER
|
|
718
|
-
// where-filtering so that where conditions can reference any property,
|
|
719
|
-
// even ones not in the `properties` projection.
|
|
720
|
-
instances.push(instance);
|
|
721
858
|
}
|
|
722
|
-
|
|
723
|
-
|
|
859
|
+
// Explicit include entries take precedence over the expansion
|
|
860
|
+
query = { ...query, include: { ...expanded, ...query.include } };
|
|
861
|
+
}
|
|
862
|
+
// Build the query input that the Rust endpoint expects.
|
|
863
|
+
// Convert the TS Query type to the executor's ModelQueryInput format.
|
|
864
|
+
const queryInput = {};
|
|
865
|
+
if (query.parent) {
|
|
866
|
+
const parentPredicate = resolveParentPredicate(query.parent, this);
|
|
867
|
+
queryInput.parent = { id: query.parent.id, predicate: parentPredicate };
|
|
868
|
+
}
|
|
869
|
+
if (query.properties)
|
|
870
|
+
queryInput.properties = query.properties;
|
|
871
|
+
if (query.include) {
|
|
872
|
+
// Split include keys: $-prefixed / IncludeProjection values → queryInput.projections
|
|
873
|
+
// All other keys (boolean | RelationSubQuery) → queryInput.include
|
|
874
|
+
const normalIncludes = {};
|
|
875
|
+
const projections = {};
|
|
876
|
+
for (const [key, val] of Object.entries(query.include)) {
|
|
877
|
+
if (key.startsWith('$')) {
|
|
878
|
+
projections[key] = val;
|
|
879
|
+
}
|
|
880
|
+
else {
|
|
881
|
+
normalIncludes[key] = val;
|
|
882
|
+
}
|
|
724
883
|
}
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
inst[relName] = sourceIds.length > 0 ? sourceIds[sourceIds.length - 1] : null;
|
|
742
|
-
}
|
|
743
|
-
else {
|
|
744
|
-
inst[relName] = sourceIds;
|
|
884
|
+
if (Object.keys(normalIncludes).length > 0)
|
|
885
|
+
queryInput.include = normalIncludes;
|
|
886
|
+
if (Object.keys(projections).length > 0) {
|
|
887
|
+
// Enrich projections with target shapes so Rust can apply where clause filtering
|
|
888
|
+
const allRelMeta = getRelationsMetadata(this);
|
|
889
|
+
for (const [, proj] of Object.entries(projections)) {
|
|
890
|
+
const relMeta = allRelMeta[proj.from];
|
|
891
|
+
if (!proj.targetShape && relMeta?.target) {
|
|
892
|
+
try {
|
|
893
|
+
const TargetClass = relMeta.target();
|
|
894
|
+
const targetMeta = TargetClass.getModelMetadata?.();
|
|
895
|
+
if (targetMeta) {
|
|
896
|
+
proj.targetShape = targetMeta;
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
catch (_) { /* target class may not be available */ }
|
|
745
900
|
}
|
|
746
901
|
}
|
|
747
|
-
|
|
902
|
+
queryInput.projections = projections;
|
|
903
|
+
}
|
|
748
904
|
}
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
:
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
//
|
|
762
|
-
//
|
|
763
|
-
|
|
764
|
-
if (
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
905
|
+
if (query.where)
|
|
906
|
+
queryInput.where = query.where;
|
|
907
|
+
if (query.order) {
|
|
908
|
+
// Convert { propName: 'ASC' | 'DESC' } to [[propName, 'ASC'|'DESC'], ...]
|
|
909
|
+
queryInput.order = Object.entries(query.order).map(([k, v]) => [k, v]);
|
|
910
|
+
}
|
|
911
|
+
if (query.offset !== undefined)
|
|
912
|
+
queryInput.offset = query.offset;
|
|
913
|
+
if (query.limit !== undefined)
|
|
914
|
+
queryInput.limit = query.limit;
|
|
915
|
+
if (query.count !== undefined)
|
|
916
|
+
queryInput.count = query.count;
|
|
917
|
+
// Enrich relation metadata with target class shapes for Rust-side
|
|
918
|
+
// include resolution. This eliminates per-relation GraphQL round-trips
|
|
919
|
+
// by letting the Rust endpoint resolve includes in-process.
|
|
920
|
+
if (queryInput.include) {
|
|
921
|
+
const allRelMeta = getRelationsMetadata(this);
|
|
922
|
+
enrichShapeForIncludes(metadata, queryInput.include, allRelMeta);
|
|
923
|
+
}
|
|
924
|
+
// ── Pre-compute conformance getters for Rust-side evaluation ──────
|
|
925
|
+
// For each relation with a target class and filter !== false, compute
|
|
926
|
+
// the conformance getter SPARQL so Rust can evaluate it in-process
|
|
927
|
+
// (eliminating N × querySparql round-trips per instance).
|
|
928
|
+
// When a relation has a `where` clause, compile the where conditions
|
|
929
|
+
// into the getter SPARQL so Rust applies them during evaluation.
|
|
930
|
+
{
|
|
931
|
+
const allRelMeta = getRelationsMetadata(this);
|
|
932
|
+
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
933
|
+
const rel = relMeta;
|
|
934
|
+
if (rel.getter)
|
|
935
|
+
continue; // explicit getter already set
|
|
936
|
+
if (rel.direction === 'reverse')
|
|
937
|
+
continue; // reverse relations use reverse link lookup
|
|
938
|
+
if (rel.filter === false)
|
|
939
|
+
continue; // opt-out of conformance filtering
|
|
940
|
+
const meta = allRelMeta[relName];
|
|
941
|
+
if (!meta?.target)
|
|
942
|
+
continue;
|
|
943
|
+
try {
|
|
944
|
+
const TargetClass = meta.target();
|
|
945
|
+
const filter = buildConformanceFilter(meta.predicate, TargetClass);
|
|
946
|
+
// Only compile where clauses to SPARQL when the target properties
|
|
947
|
+
// are stored as plain IRIs (not signed expressions). Properties
|
|
948
|
+
// without resolveLanguage or with resolveLanguage='literal' store
|
|
949
|
+
// values as signed JSON envelopes, so SPARQL exact-match fails.
|
|
950
|
+
let whereConditions = [];
|
|
951
|
+
if (rel.where) {
|
|
952
|
+
try {
|
|
953
|
+
const targetMetadata = TargetClass.getModelMetadata?.() ?? null;
|
|
954
|
+
let allSparqlFilterable = true;
|
|
955
|
+
if (targetMetadata) {
|
|
956
|
+
for (const propName of Object.keys(rel.where)) {
|
|
957
|
+
if (['id', 'author', 'timestamp'].includes(propName))
|
|
958
|
+
continue;
|
|
959
|
+
const propMeta = targetMetadata.properties[propName];
|
|
960
|
+
if (propMeta && (!propMeta.resolveLanguage || propMeta.resolveLanguage === 'literal')) {
|
|
961
|
+
allSparqlFilterable = false;
|
|
962
|
+
break;
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
else {
|
|
967
|
+
allSparqlFilterable = false;
|
|
968
|
+
}
|
|
969
|
+
if (allSparqlFilterable) {
|
|
970
|
+
whereConditions = compileWhereClause(rel.where, targetMetadata);
|
|
971
|
+
}
|
|
774
972
|
}
|
|
775
|
-
|
|
973
|
+
catch (_) { /* target metadata unavailable */ }
|
|
776
974
|
}
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
return false;
|
|
975
|
+
if (filter) {
|
|
976
|
+
let getter = filter.getter;
|
|
977
|
+
if (whereConditions.length > 0) {
|
|
978
|
+
// Append where conditions before the closing }
|
|
979
|
+
getter = getter.replace(/ \}$/, ` ${whereConditions.join(' ')} }`);
|
|
783
980
|
}
|
|
784
|
-
|
|
981
|
+
rel.getter = getter;
|
|
785
982
|
}
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
return false;
|
|
983
|
+
else if (whereConditions.length > 0) {
|
|
984
|
+
// No conformance filter but where clause exists — build getter from where alone
|
|
985
|
+
const escapedPred = meta.predicate.replace(/[<>"{}|\\^`\u0000-\u0020]/g, '');
|
|
986
|
+
rel.getter = `SELECT ?target WHERE { <Base> <${escapedPred}> ?target . ${whereConditions.join(' ')} }`;
|
|
791
987
|
}
|
|
792
988
|
}
|
|
793
|
-
|
|
794
|
-
|
|
989
|
+
catch (e) {
|
|
990
|
+
// Target class may not be available; skip silently
|
|
991
|
+
}
|
|
992
|
+
}
|
|
795
993
|
}
|
|
796
|
-
//
|
|
797
|
-
//
|
|
798
|
-
//
|
|
799
|
-
const
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
994
|
+
// Send shape metadata to the executor so it knows the model structure.
|
|
995
|
+
// This is more reliable than reading SHACL from the store because
|
|
996
|
+
// the TS decorators are the definitive source of truth.
|
|
997
|
+
const shapeJson = JSON.stringify(metadata);
|
|
998
|
+
const queryJson = JSON.stringify(queryInput);
|
|
999
|
+
const result = await perspective.modelQuery(className, queryJson, shapeJson);
|
|
1000
|
+
// Convert JSON instances to model class instances, recursively constructing
|
|
1001
|
+
// class instances for any included relations resolved by Rust.
|
|
1002
|
+
const instances = result.instances.map((json) => {
|
|
1003
|
+
return jsonToModelInstance(this, perspective, json, query.include, query.properties);
|
|
1004
|
+
});
|
|
1005
|
+
// Resolve non-literal expressions (e.g. file languages where the stored
|
|
1006
|
+
// value is a content-addressed hash that must be fetched from the language
|
|
1007
|
+
// runtime). The Rust endpoint returns raw target URIs; we resolve them here.
|
|
1008
|
+
const propsMeta = getPropertiesMetadata(this);
|
|
1009
|
+
const resolveProps = Object.entries(propsMeta).filter(([, opts]) => opts.resolveLanguage != null &&
|
|
1010
|
+
opts.resolveLanguage !== 'literal');
|
|
1011
|
+
if (resolveProps.length > 0) {
|
|
1012
|
+
await Promise.all(instances.map(async (inst) => {
|
|
1013
|
+
for (const [propName, opts] of resolveProps) {
|
|
1014
|
+
const val = inst[propName];
|
|
1015
|
+
if (typeof val !== 'string' || !val || val.startsWith('literal:'))
|
|
809
1016
|
continue;
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
comparison = String(aVal).localeCompare(String(bVal));
|
|
824
|
-
}
|
|
825
|
-
if (comparison !== 0) {
|
|
826
|
-
return orderDirection === 'DESC' ? -comparison : comparison;
|
|
1017
|
+
try {
|
|
1018
|
+
const expression = await perspective.getExpression(val);
|
|
1019
|
+
if (expression) {
|
|
1020
|
+
let resolved;
|
|
1021
|
+
try {
|
|
1022
|
+
resolved = JSON.parse(expression.data);
|
|
1023
|
+
}
|
|
1024
|
+
catch {
|
|
1025
|
+
resolved = expression.data;
|
|
1026
|
+
}
|
|
1027
|
+
const transform = opts.transform;
|
|
1028
|
+
inst[propName] = typeof transform === 'function' ? transform(resolved) : resolved;
|
|
1029
|
+
}
|
|
827
1030
|
}
|
|
828
|
-
|
|
1031
|
+
catch (_) { /* resolution failed — keep raw value */ }
|
|
829
1032
|
}
|
|
830
|
-
|
|
831
|
-
});
|
|
1033
|
+
}));
|
|
832
1034
|
}
|
|
833
|
-
//
|
|
834
|
-
|
|
835
|
-
//
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
for (const inst of paginatedInstances) {
|
|
847
|
-
for (const propName of Object.keys(metadata.properties)) {
|
|
848
|
-
if (!requested.has(propName)) {
|
|
849
|
-
delete inst[propName];
|
|
850
|
-
}
|
|
851
|
-
}
|
|
852
|
-
for (const relName of Object.keys(metadata.relations)) {
|
|
853
|
-
if (!requested.has(relName) && !(query.include && relName in query.include)) {
|
|
854
|
-
delete inst[relName];
|
|
855
|
-
}
|
|
1035
|
+
// Relation conformance getters are evaluated Rust-side via evaluate_getters()
|
|
1036
|
+
// in model_query.rs. However, for relations with non-SPARQL-filterable where
|
|
1037
|
+
// clauses (e.g. properties stored as signed expressions), we still need
|
|
1038
|
+
// TS-side evaluation as a fallback. Running evaluateCustomGettersForInstance
|
|
1039
|
+
// with skipPropertyGetters ensures conformance + JS post-filtering for
|
|
1040
|
+
// where clauses that couldn't be compiled to SPARQL.
|
|
1041
|
+
const includedRelNames = queryInput.include ? new Set(Object.keys(queryInput.include)) : new Set();
|
|
1042
|
+
for (const inst of instances) {
|
|
1043
|
+
// Save included relation values that came from Rust hydration
|
|
1044
|
+
const savedIncluded = {};
|
|
1045
|
+
for (const relName of includedRelNames) {
|
|
1046
|
+
if (inst[relName] !== undefined) {
|
|
1047
|
+
savedIncluded[relName] = inst[relName];
|
|
856
1048
|
}
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
1049
|
+
}
|
|
1050
|
+
await evaluateCustomGettersForInstance(inst, perspective, metadata, {
|
|
1051
|
+
skipPropertyGetters: true,
|
|
1052
|
+
});
|
|
1053
|
+
// Restore hydrated include objects that were overwritten by conformance getters
|
|
1054
|
+
for (const [relName, value] of Object.entries(savedIncluded)) {
|
|
1055
|
+
inst[relName] = value;
|
|
1056
|
+
}
|
|
1057
|
+
// Fix cardinality for non-included HasOne/BelongsToOne relations:
|
|
1058
|
+
// The conformance getter always produces arrays; unwrap to scalar.
|
|
1059
|
+
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
1060
|
+
if (includedRelNames.has(relName))
|
|
1061
|
+
continue;
|
|
1062
|
+
const kind = relMeta.kind;
|
|
1063
|
+
if ((kind === 'hasOne' || kind === 'belongsToOne') && Array.isArray(inst[relName])) {
|
|
1064
|
+
const arr = inst[relName];
|
|
1065
|
+
inst[relName] = arr.length > 0 ? arr[0] : null;
|
|
861
1066
|
}
|
|
862
1067
|
}
|
|
863
1068
|
}
|
|
864
|
-
//
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
}
|
|
868
|
-
// Take snapshots for dirty tracking after ALL hydration is complete
|
|
869
|
-
// (including eager-loaded relations).
|
|
870
|
-
// When `include` is specified, only snapshot those relations.
|
|
871
|
-
// Otherwise snapshot ALL fields (properties + relations) since
|
|
872
|
-
// hydrateFromLinks populates relations with stable raw IDs —
|
|
873
|
-
// this ensures push-to-array + save() correctly detects dirty relations.
|
|
874
|
-
const snapshotRelations = query.include;
|
|
875
|
-
for (const inst of paginatedInstances) {
|
|
1069
|
+
// Take snapshots for dirty tracking
|
|
1070
|
+
const snapshotRelations = queryInput.include;
|
|
1071
|
+
for (const inst of instances) {
|
|
876
1072
|
inst.takeSnapshot(snapshotRelations);
|
|
877
1073
|
}
|
|
878
1074
|
return {
|
|
879
|
-
results:
|
|
880
|
-
totalCount
|
|
1075
|
+
results: instances,
|
|
1076
|
+
totalCount: result.totalCount,
|
|
881
1077
|
};
|
|
882
1078
|
}
|
|
883
1079
|
/**
|
|
@@ -907,31 +1103,12 @@ export class Ad4mModel {
|
|
|
907
1103
|
* const recipesProlog = await Recipe.findAll(perspective, {}, false);
|
|
908
1104
|
* ```
|
|
909
1105
|
*/
|
|
910
|
-
static async findAll(perspective, query = {},
|
|
1106
|
+
static async findAll(perspective, query = {}, _engine) {
|
|
911
1107
|
if (query.properties && query.properties.length === 0) {
|
|
912
1108
|
throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
|
|
913
1109
|
}
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
? (engine ? 'sparql' : 'prolog')
|
|
917
|
-
: engine;
|
|
918
|
-
if (resolvedEngine === 'sparql') {
|
|
919
|
-
// Always use the regular SPARQL path + JS-level hydrateRelations for includes.
|
|
920
|
-
// The batch SPARQL approach had issues with sub-queries (where/order/limit on includes),
|
|
921
|
-
// non-conforming node filtering, and parse_literal compatibility.
|
|
922
|
-
// hydrateRelations handles all of these correctly via per-relation findAll calls.
|
|
923
|
-
const sparqlQuery = await this.queryToSPARQL(perspective, query);
|
|
924
|
-
const rawResult = await perspective.querySparql(sparqlQuery);
|
|
925
|
-
const grouped = groupSPARQLResults(rawResult);
|
|
926
|
-
const { results } = await this.instancesFromQueryResult(perspective, query, grouped);
|
|
927
|
-
return results;
|
|
928
|
-
}
|
|
929
|
-
else {
|
|
930
|
-
const prologQuery = await this.queryToProlog(perspective, query);
|
|
931
|
-
const result = await perspective.infer(prologQuery);
|
|
932
|
-
const { results } = await this.instancesFromPrologResult(perspective, query, result);
|
|
933
|
-
return results;
|
|
934
|
-
}
|
|
1110
|
+
const { results } = await this.executeModelQuery(perspective, query);
|
|
1111
|
+
return results;
|
|
935
1112
|
}
|
|
936
1113
|
/**
|
|
937
1114
|
* Finds the first instance matching the query, or `null` if none exists.
|
|
@@ -953,9 +1130,9 @@ export class Ad4mModel {
|
|
|
953
1130
|
* }
|
|
954
1131
|
* ```
|
|
955
1132
|
*/
|
|
956
|
-
static async findOne(perspective, query = {},
|
|
1133
|
+
static async findOne(perspective, query = {}, _engine) {
|
|
957
1134
|
const limitedQuery = { ...query, limit: 1 };
|
|
958
|
-
const results = await this.findAll(perspective, limitedQuery
|
|
1135
|
+
const results = await this.findAll(perspective, limitedQuery);
|
|
959
1136
|
return results[0] ?? null;
|
|
960
1137
|
}
|
|
961
1138
|
/**
|
|
@@ -978,21 +1155,8 @@ export class Ad4mModel {
|
|
|
978
1155
|
* const { results, totalCount } = await Recipe.findAllAndCount(perspective, {}, false);
|
|
979
1156
|
* ```
|
|
980
1157
|
*/
|
|
981
|
-
static async findAllAndCount(perspective, query = {},
|
|
982
|
-
|
|
983
|
-
? (engine ? 'sparql' : 'prolog')
|
|
984
|
-
: engine;
|
|
985
|
-
if (resolvedEngine === 'sparql') {
|
|
986
|
-
const sparqlQuery = await this.queryToSPARQL(perspective, query);
|
|
987
|
-
const rawResult = await perspective.querySparql(sparqlQuery);
|
|
988
|
-
const grouped = groupSPARQLResults(rawResult);
|
|
989
|
-
return await this.instancesFromQueryResult(perspective, query, grouped);
|
|
990
|
-
}
|
|
991
|
-
else {
|
|
992
|
-
const prologQuery = await this.queryToProlog(perspective, query);
|
|
993
|
-
const result = await perspective.infer(prologQuery);
|
|
994
|
-
return await this.instancesFromPrologResult(perspective, query, result);
|
|
995
|
-
}
|
|
1158
|
+
static async findAllAndCount(perspective, query = {}, _engine) {
|
|
1159
|
+
return await this.executeModelQuery(perspective, query);
|
|
996
1160
|
}
|
|
997
1161
|
/**
|
|
998
1162
|
* Helper function for pagination with explicit page size and number.
|
|
@@ -1001,7 +1165,6 @@ export class Ad4mModel {
|
|
|
1001
1165
|
* @param pageSize - Number of items per page
|
|
1002
1166
|
* @param pageNumber - Which page to retrieve (1-based)
|
|
1003
1167
|
* @param query - Optional additional query parameters
|
|
1004
|
-
* @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
|
|
1005
1168
|
* @returns Paginated results with metadata
|
|
1006
1169
|
*
|
|
1007
1170
|
* @example
|
|
@@ -1010,47 +1173,12 @@ export class Ad4mModel {
|
|
|
1010
1173
|
* where: { category: "Main Course" }
|
|
1011
1174
|
* });
|
|
1012
1175
|
* console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
|
|
1013
|
-
*
|
|
1014
|
-
* // Use Prolog explicitly (legacy)
|
|
1015
|
-
* const pageProlog = await Recipe.paginate(perspective, 10, 1, {}, false);
|
|
1016
1176
|
* ```
|
|
1017
1177
|
*/
|
|
1018
|
-
static async paginate(perspective, pageSize, pageNumber, query,
|
|
1178
|
+
static async paginate(perspective, pageSize, pageNumber, query, _engine) {
|
|
1019
1179
|
const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
|
|
1020
|
-
const
|
|
1021
|
-
|
|
1022
|
-
: engine;
|
|
1023
|
-
if (resolvedEngine === 'sparql') {
|
|
1024
|
-
const sparqlQuery = await this.queryToSPARQL(perspective, paginationQuery);
|
|
1025
|
-
const rawResult = await perspective.querySparql(sparqlQuery);
|
|
1026
|
-
const grouped = groupSPARQLResults(rawResult);
|
|
1027
|
-
const { results, totalCount } = await this.instancesFromQueryResult(perspective, paginationQuery, grouped);
|
|
1028
|
-
return { results, totalCount, pageSize, pageNumber };
|
|
1029
|
-
}
|
|
1030
|
-
else {
|
|
1031
|
-
const prologQuery = await this.queryToProlog(perspective, paginationQuery);
|
|
1032
|
-
const result = await perspective.infer(prologQuery);
|
|
1033
|
-
const { results, totalCount } = await this.instancesFromPrologResult(perspective, paginationQuery, result);
|
|
1034
|
-
return { results, totalCount, pageSize, pageNumber };
|
|
1035
|
-
}
|
|
1036
|
-
}
|
|
1037
|
-
static async countQueryToProlog(perspective, query = {}, modelClassName) {
|
|
1038
|
-
const { where } = query;
|
|
1039
|
-
const className = modelClassName || (await this.getClassName(perspective));
|
|
1040
|
-
const resolvedParentPredicate = query.parent
|
|
1041
|
-
? resolveParentPredicate(query.parent, this)
|
|
1042
|
-
: undefined;
|
|
1043
|
-
const instanceQueries = [buildAuthorAndTimestampQuery(), buildParentQuery(query.parent, resolvedParentPredicate), buildWhereQuery(where)];
|
|
1044
|
-
const resultSetQueries = [buildCountQuery(true), buildOrderQuery(), buildOffsetQuery(), buildLimitQuery()];
|
|
1045
|
-
const fullQuery = `
|
|
1046
|
-
findall([Base, Properties, Collections, Timestamp, Author], (
|
|
1047
|
-
subject_class("${className}", SubjectClass),
|
|
1048
|
-
instance(SubjectClass, Base),
|
|
1049
|
-
${instanceQueries.filter((q) => q).join(", ")}
|
|
1050
|
-
), UnsortedInstances),
|
|
1051
|
-
${resultSetQueries.filter((q) => q).join(", ")}
|
|
1052
|
-
`;
|
|
1053
|
-
return fullQuery;
|
|
1180
|
+
const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery);
|
|
1181
|
+
return { results, totalCount, pageSize, pageNumber };
|
|
1054
1182
|
}
|
|
1055
1183
|
/**
|
|
1056
1184
|
* Generates a SPARQL COUNT query for the model.
|
|
@@ -1061,20 +1189,12 @@ export class Ad4mModel {
|
|
|
1061
1189
|
*
|
|
1062
1190
|
* @private
|
|
1063
1191
|
*/
|
|
1064
|
-
|
|
1065
|
-
// Use the same query as the main query (with GROUP BY), just without LIMIT/OFFSET
|
|
1066
|
-
// We'll count the number of rows returned (one row per source)
|
|
1067
|
-
const countQuery = { ...query };
|
|
1068
|
-
delete countQuery.limit;
|
|
1069
|
-
delete countQuery.offset;
|
|
1070
|
-
return await this.queryToSPARQL(perspective, countQuery);
|
|
1071
|
-
}
|
|
1192
|
+
// countQueryToSPARQL — removed (zero callers; Rust COUNT fast-path supersedes)
|
|
1072
1193
|
/**
|
|
1073
1194
|
* Gets a count of all matching instances.
|
|
1074
1195
|
*
|
|
1075
1196
|
* @param perspective - The perspective to search in
|
|
1076
1197
|
* @param query - Optional query parameters to filter results
|
|
1077
|
-
* @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
|
|
1078
1198
|
* @returns Total count of matching entities
|
|
1079
1199
|
*
|
|
1080
1200
|
* @example
|
|
@@ -1083,26 +1203,11 @@ export class Ad4mModel {
|
|
|
1083
1203
|
* const activeRecipes = await Recipe.count(perspective, {
|
|
1084
1204
|
* where: { status: "active" }
|
|
1085
1205
|
* });
|
|
1086
|
-
*
|
|
1087
|
-
* // Use Prolog explicitly (legacy)
|
|
1088
|
-
* const countProlog = await Recipe.count(perspective, {}, false);
|
|
1089
1206
|
* ```
|
|
1090
1207
|
*/
|
|
1091
|
-
static async count(perspective, query = {}
|
|
1092
|
-
const
|
|
1093
|
-
|
|
1094
|
-
: engine;
|
|
1095
|
-
if (resolvedEngine === 'sparql') {
|
|
1096
|
-
const sparqlQuery = await this.queryToSPARQL(perspective, query);
|
|
1097
|
-
const rawResult = await perspective.querySparql(sparqlQuery);
|
|
1098
|
-
const grouped = groupSPARQLResults(rawResult);
|
|
1099
|
-
const { totalCount } = await this.instancesFromQueryResult(perspective, query, grouped);
|
|
1100
|
-
return totalCount;
|
|
1101
|
-
}
|
|
1102
|
-
else {
|
|
1103
|
-
const result = await perspective.infer(await this.countQueryToProlog(perspective, query));
|
|
1104
|
-
return result?.[0]?.TotalCount || 0;
|
|
1105
|
-
}
|
|
1208
|
+
static async count(perspective, query = {}) {
|
|
1209
|
+
const { totalCount } = await this.executeModelQuery(perspective, { ...query, limit: 0 });
|
|
1210
|
+
return totalCount;
|
|
1106
1211
|
}
|
|
1107
1212
|
async setProperty(key, value, batchId) {
|
|
1108
1213
|
const metadata = this.getPropertyMetadata(key);
|
|
@@ -1385,6 +1490,61 @@ export class Ad4mModel {
|
|
|
1385
1490
|
}
|
|
1386
1491
|
}
|
|
1387
1492
|
}
|
|
1493
|
+
/**
|
|
1494
|
+
* Evaluate SPARQL getters for a batch of instances on demand.
|
|
1495
|
+
*
|
|
1496
|
+
* Use after a shallow collection query (the default) to resolve
|
|
1497
|
+
* getter-backed properties for visible items only. This avoids the
|
|
1498
|
+
* O(N × getters) cost of evaluating every getter on every instance in
|
|
1499
|
+
* a large collection query.
|
|
1500
|
+
*
|
|
1501
|
+
* @param instances - Array of model instances to evaluate getters on
|
|
1502
|
+
* @param perspective - The perspective to query against
|
|
1503
|
+
* @param propertyNames - Optional list of getter-backed property names to evaluate.
|
|
1504
|
+
* If omitted, all getters are evaluated.
|
|
1505
|
+
*
|
|
1506
|
+
* @example
|
|
1507
|
+
* ```typescript
|
|
1508
|
+
* const messages = await Message.findAll(perspective, { parent: channel, limit: 30 });
|
|
1509
|
+
* // messages[i].replyingTo is undefined (getter skipped by default)
|
|
1510
|
+
*
|
|
1511
|
+
* // Evaluate getters for the visible subset
|
|
1512
|
+
* await Message.evaluateGetters(messages.slice(0, 10), perspective, ['replyingTo']);
|
|
1513
|
+
* // messages[0..9].replyingTo is now populated
|
|
1514
|
+
* ```
|
|
1515
|
+
*/
|
|
1516
|
+
static async evaluateGetters(instances, perspective, propertyNames) {
|
|
1517
|
+
if (instances.length === 0)
|
|
1518
|
+
return;
|
|
1519
|
+
const metadata = this.getModelMetadata();
|
|
1520
|
+
const opts = propertyNames && propertyNames.length > 0
|
|
1521
|
+
? { requestedProperties: propertyNames }
|
|
1522
|
+
: undefined;
|
|
1523
|
+
// Determine which property names will actually be evaluated
|
|
1524
|
+
const evaluatedPropertyNames = [];
|
|
1525
|
+
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
1526
|
+
if (propMeta.getter) {
|
|
1527
|
+
if (!propertyNames || propertyNames.length === 0 || propertyNames.includes(propName)) {
|
|
1528
|
+
evaluatedPropertyNames.push(propName);
|
|
1529
|
+
}
|
|
1530
|
+
}
|
|
1531
|
+
}
|
|
1532
|
+
for (const instance of instances) {
|
|
1533
|
+
await evaluateCustomGettersForInstance(instance, perspective, metadata, opts);
|
|
1534
|
+
// Sync snapshot so isDirty() doesn't flag getter-only changes.
|
|
1535
|
+
// evaluateGetters() mutates instances in place, but their snapshots
|
|
1536
|
+
// were already taken during hydration. Without this sync, the computed
|
|
1537
|
+
// getter values would make isDirty() return true and save() would try
|
|
1538
|
+
// to write read-only computed properties.
|
|
1539
|
+
const modelInstance = instance;
|
|
1540
|
+
if (modelInstance._snapshot) {
|
|
1541
|
+
for (const propName of evaluatedPropertyNames) {
|
|
1542
|
+
const val = instance[propName];
|
|
1543
|
+
modelInstance._snapshot[propName] = normalizeValue(Array.isArray(val) ? [...val] : val);
|
|
1544
|
+
}
|
|
1545
|
+
}
|
|
1546
|
+
}
|
|
1547
|
+
}
|
|
1388
1548
|
/**
|
|
1389
1549
|
* Gets the model instance with all properties and relations populated.
|
|
1390
1550
|
*
|
|
@@ -1752,5 +1912,88 @@ export class Ad4mModel {
|
|
|
1752
1912
|
static fromJSONSchema(schema, options) {
|
|
1753
1913
|
return buildModelFromJSONSchema(this, schema, options);
|
|
1754
1914
|
}
|
|
1915
|
+
/**
|
|
1916
|
+
* Creates a fully functional Ad4mModel subclass from a SHACL shape.
|
|
1917
|
+
*
|
|
1918
|
+
* Unlike `fromJSONSchema()`, no predicate inference is required —
|
|
1919
|
+
* `SHACLShape` already contains the exact predicate URI in `path` for
|
|
1920
|
+
* every property. The method reads each property's `path`, `maxCount`,
|
|
1921
|
+
* `writable`, and `resolveLanguage` directly and writes them to the
|
|
1922
|
+
* WeakMap metadata registries.
|
|
1923
|
+
*
|
|
1924
|
+
* Properties with `hasValue` (flag / type-discrimination markers) are
|
|
1925
|
+
* registered as hidden flag entries so that the SPARQL query builder emits
|
|
1926
|
+
* the fixed triple `?source <predicate> <value>` needed for type discrimination.
|
|
1927
|
+
* Properties without a `name` field are skipped.
|
|
1928
|
+
*
|
|
1929
|
+
* **Backward-compat:** Old Flux SHACL shapes (created before `sh:hasValue`
|
|
1930
|
+
* was persisted on property shapes) carry the flag value only in
|
|
1931
|
+
* `shape.constructor_actions` as the `target` of an `addLink` action.
|
|
1932
|
+
* This method recovers those values so that old perspectives are queried
|
|
1933
|
+
* with the correct type-discriminator triple.
|
|
1934
|
+
*
|
|
1935
|
+
* @param shape - SHACL node shape (as returned by `PerspectiveProxy.getAllShacl()`)
|
|
1936
|
+
* @param name - Class name to assign (e.g. "Channel")
|
|
1937
|
+
* @returns Generated Ad4mModel subclass, ready for querying
|
|
1938
|
+
*/
|
|
1939
|
+
static fromSHACL(shape, name) {
|
|
1940
|
+
const DynamicModelClass = class extends this {
|
|
1941
|
+
};
|
|
1942
|
+
DynamicModelClass.className = name;
|
|
1943
|
+
DynamicModelClass.prototype.className = name;
|
|
1944
|
+
// Build a backward-compat fallback map: predicate → fixed-IRI-value from
|
|
1945
|
+
// constructor actions. Old SHACL stores (created before sh:hasValue was
|
|
1946
|
+
// persisted on the property shape) don't carry sh:hasValue on properties,
|
|
1947
|
+
// but the shape-level constructor_actions always contain an addLink action
|
|
1948
|
+
// with the fixed flag value as the target.
|
|
1949
|
+
const flagValueFromConstructor = new Map();
|
|
1950
|
+
for (const action of shape.constructor_actions ?? []) {
|
|
1951
|
+
if (action.action === 'addLink' &&
|
|
1952
|
+
typeof action.predicate === 'string' &&
|
|
1953
|
+
typeof action.target === 'string' &&
|
|
1954
|
+
action.target !== 'value' &&
|
|
1955
|
+
!action.target.startsWith('literal:')) {
|
|
1956
|
+
flagValueFromConstructor.set(action.predicate, action.target);
|
|
1957
|
+
}
|
|
1958
|
+
}
|
|
1959
|
+
for (const prop of shape.properties) {
|
|
1960
|
+
const resolvedHasValue = prop.hasValue ?? flagValueFromConstructor.get(prop.path);
|
|
1961
|
+
if (resolvedHasValue !== undefined) {
|
|
1962
|
+
const flagKey = prop.name ?? `_flag_${prop.path.replace(/[^a-zA-Z0-9_]/g, '_')}`;
|
|
1963
|
+
setPropertyRegistryEntry(DynamicModelClass, flagKey, {
|
|
1964
|
+
through: prop.path,
|
|
1965
|
+
required: true,
|
|
1966
|
+
initial: resolvedHasValue,
|
|
1967
|
+
flag: true,
|
|
1968
|
+
writable: false,
|
|
1969
|
+
readOnly: true,
|
|
1970
|
+
});
|
|
1971
|
+
continue;
|
|
1972
|
+
}
|
|
1973
|
+
// Skip properties without a declared name
|
|
1974
|
+
if (!prop.name)
|
|
1975
|
+
continue;
|
|
1976
|
+
const isCollection = prop.maxCount === undefined || prop.maxCount > 1;
|
|
1977
|
+
if (isCollection) {
|
|
1978
|
+
setRelationRegistryEntry(DynamicModelClass, prop.name, {
|
|
1979
|
+
predicate: prop.path,
|
|
1980
|
+
kind: 'hasMany',
|
|
1981
|
+
...(prop.local !== undefined && { local: prop.local }),
|
|
1982
|
+
...(prop.getter !== undefined && { getter: prop.getter }),
|
|
1983
|
+
});
|
|
1984
|
+
}
|
|
1985
|
+
else {
|
|
1986
|
+
setPropertyRegistryEntry(DynamicModelClass, prop.name, {
|
|
1987
|
+
through: prop.path,
|
|
1988
|
+
writable: prop.writable ?? true,
|
|
1989
|
+
...(prop.resolveLanguage !== undefined && { resolveLanguage: prop.resolveLanguage }),
|
|
1990
|
+
...(prop.local !== undefined && { local: prop.local }),
|
|
1991
|
+
});
|
|
1992
|
+
}
|
|
1993
|
+
}
|
|
1994
|
+
const ModelDecorator = Model({ name });
|
|
1995
|
+
ModelDecorator(DynamicModelClass);
|
|
1996
|
+
return DynamicModelClass;
|
|
1997
|
+
}
|
|
1755
1998
|
}
|
|
1756
1999
|
Ad4mModel.classNamesByClass = new WeakMap();
|