@coasys/ad4m 0.13.0-test-interpretation-1 → 0.13.0-test-model-layer

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.
Files changed (279) hide show
  1. package/lib/index.cjs +2409 -625
  2. package/lib/index.js +2406 -626
  3. package/lib/src/Literal.js +8 -0
  4. package/lib/src/ai/AIClient.js +6 -3
  5. package/lib/src/apiClient.d.ts +40 -4
  6. package/lib/src/apiClient.js +149 -9
  7. package/lib/src/generated/api/RunInterpretationRequest.d.ts +16 -0
  8. package/lib/src/index.d.ts +3 -1
  9. package/lib/src/index.js +2 -0
  10. package/lib/src/model/Ad4mModel.d.ts +34 -16
  11. package/lib/src/model/Ad4mModel.js +302 -63
  12. package/lib/src/model/Ad4mModel.test.js +480 -735
  13. package/lib/src/model/ModelQueryBuilder.js +2 -2
  14. package/lib/src/model/decorators.d.ts +199 -12
  15. package/lib/src/model/decorators.js +88 -32
  16. package/lib/src/model/json-schema.js +7 -21
  17. package/lib/src/model/model-manifest.d.ts +41 -0
  18. package/lib/src/model/model-manifest.js +11 -0
  19. package/lib/src/model/query-common.d.ts +2 -2
  20. package/lib/src/model/query-sparql.d.ts +62 -0
  21. package/lib/src/model/query-sparql.js +78 -15
  22. package/lib/src/model/query-sparql.test.js +92 -10
  23. package/lib/src/model/query-utils.d.ts +7 -2
  24. package/lib/src/model/query-utils.js +21 -11
  25. package/lib/src/model/shacl-gen.js +77 -15
  26. package/lib/src/model/types.d.ts +32 -8
  27. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +33 -33
  28. package/lib/src/perspectives/AutoProcessor.d.ts +198 -2
  29. package/lib/src/perspectives/FlowInstance.d.ts +187 -0
  30. package/lib/src/perspectives/FlowInstance.js +336 -0
  31. package/lib/src/perspectives/FlowModels.d.ts +94 -0
  32. package/lib/src/perspectives/FlowModels.js +182 -0
  33. package/lib/src/perspectives/InterpretationModels.d.ts +41 -3
  34. package/lib/src/perspectives/InterpretationModels.js +60 -26
  35. package/lib/src/perspectives/PerspectiveClient.d.ts +88 -7
  36. package/lib/src/perspectives/PerspectiveClient.js +138 -11
  37. package/lib/src/perspectives/PerspectiveProxy.d.ts +150 -57
  38. package/lib/src/perspectives/PerspectiveProxy.js +411 -287
  39. package/lib/src/perspectives/SparqlBindings.d.ts +24 -3
  40. package/lib/src/perspectives/SparqlBindings.js +57 -6
  41. package/lib/src/shacl/SHACLFlow.d.ts +273 -47
  42. package/lib/src/shacl/SHACLFlow.js +397 -88
  43. package/lib/src/shacl/SHACLShape.d.ts +19 -3
  44. package/lib/src/shacl/SHACLShape.js +30 -1
  45. package/lib/src/shacl/SHACLShape.test.js +82 -0
  46. package/lib/src/shacl/index.d.ts +1 -1
  47. package/lib/src/shacl/index.js +1 -1
  48. package/package.json +3 -3
  49. package/src/Literal.ts +7 -0
  50. package/src/ai/AIClient.ts +6 -3
  51. package/src/apiClient.test.ts +227 -0
  52. package/src/apiClient.ts +185 -9
  53. package/src/generated/api/RunInterpretationRequest.ts +19 -3
  54. package/src/index.ts +3 -1
  55. package/src/model/Ad4mModel.test.ts +729 -22
  56. package/src/model/Ad4mModel.ts +305 -66
  57. package/src/model/ModelQueryBuilder.ts +2 -2
  58. package/src/model/decorators.ts +278 -44
  59. package/src/model/json-schema.ts +10 -25
  60. package/src/model/query-common.ts +2 -2
  61. package/src/model/query-sparql.test.ts +114 -13
  62. package/src/model/query-sparql.ts +83 -14
  63. package/src/model/query-utils.ts +22 -12
  64. package/src/model/relation-filtering.test.ts +70 -20
  65. package/src/model/shacl-gen.ts +78 -13
  66. package/src/model/shacl-roundtrip.test.ts +134 -2
  67. package/src/model/types.ts +30 -8
  68. package/src/perspectives/AutoProcessor.ts +204 -2
  69. package/src/perspectives/FlowInstance.ts +369 -0
  70. package/src/perspectives/FlowModels.ts +157 -0
  71. package/src/perspectives/InterpretationModels.ts +91 -21
  72. package/src/perspectives/PerspectiveClient.test.ts +67 -6
  73. package/src/perspectives/PerspectiveClient.ts +190 -14
  74. package/src/perspectives/PerspectiveProxy.test.ts +406 -0
  75. package/src/perspectives/PerspectiveProxy.ts +494 -308
  76. package/src/perspectives/SparqlBindings.test.ts +134 -0
  77. package/src/perspectives/SparqlBindings.ts +57 -6
  78. package/src/perspectives/shacl-rpc.test.ts +258 -0
  79. package/src/shacl/SHACLFlow.test.ts +762 -35
  80. package/src/shacl/SHACLFlow.ts +680 -112
  81. package/src/shacl/SHACLShape.test.ts +30 -4
  82. package/src/shacl/SHACLShape.ts +59 -6
  83. package/src/shacl/index.ts +1 -1
  84. package/lib/src/generated/rest/AIModelLoadingStatus.d.ts +0 -7
  85. package/lib/src/generated/rest/AIModelLoadingStatus.js +0 -2
  86. package/lib/src/generated/rest/AddAgentInfosRequest.d.ts +0 -3
  87. package/lib/src/generated/rest/AddAgentInfosRequest.js +0 -2
  88. package/lib/src/generated/rest/AddLinkExpressionRequest.d.ts +0 -6
  89. package/lib/src/generated/rest/AddLinkExpressionRequest.js +0 -1
  90. package/lib/src/generated/rest/AddLinkRequest.d.ts +0 -6
  91. package/lib/src/generated/rest/AddLinkRequest.js +0 -1
  92. package/lib/src/generated/rest/AddLinksBulkRequest.d.ts +0 -6
  93. package/lib/src/generated/rest/AddLinksBulkRequest.js +0 -1
  94. package/lib/src/generated/rest/AddSdnaRequest.d.ts +0 -6
  95. package/lib/src/generated/rest/AddSdnaRequest.js +0 -2
  96. package/lib/src/generated/rest/ApplyTemplateRequest.d.ts +0 -4
  97. package/lib/src/generated/rest/ApplyTemplateRequest.js +0 -2
  98. package/lib/src/generated/rest/AuthInfoInput.d.ts +0 -10
  99. package/lib/src/generated/rest/AuthInfoInput.js +0 -1
  100. package/lib/src/generated/rest/BroadcastRequest.d.ts +0 -6
  101. package/lib/src/generated/rest/BroadcastRequest.js +0 -1
  102. package/lib/src/generated/rest/CapabilityInput.d.ts +0 -5
  103. package/lib/src/generated/rest/CapabilityInput.js +0 -1
  104. package/lib/src/generated/rest/CommitBatchRequest.d.ts +0 -3
  105. package/lib/src/generated/rest/CommitBatchRequest.js +0 -2
  106. package/lib/src/generated/rest/ComputeLogEntry.d.ts +0 -9
  107. package/lib/src/generated/rest/ComputeLogEntry.js +0 -2
  108. package/lib/src/generated/rest/CreateExpressionRequest.d.ts +0 -4
  109. package/lib/src/generated/rest/CreateExpressionRequest.js +0 -2
  110. package/lib/src/generated/rest/CreatePerspectiveRequest.d.ts +0 -3
  111. package/lib/src/generated/rest/CreatePerspectiveRequest.js +0 -2
  112. package/lib/src/generated/rest/CreateSubjectRequest.d.ts +0 -6
  113. package/lib/src/generated/rest/CreateSubjectRequest.js +0 -2
  114. package/lib/src/generated/rest/CreateUserRequest.d.ts +0 -4
  115. package/lib/src/generated/rest/CreateUserRequest.js +0 -2
  116. package/lib/src/generated/rest/CreateUserResponse.d.ts +0 -5
  117. package/lib/src/generated/rest/CreateUserResponse.js +0 -2
  118. package/lib/src/generated/rest/DecoratedExpressionProof.d.ts +0 -6
  119. package/lib/src/generated/rest/DecoratedExpressionProof.js +0 -2
  120. package/lib/src/generated/rest/DecoratedLinkExpression.d.ts +0 -10
  121. package/lib/src/generated/rest/DecoratedLinkExpression.js +0 -1
  122. package/lib/src/generated/rest/DisposeQueryRequest.d.ts +0 -3
  123. package/lib/src/generated/rest/DisposeQueryRequest.js +0 -2
  124. package/lib/src/generated/rest/EmailTestRequest.d.ts +0 -6
  125. package/lib/src/generated/rest/EmailTestRequest.js +0 -2
  126. package/lib/src/generated/rest/EmbedRequest.d.ts +0 -4
  127. package/lib/src/generated/rest/EmbedRequest.js +0 -2
  128. package/lib/src/generated/rest/EntanglementProofInput.d.ts +0 -6
  129. package/lib/src/generated/rest/EntanglementProofInput.js +0 -2
  130. package/lib/src/generated/rest/EntanglementProofPreflightRequest.d.ts +0 -4
  131. package/lib/src/generated/rest/EntanglementProofPreflightRequest.js +0 -2
  132. package/lib/src/generated/rest/ExecuteCommandsRequest.d.ts +0 -4
  133. package/lib/src/generated/rest/ExecuteCommandsRequest.js +0 -2
  134. package/lib/src/generated/rest/ExportRequest.d.ts +0 -5
  135. package/lib/src/generated/rest/ExportRequest.js +0 -2
  136. package/lib/src/generated/rest/ExpressionManyRequest.d.ts +0 -3
  137. package/lib/src/generated/rest/ExpressionManyRequest.js +0 -2
  138. package/lib/src/generated/rest/ExpressionProof.d.ts +0 -4
  139. package/lib/src/generated/rest/ExpressionProof.js +0 -2
  140. package/lib/src/generated/rest/ExpressionProofInput.d.ts +0 -6
  141. package/lib/src/generated/rest/ExpressionProofInput.js +0 -2
  142. package/lib/src/generated/rest/FriendSendMessageRequest.d.ts +0 -3
  143. package/lib/src/generated/rest/FriendSendMessageRequest.js +0 -2
  144. package/lib/src/generated/rest/FriendsListRequest.d.ts +0 -3
  145. package/lib/src/generated/rest/FriendsListRequest.js +0 -2
  146. package/lib/src/generated/rest/GenerateAgentRequest.d.ts +0 -3
  147. package/lib/src/generated/rest/GenerateAgentRequest.js +0 -2
  148. package/lib/src/generated/rest/GenerateJwtRequest.d.ts +0 -4
  149. package/lib/src/generated/rest/GenerateJwtRequest.js +0 -2
  150. package/lib/src/generated/rest/GetSubjectDataRequest.d.ts +0 -4
  151. package/lib/src/generated/rest/GetSubjectDataRequest.js +0 -2
  152. package/lib/src/generated/rest/HostingInfoResponse.d.ts +0 -5
  153. package/lib/src/generated/rest/HostingInfoResponse.js +0 -2
  154. package/lib/src/generated/rest/HostingWalletResponse.d.ts +0 -4
  155. package/lib/src/generated/rest/HostingWalletResponse.js +0 -2
  156. package/lib/src/generated/rest/ImportAgentRequest.d.ts +0 -6
  157. package/lib/src/generated/rest/ImportAgentRequest.js +0 -2
  158. package/lib/src/generated/rest/ImportRequest.d.ts +0 -4
  159. package/lib/src/generated/rest/ImportRequest.js +0 -2
  160. package/lib/src/generated/rest/JoinNeighbourhoodRequest.d.ts +0 -3
  161. package/lib/src/generated/rest/JoinNeighbourhoodRequest.js +0 -2
  162. package/lib/src/generated/rest/KeepAliveQueryRequest.d.ts +0 -3
  163. package/lib/src/generated/rest/KeepAliveQueryRequest.js +0 -2
  164. package/lib/src/generated/rest/LanguageMetaInput.d.ts +0 -6
  165. package/lib/src/generated/rest/LanguageMetaInput.js +0 -2
  166. package/lib/src/generated/rest/Link.d.ts +0 -5
  167. package/lib/src/generated/rest/Link.js +0 -2
  168. package/lib/src/generated/rest/LinkExpression.d.ts +0 -10
  169. package/lib/src/generated/rest/LinkExpression.js +0 -1
  170. package/lib/src/generated/rest/LinkExpressionInput.d.ts +0 -10
  171. package/lib/src/generated/rest/LinkExpressionInput.js +0 -1
  172. package/lib/src/generated/rest/LinkInput.d.ts +0 -5
  173. package/lib/src/generated/rest/LinkInput.js +0 -2
  174. package/lib/src/generated/rest/LinkLanguageTemplatesRequest.d.ts +0 -3
  175. package/lib/src/generated/rest/LinkLanguageTemplatesRequest.js +0 -2
  176. package/lib/src/generated/rest/LinkMutationRequest.d.ts +0 -12
  177. package/lib/src/generated/rest/LinkMutationRequest.js +0 -1
  178. package/lib/src/generated/rest/LinkMutationResponse.d.ts +0 -9
  179. package/lib/src/generated/rest/LinkMutationResponse.js +0 -1
  180. package/lib/src/generated/rest/LinkMutations.d.ts +0 -6
  181. package/lib/src/generated/rest/LinkMutations.js +0 -1
  182. package/lib/src/generated/rest/LinkMutationsRequest.d.ts +0 -5
  183. package/lib/src/generated/rest/LinkMutationsRequest.js +0 -1
  184. package/lib/src/generated/rest/LinkStatus.d.ts +0 -1
  185. package/lib/src/generated/rest/LinkStatus.js +0 -2
  186. package/lib/src/generated/rest/LinkUpdateInput.d.ts +0 -5
  187. package/lib/src/generated/rest/LinkUpdateInput.js +0 -1
  188. package/lib/src/generated/rest/LockAgentRequest.d.ts +0 -3
  189. package/lib/src/generated/rest/LockAgentRequest.js +0 -2
  190. package/lib/src/generated/rest/LoginUserRequest.d.ts +0 -5
  191. package/lib/src/generated/rest/LoginUserRequest.js +0 -2
  192. package/lib/src/generated/rest/ModelType.d.ts +0 -1
  193. package/lib/src/generated/rest/ModelType.js +0 -2
  194. package/lib/src/generated/rest/NotificationGrantRequest.d.ts +0 -3
  195. package/lib/src/generated/rest/NotificationGrantRequest.js +0 -2
  196. package/lib/src/generated/rest/NotificationInput.d.ts +0 -10
  197. package/lib/src/generated/rest/NotificationInput.js +0 -2
  198. package/lib/src/generated/rest/OpenLinkRequest.d.ts +0 -3
  199. package/lib/src/generated/rest/OpenLinkRequest.js +0 -2
  200. package/lib/src/generated/rest/PermitCapabilityRequest.d.ts +0 -3
  201. package/lib/src/generated/rest/PermitCapabilityRequest.js +0 -2
  202. package/lib/src/generated/rest/PerspectiveInput.d.ts +0 -4
  203. package/lib/src/generated/rest/PerspectiveInput.js +0 -1
  204. package/lib/src/generated/rest/PromptRequest.d.ts +0 -4
  205. package/lib/src/generated/rest/PromptRequest.js +0 -2
  206. package/lib/src/generated/rest/PublicPerspectiveInput.d.ts +0 -4
  207. package/lib/src/generated/rest/PublicPerspectiveInput.js +0 -1
  208. package/lib/src/generated/rest/PublishLanguageRequest.d.ts +0 -5
  209. package/lib/src/generated/rest/PublishLanguageRequest.js +0 -1
  210. package/lib/src/generated/rest/PublishNeighbourhoodRequest.d.ts +0 -6
  211. package/lib/src/generated/rest/PublishNeighbourhoodRequest.js +0 -1
  212. package/lib/src/generated/rest/QueryRequest.d.ts +0 -7
  213. package/lib/src/generated/rest/QueryRequest.js +0 -2
  214. package/lib/src/generated/rest/RemoveLinkRequest.d.ts +0 -5
  215. package/lib/src/generated/rest/RemoveLinkRequest.js +0 -1
  216. package/lib/src/generated/rest/RemoveLinksBulkRequest.d.ts +0 -5
  217. package/lib/src/generated/rest/RemoveLinksBulkRequest.js +0 -1
  218. package/lib/src/generated/rest/RequestCapabilityRequest.d.ts +0 -4
  219. package/lib/src/generated/rest/RequestCapabilityRequest.js +0 -1
  220. package/lib/src/generated/rest/RequestPaymentRequest.d.ts +0 -3
  221. package/lib/src/generated/rest/RequestPaymentRequest.js +0 -2
  222. package/lib/src/generated/rest/RequestVerificationRequest.d.ts +0 -4
  223. package/lib/src/generated/rest/RequestVerificationRequest.js +0 -2
  224. package/lib/src/generated/rest/ResourceInput.d.ts +0 -4
  225. package/lib/src/generated/rest/ResourceInput.js +0 -2
  226. package/lib/src/generated/rest/SetDefaultModelRequest.d.ts +0 -4
  227. package/lib/src/generated/rest/SetDefaultModelRequest.js +0 -1
  228. package/lib/src/generated/rest/SetFreeHostingEnabledRequest.d.ts +0 -3
  229. package/lib/src/generated/rest/SetFreeHostingEnabledRequest.js +0 -2
  230. package/lib/src/generated/rest/SetHotWalletAddressRequest.d.ts +0 -3
  231. package/lib/src/generated/rest/SetHotWalletAddressRequest.js +0 -2
  232. package/lib/src/generated/rest/SetMultiUserRequest.d.ts +0 -3
  233. package/lib/src/generated/rest/SetMultiUserRequest.js +0 -2
  234. package/lib/src/generated/rest/SetOnlineStatusRequest.d.ts +0 -5
  235. package/lib/src/generated/rest/SetOnlineStatusRequest.js +0 -1
  236. package/lib/src/generated/rest/SetStatusRequest.d.ts +0 -3
  237. package/lib/src/generated/rest/SetStatusRequest.js +0 -2
  238. package/lib/src/generated/rest/SetUserFreeAccessRequest.d.ts +0 -4
  239. package/lib/src/generated/rest/SetUserFreeAccessRequest.js +0 -2
  240. package/lib/src/generated/rest/SignMessageRequest.d.ts +0 -3
  241. package/lib/src/generated/rest/SignMessageRequest.js +0 -2
  242. package/lib/src/generated/rest/SignalRequest.d.ts +0 -6
  243. package/lib/src/generated/rest/SignalRequest.js +0 -1
  244. package/lib/src/generated/rest/SubscribeQueryRequest.d.ts +0 -3
  245. package/lib/src/generated/rest/SubscribeQueryRequest.js +0 -2
  246. package/lib/src/generated/rest/SubscribeQueryResponse.d.ts +0 -4
  247. package/lib/src/generated/rest/SubscribeQueryResponse.js +0 -2
  248. package/lib/src/generated/rest/TrustedAgentsRequest.d.ts +0 -3
  249. package/lib/src/generated/rest/TrustedAgentsRequest.js +0 -2
  250. package/lib/src/generated/rest/UnlockAgentRequest.d.ts +0 -4
  251. package/lib/src/generated/rest/UnlockAgentRequest.js +0 -2
  252. package/lib/src/generated/rest/UpdateLinkRequest.d.ts +0 -7
  253. package/lib/src/generated/rest/UpdateLinkRequest.js +0 -1
  254. package/lib/src/generated/rest/UpdatePerspectiveRequest.d.ts +0 -3
  255. package/lib/src/generated/rest/UpdatePerspectiveRequest.js +0 -2
  256. package/lib/src/generated/rest/UpdateProfileRequest.d.ts +0 -5
  257. package/lib/src/generated/rest/UpdateProfileRequest.js +0 -1
  258. package/lib/src/generated/rest/UserStatistics.d.ts +0 -9
  259. package/lib/src/generated/rest/UserStatistics.js +0 -2
  260. package/lib/src/generated/rest/VerificationRequestResult.d.ts +0 -6
  261. package/lib/src/generated/rest/VerificationRequestResult.js +0 -2
  262. package/lib/src/generated/rest/VerifyEmailRequest.d.ts +0 -6
  263. package/lib/src/generated/rest/VerifyEmailRequest.js +0 -2
  264. package/lib/src/generated/rest/VerifySignatureRequest.d.ts +0 -5
  265. package/lib/src/generated/rest/VerifySignatureRequest.js +0 -2
  266. package/lib/src/generated/rest/WriteSettingsRequest.d.ts +0 -3
  267. package/lib/src/generated/rest/WriteSettingsRequest.js +0 -2
  268. package/lib/src/generated/rest/index.d.ts +0 -73
  269. package/lib/src/generated/rest/index.js +0 -8
  270. package/lib/src/generated/rest/routes.d.ts +0 -587
  271. package/lib/src/generated/rest/routes.js +0 -3
  272. package/lib/src/model/query-surreal.d.ts +0 -44
  273. package/lib/src/model/query-surreal.js +0 -249
  274. package/lib/src/model/surreal-utils.d.ts +0 -42
  275. package/lib/src/model/surreal-utils.js +0 -128
  276. package/lib/src/perspectives/PerspectiveProxy.test.d.ts +0 -1
  277. package/lib/src/perspectives/PerspectiveProxy.test.js +0 -34
  278. package/lib/src/restClient.d.ts +0 -52
  279. package/lib/src/restClient.js +0 -227
