@coasys/ad4m 0.13.0-test-3 → 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 +2406 -11070
- package/lib/index.js +2209 -10925
- 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 -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 +57 -38
- package/lib/src/model/Ad4mModel.js +594 -460
- package/lib/src/model/Ad4mModel.test.js +371 -815
- package/lib/src/model/ModelQueryBuilder.d.ts +9 -21
- package/lib/src/model/ModelQueryBuilder.js +138 -217
- package/lib/src/model/decorators.d.ts +22 -0
- package/lib/src/model/decorators.js +7 -0
- package/lib/src/model/hydration.d.ts +7 -60
- package/lib/src/model/hydration.js +7 -716
- 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/shacl-gen.js +4 -0
- package/lib/src/model/types.d.ts +47 -38
- 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 -17
- package/lib/src/perspectives/PerspectiveClient.js +169 -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 +92 -71
- package/lib/src/perspectives/PerspectiveProxy.js +273 -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 +1179 -1340
- 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 -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 +708 -876
- package/src/model/Ad4mModel.ts +613 -508
- package/src/model/ModelQueryBuilder.ts +178 -244
- package/src/model/decorators.ts +29 -0
- package/src/model/hydration.ts +9 -766
- 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/shacl-gen.ts +5 -0
- package/src/model/types.ts +51 -39
- 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 +228 -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 +307 -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/hydration.ts
CHANGED
|
@@ -1,24 +1,22 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* hydration.ts — Instance hydration helpers extracted from Ad4mModel.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
4
|
+
* After the Rust model_query pipeline migration (Phases 1-13), most hydration
|
|
5
|
+
* logic moved to Rust. This file retains:
|
|
6
|
+
* - normalizeValue() — snapshot dirty-tracking
|
|
7
|
+
* - matchesCondition() — JS-side post-filter (used by evaluateCustomGettersForInstance)
|
|
8
|
+
* - evaluateCustomGettersForInstance() — lazy getter evaluation (Ad4mModel.evaluateGetters)
|
|
9
|
+
* - buildConformanceGetter() — conformance SPARQL generation for relation getters
|
|
8
10
|
*/
|
|
9
11
|
|
|
10
|
-
import { Literal } from "../Literal";
|
|
11
|
-
import { LinkQuery } from "../perspectives/LinkQuery";
|
|
12
12
|
import type { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
|
|
13
|
-
import {
|
|
14
|
-
import type { RelationMetadataEntry } from "./decorators";
|
|
13
|
+
import { buildConformanceFilter } from "./decorators";
|
|
15
14
|
import { compileWhereClause } from "./query-utils";
|
|
16
15
|
import { escapeQueryString } from "../utils";
|
|
17
16
|
import type {
|
|
18
|
-
|
|
19
|
-
|
|
17
|
+
RelationMetadata, ModelMetadata,
|
|
18
|
+
WhereCondition,
|
|
20
19
|
} from "./types";
|
|
21
|
-
import { buildSPARQLGroupedCountQuery, parseSparqlGroupedCount } from "./query-sparql";
|
|
22
20
|
|
|
23
21
|
// ──────────────────────────────────────────────────────────
|
|
24
22
|
// Pure helpers
|
|
@@ -102,317 +100,6 @@ export function matchesCondition(value: any, condition: WhereCondition): boolean
|
|
|
102
100
|
return value === condition;
|
|
103
101
|
}
|
|
104
102
|
|
|
105
|
-
// ──────────────────────────────────────────────────────────
|
|
106
|
-
// Property / link hydration
|
|
107
|
-
// ──────────────────────────────────────────────────────────
|
|
108
|
-
|
|
109
|
-
/**
|
|
110
|
-
* Resolves a single property value from a raw link target string.
|
|
111
|
-
*
|
|
112
|
-
* Handles expression resolution, literal URI parsing, primitive
|
|
113
|
-
* type coercion, and optional transform functions.
|
|
114
|
-
*
|
|
115
|
-
* @param target - The raw target string from the link
|
|
116
|
-
* @param propMeta - Property metadata from the decorator registry
|
|
117
|
-
* @param perspective - The perspective for expression resolution
|
|
118
|
-
* @param expectedType - Optional JS typeof hint for coercion (e.g. 'number')
|
|
119
|
-
* @returns The resolved value
|
|
120
|
-
*/
|
|
121
|
-
export async function hydratePropertyValue(
|
|
122
|
-
target: string,
|
|
123
|
-
propMeta: PropertyMetadata,
|
|
124
|
-
perspective: PerspectiveProxy,
|
|
125
|
-
expectedType?: string,
|
|
126
|
-
): Promise<any> {
|
|
127
|
-
let value: any = target;
|
|
128
|
-
|
|
129
|
-
if (target !== undefined && target !== null && target !== '') {
|
|
130
|
-
// Non-literal expression resolution
|
|
131
|
-
if (
|
|
132
|
-
propMeta.resolveLanguage != null &&
|
|
133
|
-
propMeta.resolveLanguage !== 'literal' &&
|
|
134
|
-
typeof target === 'string' &&
|
|
135
|
-
!target.startsWith('literal:')
|
|
136
|
-
) {
|
|
137
|
-
try {
|
|
138
|
-
const expression = await perspective.getExpression(target);
|
|
139
|
-
if (expression) {
|
|
140
|
-
try { value = JSON.parse(expression.data); } catch { value = expression.data; }
|
|
141
|
-
}
|
|
142
|
-
} catch (e) {
|
|
143
|
-
console.warn(`hydratePropertyValue: failed to resolve expression for "${propMeta.name}":`, e);
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
// Literal URI parsing
|
|
147
|
-
else if (
|
|
148
|
-
propMeta.resolveLanguage === 'literal' &&
|
|
149
|
-
typeof target === 'string' &&
|
|
150
|
-
target.startsWith('literal:')
|
|
151
|
-
) {
|
|
152
|
-
try {
|
|
153
|
-
const parsed = Literal.fromUrl(target).get();
|
|
154
|
-
value = parsed.data !== undefined ? parsed.data : parsed;
|
|
155
|
-
} catch {
|
|
156
|
-
// Keep raw value
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
// Primitive type coercion
|
|
160
|
-
else if (typeof target === 'string' && expectedType) {
|
|
161
|
-
if (expectedType === 'number') value = Number(target);
|
|
162
|
-
else if (expectedType === 'boolean') value = target === 'true' || target === '1';
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
// Transform function
|
|
167
|
-
if (propMeta.transform && typeof propMeta.transform === 'function') {
|
|
168
|
-
value = propMeta.transform(value);
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
return value;
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
/**
|
|
175
|
-
* Hydrates an instance from an array of raw links.
|
|
176
|
-
*
|
|
177
|
-
* Processes properties (latest-wins semantics), relations
|
|
178
|
-
* (chronological accumulation), and timestamps/author in a single
|
|
179
|
-
* pass over the links array.
|
|
180
|
-
*
|
|
181
|
-
* @param instance - The blank model instance to populate
|
|
182
|
-
* @param links - Array of link objects (predicate, target, author?, timestamp?)
|
|
183
|
-
* @param metadata - Model metadata from `getModelMetadata()`
|
|
184
|
-
* @param perspective - The perspective for expression resolution
|
|
185
|
-
* @param requestedProperties - Optional sparse fieldset; when provided, only these
|
|
186
|
-
* property names are hydrated (relations are unaffected).
|
|
187
|
-
* Omit or pass `undefined` to hydrate all properties.
|
|
188
|
-
*/
|
|
189
|
-
export async function hydrateFromLinks(
|
|
190
|
-
instance: any,
|
|
191
|
-
links: Array<{ predicate: string; target: string; author?: string; timestamp?: string | number }>,
|
|
192
|
-
metadata: ModelMetadata,
|
|
193
|
-
perspective: PerspectiveProxy,
|
|
194
|
-
requestedProperties?: string[],
|
|
195
|
-
): Promise<void> {
|
|
196
|
-
if (!links || links.length === 0) return;
|
|
197
|
-
|
|
198
|
-
let minTimestamp: string | number | null = null;
|
|
199
|
-
let maxTimestamp: string | number | null = null;
|
|
200
|
-
let originalAuthor: string | null = null;
|
|
201
|
-
let latestAuthor: string | null = null;
|
|
202
|
-
|
|
203
|
-
// Build predicate→propName and predicate→relName lookup maps for O(1) matching
|
|
204
|
-
// When requestedProperties is provided, only include those properties in the map
|
|
205
|
-
const propFilter = requestedProperties && requestedProperties.length > 0
|
|
206
|
-
? new Set(requestedProperties)
|
|
207
|
-
: null;
|
|
208
|
-
|
|
209
|
-
const predToProperty = new Map<string, [string, PropertyMetadata]>();
|
|
210
|
-
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
211
|
-
if (propMeta.getter) continue; // Handled via custom getter evaluation
|
|
212
|
-
if (propFilter && !propFilter.has(propName)) continue; // Skip unrequested properties
|
|
213
|
-
predToProperty.set(propMeta.predicate, [propName, propMeta]);
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
const predToRelation = new Map<string, [string, RelationMetadata]>();
|
|
217
|
-
|
|
218
|
-
// Two-pass approach: first add all non-getter, non-target-filtered relations,
|
|
219
|
-
// then try to add target+filter relations only if their predicate isn't
|
|
220
|
-
// already claimed. This prevents predicate collisions (e.g. entries +
|
|
221
|
-
// messages sharing the same predicate) while still populating unique-
|
|
222
|
-
// predicate relations normally via link hydration.
|
|
223
|
-
const deferredTargetRelations: [string, RelationMetadata][] = [];
|
|
224
|
-
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
225
|
-
if (relMeta.getter) continue; // Handled via explicit custom getter evaluation
|
|
226
|
-
if (relMeta.target && relMeta.filter !== false) {
|
|
227
|
-
deferredTargetRelations.push([relName, relMeta]);
|
|
228
|
-
continue;
|
|
229
|
-
}
|
|
230
|
-
predToRelation.set(relMeta.predicate, [relName, relMeta]);
|
|
231
|
-
}
|
|
232
|
-
// Second pass: add deferred target+filter relations only if their predicate
|
|
233
|
-
// is not already claimed by a base relation. When a collision exists, the
|
|
234
|
-
// conformance getter will handle the filtered view instead.
|
|
235
|
-
for (const [relName, relMeta] of deferredTargetRelations) {
|
|
236
|
-
if (!predToRelation.has(relMeta.predicate)) {
|
|
237
|
-
predToRelation.set(relMeta.predicate, [relName, relMeta]);
|
|
238
|
-
}
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
// Per-property accumulator: track all matching targets so we can pick the last (latest-wins)
|
|
242
|
-
const propertyLatest = new Map<string, { target: string; timestamp?: string | number }>();
|
|
243
|
-
|
|
244
|
-
// Per-relation accumulator: ordered targets with metadata for sorting
|
|
245
|
-
const relationAccum = new Map<string, Array<{ target: string; timestamp: string | number; index: number }>>();
|
|
246
|
-
|
|
247
|
-
// Single pass over all links
|
|
248
|
-
for (let i = 0; i < links.length; i++) {
|
|
249
|
-
const link = links[i];
|
|
250
|
-
const { predicate, target, author, timestamp } = link;
|
|
251
|
-
if (target === 'None' || target === undefined || target === null) continue;
|
|
252
|
-
|
|
253
|
-
// Track timestamps/authors
|
|
254
|
-
if (timestamp != null) {
|
|
255
|
-
if (minTimestamp == null || timestamp < minTimestamp) {
|
|
256
|
-
minTimestamp = timestamp;
|
|
257
|
-
originalAuthor = author ?? null;
|
|
258
|
-
}
|
|
259
|
-
if (maxTimestamp == null || timestamp > maxTimestamp) {
|
|
260
|
-
maxTimestamp = timestamp;
|
|
261
|
-
latestAuthor = author ?? null;
|
|
262
|
-
}
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
// Property match — accumulate for latest-wins
|
|
266
|
-
const propEntry = predToProperty.get(predicate);
|
|
267
|
-
if (propEntry) {
|
|
268
|
-
const existing = propertyLatest.get(propEntry[0]);
|
|
269
|
-
// Latest-wins: always overwrite (links are ordered ASC so last = latest)
|
|
270
|
-
propertyLatest.set(propEntry[0], { target, timestamp });
|
|
271
|
-
continue;
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
// Relation match — accumulate all
|
|
275
|
-
const relEntry = predToRelation.get(predicate);
|
|
276
|
-
if (relEntry) {
|
|
277
|
-
const [relName] = relEntry;
|
|
278
|
-
let arr = relationAccum.get(relName);
|
|
279
|
-
if (!arr) {
|
|
280
|
-
arr = [];
|
|
281
|
-
relationAccum.set(relName, arr);
|
|
282
|
-
}
|
|
283
|
-
arr.push({ target, timestamp: timestamp ?? '', index: i });
|
|
284
|
-
}
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
// Resolve properties
|
|
288
|
-
for (const [propName, { target }] of propertyLatest) {
|
|
289
|
-
const [, propMeta] = predToProperty.get(
|
|
290
|
-
metadata.properties[propName].predicate
|
|
291
|
-
)!;
|
|
292
|
-
const expectedType = typeof instance[propName];
|
|
293
|
-
instance[propName] = await hydratePropertyValue(
|
|
294
|
-
target,
|
|
295
|
-
propMeta,
|
|
296
|
-
perspective,
|
|
297
|
-
expectedType !== 'undefined' ? expectedType : undefined,
|
|
298
|
-
);
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
// Resolve relations: sort by timestamp (stable via index tiebreaker), filter empties
|
|
302
|
-
for (const [relName, items] of relationAccum) {
|
|
303
|
-
items.sort((a, b) => {
|
|
304
|
-
const cmp = String(a.timestamp).localeCompare(String(b.timestamp));
|
|
305
|
-
return cmp !== 0 ? cmp : a.index - b.index;
|
|
306
|
-
});
|
|
307
|
-
instance[relName] = items
|
|
308
|
-
.map(i => i.target)
|
|
309
|
-
.filter((v: any) => v !== undefined && v !== null && v !== '' && v !== 'None');
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
// Assign author / timestamps
|
|
313
|
-
if (originalAuthor) instance.author = originalAuthor;
|
|
314
|
-
if (minTimestamp != null) {
|
|
315
|
-
instance.createdAt = typeof minTimestamp === 'string' && minTimestamp.includes('T')
|
|
316
|
-
? new Date(minTimestamp).getTime()
|
|
317
|
-
: typeof minTimestamp === 'string'
|
|
318
|
-
? (isNaN(parseInt(minTimestamp, 10)) ? minTimestamp : parseInt(minTimestamp, 10))
|
|
319
|
-
: minTimestamp;
|
|
320
|
-
}
|
|
321
|
-
if (maxTimestamp != null) {
|
|
322
|
-
instance.updatedAt = typeof maxTimestamp === 'string' && maxTimestamp.includes('T')
|
|
323
|
-
? new Date(maxTimestamp).getTime()
|
|
324
|
-
: typeof maxTimestamp === 'string'
|
|
325
|
-
? (isNaN(parseInt(maxTimestamp, 10)) ? maxTimestamp : parseInt(maxTimestamp, 10))
|
|
326
|
-
: maxTimestamp;
|
|
327
|
-
}
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
// ──────────────────────────────────────────────────────────
|
|
331
|
-
// Prolog result hydration (assignValuesToInstance)
|
|
332
|
-
// ──────────────────────────────────────────────────────────
|
|
333
|
-
|
|
334
|
-
/**
|
|
335
|
-
* Assigns decoded Prolog property values to an instance.
|
|
336
|
-
*
|
|
337
|
-
* Handles UTF-8 byte sequence reconstruction, expression resolution,
|
|
338
|
-
* transform functions, and read-only property filtering.
|
|
339
|
-
*/
|
|
340
|
-
export async function assignValuesToInstance(
|
|
341
|
-
perspective: PerspectiveProxy,
|
|
342
|
-
instance: any,
|
|
343
|
-
values: ValueTuple[],
|
|
344
|
-
): Promise<void> {
|
|
345
|
-
// Map properties to object
|
|
346
|
-
const propsObject = Object.fromEntries(
|
|
347
|
-
await Promise.all(
|
|
348
|
-
values.map(async ([name, value, resolve]) => {
|
|
349
|
-
let finalValue = value;
|
|
350
|
-
|
|
351
|
-
// Handle UTF-8 byte sequences from Prolog URL decoding
|
|
352
|
-
if (!resolve && typeof value === 'string') {
|
|
353
|
-
// Only attempt reconstruction if the string looks like a byte string (all code points <= 0xFF)
|
|
354
|
-
// and contains at least one high byte (>= 0x80). This avoids mangling valid Unicode.
|
|
355
|
-
const codePoints = Array.from(value, ch => ch.codePointAt(0)!);
|
|
356
|
-
const looksByteString = codePoints.every(cp => cp <= 0xFF);
|
|
357
|
-
const hasHighByte = codePoints.some(cp => cp >= 0x80);
|
|
358
|
-
if (looksByteString && hasHighByte) {
|
|
359
|
-
try {
|
|
360
|
-
const bytes = Uint8Array.from(codePoints);
|
|
361
|
-
const decoded = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
|
362
|
-
if (decoded !== value) finalValue = decoded;
|
|
363
|
-
} catch (error) {
|
|
364
|
-
// If UTF-8 conversion fails, keep the original value
|
|
365
|
-
console.warn(`UTF-8 byte reconstruction failed for property "${name}"`, { value, error });
|
|
366
|
-
}
|
|
367
|
-
}
|
|
368
|
-
}
|
|
369
|
-
|
|
370
|
-
// Resolve the value if necessary
|
|
371
|
-
if (resolve) {
|
|
372
|
-
let resolvedExpression = await perspective.getExpression(value);
|
|
373
|
-
if (resolvedExpression) {
|
|
374
|
-
try {
|
|
375
|
-
// Attempt to parse the data as JSON
|
|
376
|
-
finalValue = JSON.parse(resolvedExpression.data);
|
|
377
|
-
} catch (error) {
|
|
378
|
-
// If parsing fails, keep the original data
|
|
379
|
-
finalValue = resolvedExpression.data;
|
|
380
|
-
}
|
|
381
|
-
}
|
|
382
|
-
}
|
|
383
|
-
// Apply transform function if it exists
|
|
384
|
-
const propsMeta = getPropertiesMetadata(instance.constructor);
|
|
385
|
-
const transform = propsMeta[name]?.transform;
|
|
386
|
-
if (transform && typeof transform === "function") {
|
|
387
|
-
finalValue = transform(finalValue);
|
|
388
|
-
}
|
|
389
|
-
return [name, finalValue];
|
|
390
|
-
})
|
|
391
|
-
)
|
|
392
|
-
);
|
|
393
|
-
// Filter out properties that are read-only (getters without setters)
|
|
394
|
-
const writableProps = Object.fromEntries(
|
|
395
|
-
Object.entries(propsObject).filter(([key]) => {
|
|
396
|
-
const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(instance), key);
|
|
397
|
-
if (!descriptor) {
|
|
398
|
-
// No descriptor means it's a regular property on the instance, allow it
|
|
399
|
-
return true;
|
|
400
|
-
}
|
|
401
|
-
// Check if it's an accessor descriptor (has get/set) vs data descriptor (has value/writable)
|
|
402
|
-
const isAccessor = descriptor.get !== undefined || descriptor.set !== undefined;
|
|
403
|
-
if (isAccessor) {
|
|
404
|
-
// Accessor descriptor: only allow if it has a setter
|
|
405
|
-
return descriptor.set !== undefined;
|
|
406
|
-
} else {
|
|
407
|
-
// Data descriptor: only allow if writable is not explicitly false
|
|
408
|
-
return descriptor.writable !== false;
|
|
409
|
-
}
|
|
410
|
-
})
|
|
411
|
-
);
|
|
412
|
-
// Assign properties to instance
|
|
413
|
-
Object.assign(instance, writableProps);
|
|
414
|
-
}
|
|
415
|
-
|
|
416
103
|
// ──────────────────────────────────────────────────────────
|
|
417
104
|
// SPARQL custom getter evaluation
|
|
418
105
|
// ──────────────────────────────────────────────────────────
|
|
@@ -615,447 +302,3 @@ export async function evaluateCustomGettersForInstance(
|
|
|
615
302
|
}
|
|
616
303
|
}
|
|
617
304
|
}
|
|
618
|
-
|
|
619
|
-
/**
|
|
620
|
-
* Hydrates relation fields on instances according to the provided IncludeMap.
|
|
621
|
-
*
|
|
622
|
-
* For each relation listed in `includeMap`, the raw expression-URI strings
|
|
623
|
-
* stored on the instance are replaced with fully-hydrated model instances
|
|
624
|
-
* (fetched via the relation's `target()` class). Nested IncludeMaps are
|
|
625
|
-
* supported for multi-level eager loading.
|
|
626
|
-
*
|
|
627
|
-
* @param modelClass - The model class whose relation metadata to read
|
|
628
|
-
* @param instances - The instances whose relations should be hydrated
|
|
629
|
-
* @param perspective - The perspective to fetch related instances from
|
|
630
|
-
* @param includeMap - Describes which relations to hydrate
|
|
631
|
-
*/
|
|
632
|
-
export async function hydrateRelations<T>(
|
|
633
|
-
modelClass: any,
|
|
634
|
-
instances: T[],
|
|
635
|
-
perspective: PerspectiveProxy,
|
|
636
|
-
includeMap: IncludeMap | undefined,
|
|
637
|
-
): Promise<void> {
|
|
638
|
-
if (!includeMap || Object.keys(includeMap).length === 0) return;
|
|
639
|
-
|
|
640
|
-
const relMeta = getRelationsMetadata(modelClass);
|
|
641
|
-
|
|
642
|
-
// ── Projections ($-prefixed keys) ────────────────────────────────────────
|
|
643
|
-
// Collect all projection entries up-front so we can batch the count queries
|
|
644
|
-
// together per-projection before processing. Each projection key starts
|
|
645
|
-
// with '$' and has a descriptor with a `from` field.
|
|
646
|
-
const projectionEntries: Array<[string, IncludeProjection]> = [];
|
|
647
|
-
for (const [key, val] of Object.entries(includeMap)) {
|
|
648
|
-
if (key.startsWith('$') && val !== null && typeof val === 'object' && 'from' in val) {
|
|
649
|
-
projectionEntries.push([key, val as IncludeProjection]);
|
|
650
|
-
}
|
|
651
|
-
}
|
|
652
|
-
|
|
653
|
-
for (const [projKey, proj] of projectionEntries) {
|
|
654
|
-
const sourceMeta: RelationMetadataEntry | undefined = relMeta[proj.from];
|
|
655
|
-
if (!sourceMeta) {
|
|
656
|
-
console.warn(`include projection "${projKey}": relation "${proj.from}" not found in metadata, skipping`);
|
|
657
|
-
for (const inst of instances) (inst as any)[projKey] = proj.count ? 0 : [];
|
|
658
|
-
continue;
|
|
659
|
-
}
|
|
660
|
-
|
|
661
|
-
const TargetClass = sourceMeta.target() as any;
|
|
662
|
-
const allParentIds = instances.map(inst => (inst as any).id).filter(Boolean) as string[];
|
|
663
|
-
|
|
664
|
-
if (proj.count) {
|
|
665
|
-
// ── Path A: grouped SPARQL COUNT ─────────────────────────────────────
|
|
666
|
-
// One round-trip, zero instance hydration. Returns one row per parent.
|
|
667
|
-
const targetMetadata = TargetClass.getModelMetadata?.() ?? null;
|
|
668
|
-
const targetRelMeta = TargetClass.getAllRelationsMetadata?.() ?? {};
|
|
669
|
-
let countMap = new Map<string, number>();
|
|
670
|
-
|
|
671
|
-
if (targetMetadata && allParentIds.length > 0) {
|
|
672
|
-
try {
|
|
673
|
-
const sparql = buildSPARQLGroupedCountQuery(
|
|
674
|
-
targetMetadata,
|
|
675
|
-
targetRelMeta,
|
|
676
|
-
sourceMeta.predicate,
|
|
677
|
-
allParentIds,
|
|
678
|
-
proj.where,
|
|
679
|
-
);
|
|
680
|
-
const raw = await perspective.querySparql(sparql);
|
|
681
|
-
const rows = Array.isArray(raw) ? raw
|
|
682
|
-
: raw?.results?.bindings ?? raw?.bindings ?? [];
|
|
683
|
-
countMap = parseSparqlGroupedCount(rows);
|
|
684
|
-
} catch (e) {
|
|
685
|
-
console.warn(`include projection "${projKey}" count query failed, falling back to 0:`, e);
|
|
686
|
-
}
|
|
687
|
-
}
|
|
688
|
-
|
|
689
|
-
for (const inst of instances) {
|
|
690
|
-
(inst as any)[projKey] = countMap.get((inst as any).id) ?? 0;
|
|
691
|
-
}
|
|
692
|
-
} else {
|
|
693
|
-
// ── Path B: findAll + Map distribution ───────────────────────────────
|
|
694
|
-
// For reverse relations we don't have the child IDs on the instance,
|
|
695
|
-
// so fall back to a parent-scoped findAll per instance (uncommon path).
|
|
696
|
-
const isReverse = sourceMeta.kind === 'belongsToOne' || sourceMeta.kind === 'belongsToMany';
|
|
697
|
-
|
|
698
|
-
if (isReverse) {
|
|
699
|
-
// Reverse: the link goes child→parent, reuse the batched SPARQL pattern
|
|
700
|
-
// from the existing belongsTo path to collect source IDs per parent.
|
|
701
|
-
if (allParentIds.length > 0) {
|
|
702
|
-
const sparqlQuery = `SELECT ?source ?target WHERE {
|
|
703
|
-
GRAPH ?g { ?source <${sourceMeta.predicate}> ?target }
|
|
704
|
-
FILTER(?target IN (${allParentIds.map(id => `<${id}>`).join(', ')}))
|
|
705
|
-
}`;
|
|
706
|
-
const sourcesByTarget = new Map<string, string[]>();
|
|
707
|
-
try {
|
|
708
|
-
const raw = await perspective.querySparql(sparqlQuery);
|
|
709
|
-
const bindings = Array.isArray(raw) ? raw : raw?.results?.bindings ?? raw?.bindings ?? [];
|
|
710
|
-
for (const row of bindings) {
|
|
711
|
-
const source = row.source?.value ?? row.source;
|
|
712
|
-
const target = row.target?.value ?? row.target;
|
|
713
|
-
if (!source || !target) continue;
|
|
714
|
-
if (!sourcesByTarget.has(target)) sourcesByTarget.set(target, []);
|
|
715
|
-
sourcesByTarget.get(target)!.push(source);
|
|
716
|
-
}
|
|
717
|
-
} catch (e) {
|
|
718
|
-
console.warn(`include projection "${projKey}" reverse SPARQL failed:`, e);
|
|
719
|
-
}
|
|
720
|
-
|
|
721
|
-
const allSourceIds = new Set<string>();
|
|
722
|
-
for (const ids of sourcesByTarget.values()) for (const id of ids) allSourceIds.add(id);
|
|
723
|
-
|
|
724
|
-
const hydratedMap = new Map<string, any>();
|
|
725
|
-
if (allSourceIds.size > 0) {
|
|
726
|
-
const results = await TargetClass.findAll(perspective, {
|
|
727
|
-
where: { id: Array.from(allSourceIds), ...(proj.where ?? {}) },
|
|
728
|
-
});
|
|
729
|
-
for (const r of results) hydratedMap.set(r.id, r);
|
|
730
|
-
}
|
|
731
|
-
|
|
732
|
-
for (const inst of instances) {
|
|
733
|
-
const sourceIds = sourcesByTarget.get((inst as any).id) ?? [];
|
|
734
|
-
let resolved = sourceIds.map(id => hydratedMap.get(id)).filter((v: any): v is any => v != null);
|
|
735
|
-
if (proj.limit != null) {
|
|
736
|
-
if (proj.limit === 1) {
|
|
737
|
-
(inst as any)[projKey] = resolved[0] ?? null;
|
|
738
|
-
} else {
|
|
739
|
-
(inst as any)[projKey] = resolved.slice(0, proj.limit);
|
|
740
|
-
}
|
|
741
|
-
} else {
|
|
742
|
-
(inst as any)[projKey] = resolved;
|
|
743
|
-
}
|
|
744
|
-
}
|
|
745
|
-
} else {
|
|
746
|
-
for (const inst of instances) (inst as any)[projKey] = proj.limit === 1 ? null : [];
|
|
747
|
-
}
|
|
748
|
-
} else {
|
|
749
|
-
// Forward: instance[from] holds raw child URIs — collect across all parents
|
|
750
|
-
const uriSet = new Set<string>();
|
|
751
|
-
const rawCache = new Map<any, string[]>();
|
|
752
|
-
for (const inst of instances) {
|
|
753
|
-
const raw = (inst as any)[proj.from];
|
|
754
|
-
const uris: string[] = [];
|
|
755
|
-
if (Array.isArray(raw)) {
|
|
756
|
-
for (const v of raw) {
|
|
757
|
-
const id = typeof v === 'string' ? v : v?.id;
|
|
758
|
-
if (id) { uriSet.add(id); uris.push(id); }
|
|
759
|
-
}
|
|
760
|
-
} else if (typeof raw === 'string') {
|
|
761
|
-
uriSet.add(raw); uris.push(raw);
|
|
762
|
-
} else if (raw?.id) {
|
|
763
|
-
uriSet.add(raw.id); uris.push(raw.id);
|
|
764
|
-
}
|
|
765
|
-
rawCache.set(inst, uris);
|
|
766
|
-
}
|
|
767
|
-
|
|
768
|
-
const hydratedMap = new Map<string, any>();
|
|
769
|
-
if (uriSet.size > 0) {
|
|
770
|
-
const results = await TargetClass.findAll(perspective, {
|
|
771
|
-
where: { id: Array.from(uriSet), ...(proj.where ?? {}) },
|
|
772
|
-
});
|
|
773
|
-
for (const r of results) hydratedMap.set(r.id, r);
|
|
774
|
-
}
|
|
775
|
-
|
|
776
|
-
for (const inst of instances) {
|
|
777
|
-
const uris = rawCache.get(inst) ?? [];
|
|
778
|
-
const resolved = uris.map(id => hydratedMap.get(id)).filter((v: any): v is any => v != null);
|
|
779
|
-
if (proj.limit === 1) {
|
|
780
|
-
(inst as any)[projKey] = resolved[0] ?? null;
|
|
781
|
-
} else if (proj.limit != null) {
|
|
782
|
-
(inst as any)[projKey] = resolved.slice(0, proj.limit);
|
|
783
|
-
} else {
|
|
784
|
-
(inst as any)[projKey] = resolved;
|
|
785
|
-
}
|
|
786
|
-
}
|
|
787
|
-
}
|
|
788
|
-
}
|
|
789
|
-
}
|
|
790
|
-
|
|
791
|
-
// ── Standard relations (non-projected) ───────────────────────────────────
|
|
792
|
-
for (const [relName, includeValue] of Object.entries(includeMap)) {
|
|
793
|
-
// Skip projection keys — already handled above
|
|
794
|
-
if (relName.startsWith('$') && typeof includeValue === 'object' && includeValue !== null && 'from' in includeValue) continue;
|
|
795
|
-
|
|
796
|
-
const meta: RelationMetadataEntry | undefined = relMeta[relName];
|
|
797
|
-
if (!meta) {
|
|
798
|
-
console.warn(`include: relation "${relName}" not found in metadata, skipping`);
|
|
799
|
-
continue;
|
|
800
|
-
}
|
|
801
|
-
|
|
802
|
-
const TargetClass = meta.target() as any;
|
|
803
|
-
|
|
804
|
-
// Determine if a RelationSubQuery was supplied (object) vs a plain `true`
|
|
805
|
-
const subQuery: RelationSubQuery | undefined =
|
|
806
|
-
typeof includeValue === 'object' && includeValue !== null
|
|
807
|
-
? (includeValue as RelationSubQuery)
|
|
808
|
-
: undefined;
|
|
809
|
-
const nestedInclude: IncludeMap | undefined = subQuery?.include;
|
|
810
|
-
|
|
811
|
-
// ── Reverse relations (belongsToOne / belongsToMany) ──────────────────
|
|
812
|
-
// The link goes target→instance, so we query backwards:
|
|
813
|
-
// predicate = meta.predicate, target = inst.id → source is the related id
|
|
814
|
-
//
|
|
815
|
-
// PERF: Batch all reverse lookups into a single SPARQL query instead of
|
|
816
|
-
// N sequential perspective.get() calls (N+1 → 1 optimisation).
|
|
817
|
-
if (meta.kind === 'belongsToOne' || meta.kind === 'belongsToMany') {
|
|
818
|
-
const allIds = instances.map(inst => (inst as any).id).filter(Boolean);
|
|
819
|
-
|
|
820
|
-
// Batch query: find all (source, target) pairs for this predicate
|
|
821
|
-
// where target is one of our instance IDs
|
|
822
|
-
const sourcesByTarget = new Map<string, string[]>();
|
|
823
|
-
if (allIds.length > 0) {
|
|
824
|
-
const sparqlQuery = `SELECT ?source ?target WHERE {
|
|
825
|
-
GRAPH ?g { ?source <${meta.predicate}> ?target }
|
|
826
|
-
FILTER(?target IN (${allIds.map(id => `<${id}>`).join(', ')}))
|
|
827
|
-
}`;
|
|
828
|
-
try {
|
|
829
|
-
const sparqlResult = await perspective.querySparql(sparqlQuery);
|
|
830
|
-
// Parse SPARQL results — querySparql returns a flat array of row objects
|
|
831
|
-
// e.g. [{ source: "uri1", target: "uri2" }, ...]
|
|
832
|
-
const bindings = Array.isArray(sparqlResult) ? sparqlResult
|
|
833
|
-
: sparqlResult?.results?.bindings ?? sparqlResult?.bindings ?? [];
|
|
834
|
-
for (const row of bindings) {
|
|
835
|
-
const source = row.source?.value ?? row.source;
|
|
836
|
-
const target = row.target?.value ?? row.target;
|
|
837
|
-
if (!source || !target) continue;
|
|
838
|
-
if (!sourcesByTarget.has(target)) sourcesByTarget.set(target, []);
|
|
839
|
-
sourcesByTarget.get(target)!.push(source);
|
|
840
|
-
}
|
|
841
|
-
} catch (e) {
|
|
842
|
-
// Fallback: sequential queries if SPARQL fails
|
|
843
|
-
console.warn('Batched reverse relation SPARQL failed, falling back to sequential:', e);
|
|
844
|
-
for (const inst of instances) {
|
|
845
|
-
const reverseLinks = await perspective.get(
|
|
846
|
-
new LinkQuery({ predicate: meta.predicate, target: (inst as any).id })
|
|
847
|
-
);
|
|
848
|
-
const sourceIds = reverseLinks
|
|
849
|
-
.filter(l => l.data.target === (inst as any).id)
|
|
850
|
-
.map(l => l.data.source);
|
|
851
|
-
if (sourceIds.length > 0) {
|
|
852
|
-
sourcesByTarget.set((inst as any).id, sourceIds);
|
|
853
|
-
}
|
|
854
|
-
}
|
|
855
|
-
}
|
|
856
|
-
}
|
|
857
|
-
|
|
858
|
-
// Collect ALL source IDs across all instances for batch hydration
|
|
859
|
-
const allSourceIds = new Set<string>();
|
|
860
|
-
for (const ids of sourcesByTarget.values()) {
|
|
861
|
-
for (const id of ids) allSourceIds.add(id);
|
|
862
|
-
}
|
|
863
|
-
|
|
864
|
-
// Batch-hydrate all related instances at once (1 findAll instead of N)
|
|
865
|
-
const hydratedMap = new Map<string, any>();
|
|
866
|
-
if (allSourceIds.size > 0) {
|
|
867
|
-
const fetchQuery: any = {
|
|
868
|
-
where: {
|
|
869
|
-
id: Array.from(allSourceIds),
|
|
870
|
-
...(subQuery?.where ?? {}),
|
|
871
|
-
},
|
|
872
|
-
...(subQuery?.order && { order: subQuery.order }),
|
|
873
|
-
...(subQuery?.properties && { properties: subQuery.properties }),
|
|
874
|
-
};
|
|
875
|
-
try {
|
|
876
|
-
const allResults = await TargetClass.findAll(perspective, fetchQuery);
|
|
877
|
-
for (const r of allResults) hydratedMap.set(r.id, r);
|
|
878
|
-
} catch {
|
|
879
|
-
// Fallback: hydrate individually
|
|
880
|
-
await Promise.all(Array.from(allSourceIds).map(async (sid) => {
|
|
881
|
-
try {
|
|
882
|
-
const related = new TargetClass(perspective, sid);
|
|
883
|
-
await related.get(
|
|
884
|
-
subQuery?.properties ? { properties: subQuery.properties } : undefined
|
|
885
|
-
);
|
|
886
|
-
hydratedMap.set(sid, related);
|
|
887
|
-
} catch { /* skip */ }
|
|
888
|
-
}));
|
|
889
|
-
}
|
|
890
|
-
}
|
|
891
|
-
|
|
892
|
-
// Assign hydrated instances to each parent
|
|
893
|
-
for (const inst of instances) {
|
|
894
|
-
const instId = (inst as any).id;
|
|
895
|
-
const sourceIds = sourcesByTarget.get(instId) ?? [];
|
|
896
|
-
|
|
897
|
-
if (meta.kind === 'belongsToOne') {
|
|
898
|
-
if (sourceIds.length === 0) {
|
|
899
|
-
(inst as any)[relName] = null;
|
|
900
|
-
continue;
|
|
901
|
-
}
|
|
902
|
-
const sourceId = sourceIds[sourceIds.length - 1]; // latest-wins
|
|
903
|
-
(inst as any)[relName] = hydratedMap.get(sourceId) ?? null;
|
|
904
|
-
} else {
|
|
905
|
-
// belongsToMany — return array of hydrated instances
|
|
906
|
-
let hydrated = sourceIds
|
|
907
|
-
.map(sid => hydratedMap.get(sid))
|
|
908
|
-
.filter((v: any): v is any => v != null);
|
|
909
|
-
|
|
910
|
-
// Apply order (client-side)
|
|
911
|
-
if (subQuery?.order) {
|
|
912
|
-
const orderEntries = Object.entries(subQuery.order);
|
|
913
|
-
hydrated = hydrated.sort((a: any, b: any) => {
|
|
914
|
-
for (const [field, dir] of orderEntries) {
|
|
915
|
-
const av = String(a[field] ?? '');
|
|
916
|
-
const bv = String(b[field] ?? '');
|
|
917
|
-
const diff = av.localeCompare(bv);
|
|
918
|
-
if (diff !== 0) return dir === 'DESC' ? -diff : diff;
|
|
919
|
-
}
|
|
920
|
-
return 0;
|
|
921
|
-
});
|
|
922
|
-
}
|
|
923
|
-
|
|
924
|
-
// Apply offset and limit
|
|
925
|
-
if (subQuery?.offset != null || subQuery?.limit != null) {
|
|
926
|
-
const start = subQuery.offset ?? 0;
|
|
927
|
-
const end = subQuery.limit != null ? start + subQuery.limit : undefined;
|
|
928
|
-
hydrated = hydrated.slice(start, end);
|
|
929
|
-
}
|
|
930
|
-
|
|
931
|
-
(inst as any)[relName] = hydrated;
|
|
932
|
-
|
|
933
|
-
// Recurse for nested includes
|
|
934
|
-
if (nestedInclude && hydrated.length > 0) {
|
|
935
|
-
await hydrateRelations(TargetClass, hydrated, perspective, nestedInclude);
|
|
936
|
-
}
|
|
937
|
-
}
|
|
938
|
-
}
|
|
939
|
-
continue; // skip the forward-relation path below
|
|
940
|
-
}
|
|
941
|
-
|
|
942
|
-
// ── Forward relations (hasMany / hasOne) ──────────────────────────────
|
|
943
|
-
// Collect all unique URIs across all instances for batch-friendly lookup.
|
|
944
|
-
// IMPORTANT: We cache each instance's raw value NOW (before the async
|
|
945
|
-
// findAll) so that concurrent getData() calls on the same instance can't
|
|
946
|
-
// overwrite the relation field between the uriSet relation and the
|
|
947
|
-
// post-await assignment loop. Without this cache, a concurrent call
|
|
948
|
-
// can replace the raw URI strings with hydrated model objects, causing
|
|
949
|
-
// the `typeof v === 'string'` check to fail and the array to end up empty.
|
|
950
|
-
const uriSet = new Set<string>();
|
|
951
|
-
const rawCache = new Map<T, any>();
|
|
952
|
-
for (const inst of instances) {
|
|
953
|
-
const raw = (inst as any)[relName];
|
|
954
|
-
rawCache.set(inst, Array.isArray(raw) ? [...raw] : raw);
|
|
955
|
-
if (raw == null) continue;
|
|
956
|
-
if (Array.isArray(raw)) {
|
|
957
|
-
for (const v of raw) {
|
|
958
|
-
if (typeof v === 'string') uriSet.add(v);
|
|
959
|
-
// Handle already-hydrated instances (from a concurrent call)
|
|
960
|
-
else if (v && typeof v === 'object' && typeof v.id === 'string') uriSet.add(v.id);
|
|
961
|
-
}
|
|
962
|
-
} else if (typeof raw === 'string') {
|
|
963
|
-
uriSet.add(raw);
|
|
964
|
-
} else if (raw && typeof raw === 'object' && typeof raw.id === 'string') {
|
|
965
|
-
uriSet.add(raw.id);
|
|
966
|
-
}
|
|
967
|
-
}
|
|
968
|
-
|
|
969
|
-
if (uriSet.size === 0) continue;
|
|
970
|
-
|
|
971
|
-
// Hydrate related instances using findAll to ensure conformance checking.
|
|
972
|
-
// findAll validates model membership via graph traversal (required predicates / flags),
|
|
973
|
-
// so non-conforming linked URIs are silently dropped — matching the documented behaviour.
|
|
974
|
-
const hydrated = new Map<string, any>();
|
|
975
|
-
|
|
976
|
-
const whereWithIds: Record<string, any> = {
|
|
977
|
-
id: Array.from(uriSet),
|
|
978
|
-
...(subQuery?.where ?? {}),
|
|
979
|
-
};
|
|
980
|
-
const fetchQuery: any = {
|
|
981
|
-
where: whereWithIds,
|
|
982
|
-
...(subQuery?.order && { order: subQuery.order }),
|
|
983
|
-
...(subQuery?.properties && { properties: subQuery.properties }),
|
|
984
|
-
};
|
|
985
|
-
const results = await TargetClass.findAll(perspective, fetchQuery);
|
|
986
|
-
for (const result of results) {
|
|
987
|
-
hydrated.set(result.id, result);
|
|
988
|
-
}
|
|
989
|
-
|
|
990
|
-
// Replace raw URIs with hydrated instances on each parent instance.
|
|
991
|
-
// Use the cached raw values captured BEFORE the async findAll to avoid
|
|
992
|
-
// the race condition where a concurrent getData() already replaced the
|
|
993
|
-
// strings with hydrated objects.
|
|
994
|
-
for (const inst of instances) {
|
|
995
|
-
const raw = rawCache.get(inst);
|
|
996
|
-
if (raw == null) continue;
|
|
997
|
-
if (Array.isArray(raw)) {
|
|
998
|
-
// Map URIs → instances; handle both raw strings and already-hydrated objects
|
|
999
|
-
let resolved: any[] = raw
|
|
1000
|
-
.map((v: any) => {
|
|
1001
|
-
if (typeof v === 'string') {
|
|
1002
|
-
return hydrated.has(v) ? hydrated.get(v)! : null;
|
|
1003
|
-
}
|
|
1004
|
-
// Already a hydrated model instance (from a concurrent call)
|
|
1005
|
-
if (v && typeof v === 'object' && typeof v.id === 'string') {
|
|
1006
|
-
return hydrated.has(v.id) ? hydrated.get(v.id)! : v;
|
|
1007
|
-
}
|
|
1008
|
-
return null;
|
|
1009
|
-
})
|
|
1010
|
-
.filter((v: any): v is any => v !== null);
|
|
1011
|
-
|
|
1012
|
-
// Per-instance sort (client-side, after filtering)
|
|
1013
|
-
if (subQuery?.order) {
|
|
1014
|
-
const orderEntries = Object.entries(subQuery.order);
|
|
1015
|
-
resolved = resolved.sort((a: any, b: any) => {
|
|
1016
|
-
for (const [field, dir] of orderEntries) {
|
|
1017
|
-
const av = String(a[field] ?? '');
|
|
1018
|
-
const bv = String(b[field] ?? '');
|
|
1019
|
-
const diff = av.localeCompare(bv);
|
|
1020
|
-
if (diff !== 0) return dir === 'DESC' ? -diff : diff;
|
|
1021
|
-
}
|
|
1022
|
-
return 0;
|
|
1023
|
-
});
|
|
1024
|
-
}
|
|
1025
|
-
|
|
1026
|
-
// Per-instance limit / offset
|
|
1027
|
-
if (subQuery?.offset != null || subQuery?.limit != null) {
|
|
1028
|
-
const start = subQuery.offset ?? 0;
|
|
1029
|
-
const end =
|
|
1030
|
-
subQuery.limit != null ? start + subQuery.limit : undefined;
|
|
1031
|
-
resolved = resolved.slice(start, end);
|
|
1032
|
-
}
|
|
1033
|
-
|
|
1034
|
-
// Enforce maxCount guard — single-valued relations keep only the last item
|
|
1035
|
-
if (meta.maxCount === 1) {
|
|
1036
|
-
if (resolved.length > 1) {
|
|
1037
|
-
console.warn(
|
|
1038
|
-
`include: relation "${relName}" has maxCount 1 but ${resolved.length} values found; keeping the last`,
|
|
1039
|
-
);
|
|
1040
|
-
}
|
|
1041
|
-
(inst as any)[relName] = resolved.length > 0
|
|
1042
|
-
? resolved[resolved.length - 1]
|
|
1043
|
-
: null;
|
|
1044
|
-
} else {
|
|
1045
|
-
(inst as any)[relName] = resolved;
|
|
1046
|
-
}
|
|
1047
|
-
} else if (typeof raw === 'string' && hydrated.has(raw)) {
|
|
1048
|
-
(inst as any)[relName] = hydrated.get(raw);
|
|
1049
|
-
} else if (raw && typeof raw === 'object' && typeof raw.id === 'string') {
|
|
1050
|
-
// Already-hydrated object — look up refreshed version or keep as-is
|
|
1051
|
-
(inst as any)[relName] = hydrated.has(raw.id) ? hydrated.get(raw.id) : raw;
|
|
1052
|
-
}
|
|
1053
|
-
}
|
|
1054
|
-
|
|
1055
|
-
// Recurse for nested includes
|
|
1056
|
-
if (nestedInclude) {
|
|
1057
|
-
const hydratedInstances = Array.from(hydrated.values());
|
|
1058
|
-
await hydrateRelations(TargetClass, hydratedInstances, perspective, nestedInclude);
|
|
1059
|
-
}
|
|
1060
|
-
}
|
|
1061
|
-
}
|