@coasys/ad4m 0.13.0-test-3 → 0.13.0-test-5
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 +6717 -15519
- package/lib/index.js +4811 -13662
- package/lib/src/Ad4mClient.d.ts +7 -3
- package/lib/src/Ad4mClient.js +39 -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 -1
- package/lib/src/index.js +6 -1
- 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 +1 -1
- package/lib/src/language/Language.js +10 -76
- 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 +76 -44
- package/lib/src/model/Ad4mModel.js +635 -479
- package/lib/src/model/Ad4mModel.test.js +371 -815
- package/lib/src/model/ModelQueryBuilder.d.ts +15 -27
- package/lib/src/model/ModelQueryBuilder.js +163 -224
- package/lib/src/model/decorators.d.ts +22 -0
- package/lib/src/model/decorators.js +7 -0
- package/lib/src/model/hydration.d.ts +3 -93
- package/lib/src/model/hydration.js +3 -970
- 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 +4 -67
- package/lib/src/model/query-sparql.js +26 -322
- package/lib/src/model/query-sparql.test.js +35 -218
- package/lib/src/model/query-utils.d.ts +1 -0
- package/lib/src/model/query-utils.js +46 -1
- package/lib/src/model/shacl-gen.js +4 -0
- package/lib/src/model/types.d.ts +51 -43
- 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 +13 -17
- package/lib/src/perspectives/PerspectiveClient.js +179 -429
- package/lib/src/perspectives/PerspectiveClient.test.js +55 -0
- package/lib/src/perspectives/PerspectiveDiff.js +4 -31
- package/lib/src/perspectives/PerspectiveHandle.js +3 -43
- package/lib/src/perspectives/PerspectiveProxy.d.ts +106 -71
- package/lib/src/perspectives/PerspectiveProxy.js +289 -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 +6 -18
- package/rollup.config.js +0 -7
- package/src/Ad4mClient.test.ts +1179 -1340
- package/src/Ad4mClient.ts +40 -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 -1
- package/src/jestSetup.ts +1 -1
- package/src/language/Icon.ts +0 -4
- package/src/language/Language.ts +2 -23
- 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 +766 -1173
- package/src/model/Ad4mModel.ts +664 -529
- package/src/model/ModelQueryBuilder.ts +203 -251
- package/src/model/decorators.ts +29 -0
- package/src/model/hydration.ts +3 -1037
- package/src/model/index.ts +0 -4
- package/src/model/query-sparql.test.ts +34 -242
- package/src/model/query-sparql.ts +27 -337
- package/src/model/query-utils.ts +47 -2
- package/src/model/shacl-gen.ts +5 -0
- package/src/model/types.ts +55 -44
- 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 +206 -148
- package/src/perspectives/PerspectiveClient.ts +247 -442
- 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 +331 -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/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/LanguageResolver.ts +0 -98
- package/src/model/Subject.ts +0 -159
- package/src/model/hydration-batch.ts +0 -205
- package/src/model/hydration-batching.test.ts +0 -563
- 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-delta.test.ts +0 -207
- package/src/model/subscription-pool.ts +0 -211
- 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/src/model/Ad4mModel.ts
CHANGED
|
@@ -3,30 +3,179 @@ import { Link } from "../links/Links";
|
|
|
3
3
|
import { LinkQuery } from "../perspectives/LinkQuery";
|
|
4
4
|
import { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
|
|
5
5
|
import { makeRandomId } from "./util";
|
|
6
|
-
import { getPropertiesMetadata, getRelationsMetadata } from "./decorators";
|
|
6
|
+
import { getPropertiesMetadata, getRelationsMetadata, buildConformanceFilter, setPropertyRegistryEntry, setRelationRegistryEntry, Model } from "./decorators";
|
|
7
7
|
import type { PropertyOptions, PropertyMetadataEntry, RelationMetadataEntry } from "./decorators";
|
|
8
|
-
import { formatQueryValue } from "./query-utils";
|
|
8
|
+
import { formatQueryValue, compileWhereClause } from "./query-utils";
|
|
9
9
|
import { resolveParentPredicate } from "./query-common";
|
|
10
|
-
import { buildParentQuery, buildAuthorAndTimestampQuery, buildPropertiesQuery, buildWhereQuery, buildCountQuery, buildOrderQuery, buildOffsetQuery, buildLimitQuery } from "./query-prolog";
|
|
11
10
|
import { isArrayType, determinePredicate, determineNamespace, buildModelFromJSONSchema } from "./json-schema";
|
|
11
|
+
import type { SHACLShape } from "../shacl/SHACLShape";
|
|
12
12
|
import type { JSONSchemaProperty, JSONSchema, JSONSchemaToModelOptions } from "./json-schema";
|
|
13
13
|
|
|
14
|
-
import { buildSPARQLQuery
|
|
15
|
-
import { buildBatchSPARQLQuery } from "./query-sparql-batch";
|
|
16
|
-
import { hydrateBatchResult } from "./hydration-batch";
|
|
14
|
+
import { buildSPARQLQuery } from "./query-sparql";
|
|
17
15
|
import { ModelQueryBuilder } from "./ModelQueryBuilder";
|
|
18
16
|
import {
|
|
19
|
-
normalizeValue,
|
|
20
|
-
assignValuesToInstance as _assignValuesToInstance,
|
|
21
|
-
evaluateCustomGettersForInstance,
|
|
22
|
-
hydrateRelations,
|
|
17
|
+
normalizeValue,
|
|
23
18
|
} from "./hydration";
|
|
24
19
|
import type {
|
|
25
20
|
ParentScope, IncludeMap, Query,
|
|
26
21
|
GetOptions, AllInstancesResult, ResultsWithTotalCount,
|
|
27
|
-
PaginationResult, PropertyMetadata, RelationMetadata, ModelMetadata,
|
|
22
|
+
PaginationResult, PropertyMetadata, RelationMetadata, ModelMetadata,
|
|
23
|
+
IncludeProjection,
|
|
28
24
|
} from "./types";
|
|
29
25
|
|
|
26
|
+
|
|
27
|
+
// ---------------------------------------------------------------------------
|
|
28
|
+
// Helpers for Rust-side include resolution
|
|
29
|
+
// ---------------------------------------------------------------------------
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Recursively enrich relation metadata in the shape with target class shapes
|
|
33
|
+
* so the Rust endpoint can resolve includes in-process (no extra GraphQL
|
|
34
|
+
* round-trips per relation).
|
|
35
|
+
*/
|
|
36
|
+
function enrichShapeForIncludes(
|
|
37
|
+
metadata: ModelMetadata,
|
|
38
|
+
include: IncludeMap,
|
|
39
|
+
allRelMeta: Record<string, RelationMetadataEntry>,
|
|
40
|
+
): void {
|
|
41
|
+
for (const [relName, includeVal] of Object.entries(include)) {
|
|
42
|
+
if (!includeVal) continue;
|
|
43
|
+
const meta = allRelMeta[relName];
|
|
44
|
+
if (!meta?.target) continue;
|
|
45
|
+
|
|
46
|
+
const TargetClass = meta.target() as typeof Ad4mModel;
|
|
47
|
+
// Deep-copy so we don't mutate the cached metadata
|
|
48
|
+
const targetMeta = JSON.parse(JSON.stringify(TargetClass.getModelMetadata()));
|
|
49
|
+
|
|
50
|
+
// Ensure the relation is in metadata.relations (fallback for edge cases)
|
|
51
|
+
if (!metadata.relations[relName]) {
|
|
52
|
+
metadata.relations[relName] = {
|
|
53
|
+
name: relName,
|
|
54
|
+
predicate: meta.predicate,
|
|
55
|
+
direction:
|
|
56
|
+
meta.kind === 'belongsToMany' || meta.kind === 'belongsToOne'
|
|
57
|
+
? 'reverse'
|
|
58
|
+
: 'forward',
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
const rel = metadata.relations[relName] as any;
|
|
62
|
+
rel.kind = meta.kind;
|
|
63
|
+
rel.maxCount = meta.maxCount;
|
|
64
|
+
rel.targetShape = targetMeta;
|
|
65
|
+
rel.targetClassName = targetMeta.className;
|
|
66
|
+
|
|
67
|
+
// Recurse for nested includes
|
|
68
|
+
const nested =
|
|
69
|
+
typeof includeVal === 'object' && includeVal !== null
|
|
70
|
+
? (includeVal as any).include
|
|
71
|
+
: undefined;
|
|
72
|
+
if (nested) {
|
|
73
|
+
const targetRelMeta = getRelationsMetadata(TargetClass as any);
|
|
74
|
+
enrichShapeForIncludes(targetMeta, nested, targetRelMeta);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Construct a model class instance from a plain JSON object returned by the
|
|
81
|
+
* Rust endpoint. Recursively converts included relation values (which come
|
|
82
|
+
* back as plain JSON objects) into proper model class instances.
|
|
83
|
+
*/
|
|
84
|
+
function jsonToModelInstance<T extends Ad4mModel>(
|
|
85
|
+
ModelClass: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
86
|
+
perspective: PerspectiveProxy,
|
|
87
|
+
json: any,
|
|
88
|
+
include?: IncludeMap,
|
|
89
|
+
properties?: string[],
|
|
90
|
+
): T {
|
|
91
|
+
const instance = new ModelClass(perspective, json.id || json.baseExpression) as any;
|
|
92
|
+
|
|
93
|
+
// When a properties projection is active, remove own properties set by the
|
|
94
|
+
// constructor that are not in the projected JSON. This ensures assertions
|
|
95
|
+
// like `expect(r).to.not.have.own.property("body")` pass.
|
|
96
|
+
if (properties) {
|
|
97
|
+
const jsonKeys = new Set(Object.keys(json));
|
|
98
|
+
for (const key of Object.getOwnPropertyNames(instance)) {
|
|
99
|
+
// Keep internal fields (backing store for getters), id, baseExpression, perspective
|
|
100
|
+
if (key === 'id' || key === 'baseExpression' || key === 'perspective' || key.startsWith('_')) continue;
|
|
101
|
+
if (!jsonKeys.has(key)) {
|
|
102
|
+
delete instance[key];
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
for (const [key, value] of Object.entries(json)) {
|
|
108
|
+
if (key === 'baseExpression' || key === 'id') continue;
|
|
109
|
+
|
|
110
|
+
// Skip getter-only properties anywhere in the prototype chain
|
|
111
|
+
let isReadonly = false;
|
|
112
|
+
let proto = Object.getPrototypeOf(instance);
|
|
113
|
+
while (proto) {
|
|
114
|
+
const desc = Object.getOwnPropertyDescriptor(proto, key);
|
|
115
|
+
if (desc) { isReadonly = !!(desc.get && !desc.set); break; }
|
|
116
|
+
proto = Object.getPrototypeOf(proto);
|
|
117
|
+
}
|
|
118
|
+
if (isReadonly) continue;
|
|
119
|
+
|
|
120
|
+
// Parse ISO timestamps to epoch milliseconds (matches hydrateFromLinks behaviour)
|
|
121
|
+
if ((key === 'createdAt' || key === 'updatedAt') && typeof value === 'string' && value.includes('T')) {
|
|
122
|
+
instance[key] = new Date(value).getTime();
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
instance[key] = value;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// Apply property transform functions from decorators (only for literal-resolved
|
|
130
|
+
// or no-resolveLanguage properties; non-literal properties are resolved + transformed
|
|
131
|
+
// asynchronously in executeModelQuery).
|
|
132
|
+
try {
|
|
133
|
+
const propsMeta = getPropertiesMetadata(ModelClass as any);
|
|
134
|
+
for (const [propName, opts] of Object.entries(propsMeta)) {
|
|
135
|
+
const o = opts as any;
|
|
136
|
+
if (typeof o.transform !== 'function' || !(propName in json)) continue;
|
|
137
|
+
// Skip non-literal resolveLanguage props — they need async expression resolution first
|
|
138
|
+
if (o.resolveLanguage != null && o.resolveLanguage !== 'literal') continue;
|
|
139
|
+
instance[propName] = o.transform(instance[propName]);
|
|
140
|
+
}
|
|
141
|
+
} catch (_) { /* no metadata available */ }
|
|
142
|
+
|
|
143
|
+
// Recursively convert included relation values to class instances
|
|
144
|
+
if (include) {
|
|
145
|
+
const relMeta = getRelationsMetadata(ModelClass as any);
|
|
146
|
+
for (const [relName, includeVal] of Object.entries(include)) {
|
|
147
|
+
if (!includeVal) continue;
|
|
148
|
+
const meta = relMeta[relName];
|
|
149
|
+
if (!meta?.target) continue;
|
|
150
|
+
const TargetClass = meta.target() as any;
|
|
151
|
+
const nestedInclude =
|
|
152
|
+
typeof includeVal === 'object' && includeVal !== null
|
|
153
|
+
? (includeVal as any).include
|
|
154
|
+
: undefined;
|
|
155
|
+
const nestedProperties =
|
|
156
|
+
typeof includeVal === 'object' && includeVal !== null
|
|
157
|
+
? (includeVal as any).properties
|
|
158
|
+
: undefined;
|
|
159
|
+
|
|
160
|
+
const raw = instance[relName];
|
|
161
|
+
if (Array.isArray(raw)) {
|
|
162
|
+
instance[relName] = raw.map((item: any) => {
|
|
163
|
+
if (typeof item === 'object' && item !== null && item.id) {
|
|
164
|
+
return jsonToModelInstance(TargetClass, perspective, item, nestedInclude, nestedProperties);
|
|
165
|
+
}
|
|
166
|
+
return item;
|
|
167
|
+
});
|
|
168
|
+
} else if (typeof raw === 'object' && raw !== null && raw.id) {
|
|
169
|
+
instance[relName] = jsonToModelInstance(
|
|
170
|
+
TargetClass, perspective, raw, nestedInclude, nestedProperties,
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
return instance;
|
|
177
|
+
}
|
|
178
|
+
|
|
30
179
|
/**
|
|
31
180
|
* Base class for defining data models in AD4M.
|
|
32
181
|
*
|
|
@@ -131,6 +280,14 @@ export class Ad4mModel {
|
|
|
131
280
|
createdAt: any;
|
|
132
281
|
updatedAt: any;
|
|
133
282
|
|
|
283
|
+
/**
|
|
284
|
+
* Backwards compatibility alias for createdAt.
|
|
285
|
+
* @deprecated Use createdAt instead. This will be removed in a future version.
|
|
286
|
+
*/
|
|
287
|
+
get timestamp(): any {
|
|
288
|
+
return (this as any).createdAt;
|
|
289
|
+
}
|
|
290
|
+
|
|
134
291
|
private static classNamesByClass = new WeakMap<typeof Ad4mModel, { [perspectiveId: string]: string }>();
|
|
135
292
|
|
|
136
293
|
/**
|
|
@@ -177,14 +334,6 @@ export class Ad4mModel {
|
|
|
177
334
|
return classCache[perspectiveID];
|
|
178
335
|
}
|
|
179
336
|
|
|
180
|
-
/**
|
|
181
|
-
* Backwards compatibility alias for createdAt.
|
|
182
|
-
* @deprecated Use createdAt instead. This will be removed in a future version.
|
|
183
|
-
*/
|
|
184
|
-
get timestamp(): any {
|
|
185
|
-
return (this as any).createdAt;
|
|
186
|
-
}
|
|
187
|
-
|
|
188
337
|
/**
|
|
189
338
|
* Extracts metadata from decorators for query building.
|
|
190
339
|
*
|
|
@@ -261,9 +410,7 @@ export class Ad4mModel {
|
|
|
261
410
|
// Extract relations (relations) from WeakMap registry
|
|
262
411
|
const relationsMetadata: Record<string, RelationMetadata> = {};
|
|
263
412
|
const allRelationsMeta = getRelationsMetadata(this as any);
|
|
264
|
-
const prototypeRelations =
|
|
265
|
-
Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany')
|
|
266
|
-
);
|
|
413
|
+
const prototypeRelations = allRelationsMeta;
|
|
267
414
|
|
|
268
415
|
for (const [relationName, opts] of Object.entries(prototypeRelations)) {
|
|
269
416
|
const options = opts as RelationMetadataEntry;
|
|
@@ -273,6 +420,8 @@ export class Ad4mModel {
|
|
|
273
420
|
...(options.local !== undefined && { local: options.local }),
|
|
274
421
|
...(options.getter !== undefined && { getter: options.getter }),
|
|
275
422
|
direction: (options.kind === 'belongsToMany' || options.kind === 'belongsToOne') ? 'reverse' : 'forward',
|
|
423
|
+
...(options.kind !== undefined && { kind: options.kind }),
|
|
424
|
+
...(options.maxCount !== undefined && { maxCount: options.maxCount }),
|
|
276
425
|
...(options.target !== undefined && { target: options.target }),
|
|
277
426
|
...(options.filter !== undefined && { filter: options.filter }),
|
|
278
427
|
...(options.where !== undefined && { where: options.where }),
|
|
@@ -359,13 +508,6 @@ export class Ad4mModel {
|
|
|
359
508
|
return this._baseExpression;
|
|
360
509
|
}
|
|
361
510
|
|
|
362
|
-
/**
|
|
363
|
-
* @deprecated Use `.id` instead. Will be removed in a future version.
|
|
364
|
-
*/
|
|
365
|
-
get baseExpression(): string {
|
|
366
|
-
return this._baseExpression;
|
|
367
|
-
}
|
|
368
|
-
|
|
369
511
|
/**
|
|
370
512
|
* Protected getter for the perspective.
|
|
371
513
|
* Allows subclasses to access the perspective while keeping it private from external code.
|
|
@@ -462,14 +604,6 @@ export class Ad4mModel {
|
|
|
462
604
|
}];
|
|
463
605
|
}
|
|
464
606
|
|
|
465
|
-
/**
|
|
466
|
-
* Assigns decoded Prolog property values to an instance.
|
|
467
|
-
* Delegates to the standalone function in hydration.ts.
|
|
468
|
-
*/
|
|
469
|
-
public static async assignValuesToInstance(perspective: PerspectiveProxy, instance: Ad4mModel, values: ValueTuple[]) {
|
|
470
|
-
return _assignValuesToInstance(perspective, instance, values);
|
|
471
|
-
}
|
|
472
|
-
|
|
473
607
|
// ──────────────────────────────────────────────────────────
|
|
474
608
|
// Snapshot / dirty tracking
|
|
475
609
|
// ──────────────────────────────────────────────────────────
|
|
@@ -603,89 +737,51 @@ export class Ad4mModel {
|
|
|
603
737
|
}
|
|
604
738
|
|
|
605
739
|
private async getData(opts?: GetOptions) {
|
|
606
|
-
//
|
|
607
|
-
//
|
|
740
|
+
// Route through the Rust model query endpoint — same pipeline as executeModelQuery
|
|
741
|
+
// but for a single instance by ID.
|
|
608
742
|
try {
|
|
609
743
|
const ctor = this.constructor as typeof Ad4mModel;
|
|
610
|
-
const
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
744
|
+
const query: Query = {
|
|
745
|
+
where: { id: this._baseExpression },
|
|
746
|
+
limit: 1,
|
|
747
|
+
deepQuery: true, // Single-instance get() always evaluates property getters
|
|
748
|
+
};
|
|
749
|
+
if (opts?.properties) query.properties = opts.properties;
|
|
750
|
+
if (opts?.include) query.include = opts.include;
|
|
615
751
|
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
await hydrateFromLinks(this, links, metadata, this._perspective, requestedProperties);
|
|
620
|
-
}
|
|
752
|
+
const { results } = await (ctor as any).executeModelQuery(
|
|
753
|
+
this._perspective, query, null
|
|
754
|
+
);
|
|
621
755
|
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
(this as any)[
|
|
756
|
+
if (results.length > 0) {
|
|
757
|
+
const hydrated = results[0];
|
|
758
|
+
// Copy all hydrated values from the Rust-side result onto this instance
|
|
759
|
+
for (const [key, value] of Object.entries(hydrated as any)) {
|
|
760
|
+
if (key === '_baseExpression' || key === '_perspective' || key === '_snapshot') continue;
|
|
761
|
+
if (key.startsWith('_')) continue;
|
|
762
|
+
// Check for readonly getters
|
|
763
|
+
let isReadonly = false;
|
|
764
|
+
let proto = Object.getPrototypeOf(this);
|
|
765
|
+
while (proto) {
|
|
766
|
+
const desc = Object.getOwnPropertyDescriptor(proto, key);
|
|
767
|
+
if (desc) { isReadonly = !!(desc.get && !desc.set); break; }
|
|
768
|
+
proto = Object.getPrototypeOf(proto);
|
|
769
|
+
}
|
|
770
|
+
if (isReadonly) continue;
|
|
771
|
+
(this as any)[key] = value;
|
|
638
772
|
}
|
|
639
773
|
}
|
|
640
774
|
|
|
641
|
-
//
|
|
642
|
-
|
|
643
|
-
? { requestedProperties: opts?.properties, include: opts?.include }
|
|
644
|
-
: undefined;
|
|
645
|
-
await evaluateCustomGettersForInstance(this, this._perspective, metadata, getterOpts);
|
|
646
|
-
|
|
647
|
-
// Eager-load relations if requested
|
|
648
|
-
if (opts?.include) {
|
|
649
|
-
await hydrateRelations(ctor, [this], this._perspective, opts.include);
|
|
650
|
-
}
|
|
775
|
+
// Property getters and relation conformance getters are now evaluated
|
|
776
|
+
// Rust-side via evaluate_getters() in model_query.rs.
|
|
651
777
|
} catch (e) {
|
|
652
|
-
console.error(`
|
|
778
|
+
console.error(`getData via Rust model query failed for ${this._baseExpression}:`, e);
|
|
653
779
|
}
|
|
654
780
|
|
|
655
|
-
this.takeSnapshot();
|
|
781
|
+
this.takeSnapshot(opts?.include);
|
|
656
782
|
return this;
|
|
657
783
|
}
|
|
658
784
|
|
|
659
|
-
public static async queryToProlog(perspective: PerspectiveProxy, query: Query, modelClassName?: string | null) {
|
|
660
|
-
const { properties, where, order, offset, limit, count } = query;
|
|
661
|
-
const className = modelClassName || (await this.getClassName(perspective));
|
|
662
|
-
|
|
663
|
-
// Resolve parent predicate from model metadata if needed
|
|
664
|
-
const resolvedParentPredicate = query.parent
|
|
665
|
-
? resolveParentPredicate(query.parent, this)
|
|
666
|
-
: undefined;
|
|
667
|
-
|
|
668
|
-
const instanceQueries = [
|
|
669
|
-
buildAuthorAndTimestampQuery(),
|
|
670
|
-
buildParentQuery(query.parent, resolvedParentPredicate),
|
|
671
|
-
buildPropertiesQuery(properties),
|
|
672
|
-
buildWhereQuery(where),
|
|
673
|
-
];
|
|
674
|
-
|
|
675
|
-
const resultSetQueries = [buildCountQuery(count), buildOrderQuery(order), buildOffsetQuery(offset), buildLimitQuery(limit)];
|
|
676
|
-
|
|
677
|
-
const fullQuery = `
|
|
678
|
-
findall([Base, Properties, Collections, Timestamp, Author], (
|
|
679
|
-
subject_class("${className}", SubjectClass),
|
|
680
|
-
instance(SubjectClass, Base),
|
|
681
|
-
${instanceQueries.filter((q) => q).join(", ")}
|
|
682
|
-
), UnsortedInstances),
|
|
683
|
-
${resultSetQueries.filter((q) => q).join(", ")}
|
|
684
|
-
`;
|
|
685
|
-
|
|
686
|
-
return fullQuery;
|
|
687
|
-
}
|
|
688
|
-
|
|
689
785
|
/**
|
|
690
786
|
* Generates a SPARQL query from a Query object.
|
|
691
787
|
*
|
|
@@ -728,341 +824,329 @@ export class Ad4mModel {
|
|
|
728
824
|
return buildSPARQLQuery(metadata, allRelMeta, query, this);
|
|
729
825
|
}
|
|
730
826
|
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
const
|
|
741
|
-
|
|
827
|
+
/**
|
|
828
|
+
* Build the JSON parameters needed for a model query/subscription endpoint.
|
|
829
|
+
* Returns the className, queryJson, and shapeJson that the Rust executor expects.
|
|
830
|
+
* @internal
|
|
831
|
+
*/
|
|
832
|
+
static prepareModelQueryParams(
|
|
833
|
+
query: Query = {},
|
|
834
|
+
classNameOverride?: string | null,
|
|
835
|
+
): { className: string; queryJson: string; shapeJson: string } {
|
|
836
|
+
const metadata = this.getModelMetadata();
|
|
837
|
+
const className = classNameOverride || metadata.className;
|
|
838
|
+
|
|
839
|
+
const queryInput: any = {};
|
|
840
|
+
if (query.parent) {
|
|
841
|
+
const parentPredicate = resolveParentPredicate(query.parent, this);
|
|
842
|
+
queryInput.parent = { id: query.parent.id, predicate: parentPredicate };
|
|
843
|
+
}
|
|
844
|
+
if (query.properties) queryInput.properties = query.properties;
|
|
845
|
+
if (query.include) queryInput.include = query.include;
|
|
846
|
+
if (query.where) queryInput.where = query.where;
|
|
847
|
+
if (query.order) {
|
|
848
|
+
queryInput.order = Object.entries(query.order).map(([k, v]) => [k, v]);
|
|
849
|
+
}
|
|
850
|
+
if (query.offset !== undefined) queryInput.offset = query.offset;
|
|
851
|
+
if (query.limit !== undefined) queryInput.limit = query.limit;
|
|
852
|
+
if (query.count !== undefined) queryInput.count = query.count;
|
|
853
|
+
queryInput.deepQuery = query.deepQuery ?? true;
|
|
854
|
+
|
|
855
|
+
if (query.include) {
|
|
856
|
+
const allRelMeta = getRelationsMetadata(this as any);
|
|
857
|
+
enrichShapeForIncludes(metadata, query.include, allRelMeta);
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
// Pre-compute conformance getters (with where-clause support)
|
|
861
|
+
{
|
|
862
|
+
const allRelMeta = getRelationsMetadata(this as any);
|
|
863
|
+
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
864
|
+
const rel = relMeta as any;
|
|
865
|
+
if (rel.getter || rel.direction === 'reverse' || rel.filter === false) continue;
|
|
866
|
+
const meta = allRelMeta[relName];
|
|
867
|
+
if (!meta?.target) continue;
|
|
742
868
|
try {
|
|
743
|
-
const
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
869
|
+
const TargetClass = meta.target();
|
|
870
|
+
const filter = buildConformanceFilter(meta.predicate, TargetClass);
|
|
871
|
+
|
|
872
|
+
// Compile where clauses to SPARQL when all target properties use
|
|
873
|
+
// literal encoding (literal:string:X etc.) which is SPARQL-matchable.
|
|
874
|
+
// Properties with a non-literal resolveLanguage store expression hashes
|
|
875
|
+
// that can't be matched by value in SPARQL.
|
|
876
|
+
let whereConditions: string[] = [];
|
|
877
|
+
if (rel.where) {
|
|
878
|
+
try {
|
|
879
|
+
const targetMetadata = (TargetClass as any).getModelMetadata?.() ?? null;
|
|
880
|
+
let allSparqlFilterable = true;
|
|
881
|
+
if (targetMetadata) {
|
|
882
|
+
for (const propName of Object.keys(rel.where)) {
|
|
883
|
+
if (['id', 'author', 'timestamp'].includes(propName)) continue;
|
|
884
|
+
const propMeta = targetMetadata.properties[propName];
|
|
885
|
+
if (propMeta?.resolveLanguage && propMeta.resolveLanguage !== 'literal') {
|
|
886
|
+
allSparqlFilterable = false;
|
|
887
|
+
break;
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
if (allSparqlFilterable) {
|
|
892
|
+
whereConditions = compileWhereClause(rel.where, targetMetadata);
|
|
893
|
+
}
|
|
894
|
+
} catch (_) {}
|
|
749
895
|
}
|
|
750
|
-
// Collect values to assign to instance
|
|
751
|
-
const values = [...Properties, ...Collections, ["createdAt", Timestamp], ["author", Author]];
|
|
752
|
-
await Ad4mModel.assignValuesToInstance(perspective, instance, values);
|
|
753
|
-
|
|
754
|
-
return instance;
|
|
755
|
-
} catch (error) {
|
|
756
|
-
console.error(`Failed to process instance ${Base}:`, error);
|
|
757
|
-
// Return null for failed instances - we'll filter these out below
|
|
758
|
-
return null;
|
|
759
|
-
}
|
|
760
|
-
})
|
|
761
|
-
);
|
|
762
|
-
const instances = allInstances.filter((instance) => instance !== null) as T[];
|
|
763
896
|
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
897
|
+
if (filter) {
|
|
898
|
+
let getter = filter.getter;
|
|
899
|
+
if (whereConditions.length > 0) {
|
|
900
|
+
getter = getter.replace(/ \}$/, ` ${whereConditions.join(' ')} }`);
|
|
901
|
+
}
|
|
902
|
+
rel.getter = getter;
|
|
903
|
+
} else if (whereConditions.length > 0) {
|
|
904
|
+
const escapedPred = meta.predicate.replace(/[<>"{}|\\^`\u0000-\u0020]/g, '');
|
|
905
|
+
rel.getter = `SELECT ?target WHERE { <Base> <${escapedPred}> ?target . ${whereConditions.join(' ')} }`;
|
|
906
|
+
}
|
|
907
|
+
} catch (_) {}
|
|
908
|
+
}
|
|
767
909
|
}
|
|
768
910
|
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
for (const inst of instances) {
|
|
776
|
-
(inst as Ad4mModel).takeSnapshot(snapshotRelations);
|
|
777
|
-
}
|
|
911
|
+
return {
|
|
912
|
+
className,
|
|
913
|
+
queryJson: JSON.stringify(queryInput),
|
|
914
|
+
shapeJson: JSON.stringify(metadata),
|
|
915
|
+
};
|
|
916
|
+
}
|
|
778
917
|
|
|
779
|
-
|
|
918
|
+
/**
|
|
919
|
+
* Parse raw model query/subscription result JSON into typed model instances.
|
|
920
|
+
* Used by ModelQueryBuilder to convert subscription updates without circular imports.
|
|
921
|
+
* @internal
|
|
922
|
+
*/
|
|
923
|
+
static parseModelResult<T extends Ad4mModel>(
|
|
924
|
+
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
925
|
+
perspective: PerspectiveProxy,
|
|
926
|
+
raw: any,
|
|
927
|
+
include?: IncludeMap,
|
|
928
|
+
properties?: string[],
|
|
929
|
+
): T[] {
|
|
930
|
+
const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
|
|
931
|
+
const arr = data.instances || data;
|
|
932
|
+
if (!Array.isArray(arr)) return [];
|
|
933
|
+
return arr.map((json: any) => jsonToModelInstance(this, perspective, json, include, properties));
|
|
780
934
|
}
|
|
781
935
|
|
|
936
|
+
// instancesFromQueryResult — removed (superseded by Rust executeModelQuery pipeline)
|
|
937
|
+
|
|
782
938
|
/**
|
|
783
|
-
*
|
|
939
|
+
* Execute a model query via the executor-side endpoint.
|
|
784
940
|
*
|
|
785
|
-
*
|
|
786
|
-
*
|
|
787
|
-
* @param result - Array of result objects from SPARQL
|
|
788
|
-
* @returns Promise resolving to results with total count
|
|
941
|
+
* This replaces the old SPARQL-build → hydrate → JS-filter → JS-sort → JS-paginate pipeline
|
|
942
|
+
* with a single RPC to the executor that handles everything in Rust.
|
|
789
943
|
*
|
|
790
944
|
* @internal
|
|
791
945
|
*/
|
|
792
|
-
|
|
793
|
-
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
946
|
+
private static async executeModelQuery<T extends Ad4mModel>(
|
|
947
|
+
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
794
948
|
perspective: PerspectiveProxy,
|
|
795
|
-
query: Query,
|
|
796
|
-
|
|
797
|
-
computeTotalCount: boolean = false
|
|
949
|
+
query: Query = {},
|
|
950
|
+
classNameOverride?: string | null,
|
|
798
951
|
): Promise<ResultsWithTotalCount<T>> {
|
|
799
|
-
if (!result || result.length === 0) return { results: [], totalCount: 0 };
|
|
800
|
-
|
|
801
952
|
const metadata = this.getModelMetadata();
|
|
802
|
-
const
|
|
803
|
-
|
|
804
|
-
// The query used GROUP BY with graph traversal, so each row has:
|
|
805
|
-
// - source: the node ID (e.g., "node:abc123")
|
|
806
|
-
// - source_uri: the actual URI (the base expression)
|
|
807
|
-
// - links: array of link objects with {predicate, target, author, timestamp}
|
|
808
|
-
|
|
809
|
-
const instances: T[] = [];
|
|
810
|
-
for (const row of result) {
|
|
811
|
-
let base;
|
|
812
|
-
try {
|
|
813
|
-
// Use source_uri as the base (the actual URI), not the node ID
|
|
814
|
-
base = row.source_uri;
|
|
953
|
+
const className = classNameOverride || metadata.className;
|
|
815
954
|
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
// Core hydration via unified helper (pass requestedProperties for sparse fieldset).
|
|
826
|
-
// Also hydrate any properties referenced in `where` so the JS post-filter can match them,
|
|
827
|
-
// even if they're not in the user's `properties` projection.
|
|
828
|
-
let hydrationProps = requestedProperties.length > 0 ? [...requestedProperties] : undefined;
|
|
829
|
-
if (hydrationProps && query.where) {
|
|
830
|
-
for (const key of Object.keys(query.where)) {
|
|
831
|
-
if (!hydrationProps.includes(key)) {
|
|
832
|
-
hydrationProps.push(key);
|
|
833
|
-
}
|
|
834
|
-
}
|
|
955
|
+
// Expand includeAll: true to a full IncludeMap covering every forward relation.
|
|
956
|
+
// Done before queryInput is built so all downstream uses of query.include see the expansion.
|
|
957
|
+
if (query.includeAll) {
|
|
958
|
+
const allRelMeta = getRelationsMetadata(this as any);
|
|
959
|
+
const expanded: IncludeMap = {};
|
|
960
|
+
for (const [relName, relMeta] of Object.entries(allRelMeta)) {
|
|
961
|
+
if ((relMeta as any).direction !== 'reverse') {
|
|
962
|
+
expanded[relName] = true;
|
|
835
963
|
}
|
|
836
|
-
await hydrateFromLinks(instance, links, metadata, perspective, hydrationProps);
|
|
837
|
-
|
|
838
|
-
// NOTE: Property deletion for sparse fieldsets is deferred until AFTER
|
|
839
|
-
// where-filtering so that where conditions can reference any property,
|
|
840
|
-
// even ones not in the `properties` projection.
|
|
841
|
-
|
|
842
|
-
instances.push(instance);
|
|
843
|
-
} catch (error) {
|
|
844
|
-
console.error(`Failed to process SPARQL instance ${base}:`, error);
|
|
845
964
|
}
|
|
965
|
+
// Explicit include entries take precedence over the expansion
|
|
966
|
+
query = { ...query, include: { ...expanded, ...query.include } };
|
|
846
967
|
}
|
|
847
968
|
|
|
848
|
-
//
|
|
849
|
-
//
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
([relName, meta]) =>
|
|
855
|
-
(meta.kind === 'belongsToOne' || meta.kind === 'belongsToMany') &&
|
|
856
|
-
(requestedProperties.length === 0 || requestedProperties.includes(relName))
|
|
857
|
-
);
|
|
858
|
-
if (reverseRelEntries.length > 0 && instances.length > 0) {
|
|
859
|
-
await Promise.all(
|
|
860
|
-
instances.map(async (inst) => {
|
|
861
|
-
for (const [relName, relMeta] of reverseRelEntries) {
|
|
862
|
-
const reverseLinks = await perspective.get(
|
|
863
|
-
new LinkQuery({ predicate: relMeta.predicate, target: inst.id })
|
|
864
|
-
);
|
|
865
|
-
const sourceIds = reverseLinks
|
|
866
|
-
.filter((l) => l.data.target === inst.id)
|
|
867
|
-
.map((l) => l.data.source);
|
|
868
|
-
if (relMeta.kind === 'belongsToOne') {
|
|
869
|
-
(inst as any)[relName] = sourceIds.length > 0 ? sourceIds[sourceIds.length - 1] : null;
|
|
870
|
-
} else {
|
|
871
|
-
(inst as any)[relName] = sourceIds;
|
|
872
|
-
}
|
|
873
|
-
}
|
|
874
|
-
})
|
|
875
|
-
);
|
|
969
|
+
// Build the query input that the Rust endpoint expects.
|
|
970
|
+
// Convert the TS Query type to the executor's ModelQueryInput format.
|
|
971
|
+
const queryInput: any = {};
|
|
972
|
+
if (query.parent) {
|
|
973
|
+
const parentPredicate = resolveParentPredicate(query.parent, this);
|
|
974
|
+
queryInput.parent = { id: query.parent.id, predicate: parentPredicate };
|
|
876
975
|
}
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
? (requestedProperties.length > 0
|
|
890
|
-
? Array.from(new Set([...requestedProperties, ...whereGetterProperties]))
|
|
891
|
-
: query.deepQuery === true
|
|
892
|
-
? [] // deepQuery: evaluate all getters
|
|
893
|
-
: whereGetterProperties) // only evaluate where-referenced getters
|
|
894
|
-
: [];
|
|
895
|
-
const getterOpts = {
|
|
896
|
-
...(getterRequestedProperties.length > 0 && { requestedProperties: getterRequestedProperties }),
|
|
897
|
-
...(query.include && { include: query.include }),
|
|
898
|
-
skipPropertyGetters,
|
|
899
|
-
};
|
|
900
|
-
for (const instance of instances) {
|
|
901
|
-
await evaluateCustomGettersForInstance(instance, perspective, metadata, getterOpts);
|
|
976
|
+
if (query.properties) queryInput.properties = query.properties;
|
|
977
|
+
if (query.include) {
|
|
978
|
+
// Split include keys: $-prefixed / IncludeProjection values → queryInput.projections
|
|
979
|
+
// All other keys (boolean | RelationSubQuery) → queryInput.include
|
|
980
|
+
const normalIncludes: IncludeMap = {};
|
|
981
|
+
const projections: Record<string, IncludeProjection> = {};
|
|
982
|
+
for (const [key, val] of Object.entries(query.include)) {
|
|
983
|
+
if (key.startsWith('$')) {
|
|
984
|
+
projections[key] = val as IncludeProjection;
|
|
985
|
+
} else {
|
|
986
|
+
normalIncludes[key] = val;
|
|
987
|
+
}
|
|
902
988
|
}
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
// Skip 'base'/'id' as it's filtered in SPARQL
|
|
918
|
-
if (propertyName === 'base' || propertyName === 'id') continue;
|
|
919
|
-
|
|
920
|
-
// For author and timestamp, always filter in JS
|
|
921
|
-
if (propertyName === 'author' || propertyName === 'timestamp') {
|
|
922
|
-
if (!matchesCondition(instance[propertyName], condition)) {
|
|
923
|
-
return false;
|
|
924
|
-
}
|
|
925
|
-
continue;
|
|
926
|
-
}
|
|
927
|
-
|
|
928
|
-
// Check if this is a relation field (not in properties metadata)
|
|
929
|
-
const isPropField = propertyName in metadata.properties;
|
|
930
|
-
|
|
931
|
-
if (!isPropField) {
|
|
932
|
-
// Relation-based where — filter in JS against the populated field
|
|
933
|
-
if (!matchesCondition(instance[propertyName], condition)) {
|
|
934
|
-
return false;
|
|
935
|
-
}
|
|
936
|
-
continue;
|
|
937
|
-
}
|
|
938
|
-
|
|
939
|
-
// Filter ALL property conditions in JS (safety net).
|
|
940
|
-
// Equality/IN/NOT are also filtered in SPARQL via <ad4m://fn/parse_literal>()
|
|
941
|
-
// but JS re-validates after hydration resolves values.
|
|
942
|
-
if (!matchesCondition(instance[propertyName], condition)) {
|
|
943
|
-
return false;
|
|
989
|
+
if (Object.keys(normalIncludes).length > 0) queryInput.include = normalIncludes;
|
|
990
|
+
if (Object.keys(projections).length > 0) {
|
|
991
|
+
// Enrich projections with target shapes so Rust can apply where clause filtering
|
|
992
|
+
const allRelMeta = getRelationsMetadata(this as any);
|
|
993
|
+
for (const [, proj] of Object.entries(projections)) {
|
|
994
|
+
const relMeta = allRelMeta[proj.from];
|
|
995
|
+
if (!proj.targetShape && relMeta?.target) {
|
|
996
|
+
try {
|
|
997
|
+
const TargetClass = relMeta.target();
|
|
998
|
+
const targetMeta = (TargetClass as any).getModelMetadata?.();
|
|
999
|
+
if (targetMeta) {
|
|
1000
|
+
proj.targetShape = targetMeta;
|
|
1001
|
+
}
|
|
1002
|
+
} catch (_) { /* target class may not be available */ }
|
|
944
1003
|
}
|
|
945
1004
|
}
|
|
946
|
-
|
|
947
|
-
}
|
|
1005
|
+
queryInput.projections = projections;
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
if (query.where) queryInput.where = query.where;
|
|
1009
|
+
if (query.order) {
|
|
1010
|
+
// Convert { propName: 'ASC' | 'DESC' } to [[propName, 'ASC'|'DESC'], ...]
|
|
1011
|
+
queryInput.order = Object.entries(query.order).map(([k, v]) => [k, v]);
|
|
1012
|
+
}
|
|
1013
|
+
if (query.offset !== undefined) queryInput.offset = query.offset;
|
|
1014
|
+
if (query.limit !== undefined) queryInput.limit = query.limit;
|
|
1015
|
+
if (query.count !== undefined) queryInput.count = query.count;
|
|
1016
|
+
queryInput.deepQuery = query.deepQuery ?? true;
|
|
1017
|
+
|
|
1018
|
+
// Enrich relation metadata with target class shapes for Rust-side
|
|
1019
|
+
// include resolution. This eliminates per-relation GraphQL round-trips
|
|
1020
|
+
// by letting the Rust endpoint resolve includes in-process.
|
|
1021
|
+
if (queryInput.include) {
|
|
1022
|
+
const allRelMeta = getRelationsMetadata(this as any);
|
|
1023
|
+
enrichShapeForIncludes(metadata, queryInput.include, allRelMeta);
|
|
948
1024
|
}
|
|
949
1025
|
|
|
950
|
-
//
|
|
951
|
-
//
|
|
952
|
-
//
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
const
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
1026
|
+
// ── Pre-compute conformance getters for Rust-side evaluation ──────
|
|
1027
|
+
// For each relation with a target class and filter !== false, compute
|
|
1028
|
+
// the conformance getter SPARQL so Rust can evaluate it in-process
|
|
1029
|
+
// (eliminating N × querySparql round-trips per instance).
|
|
1030
|
+
// When a relation has a `where` clause, compile the where conditions
|
|
1031
|
+
// into the getter SPARQL so Rust applies them during evaluation.
|
|
1032
|
+
{
|
|
1033
|
+
const allRelMeta = getRelationsMetadata(this as any);
|
|
1034
|
+
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
1035
|
+
const rel = relMeta as any;
|
|
1036
|
+
if (rel.getter) continue; // explicit getter already set
|
|
1037
|
+
if (rel.direction === 'reverse') continue; // reverse relations use reverse link lookup
|
|
1038
|
+
if (rel.filter === false) continue; // opt-out of conformance filtering
|
|
963
1039
|
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
if (aVal === undefined) return orderDirection === 'ASC' ? 1 : -1;
|
|
967
|
-
if (bVal === undefined) return orderDirection === 'ASC' ? -1 : 1;
|
|
1040
|
+
const meta = allRelMeta[relName];
|
|
1041
|
+
if (!meta?.target) continue;
|
|
968
1042
|
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
1043
|
+
try {
|
|
1044
|
+
const TargetClass = meta.target();
|
|
1045
|
+
const filter = buildConformanceFilter(meta.predicate, TargetClass);
|
|
1046
|
+
|
|
1047
|
+
// Compile where clauses to SPARQL when all target properties use
|
|
1048
|
+
// literal encoding (literal:string:X etc.) which is SPARQL-matchable.
|
|
1049
|
+
// Properties with a non-literal resolveLanguage store expression hashes
|
|
1050
|
+
// that can't be matched by value in SPARQL.
|
|
1051
|
+
let whereConditions: string[] = [];
|
|
1052
|
+
if (rel.where) {
|
|
1053
|
+
try {
|
|
1054
|
+
const targetMetadata = (TargetClass as any).getModelMetadata?.() ?? null;
|
|
1055
|
+
let allSparqlFilterable = true;
|
|
1056
|
+
if (targetMetadata) {
|
|
1057
|
+
for (const propName of Object.keys(rel.where)) {
|
|
1058
|
+
if (['id', 'author', 'timestamp'].includes(propName)) continue;
|
|
1059
|
+
const propMeta = targetMetadata.properties[propName];
|
|
1060
|
+
if (propMeta?.resolveLanguage && propMeta.resolveLanguage !== 'literal') {
|
|
1061
|
+
allSparqlFilterable = false;
|
|
1062
|
+
break;
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
if (allSparqlFilterable) {
|
|
1067
|
+
whereConditions = compileWhereClause(rel.where, targetMetadata);
|
|
1068
|
+
}
|
|
1069
|
+
} catch (_) { /* target metadata unavailable */ }
|
|
977
1070
|
}
|
|
978
1071
|
|
|
979
|
-
if (
|
|
980
|
-
|
|
1072
|
+
if (filter) {
|
|
1073
|
+
let getter = filter.getter;
|
|
1074
|
+
if (whereConditions.length > 0) {
|
|
1075
|
+
// Append where conditions before the closing }
|
|
1076
|
+
getter = getter.replace(/ \}$/, ` ${whereConditions.join(' ')} }`);
|
|
1077
|
+
}
|
|
1078
|
+
rel.getter = getter;
|
|
1079
|
+
} else if (whereConditions.length > 0) {
|
|
1080
|
+
// No conformance filter but where clause exists — build getter from where alone
|
|
1081
|
+
const escapedPred = meta.predicate.replace(/[<>"{}|\\^`\u0000-\u0020]/g, '');
|
|
1082
|
+
rel.getter = `SELECT ?target WHERE { <Base> <${escapedPred}> ?target . ${whereConditions.join(' ')} }`;
|
|
981
1083
|
}
|
|
982
|
-
|
|
1084
|
+
} catch (e) {
|
|
1085
|
+
// Target class may not be available; skip silently
|
|
983
1086
|
}
|
|
984
|
-
|
|
985
|
-
});
|
|
1087
|
+
}
|
|
986
1088
|
}
|
|
987
1089
|
|
|
988
|
-
//
|
|
989
|
-
//
|
|
990
|
-
//
|
|
991
|
-
const
|
|
992
|
-
const
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
// Only run the COUNT query when the caller actually needs it (computeTotalCount=true).
|
|
1000
|
-
let totalCount: number;
|
|
1001
|
-
if (sparqlPaginated && computeTotalCount) {
|
|
1002
|
-
try {
|
|
1003
|
-
const countSparql = buildSPARQLCountQuery(metadata, allRelsMeta2, query, this);
|
|
1004
|
-
const countResult = await perspective.querySparql(countSparql);
|
|
1005
|
-
totalCount = parseSparqlCount(countResult) ?? filteredInstances.length;
|
|
1006
|
-
} catch {
|
|
1007
|
-
// Fallback: if count query fails, use what we have
|
|
1008
|
-
totalCount = filteredInstances.length;
|
|
1009
|
-
}
|
|
1010
|
-
} else {
|
|
1011
|
-
totalCount = filteredInstances.length;
|
|
1012
|
-
}
|
|
1013
|
-
|
|
1014
|
-
// Apply offset and limit in JavaScript only when SPARQL didn't already paginate.
|
|
1015
|
-
// Subscription queries use unpaginated SPARQL, so JS must apply pagination.
|
|
1016
|
-
// Direct queries use SPARQL-level pagination, so JS slicing would double-apply.
|
|
1017
|
-
let paginatedInstances = filteredInstances;
|
|
1018
|
-
if (!sparqlPaginated && (query.offset !== undefined || query.limit !== undefined)) {
|
|
1019
|
-
const start = query.offset || 0;
|
|
1020
|
-
const end = query.limit ? start + query.limit : undefined;
|
|
1021
|
-
paginatedInstances = filteredInstances.slice(start, end);
|
|
1022
|
-
}
|
|
1023
|
-
|
|
1024
|
-
// Now that where-filtering is done, strip unrequested properties for sparse fieldsets.
|
|
1025
|
-
// This must happen AFTER where-filtering so conditions can reference any property.
|
|
1026
|
-
if (requestedProperties.length > 0) {
|
|
1027
|
-
const requested = new Set(requestedProperties);
|
|
1028
|
-
for (const inst of paginatedInstances) {
|
|
1029
|
-
for (const propName of Object.keys(metadata.properties)) {
|
|
1030
|
-
if (!requested.has(propName)) {
|
|
1031
|
-
delete (inst as any)[propName];
|
|
1032
|
-
}
|
|
1033
|
-
}
|
|
1034
|
-
for (const relName of Object.keys(metadata.relations)) {
|
|
1035
|
-
if (!requested.has(relName) && !(query.include && relName in query.include)) {
|
|
1036
|
-
delete (inst as any)[relName];
|
|
1037
|
-
}
|
|
1038
|
-
}
|
|
1039
|
-
for (const metaField of ['author', 'createdAt', 'updatedAt'] as const) {
|
|
1040
|
-
if (!requested.has(metaField)) {
|
|
1041
|
-
delete (inst as any)[metaField];
|
|
1042
|
-
}
|
|
1043
|
-
}
|
|
1090
|
+
// Send shape metadata to the executor so it knows the model structure.
|
|
1091
|
+
// This is more reliable than reading SHACL from the store because
|
|
1092
|
+
// the TS decorators are the definitive source of truth.
|
|
1093
|
+
const shapeJson = JSON.stringify(metadata);
|
|
1094
|
+
const queryJson = JSON.stringify(queryInput);
|
|
1095
|
+
|
|
1096
|
+
// TEMP DEBUG: Log getters with where-clause filters to diagnose CI failure
|
|
1097
|
+
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
1098
|
+
const rel = relMeta as any;
|
|
1099
|
+
if (rel.where) {
|
|
1100
|
+
console.log(`[MODEL_QUERY_DEBUG] relation="${relName}" getter=${rel.getter ?? 'NONE'} where=${JSON.stringify(rel.where)}`);
|
|
1044
1101
|
}
|
|
1045
1102
|
}
|
|
1046
1103
|
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1104
|
+
const result = await perspective.modelQuery(className, queryJson, shapeJson);
|
|
1105
|
+
|
|
1106
|
+
// Convert JSON instances to model class instances, recursively constructing
|
|
1107
|
+
// class instances for any included relations resolved by Rust.
|
|
1108
|
+
const instances: T[] = result.instances.map((json: any) => {
|
|
1109
|
+
return jsonToModelInstance(this, perspective, json, query.include, query.properties);
|
|
1110
|
+
});
|
|
1111
|
+
|
|
1112
|
+
// Resolve non-literal expressions (e.g. file languages where the stored
|
|
1113
|
+
// value is a content-addressed hash that must be fetched from the language
|
|
1114
|
+
// runtime). The Rust endpoint returns raw target URIs; we resolve them here.
|
|
1115
|
+
const propsMeta = getPropertiesMetadata(this as any);
|
|
1116
|
+
const resolveProps = Object.entries(propsMeta).filter(
|
|
1117
|
+
([, opts]: [string, any]) =>
|
|
1118
|
+
opts.resolveLanguage != null &&
|
|
1119
|
+
opts.resolveLanguage !== 'literal',
|
|
1120
|
+
);
|
|
1121
|
+
if (resolveProps.length > 0) {
|
|
1122
|
+
await Promise.all(
|
|
1123
|
+
instances.map(async (inst: any) => {
|
|
1124
|
+
for (const [propName, opts] of resolveProps) {
|
|
1125
|
+
const val = inst[propName];
|
|
1126
|
+
if (typeof val !== 'string' || !val || val.startsWith('literal:')) continue;
|
|
1127
|
+
try {
|
|
1128
|
+
const expression = await perspective.getExpression(val);
|
|
1129
|
+
if (expression) {
|
|
1130
|
+
let resolved: any;
|
|
1131
|
+
try { resolved = JSON.parse(expression.data); } catch { resolved = expression.data; }
|
|
1132
|
+
const transform = (opts as any).transform;
|
|
1133
|
+
inst[propName] = typeof transform === 'function' ? transform(resolved) : resolved;
|
|
1134
|
+
}
|
|
1135
|
+
} catch (_) { /* resolution failed — keep raw value */ }
|
|
1136
|
+
}
|
|
1137
|
+
}),
|
|
1138
|
+
);
|
|
1050
1139
|
}
|
|
1051
1140
|
|
|
1052
|
-
// Take snapshots for dirty tracking
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
// Otherwise snapshot ALL fields (properties + relations) since
|
|
1056
|
-
// hydrateFromLinks populates relations with stable raw IDs —
|
|
1057
|
-
// this ensures push-to-array + save() correctly detects dirty relations.
|
|
1058
|
-
const snapshotRelations = query.include;
|
|
1059
|
-
for (const inst of paginatedInstances) {
|
|
1141
|
+
// Take snapshots for dirty tracking
|
|
1142
|
+
const snapshotRelations = queryInput.include;
|
|
1143
|
+
for (const inst of instances) {
|
|
1060
1144
|
(inst as Ad4mModel).takeSnapshot(snapshotRelations);
|
|
1061
1145
|
}
|
|
1062
1146
|
|
|
1063
1147
|
return {
|
|
1064
|
-
results:
|
|
1065
|
-
totalCount
|
|
1148
|
+
results: instances,
|
|
1149
|
+
totalCount: result.totalCount,
|
|
1066
1150
|
};
|
|
1067
1151
|
}
|
|
1068
1152
|
|
|
@@ -1097,33 +1181,14 @@ export class Ad4mModel {
|
|
|
1097
1181
|
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
1098
1182
|
perspective: PerspectiveProxy,
|
|
1099
1183
|
query: Query = {},
|
|
1100
|
-
|
|
1184
|
+
_engine?: 'sparql' | 'prolog' | boolean
|
|
1101
1185
|
): Promise<T[]> {
|
|
1102
1186
|
if (query.properties && query.properties.length === 0) {
|
|
1103
1187
|
throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
|
|
1104
1188
|
}
|
|
1105
1189
|
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
? (engine ? 'sparql' : 'prolog')
|
|
1109
|
-
: engine;
|
|
1110
|
-
|
|
1111
|
-
if (resolvedEngine === 'sparql') {
|
|
1112
|
-
// Always use the regular SPARQL path + JS-level hydrateRelations for includes.
|
|
1113
|
-
// The batch SPARQL approach had issues with sub-queries (where/order/limit on includes),
|
|
1114
|
-
// non-conforming node filtering, and parse_literal compatibility.
|
|
1115
|
-
// hydrateRelations handles all of these correctly via per-relation findAll calls.
|
|
1116
|
-
const sparqlQuery = await this.queryToSPARQL(perspective, query);
|
|
1117
|
-
const rawResult = await perspective.querySparql(sparqlQuery);
|
|
1118
|
-
const grouped = groupSPARQLResults(rawResult);
|
|
1119
|
-
const { results } = await this.instancesFromQueryResult(perspective, query, grouped);
|
|
1120
|
-
return results;
|
|
1121
|
-
} else {
|
|
1122
|
-
const prologQuery = await this.queryToProlog(perspective, query);
|
|
1123
|
-
const result = await perspective.infer(prologQuery);
|
|
1124
|
-
const { results } = await this.instancesFromPrologResult(perspective, query, result);
|
|
1125
|
-
return results;
|
|
1126
|
-
}
|
|
1190
|
+
const { results } = await this.executeModelQuery(perspective, query);
|
|
1191
|
+
return results;
|
|
1127
1192
|
}
|
|
1128
1193
|
|
|
1129
1194
|
/**
|
|
@@ -1150,10 +1215,10 @@ export class Ad4mModel {
|
|
|
1150
1215
|
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
1151
1216
|
perspective: PerspectiveProxy,
|
|
1152
1217
|
query: Query = {},
|
|
1153
|
-
|
|
1218
|
+
_engine?: 'sparql' | 'prolog' | boolean,
|
|
1154
1219
|
): Promise<T | null> {
|
|
1155
1220
|
const limitedQuery = { ...query, limit: 1 };
|
|
1156
|
-
const results = await this.findAll(perspective, limitedQuery
|
|
1221
|
+
const results = await this.findAll(perspective, limitedQuery);
|
|
1157
1222
|
return results[0] ?? null;
|
|
1158
1223
|
}
|
|
1159
1224
|
|
|
@@ -1181,22 +1246,9 @@ export class Ad4mModel {
|
|
|
1181
1246
|
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
1182
1247
|
perspective: PerspectiveProxy,
|
|
1183
1248
|
query: Query = {},
|
|
1184
|
-
|
|
1249
|
+
_engine?: 'sparql' | 'prolog' | boolean
|
|
1185
1250
|
): Promise<ResultsWithTotalCount<T>> {
|
|
1186
|
-
|
|
1187
|
-
? (engine ? 'sparql' : 'prolog')
|
|
1188
|
-
: engine;
|
|
1189
|
-
|
|
1190
|
-
if (resolvedEngine === 'sparql') {
|
|
1191
|
-
const sparqlQuery = await this.queryToSPARQL(perspective, query);
|
|
1192
|
-
const rawResult = await perspective.querySparql(sparqlQuery);
|
|
1193
|
-
const grouped = groupSPARQLResults(rawResult);
|
|
1194
|
-
return await this.instancesFromQueryResult(perspective, query, grouped, true);
|
|
1195
|
-
} else {
|
|
1196
|
-
const prologQuery = await this.queryToProlog(perspective, query);
|
|
1197
|
-
const result = await perspective.infer(prologQuery);
|
|
1198
|
-
return await this.instancesFromPrologResult(perspective, query, result);
|
|
1199
|
-
}
|
|
1251
|
+
return await this.executeModelQuery(perspective, query);
|
|
1200
1252
|
}
|
|
1201
1253
|
|
|
1202
1254
|
/**
|
|
@@ -1206,7 +1258,6 @@ export class Ad4mModel {
|
|
|
1206
1258
|
* @param pageSize - Number of items per page
|
|
1207
1259
|
* @param pageNumber - Which page to retrieve (1-based)
|
|
1208
1260
|
* @param query - Optional additional query parameters
|
|
1209
|
-
* @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
|
|
1210
1261
|
* @returns Paginated results with metadata
|
|
1211
1262
|
*
|
|
1212
1263
|
* @example
|
|
@@ -1215,9 +1266,6 @@ export class Ad4mModel {
|
|
|
1215
1266
|
* where: { category: "Main Course" }
|
|
1216
1267
|
* });
|
|
1217
1268
|
* console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
|
|
1218
|
-
*
|
|
1219
|
-
* // Use Prolog explicitly (legacy)
|
|
1220
|
-
* const pageProlog = await Recipe.paginate(perspective, 10, 1, {}, false);
|
|
1221
1269
|
* ```
|
|
1222
1270
|
*/
|
|
1223
1271
|
static async paginate<T extends Ad4mModel>(
|
|
@@ -1226,46 +1274,11 @@ export class Ad4mModel {
|
|
|
1226
1274
|
pageSize: number,
|
|
1227
1275
|
pageNumber: number,
|
|
1228
1276
|
query?: Query,
|
|
1229
|
-
|
|
1277
|
+
_engine?: 'sparql' | 'prolog' | boolean
|
|
1230
1278
|
): Promise<PaginationResult<T>> {
|
|
1231
1279
|
const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
|
|
1232
|
-
const
|
|
1233
|
-
|
|
1234
|
-
: engine;
|
|
1235
|
-
|
|
1236
|
-
if (resolvedEngine === 'sparql') {
|
|
1237
|
-
const sparqlQuery = await this.queryToSPARQL(perspective, paginationQuery);
|
|
1238
|
-
const rawResult = await perspective.querySparql(sparqlQuery);
|
|
1239
|
-
const grouped = groupSPARQLResults(rawResult);
|
|
1240
|
-
const { results, totalCount } = await this.instancesFromQueryResult(perspective, paginationQuery, grouped, true);
|
|
1241
|
-
return { results, totalCount, pageSize, pageNumber };
|
|
1242
|
-
} else {
|
|
1243
|
-
const prologQuery = await this.queryToProlog(perspective, paginationQuery);
|
|
1244
|
-
const result = await perspective.infer(prologQuery);
|
|
1245
|
-
const { results, totalCount } = await this.instancesFromPrologResult(perspective, paginationQuery, result);
|
|
1246
|
-
return { results, totalCount, pageSize, pageNumber };
|
|
1247
|
-
}
|
|
1248
|
-
}
|
|
1249
|
-
|
|
1250
|
-
static async countQueryToProlog(perspective: PerspectiveProxy, query: Query = {}, modelClassName?: string | null) {
|
|
1251
|
-
const { where } = query;
|
|
1252
|
-
const className = modelClassName || (await this.getClassName(perspective));
|
|
1253
|
-
const resolvedParentPredicate = query.parent
|
|
1254
|
-
? resolveParentPredicate(query.parent, this)
|
|
1255
|
-
: undefined;
|
|
1256
|
-
const instanceQueries = [buildAuthorAndTimestampQuery(), buildParentQuery(query.parent, resolvedParentPredicate), buildWhereQuery(where)];
|
|
1257
|
-
const resultSetQueries = [buildCountQuery(true), buildOrderQuery(), buildOffsetQuery(), buildLimitQuery()];
|
|
1258
|
-
|
|
1259
|
-
const fullQuery = `
|
|
1260
|
-
findall([Base, Properties, Collections, Timestamp, Author], (
|
|
1261
|
-
subject_class("${className}", SubjectClass),
|
|
1262
|
-
instance(SubjectClass, Base),
|
|
1263
|
-
${instanceQueries.filter((q) => q).join(", ")}
|
|
1264
|
-
), UnsortedInstances),
|
|
1265
|
-
${resultSetQueries.filter((q) => q).join(", ")}
|
|
1266
|
-
`;
|
|
1267
|
-
|
|
1268
|
-
return fullQuery;
|
|
1280
|
+
const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery);
|
|
1281
|
+
return { results, totalCount, pageSize, pageNumber };
|
|
1269
1282
|
}
|
|
1270
1283
|
|
|
1271
1284
|
/**
|
|
@@ -1277,18 +1290,13 @@ export class Ad4mModel {
|
|
|
1277
1290
|
*
|
|
1278
1291
|
* @private
|
|
1279
1292
|
*/
|
|
1280
|
-
|
|
1281
|
-
const metadata = this.getModelMetadata();
|
|
1282
|
-
const allRelMeta = getRelationsMetadata(this as any);
|
|
1283
|
-
return buildSPARQLCountQuery(metadata, allRelMeta, query, this);
|
|
1284
|
-
}
|
|
1293
|
+
// countQueryToSPARQL — removed (zero callers; Rust COUNT fast-path supersedes)
|
|
1285
1294
|
|
|
1286
1295
|
/**
|
|
1287
1296
|
* Gets a count of all matching instances.
|
|
1288
1297
|
*
|
|
1289
1298
|
* @param perspective - The perspective to search in
|
|
1290
1299
|
* @param query - Optional query parameters to filter results
|
|
1291
|
-
* @param useSPARQL - Whether to use SPARQL (default: true, 10-100x faster) or Prolog (legacy)
|
|
1292
1300
|
* @returns Total count of matching entities
|
|
1293
1301
|
*
|
|
1294
1302
|
* @example
|
|
@@ -1297,36 +1305,11 @@ export class Ad4mModel {
|
|
|
1297
1305
|
* const activeRecipes = await Recipe.count(perspective, {
|
|
1298
1306
|
* where: { status: "active" }
|
|
1299
1307
|
* });
|
|
1300
|
-
*
|
|
1301
|
-
* // Use Prolog explicitly (legacy)
|
|
1302
|
-
* const countProlog = await Recipe.count(perspective, {}, false);
|
|
1303
1308
|
* ```
|
|
1304
1309
|
*/
|
|
1305
|
-
static async count(perspective: PerspectiveProxy, query: Query = {}
|
|
1306
|
-
const
|
|
1307
|
-
|
|
1308
|
-
: engine;
|
|
1309
|
-
|
|
1310
|
-
if (resolvedEngine === 'sparql') {
|
|
1311
|
-
// When query has JS-only where filters (gt, between, author, timestamp, etc.),
|
|
1312
|
-
// we must fall back to full hydration + JS filtering to get accurate count.
|
|
1313
|
-
const metadata = this.getModelMetadata();
|
|
1314
|
-
const allRelMeta = getRelationsMetadata(this as any);
|
|
1315
|
-
if (hasJsOnlyWhereFilters(metadata, allRelMeta, query.where)) {
|
|
1316
|
-
// Fall back to full query + JS filter path for accurate count
|
|
1317
|
-
const sparqlQuery = await this.queryToSPARQL(perspective, query);
|
|
1318
|
-
const rawResult = await perspective.querySparql(sparqlQuery);
|
|
1319
|
-
const grouped = groupSPARQLResults(rawResult);
|
|
1320
|
-
const { totalCount } = await this.instancesFromQueryResult(perspective, query, grouped, true); return totalCount;
|
|
1321
|
-
}
|
|
1322
|
-
// No JS-only filters — use efficient COUNT query
|
|
1323
|
-
const countSparql = await this.countQueryToSPARQL(perspective, query);
|
|
1324
|
-
const countResult = await perspective.querySparql(countSparql);
|
|
1325
|
-
return parseSparqlCount(countResult) ?? 0;
|
|
1326
|
-
} else {
|
|
1327
|
-
const result = await perspective.infer(await this.countQueryToProlog(perspective, query));
|
|
1328
|
-
return result?.[0]?.TotalCount || 0;
|
|
1329
|
-
}
|
|
1310
|
+
static async count(perspective: PerspectiveProxy, query: Query = {}): Promise<number> {
|
|
1311
|
+
const { totalCount } = await this.executeModelQuery(perspective, { ...query, limit: 0 });
|
|
1312
|
+
return totalCount;
|
|
1330
1313
|
}
|
|
1331
1314
|
|
|
1332
1315
|
private async setProperty(key: string, value: any, batchId?: string) {
|
|
@@ -1661,10 +1644,10 @@ export class Ad4mModel {
|
|
|
1661
1644
|
/**
|
|
1662
1645
|
* Evaluate SPARQL getters for a batch of instances on demand.
|
|
1663
1646
|
*
|
|
1664
|
-
*
|
|
1665
|
-
*
|
|
1666
|
-
*
|
|
1667
|
-
* a
|
|
1647
|
+
* Since deepQuery defaults to true, property getters are evaluated
|
|
1648
|
+
* automatically during collection queries. Use this method when
|
|
1649
|
+
* deepQuery was explicitly set to false and you want to lazily
|
|
1650
|
+
* resolve getter-backed properties for a subset of instances.
|
|
1668
1651
|
*
|
|
1669
1652
|
* @param instances - Array of model instances to evaluate getters on
|
|
1670
1653
|
* @param perspective - The perspective to query against
|
|
@@ -1673,8 +1656,8 @@ export class Ad4mModel {
|
|
|
1673
1656
|
*
|
|
1674
1657
|
* @example
|
|
1675
1658
|
* ```typescript
|
|
1676
|
-
* const messages = await Message.
|
|
1677
|
-
* // messages[i].replyingTo is undefined (getter skipped
|
|
1659
|
+
* const messages = await Message.query(perspective).deepQuery(false).limit(30).get();
|
|
1660
|
+
* // messages[i].replyingTo is undefined (getter skipped)
|
|
1678
1661
|
*
|
|
1679
1662
|
* // Evaluate getters for the visible subset
|
|
1680
1663
|
* await Message.evaluateGetters(messages.slice(0, 10), perspective, ['replyingTo']);
|
|
@@ -1688,11 +1671,33 @@ export class Ad4mModel {
|
|
|
1688
1671
|
): Promise<void> {
|
|
1689
1672
|
if (instances.length === 0) return;
|
|
1690
1673
|
const metadata = this.getModelMetadata();
|
|
1691
|
-
const opts = propertyNames && propertyNames.length > 0
|
|
1692
|
-
? { requestedProperties: propertyNames }
|
|
1693
|
-
: undefined;
|
|
1694
1674
|
|
|
1695
|
-
//
|
|
1675
|
+
// Pre-compute conformance getters so the shape sent to Rust includes them
|
|
1676
|
+
const allRelMeta = getRelationsMetadata(this as any);
|
|
1677
|
+
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
1678
|
+
const rel = relMeta as any;
|
|
1679
|
+
if (rel.getter || rel.direction === 'reverse' || rel.filter === false) continue;
|
|
1680
|
+
const meta = allRelMeta[relName];
|
|
1681
|
+
if (!meta?.target) continue;
|
|
1682
|
+
try {
|
|
1683
|
+
const TargetClass = meta.target();
|
|
1684
|
+
const filter = buildConformanceFilter(meta.predicate, TargetClass);
|
|
1685
|
+
if (filter) rel.getter = filter.getter;
|
|
1686
|
+
} catch (_) { /* target class may not be available */ }
|
|
1687
|
+
}
|
|
1688
|
+
|
|
1689
|
+
const shapeJson = JSON.stringify(metadata);
|
|
1690
|
+
const instanceIds = instances.map(inst => inst.id || (inst as any)._baseExpression);
|
|
1691
|
+
|
|
1692
|
+
// Single RPC call evaluates all getters in-process on the executor
|
|
1693
|
+
const result = await perspective.evaluateGetters(
|
|
1694
|
+
metadata.className,
|
|
1695
|
+
instanceIds,
|
|
1696
|
+
shapeJson,
|
|
1697
|
+
propertyNames,
|
|
1698
|
+
);
|
|
1699
|
+
|
|
1700
|
+
// Determine which property names were evaluated for snapshot sync
|
|
1696
1701
|
const evaluatedPropertyNames: string[] = [];
|
|
1697
1702
|
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
1698
1703
|
if ((propMeta as any).getter) {
|
|
@@ -1701,14 +1706,25 @@ export class Ad4mModel {
|
|
|
1701
1706
|
}
|
|
1702
1707
|
}
|
|
1703
1708
|
}
|
|
1709
|
+
// Also include relation getters
|
|
1710
|
+
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
1711
|
+
if ((relMeta as any).getter) {
|
|
1712
|
+
if (!propertyNames || propertyNames.length === 0 || propertyNames.includes(relName)) {
|
|
1713
|
+
evaluatedPropertyNames.push(relName);
|
|
1714
|
+
}
|
|
1715
|
+
}
|
|
1716
|
+
}
|
|
1704
1717
|
|
|
1718
|
+
// Apply results to instances and sync snapshots
|
|
1705
1719
|
for (const instance of instances) {
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1720
|
+
const id = (instance as any).id || (instance as any)._baseExpression;
|
|
1721
|
+
const props = result[id];
|
|
1722
|
+
if (props) {
|
|
1723
|
+
for (const [key, value] of Object.entries(props)) {
|
|
1724
|
+
(instance as any)[key] = value;
|
|
1725
|
+
}
|
|
1726
|
+
}
|
|
1727
|
+
// Sync snapshot so isDirty() doesn't flag getter-only changes
|
|
1712
1728
|
const modelInstance = instance as Ad4mModel;
|
|
1713
1729
|
if (modelInstance._snapshot) {
|
|
1714
1730
|
for (const propName of evaluatedPropertyNames) {
|
|
@@ -2132,5 +2148,124 @@ export class Ad4mModel {
|
|
|
2132
2148
|
): typeof Ad4mModel {
|
|
2133
2149
|
return buildModelFromJSONSchema(this, schema, options);
|
|
2134
2150
|
}
|
|
2151
|
+
|
|
2152
|
+
/**
|
|
2153
|
+
* Creates a fully functional Ad4mModel subclass from a SHACL shape.
|
|
2154
|
+
*
|
|
2155
|
+
* Unlike `fromJSONSchema()`, no predicate inference is required —
|
|
2156
|
+
* `SHACLShape` already contains the exact predicate URI in `path` for
|
|
2157
|
+
* every property. The method reads each property's `path`, `maxCount`,
|
|
2158
|
+
* `writable`, and `resolveLanguage` directly and writes them to the
|
|
2159
|
+
* WeakMap metadata registries.
|
|
2160
|
+
*
|
|
2161
|
+
* Properties with `hasValue` (flag / type-discrimination markers) are
|
|
2162
|
+
* registered as hidden flag entries so that the SPARQL query builder emits
|
|
2163
|
+
* the fixed triple `?source <predicate> <value>` needed for type discrimination.
|
|
2164
|
+
* Properties without a `name` field are skipped.
|
|
2165
|
+
*
|
|
2166
|
+
* **Backward-compat:** Old Flux SHACL shapes (created before `sh:hasValue`
|
|
2167
|
+
* was persisted on property shapes) carry the flag value only in
|
|
2168
|
+
* `shape.constructor_actions` as the `target` of an `addLink` action.
|
|
2169
|
+
* This method recovers those values so that old perspectives are queried
|
|
2170
|
+
* with the correct type-discriminator triple.
|
|
2171
|
+
*
|
|
2172
|
+
* @param shape - SHACL node shape (as returned by `PerspectiveProxy.getAllShacl()`)
|
|
2173
|
+
* @param name - Class name to assign (e.g. "Channel")
|
|
2174
|
+
* @returns Generated Ad4mModel subclass, ready for querying
|
|
2175
|
+
*/
|
|
2176
|
+
/**
|
|
2177
|
+
* Synthesise an `Ad4mModel` subclass from a SHACL shape.
|
|
2178
|
+
*
|
|
2179
|
+
* @param shape - The SHACL shape to synthesise from.
|
|
2180
|
+
* @param name - The model name (e.g. "Channel").
|
|
2181
|
+
* @param classResolver - Optional thunk factory. When provided, any collection
|
|
2182
|
+
* property that carries a `sh:class` URI will have its `target` wired up lazily:
|
|
2183
|
+
* `target: () => classResolver(localName)`. Because `target` is only called at
|
|
2184
|
+
* query time (inside `enrichShapeForIncludes` / `jsonToModelInstance`), the
|
|
2185
|
+
* resolver just needs to return the correct class by the time a query runs —
|
|
2186
|
+
* making it safe to pass a closure over a registry object that is still being
|
|
2187
|
+
* populated (e.g. the `result` record inside `getModelClasses`).
|
|
2188
|
+
*/
|
|
2189
|
+
static fromSHACL(
|
|
2190
|
+
shape: SHACLShape,
|
|
2191
|
+
name: string,
|
|
2192
|
+
classResolver?: (localName: string) => typeof Ad4mModel | undefined,
|
|
2193
|
+
): typeof Ad4mModel {
|
|
2194
|
+
const DynamicModelClass = class extends (this as any) {} as unknown as typeof Ad4mModel;
|
|
2195
|
+
(DynamicModelClass as any).className = name;
|
|
2196
|
+
(DynamicModelClass.prototype as any).className = name;
|
|
2197
|
+
|
|
2198
|
+
// Build a backward-compat fallback map: predicate → fixed-IRI-value from
|
|
2199
|
+
// constructor actions. Old SHACL stores (created before sh:hasValue was
|
|
2200
|
+
// persisted on the property shape) don't carry sh:hasValue on properties,
|
|
2201
|
+
// but the shape-level constructor_actions always contain an addLink action
|
|
2202
|
+
// with the fixed flag value as the target.
|
|
2203
|
+
const flagValueFromConstructor = new Map<string, string>();
|
|
2204
|
+
for (const action of shape.constructor_actions ?? []) {
|
|
2205
|
+
if (
|
|
2206
|
+
action.action === 'addLink' &&
|
|
2207
|
+
typeof action.predicate === 'string' &&
|
|
2208
|
+
typeof action.target === 'string' &&
|
|
2209
|
+
action.target !== 'value' &&
|
|
2210
|
+
!action.target.startsWith('literal:')
|
|
2211
|
+
) {
|
|
2212
|
+
flagValueFromConstructor.set(action.predicate, action.target);
|
|
2213
|
+
}
|
|
2214
|
+
}
|
|
2215
|
+
|
|
2216
|
+
for (const prop of shape.properties) {
|
|
2217
|
+
const resolvedHasValue = prop.hasValue ?? flagValueFromConstructor.get(prop.path);
|
|
2218
|
+
|
|
2219
|
+
if (resolvedHasValue !== undefined) {
|
|
2220
|
+
const flagKey = prop.name ?? `_flag_${prop.path.replace(/[^a-zA-Z0-9_]/g, '_')}`;
|
|
2221
|
+
setPropertyRegistryEntry(DynamicModelClass, flagKey, {
|
|
2222
|
+
through: prop.path,
|
|
2223
|
+
required: true,
|
|
2224
|
+
initial: resolvedHasValue,
|
|
2225
|
+
flag: true,
|
|
2226
|
+
writable: false,
|
|
2227
|
+
readOnly: true,
|
|
2228
|
+
});
|
|
2229
|
+
continue;
|
|
2230
|
+
}
|
|
2231
|
+
|
|
2232
|
+
// Skip properties without a declared name
|
|
2233
|
+
if (!prop.name) continue;
|
|
2234
|
+
|
|
2235
|
+
const isCollection = prop.maxCount === undefined || prop.maxCount > 1;
|
|
2236
|
+
|
|
2237
|
+
if (isCollection) {
|
|
2238
|
+
// Derive a lazy `target` thunk when a sh:class URI is present and a
|
|
2239
|
+
// classResolver was supplied. The thunk is evaluated at query time so
|
|
2240
|
+
// it is safe even if the target class hasn't been registered yet.
|
|
2241
|
+
let targetThunk: (() => typeof Ad4mModel) | undefined;
|
|
2242
|
+
if (prop.class && classResolver) {
|
|
2243
|
+
const sep = Math.max(prop.class.lastIndexOf('#'), prop.class.lastIndexOf('/'));
|
|
2244
|
+
const localName = sep >= 0 ? prop.class.slice(sep + 1) : prop.class;
|
|
2245
|
+
targetThunk = () => classResolver(localName) as typeof Ad4mModel;
|
|
2246
|
+
}
|
|
2247
|
+
|
|
2248
|
+
setRelationRegistryEntry(DynamicModelClass, prop.name, {
|
|
2249
|
+
predicate: prop.path,
|
|
2250
|
+
kind: 'hasMany',
|
|
2251
|
+
...(targetThunk !== undefined && { target: targetThunk }),
|
|
2252
|
+
...(prop.local !== undefined && { local: prop.local }),
|
|
2253
|
+
...(prop.getter !== undefined && { getter: prop.getter }),
|
|
2254
|
+
});
|
|
2255
|
+
} else {
|
|
2256
|
+
setPropertyRegistryEntry(DynamicModelClass, prop.name, {
|
|
2257
|
+
through: prop.path,
|
|
2258
|
+
writable: prop.writable ?? true,
|
|
2259
|
+
...(prop.resolveLanguage !== undefined && { resolveLanguage: prop.resolveLanguage }),
|
|
2260
|
+
...(prop.local !== undefined && { local: prop.local }),
|
|
2261
|
+
});
|
|
2262
|
+
}
|
|
2263
|
+
}
|
|
2264
|
+
|
|
2265
|
+
const ModelDecorator = Model({ name });
|
|
2266
|
+
ModelDecorator(DynamicModelClass);
|
|
2267
|
+
|
|
2268
|
+
return DynamicModelClass as typeof Ad4mModel;
|
|
2269
|
+
}
|
|
2135
2270
|
}
|
|
2136
2271
|
|