@@ -2,6 +2,7 @@ import { Literal } from "../Literal";
2
2
  import { Link } from "../links/Links";
3
3
  import { LinkQuery } from "../perspectives/LinkQuery";
4
4
  import { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
5
+ import { CallOptions } from "../apiClient";
5
6
  import { makeRandomId } from "./util";
6
7
  import { getPropertiesMetadata, getRelationsMetadata, setPropertyRegistryEntry, setRelationRegistryEntry, Model } from "./decorators";
7
8
  import type { PropertyOptions, PropertyMetadataEntry, RelationMetadataEntry } from "./decorators";
@@ -11,13 +12,13 @@ import { isArrayType, determinePredicate, determineNamespace, buildModelFromJSON
11
12
  import type { SHACLShape } from "../shacl/SHACLShape";
12
13
  import type { JSONSchemaProperty, JSONSchema, JSONSchemaToModelOptions } from "./json-schema";
13
14
 
14
- import { buildSPARQLQuery } from "./query-sparql";
15
+ import { buildSPARQLQuery, valueToLiteralIri, effectiveLiteralStorage } from "./query-sparql";
15
16
  import { ModelQueryBuilder } from "./ModelQueryBuilder";
16
17
  import {
17
18
  normalizeValue,
18
19
  } from "./hydration";
19
20
  import type {
20
- ParentScope, IncludeMap, Query,
21
+ Scope, IncludeMap, Query,
21
22
  GetOptions, AllInstancesResult, ResultsWithTotalCount,
22
23
  PaginationResult, PropertyMetadata, RelationMetadata, ModelMetadata,
23
24
  IncludeProjection,
@@ -35,6 +36,109 @@ import type {
35
36
  * Rust endpoint. Recursively converts included relation values (which come
36
37
  * back as plain JSON objects) into proper model class instances.
37
38
  */
39
+ /**
40
+ * Key under which the executor returns a polymorphically-hydrated instance's
41
+ * concrete class.
42
+ *
43
+ * Half of a wire contract: the writer is `SUBJECT_CLASS_KEY` in
44
+ * `rust-executor/src/perspectives/model_query/relations.rs`, and the two are
45
+ * separate literals in separate languages. Renaming one alone does not fail to
46
+ * compile — it degrades to every instance staying plain JSON, which looks
47
+ * identical to a relation that declared no classes to build.
48
+ * `tests/js/tests/model/model-polymorphic.test.ts` drives both ends against one
49
+ * executor, so the drift fails a test rather than a user's query.
50
+ *
51
+ * The executor also returns `__subjectClasses`, the whole set this one names the
52
+ * head of. Nothing here reads it — it rides onto the instance with every other
53
+ * JSON key, for a caller that wants to know a choice was made.
54
+ */
55
+ const SUBJECT_CLASS_KEY = '__subjectClass';
56
+
57
+ /**
58
+ * Turn on `polymorphic` for every relation that declares it, at every depth of
59
+ * an include map.
60
+ *
61
+ * A relation being heterogeneous is a fact about the data, not about one query,
62
+ * so the declaration lives on the model and the call site writes
63
+ * `include: { children: true }`. That has to hold just as much one level down:
64
+ * in `include: { posts: { include: { children: true } } }`, `children` is a
65
+ * relation on `Post`, so the walk carries the class it is reading against down
66
+ * with it. Without that, a nested include of an untyped polymorphic relation
67
+ * reaches the executor with no shape to resolve and fails the query outright.
68
+ *
69
+ * An explicit `polymorphic: false` at any level still wins — `undefined` is the
70
+ * only state the default fills in.
71
+ *
72
+ * The walk stops descending *through* a polymorphic relation, because there is
73
+ * nothing to descend into: its targets are of several classes by definition, so
74
+ * no single class's metadata could say what a deeper include means. The
75
+ * executor resolves those nested includes against each concrete class instead.
76
+ */
77
+ function applyPolymorphicIncludeDefaults(includes: IncludeMap, ctor: Function): void {
78
+ const relMeta = getRelationsMetadata(ctor);
79
+ for (const [relName, val] of Object.entries(includes)) {
80
+ // `$`-prefixed keys are projections, not relations.
81
+ if (relName.startsWith('$')) continue;
82
+ const meta = relMeta[relName];
83
+ if (!meta) continue;
84
+
85
+ let subQuery = val as any;
86
+ if (meta.polymorphic) {
87
+ if (val === true) {
88
+ subQuery = { polymorphic: true };
89
+ includes[relName] = subQuery;
90
+ } else if (typeof val === 'object' && val !== null && subQuery.polymorphic === undefined) {
91
+ subQuery.polymorphic = true;
92
+ }
93
+ // The classes this call site can build are also the classes it wants its
94
+ // targets read as, so the declaration answers both questions and the call
95
+ // site repeats neither. Sent as part of the query rather than applied to
96
+ // the results: a preference in the request is reproducible by anyone who
97
+ // sends it, where one applied afterwards would make the same data read
98
+ // differently depending on which classes the caller happened to import.
99
+ //
100
+ // It ranks and does not narrow — a target matching none of them still
101
+ // arrives — so declaring what you can construct never costs you a member
102
+ // of a relation that is heterogeneous by definition.
103
+ if (
104
+ typeof subQuery === 'object' &&
105
+ subQuery !== null &&
106
+ subQuery.polymorphic &&
107
+ subQuery.preferClasses === undefined &&
108
+ meta.instantiateAs
109
+ ) {
110
+ const names = (meta.instantiateAs() ?? [])
111
+ .map((cls) => (cls as any)?.className)
112
+ .filter((name): name is string => typeof name === 'string');
113
+ if (names.length) subQuery.preferClasses = names;
114
+ }
115
+ }
116
+
117
+ if (typeof subQuery !== 'object' || subQuery === null) continue;
118
+ const nested = subQuery.include as IncludeMap | undefined;
119
+ if (!nested || subQuery.polymorphic) continue;
120
+
121
+ // The thunk is only evaluated here, at query time, so a self-referential or
122
+ // circularly-imported target that is not yet defined costs the nested
123
+ // default rather than the whole query.
124
+ let TargetClass: any;
125
+ try {
126
+ TargetClass = meta.target?.();
127
+ } catch (e) {
128
+ // A class not yet initialised throws `ReferenceError` from the temporal
129
+ // dead zone, which is the expected cost of an import cycle and not worth
130
+ // saying anything about. Anything else — a thunk closing over nothing,
131
+ // typically — is a broken declaration that would otherwise cost the nested
132
+ // default in silence, so it gets said out loud.
133
+ const circularImport = e instanceof ReferenceError;
134
+ const say = circularImport ? console.debug : console.warn;
135
+ say(`prepareModelQueryParams: target class unavailable for include '${relName}':`, e);
136
+ continue;
137
+ }
138
+ if (TargetClass) applyPolymorphicIncludeDefaults(nested, TargetClass);
139
+ }
140
+ }
141
+
38
142
  function jsonToModelInstance<T extends Ad4mModel>(
39
143
  ModelClass: typeof Ad4mModel & (new (...args: any[]) => T),
40
144
  perspective: PerspectiveProxy,
@@ -87,8 +191,56 @@ function jsonToModelInstance<T extends Ad4mModel>(
87
191
  for (const [relName, includeVal] of Object.entries(include)) {
88
192
  if (!includeVal) continue;
89
193
  const meta = relMeta[relName];
90
- if (!meta?.target) continue;
91
- const TargetClass = meta.target() as any;
194
+ // A polymorphic relation may legitimately declare no target at all —
195
+ // that is the case it exists for — so it must not be gated on one.
196
+ if (!meta) continue;
197
+ if (!meta.target && !meta.polymorphic) continue;
198
+ const TargetClass = meta.target?.() as any;
199
+ // For a polymorphic relation the executor sends each child's concrete
200
+ // class back on the instance, because it had to know it in order to
201
+ // hydrate against the right shape at all. What it cannot send is the
202
+ // constructor, so `instantiateAs` names the classes this side can build
203
+ // and the name → class map is derived from them: `@Model` records each
204
+ // class's name on the class itself, so listing the classes and listing
205
+ // their names would be the same list written twice, free to disagree.
206
+ //
207
+ // Built on first use rather than at decoration time, because the thunk
208
+ // exists to be called late: a class defined further round a circular
209
+ // import graph is not there yet when the decorator runs.
210
+ let byClassName: Record<string, any> | undefined;
211
+ // May resolve to nothing: a polymorphic relation is allowed to declare no
212
+ // target at all, and the list may not name the class that arrived — it
213
+ // says what this call site can construct, not what the relation may hold.
214
+ // The item then stays plain JSON — correct data, carrying its class name
215
+ // for a caller that wants to dispatch on it — rather than being forced
216
+ // through a constructor that does not exist.
217
+ const resolveChildClass = (item: any): any => {
218
+ if (!meta.polymorphic) return TargetClass;
219
+ const concrete = item?.[SUBJECT_CLASS_KEY];
220
+ // No concrete class means this was not read polymorphically after all —
221
+ // an explicit `polymorphic: false` at the call site — so the relation's
222
+ // own declared target is the right shape.
223
+ if (typeof concrete !== 'string') return TargetClass;
224
+ if (meta.instantiateAs) {
225
+ if (!byClassName) {
226
+ byClassName = {};
227
+ for (const cls of meta.instantiateAs() ?? []) {
228
+ const name = (cls as any)?.className;
229
+ if (typeof name === 'string') byClassName[name] = cls;
230
+ }
231
+ }
232
+ if (byClassName[concrete]) return byClassName[concrete];
233
+ }
234
+ // The declared target is not a fallback, and having named no classes to
235
+ // build does not make it one. Where a relation both declares a target
236
+ // and reads polymorphically, a child of some third class was hydrated
237
+ // against *its own* shape, so constructing the declared class over that
238
+ // JSON produces an instance that answers `instanceof` for a class it is
239
+ // not, carrying fields that class never declared — the exact
240
+ // mislabelling polymorphic reads exist to prevent. It fits only when it
241
+ // is the class the executor named.
242
+ return (TargetClass as any)?.className === concrete ? TargetClass : undefined;
243
+ };
92
244
  const nestedInclude =
93
245
  typeof includeVal === 'object' && includeVal !== null
94
246
  ? (includeVal as any).include
@@ -101,15 +253,19 @@ function jsonToModelInstance<T extends Ad4mModel>(
101
253
  const raw = instance[relName];
102
254
  if (Array.isArray(raw)) {
103
255
  instance[relName] = raw.map((item: any) => {
104
- if (typeof item === 'object' && item !== null && item.id) {
105
- return jsonToModelInstance(TargetClass, perspective, item, nestedInclude, nestedProperties);
256
+ const ChildClass = resolveChildClass(item);
257
+ if (ChildClass && typeof item === 'object' && item !== null && item.id) {
258
+ return jsonToModelInstance(ChildClass, perspective, item, nestedInclude, nestedProperties);
106
259
  }
107
260
  return item;
108
261
  });
109
262
  } else if (typeof raw === 'object' && raw !== null && raw.id) {
110
- instance[relName] = jsonToModelInstance(
111
- TargetClass, perspective, raw, nestedInclude, nestedProperties,
112
- );
263
+ const ChildClass = resolveChildClass(raw);
264
+ if (ChildClass) {
265
+ instance[relName] = jsonToModelInstance(
266
+ ChildClass, perspective, raw, nestedInclude, nestedProperties,
267
+ );
268
+ }
113
269
  }
114
270
  }
115
271
  }
@@ -138,13 +294,29 @@ function jsonToModelInstance<T extends Ad4mModel>(
138
294
  * // Define a recipe model
139
295
  * @Model({ name: "Recipe" })
140
296
  * class Recipe extends Ad4mModel {
141
- * // Required property with literal value
297
+ * // Plain property — no `resolveLanguage` → deterministic typed literal
298
+ * // storage (fast POS-index path). This is the perf default.
299
+ * @Property({ through: "recipe://name" })
300
+ * name: string = "";
301
+ *
302
+ * // Property that needs per-value provenance (e.g. a signed message body):
303
+ * // `resolveLanguage: "literal"` routes values through expression_create on
304
+ * // the built-in literal language, producing a signed envelope URI
305
+ * // (author/timestamp/proof) instead of a bare typed literal.
142
306
  * @Property({
143
- * through: "recipe://name",
307
+ * through: "recipe://signed_note",
144
308
  * resolveLanguage: "literal"
145
309
  * })
146
- * name: string = "";
147
- *
310
+ * signedNote: string = "";
311
+ *
312
+ * // Property resolved through a custom language: values are routed through
313
+ * // expression_create on that language (signed expression URIs).
314
+ * @Optional({
315
+ * through: "recipe://photo",
316
+ * resolveLanguage: "QmFileStorageLanguageAddress..."
317
+ * })
318
+ * photo: string = "";
319
+ *
148
320
  * // Optional property with custom initial value
149
321
  * @Optional({
150
322
  * through: "recipe://status",
@@ -300,9 +472,9 @@ export class Ad4mModel {
300
472
  * ```typescript
301
473
  * @Model({ name: "Recipe" })
302
474
  * class Recipe extends Ad4mModel {
303
- * @Property({ through: "recipe://name", resolveLanguage: "literal" })
475
+ * @Property({ through: "recipe://name" })
304
476
  * name: string = "";
305
- *
477
+ *
306
478
  * @HasMany({ through: "recipe://ingredient" })
307
479
  * ingredients: string[] = [];
308
480
  * }
@@ -366,6 +538,7 @@ export class Ad4mModel {
366
538
  ...(options.target !== undefined && { target: options.target }),
367
539
  ...(options.filter !== undefined && { filter: options.filter }),
368
540
  ...(options.where !== undefined && { where: options.where }),
541
+ ...(options.ordering !== undefined && { ordering: options.ordering }),
369
542
  };
370
543
  }
371
544
 
@@ -404,7 +577,7 @@ export class Ad4mModel {
404
577
  predicate: predicate,
405
578
  required: isRequired,
406
579
  readOnly: propertySchema["x-ad4m"]?.writable === false,
407
- ...(propertySchema["x-ad4m"]?.resolveLanguage && { resolveLanguage: propertySchema["x-ad4m"].resolveLanguage }),
580
+ ...(propertySchema["x-ad4m"]?.resolveLanguage !== undefined && { resolveLanguage: propertySchema["x-ad4m"].resolveLanguage }),
408
581
  ...(propertySchema["x-ad4m"]?.initial && { initial: propertySchema["x-ad4m"].initial }),
409
582
  ...(propertySchema["x-ad4m"]?.local !== undefined && { local: propertySchema["x-ad4m"].local })
410
583
  };
@@ -425,20 +598,31 @@ export class Ad4mModel {
425
598
  *
426
599
  * @param perspective - The perspective where this model will be stored
427
600
  * @param baseExpression - Optional expression URI for this instance.
428
- * If omitted, a random Literal URL is generated.
601
+ * If omitted, a random `ad4m://obj/<id>` IRI is generated,
602
+ * independent of any property content — this is what keeps
603
+ * two instances with identical property values distinct.
429
604
  * @param source - Optional source expression this instance is linked to
430
- *
605
+ *
431
606
  * @example
432
607
  * ```typescript
433
608
  * // Create a new recipe with auto-generated base expression
434
609
  * const recipe = new Recipe(perspective);
435
- *
610
+ *
436
611
  * // Create with specific base expression
437
- * const recipe = new Recipe(perspective, "literal:...");
612
+ * const recipe = new Recipe(perspective, "ad4m://obj/existing-id");
438
613
  * ```
439
614
  */
440
615
  constructor(perspective: PerspectiveProxy, baseExpression?: string) {
441
- this._baseExpression = baseExpression ? baseExpression : Literal.from(makeRandomId(24)).toUrl();
616
+ // Use a dedicated `ad4m://obj/<id>` scheme for auto-generated
617
+ // baseExpressions instead of `Literal.from(...).toUrl()`'s
618
+ // `literal:string:<id>`. After typed-literal storage lands, the storage
619
+ // layer translates any `literal:string:X` target into a typed
620
+ // `"X"^^xsd:string` literal — which is correct for property values but
621
+ // wrong for relation targets (which must remain NamedNode IRIs). Using
622
+ // a distinct scheme keeps auto-generated instance IDs unambiguously
623
+ // IRIs, so relation links like `<post> --has_comment--> <comment-id>`
624
+ // round-trip correctly through the SPARQL store.
625
+ this._baseExpression = baseExpression ? baseExpression : `ad4m://obj/${makeRandomId(24)}`;
442
626
  this._perspective = perspective;
443
627
  }
444
628
 
@@ -664,10 +848,22 @@ export class Ad4mModel {
664
848
  const original = this._snapshot[field];
665
849
 
666
850
  if (Array.isArray(current) || Array.isArray(original)) {
667
- // Order-insensitive comparison (sorted) so reordering alone
668
- // doesn't mark a relation as dirty.
669
- const a = Array.isArray(current) ? [...current].sort() : [];
670
- const b = Array.isArray(original) ? [...original].sort() : [];
851
+ // For an ordered relation the sequence *is* the state, so a reorder is
852
+ // the whole change and must mark the field dirty — sorting first would
853
+ // make `save()` a no-op for the one edit the ordering feature exists to
854
+ // support.
855
+ //
856
+ // Everything else compares order-insensitively, because an unordered
857
+ // relation is a set: the executor returns its members by link timestamp,
858
+ // and a caller who assigned the same members in another order has not
859
+ // changed anything.
860
+ const ordered = !!(metadata.relations as any)[field]?.ordering;
861
+ const a = Array.isArray(current) ? [...current] : [];
862
+ const b = Array.isArray(original) ? [...original] : [];
863
+ if (!ordered) {
864
+ a.sort();
865
+ b.sort();
866
+ }
671
867
  if (a.length !== b.length || a.some((v: any, i: number) => v !== b[i])) {
672
868
  changed.push(field);
673
869
  }
@@ -809,7 +1005,17 @@ export class Ad4mModel {
809
1005
  normalIncludes[key] = val;
810
1006
  }
811
1007
  }
812
- if (Object.keys(normalIncludes).length > 0) queryInput.include = normalIncludes;
1008
+ // A relation declared `polymorphic` reads that way by default, so the
1009
+ // caller writes `include: { children: true }` and still gets each child
1010
+ // hydrated as the class it actually is. Declaring it on the model rather
1011
+ // than repeating it at every call site is the point — the relation being
1012
+ // heterogeneous is a fact about the data, not about one query — but an
1013
+ // explicit `polymorphic: false` at the call site still wins. Applied at
1014
+ // every depth, since a nested include is a fact about the data too.
1015
+ if (Object.keys(normalIncludes).length > 0) {
1016
+ applyPolymorphicIncludeDefaults(normalIncludes, this as any);
1017
+ queryInput.include = normalIncludes;
1018
+ }
813
1019
  if (Object.keys(projections).length > 0) {
814
1020
  // Tag each projection with its target class name so the executor can
815
1021
  // resolve the target shape through its in-memory cache when applying
@@ -884,6 +1090,7 @@ export class Ad4mModel {
884
1090
  perspective: PerspectiveProxy,
885
1091
  query: Query = {},
886
1092
  classNameOverride?: string | null,
1093
+ options?: CallOptions,
887
1094
  ): Promise<ResultsWithTotalCount<T>> {
888
1095
  // Delegate query input building to the shared prepareModelQueryParams
889
1096
  // helper. The executor resolves the shape from SHACL server-side.
@@ -891,7 +1098,7 @@ export class Ad4mModel {
891
1098
  query, classNameOverride,
892
1099
  );
893
1100
 
894
- const result = await perspective.modelQuery(className, queryJson);
1101
+ const result = await perspective.modelQuery(className, queryJson, options);
895
1102
 
896
1103
  // Convert JSON instances to model class instances, recursively constructing
897
1104
  // class instances for any included relations resolved by Rust.
@@ -942,13 +1149,14 @@ export class Ad4mModel {
942
1149
  this: typeof Ad4mModel & (new (...args: any[]) => T),
943
1150
  perspective: PerspectiveProxy,
944
1151
  query?: Q,
1152
+ options?: CallOptions,
945
1153
  ): Promise<(T & IncludeExtras<T, IncludeOf<Q>>)[]> {
946
1154
  const q = (query ?? {}) as Query;
947
1155
  if (q.properties && q.properties.length === 0) {
948
1156
  throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
949
1157
  }
950
1158
 
951
- const { results } = await this.executeModelQuery(perspective, q);
1159
+ const { results } = await this.executeModelQuery(perspective, q, undefined, options);
952
1160
  return results as (T & IncludeExtras<T, IncludeOf<Q>>)[];
953
1161
  }
954
1162
 
@@ -976,9 +1184,10 @@ export class Ad4mModel {
976
1184
  this: typeof Ad4mModel & (new (...args: any[]) => T),
977
1185
  perspective: PerspectiveProxy,
978
1186
  query?: Q,
1187
+ options?: CallOptions,
979
1188
  ): Promise<(T & IncludeExtras<T, IncludeOf<Q>>) | null> {
980
1189
  const limitedQuery = { ...((query ?? {}) as Query), limit: 1 } as Q;
981
- const results = await this.findAll<T, Q>(perspective, limitedQuery);
1190
+ const results = await this.findAll<T, Q>(perspective, limitedQuery, options);
982
1191
  return results[0] ?? null;
983
1192
  }
984
1193
 
@@ -1003,8 +1212,9 @@ export class Ad4mModel {
1003
1212
  this: typeof Ad4mModel & (new (...args: any[]) => T),
1004
1213
  perspective: PerspectiveProxy,
1005
1214
  query?: Q,
1215
+ options?: CallOptions,
1006
1216
  ): Promise<ResultsWithTotalCount<T & IncludeExtras<T, IncludeOf<Q>>>> {
1007
- const out = await this.executeModelQuery(perspective, (query ?? {}) as Query);
1217
+ const out = await this.executeModelQuery(perspective, (query ?? {}) as Query, undefined, options);
1008
1218
  return out as ResultsWithTotalCount<T & IncludeExtras<T, IncludeOf<Q>>>;
1009
1219
  }
1010
1220
 
@@ -1031,9 +1241,10 @@ export class Ad4mModel {
1031
1241
  pageSize: number,
1032
1242
  pageNumber: number,
1033
1243
  query?: Q,
1244
+ options?: CallOptions,
1034
1245
  ): Promise<PaginationResult<T & IncludeExtras<T, IncludeOf<Q>>>> {
1035
1246
  const paginationQuery = { ...((query ?? {}) as Query), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
1036
- const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery);
1247
+ const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery, undefined, options);
1037
1248
  return { results: results as (T & IncludeExtras<T, IncludeOf<Q>>)[], totalCount, pageSize, pageNumber };
1038
1249
  }
1039
1250
 
@@ -1067,8 +1278,9 @@ export class Ad4mModel {
1067
1278
  this: typeof Ad4mModel & (new (...args: any[]) => T),
1068
1279
  perspective: PerspectiveProxy,
1069
1280
  query?: TypedQuery<T>,
1281
+ options?: CallOptions,
1070
1282
  ): Promise<number> {
1071
- const { totalCount } = await this.executeModelQuery(perspective, { ...((query ?? {}) as Query), limit: 0 });
1283
+ const { totalCount } = await this.executeModelQuery(perspective, { ...((query ?? {}) as Query), limit: 0 }, undefined, options);
1072
1284
  return totalCount;
1073
1285
  }
1074
1286
 
@@ -1082,16 +1294,21 @@ export class Ad4mModel {
1082
1294
  // Generate actions from metadata (replaces Prolog query)
1083
1295
  const actions = this.generatePropertySetterAction(key, metadata);
1084
1296
 
1085
- // Get resolve language from metadata (replaces Prolog query)
1086
- let resolveLanguage = metadata.resolveLanguage;
1087
-
1088
1297
  // Skip storing empty/null/undefined values to avoid invalid empty literals (e.g. literal:string:)
1089
1298
  if (value === undefined || value === null || value === "") {
1090
1299
  return;
1091
1300
  }
1092
1301
 
1093
- if (resolveLanguage) {
1094
- value = await this._perspective.createExpression(value, resolveLanguage);
1302
+ const mode = effectiveLiteralStorage(metadata);
1303
+ if (mode.kind === "custom") {
1304
+ // Custom language: route through expression_create on that language.
1305
+ value = await this._perspective.createExpression(value, mode.language);
1306
+ } else if (mode.kind === "envelope") {
1307
+ // Built-in literal language: signed-envelope expression (provenance).
1308
+ value = await this._perspective.createExpression(value, "literal");
1309
+ } else {
1310
+ // Deterministic literal: IRI (POS-index friendly).
1311
+ value = valueToLiteralIri(value);
1095
1312
  }
1096
1313
 
1097
1314
  await this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value }], batchId);
@@ -1235,34 +1452,37 @@ export class Ad4mModel {
1235
1452
  (p) => p.required || p.flag || p.initial !== undefined
1236
1453
  );
1237
1454
 
1238
- // Track properties that have resolveLanguage (non-literal) so they can be
1239
- // set via setProperty after createSubject (which doesn't resolve languages).
1240
- const deferredResolveLanguageProps: string[] = [];
1455
+ // Track properties resolved through expression_create — a signed literal
1456
+ // envelope or a custom (non-"literal") resolveLanguage. These may fail
1457
+ // inside a batch context, so defer them to setProperty after createSubject.
1458
+ const deferredExpressionProps: string[] = [];
1241
1459
 
1242
1460
  if (hasConstructor) {
1243
- // First filter out the properties that are not relations (arrays)
1244
1461
  const initialValues = {};
1245
1462
  for (const [key, value] of Object.entries(this)) {
1246
1463
  if (value !== undefined && value !== null && !(Array.isArray(value) && value.length > 0) && !value?.action) {
1247
- // Check if this property requires language resolution (e.g. file storage).
1248
- // If so, resolve the expression *before* passing to createSubject so
1249
- // the constructor receives a valid URI instead of raw data.
1250
1464
  const propMeta = metadata.properties[key];
1251
- if (propMeta?.resolveLanguage && propMeta.resolveLanguage !== 'literal' && typeof value === 'object') {
1252
- // Defer these properties — they need createExpression which may
1253
- // fail inside a batch context on some languages. We'll set them
1254
- // via setProperty after createSubject.
1255
- deferredResolveLanguageProps.push(key);
1465
+ // Only offer keys with a declared, settable model property. This
1466
+ // excludes ORM bookkeeping fields (_baseExpression, _perspective —
1467
+ // enumerable instance fields, not model properties), HasMany
1468
+ // relations (tracked in a separate registry, never in
1469
+ // `metadata.properties`), and read-only properties/flags
1470
+ // (readOnly: true). None of these have an `ad4m://setter` on the
1471
+ // Rust side, which otherwise logs a "declares no setter" warning
1472
+ // per key on every save().
1473
+ if (!propMeta || propMeta.readOnly) {
1474
+ continue;
1475
+ }
1476
+ if (effectiveLiteralStorage(propMeta).kind !== "deterministic") {
1477
+ deferredExpressionProps.push(key);
1256
1478
  continue;
1257
1479
  }
1258
1480
  initialValues[key] = value;
1259
1481
  }
1260
1482
  }
1261
1483
 
1262
- // Get the class name instead of passing the instance to avoid Prolog query generation
1263
1484
  const className = await this.perspective.stringOrTemplateObjectToSubjectClassName(this);
1264
1485
 
1265
- // Create the subject with the initial values
1266
1486
  await this.perspective.createSubject(
1267
1487
  className,
1268
1488
  this._baseExpression,
@@ -1276,10 +1496,7 @@ export class Ad4mModel {
1276
1496
  // property writing so that scalar values are persisted as links.
1277
1497
  await this.innerUpdate(!hasConstructor, batchId)
1278
1498
 
1279
- // Now handle any deferred resolveLanguage properties that were excluded
1280
- // from initialValues. setProperty will call createExpression to upload
1281
- // the data to the appropriate language and store the resulting URI.
1282
- for (const key of deferredResolveLanguageProps) {
1499
+ for (const key of deferredExpressionProps) {
1283
1500
  const value = (this as any)[key];
1284
1501
  if (value !== undefined && value !== null) {
1285
1502
  await this.setProperty(key, value, batchId);
@@ -1380,14 +1597,37 @@ export class Ad4mModel {
1380
1597
  // Handle all arrays as relations, including empty ones (which clears the relation)
1381
1598
  await this.setRelationValues(key, value, batchId);
1382
1599
  } else if (value !== undefined && value !== null && value !== "") {
1383
- if (setProperties) {
1384
- // Check if this is a relation property (has relation metadata)
1385
- const relationMeta = this.getRelationOptions(key);
1386
- if (relationMeta) {
1387
- // Skip - it's a relation, not a regular property
1388
- continue;
1389
- }
1600
+ // A scalar handed to a relation field is a single-member relation.
1601
+ //
1602
+ // This used to `continue` — "Skip, it's a relation, not a regular
1603
+ // property" — so `Model.create(p, { source: 'uri://x' })` typechecked,
1604
+ // ran, resolved, and wrote no link. The record was created with the
1605
+ // relation empty and nothing anywhere said so, which surfaces later as
1606
+ // a *reader* complaining about a malformed instance: a Relationship
1607
+ // with no endpoints, a Placement pointing at nothing. Both look like
1608
+ // rendering bugs from the outside, because the record exists and the
1609
+ // thing that should reference it does not.
1610
+ //
1611
+ // The array form is the documented path and stays correct; the problem
1612
+ // is that the scalar form is plausible, typechecks against a field
1613
+ // declared `string`, and fails silently. Coercing matches what a caller
1614
+ // reaching for it meant. A value `setRelationValues` cannot use now
1615
+ // fails there, loudly, instead of vanishing here.
1616
+ //
1617
+ // Deliberately outside the `setProperties` gate, mirroring the array
1618
+ // branch above. `create` passes `setProperties: false` when the class
1619
+ // has a constructor, because `create_subject` writes the values map —
1620
+ // but a relation carries `ad4m://adder`, not `ad4m://setter`, so
1621
+ // `create_subject` drops it (see the warning added in 3ee2b5bc6).
1622
+ // Relations have to be written here in both cases or they are lost by
1623
+ // both paths at once.
1624
+ const relationMeta = this.getRelationOptions(key);
1625
+ if (relationMeta) {
1626
+ await this.setRelationValues(key, [value], batchId);
1627
+ continue;
1628
+ }
1390
1629
 
1630
+ if (setProperties) {
1391
1631
  // Skip flag properties — they are immutable after creation
1392
1632
  const propMeta = this.getPropertyMetadata(key);
1393
1633
  if (propMeta?.flag) {
@@ -1599,7 +1839,7 @@ export class Ad4mModel {
1599
1839
  * @param perspective - The perspective to create the instance in
1600
1840
  * @param data - Property values to assign before saving
1601
1841
  * @param options - Optional settings:
1602
- * - `parent` — a `ParentScope` (model form or raw form) whose `id` will
1842
+ * - `parent` — a `Scope` (model form or raw form) whose `id` will
1603
1843
  * be used to create an incoming link from the parent to the new instance.
1604
1844
  * - `batchId` — an existing batch id; when provided the link write and
1605
1845
  * `save()` are added to the batch instead of committed immediately.
@@ -1628,7 +1868,7 @@ export class Ad4mModel {
1628
1868
  this: typeof Ad4mModel & (new (...args: any[]) => T),
1629
1869
  perspective: PerspectiveProxy,
1630
1870
  data: Record<string, any> = {},
1631
- options?: { parent?: ParentScope; batchId?: string },
1871
+ options?: { parent?: Scope; batchId?: string },
1632
1872
  ): Promise<T> {
1633
1873
  const instance = new this(perspective) as T;
1634
1874
  Object.assign(instance, data);
@@ -1874,8 +2114,7 @@ export class Ad4mModel {
1874
2114
  * // With explicit configuration
1875
2115
  * const PersonClass = Ad4mModel.fromJSONSchema(schema, {
1876
2116
  * name: "Person",
1877
- * namespace: "person://",
1878
- * resolveLanguage: "literal"
2117
+ * namespace: "person://"
1879
2118
  * });
1880
2119
  *
1881
2120
  * // With property mapping
@@ -192,10 +192,10 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
192
192
  const field = options?.field;
193
193
 
194
194
  if (typeof modelOrPredicate === 'string') {
195
- // Raw predicate string → raw form of ParentScope
195
+ // Raw predicate string → raw form of Scope
196
196
  this.queryParams.parent = { id, predicate: modelOrPredicate };
197
197
  } else if (typeof modelOrPredicate === 'function') {
198
- // Model class → model form of ParentScope
198
+ // Model class → model form of Scope
199
199
  this.queryParams.parent = { id, model: modelOrPredicate, ...(field && { field }) };
200
200
  } else if (typeof idOrInstance !== 'string') {
201
201
  // Ad4mModel instance — derive model class from constructor