@linked.archi/kernel 0.0.0-stage → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (365) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +11 -0
  3. package/README.md +96 -2
  4. package/assets/arch-decision/arch-decision-metamodel.ttl +44 -0
  5. package/assets/arch-decision/arch-decision-onto.ttl +1566 -0
  6. package/assets/arch-decision/arch-decision-shapes.ttl +582 -0
  7. package/assets/arch-decision/arch-decision-tax.ttl +129 -0
  8. package/assets/arch-processes/arch-processes-metamodel.ttl +42 -0
  9. package/assets/arch-processes/arch-processes-tax.ttl +136 -0
  10. package/assets/arch-processes/archProcesses-shapes.ttl +189 -0
  11. package/assets/arch-processes/archProcesses.ttl +953 -0
  12. package/assets/archimate3/archimate3.2-element-shapes.ttl +379 -0
  13. package/assets/archimate3/archimate3.2-metamodel.ttl +205 -0
  14. package/assets/archimate3/archimate3.2-notation.ttl +1503 -0
  15. package/assets/archimate3/archimate3.2-onto.ttl +1579 -0
  16. package/assets/archimate3/archimate3.2-presentation-contexts.ttl +90 -0
  17. package/assets/archimate3/archimate3.2-principle-shapes.ttl +923 -0
  18. package/assets/archimate3/archimate3.2-questions.ttl +1125 -0
  19. package/assets/archimate3/archimate3.2-reference-data.ttl +74 -0
  20. package/assets/archimate3/archimate3.2-relationship-shapes.ttl +30956 -0
  21. package/assets/archimate3/archimate3.2-relationship-tables.ttl +5992 -0
  22. package/assets/archimate3/archimate3.2-tax.ttl +724 -0
  23. package/assets/archimate3/archimate3.2-viewpoint-shapes.ttl +59 -0
  24. package/assets/archimate3/archimate3.2-viewpoints.ttl +793 -0
  25. package/assets/archimate3/icons/and-junction.svg +3 -0
  26. package/assets/archimate3/icons/application-collaboration.svg +22 -0
  27. package/assets/archimate3/icons/application-component.svg +18 -0
  28. package/assets/archimate3/icons/application-event.svg +15 -0
  29. package/assets/archimate3/icons/application-function.svg +14 -0
  30. package/assets/archimate3/icons/application-interaction.svg +17 -0
  31. package/assets/archimate3/icons/application-interface.svg +16 -0
  32. package/assets/archimate3/icons/application-process.svg +14 -0
  33. package/assets/archimate3/icons/application-service.svg +14 -0
  34. package/assets/archimate3/icons/artifact.svg +16 -0
  35. package/assets/archimate3/icons/assessment.svg +17 -0
  36. package/assets/archimate3/icons/business-actor.svg +22 -0
  37. package/assets/archimate3/icons/business-collaboration.svg +21 -0
  38. package/assets/archimate3/icons/business-event.svg +15 -0
  39. package/assets/archimate3/icons/business-function.svg +14 -0
  40. package/assets/archimate3/icons/business-interaction.svg +18 -0
  41. package/assets/archimate3/icons/business-interface.svg +16 -0
  42. package/assets/archimate3/icons/business-object.svg +14 -0
  43. package/assets/archimate3/icons/business-process.svg +15 -0
  44. package/assets/archimate3/icons/business-role.svg +16 -0
  45. package/assets/archimate3/icons/business-service.svg +14 -0
  46. package/assets/archimate3/icons/capability.svg +40 -0
  47. package/assets/archimate3/icons/communication-network.svg +18 -0
  48. package/assets/archimate3/icons/constraint.svg +18 -0
  49. package/assets/archimate3/icons/contract.svg +13 -0
  50. package/assets/archimate3/icons/course-of-action.svg +20 -0
  51. package/assets/archimate3/icons/data-object.svg +14 -0
  52. package/assets/archimate3/icons/deliverable.svg +11 -0
  53. package/assets/archimate3/icons/device.svg +18 -0
  54. package/assets/archimate3/icons/distribution-network.svg +19 -0
  55. package/assets/archimate3/icons/driver.svg +24 -0
  56. package/assets/archimate3/icons/equipment.svg +31 -0
  57. package/assets/archimate3/icons/facility.svg +16 -0
  58. package/assets/archimate3/icons/gap.svg +22 -0
  59. package/assets/archimate3/icons/glyphs/activity.svg +3 -0
  60. package/assets/archimate3/icons/glyphs/actor.svg +14 -0
  61. package/assets/archimate3/icons/glyphs/application-component.svg +12 -0
  62. package/assets/archimate3/icons/glyphs/artifact.svg +9 -0
  63. package/assets/archimate3/icons/glyphs/assessment.svg +9 -0
  64. package/assets/archimate3/icons/glyphs/capability.svg +32 -0
  65. package/assets/archimate3/icons/glyphs/cloud-gear.svg +3 -0
  66. package/assets/archimate3/icons/glyphs/collaboration.svg +15 -0
  67. package/assets/archimate3/icons/glyphs/communication-network.svg +12 -0
  68. package/assets/archimate3/icons/glyphs/constraint.svg +10 -0
  69. package/assets/archimate3/icons/glyphs/contract.svg +5 -0
  70. package/assets/archimate3/icons/glyphs/course-of-action.svg +12 -0
  71. package/assets/archimate3/icons/glyphs/data-object.svg +4 -0
  72. package/assets/archimate3/icons/glyphs/deliverable.svg +3 -0
  73. package/assets/archimate3/icons/glyphs/device.svg +10 -0
  74. package/assets/archimate3/icons/glyphs/distribution-network.svg +11 -0
  75. package/assets/archimate3/icons/glyphs/driver.svg +16 -0
  76. package/assets/archimate3/icons/glyphs/equipment.svg +22 -0
  77. package/assets/archimate3/icons/glyphs/event.svg +6 -0
  78. package/assets/archimate3/icons/glyphs/facility.svg +7 -0
  79. package/assets/archimate3/icons/glyphs/function.svg +6 -0
  80. package/assets/archimate3/icons/glyphs/gap.svg +14 -0
  81. package/assets/archimate3/icons/glyphs/goal.svg +10 -0
  82. package/assets/archimate3/icons/glyphs/grouping.svg +4 -0
  83. package/assets/archimate3/icons/glyphs/interaction.svg +10 -0
  84. package/assets/archimate3/icons/glyphs/interface.svg +8 -0
  85. package/assets/archimate3/icons/glyphs/location.svg +6 -0
  86. package/assets/archimate3/icons/glyphs/material.svg +12 -0
  87. package/assets/archimate3/icons/glyphs/meaning.svg +3 -0
  88. package/assets/archimate3/icons/glyphs/node.svg +8 -0
  89. package/assets/archimate3/icons/glyphs/object.svg +4 -0
  90. package/assets/archimate3/icons/glyphs/outcome.svg +16 -0
  91. package/assets/archimate3/icons/glyphs/path.svg +10 -0
  92. package/assets/archimate3/icons/glyphs/person-silhouette.svg +3 -0
  93. package/assets/archimate3/icons/glyphs/plateau.svg +8 -0
  94. package/assets/archimate3/icons/glyphs/principle.svg +12 -0
  95. package/assets/archimate3/icons/glyphs/process.svg +6 -0
  96. package/assets/archimate3/icons/glyphs/product.svg +4 -0
  97. package/assets/archimate3/icons/glyphs/representation.svg +4 -0
  98. package/assets/archimate3/icons/glyphs/requirement.svg +6 -0
  99. package/assets/archimate3/icons/glyphs/resource.svg +14 -0
  100. package/assets/archimate3/icons/glyphs/role.svg +6 -0
  101. package/assets/archimate3/icons/glyphs/service.svg +6 -0
  102. package/assets/archimate3/icons/glyphs/stakeholder.svg +6 -0
  103. package/assets/archimate3/icons/glyphs/system-software.svg +14 -0
  104. package/assets/archimate3/icons/glyphs/value-stream.svg +3 -0
  105. package/assets/archimate3/icons/glyphs/value.svg +3 -0
  106. package/assets/archimate3/icons/glyphs/work-package.svg +4 -0
  107. package/assets/archimate3/icons/goal.svg +18 -0
  108. package/assets/archimate3/icons/grouping.svg +12 -0
  109. package/assets/archimate3/icons/implementation-event.svg +15 -0
  110. package/assets/archimate3/icons/location.svg +14 -0
  111. package/assets/archimate3/icons/material.svg +21 -0
  112. package/assets/archimate3/icons/meaning.svg +11 -0
  113. package/assets/archimate3/icons/node.svg +14 -0
  114. package/assets/archimate3/icons/or-junction.svg +3 -0
  115. package/assets/archimate3/icons/outcome.svg +25 -0
  116. package/assets/archimate3/icons/path.svg +18 -0
  117. package/assets/archimate3/icons/plateau.svg +16 -0
  118. package/assets/archimate3/icons/principle.svg +21 -0
  119. package/assets/archimate3/icons/product.svg +12 -0
  120. package/assets/archimate3/icons/representation.svg +12 -0
  121. package/assets/archimate3/icons/requirement.svg +14 -0
  122. package/assets/archimate3/icons/resource.svg +23 -0
  123. package/assets/archimate3/icons/stakeholder.svg +15 -0
  124. package/assets/archimate3/icons/system-software.svg +22 -0
  125. package/assets/archimate3/icons/technology-collaboration.svg +22 -0
  126. package/assets/archimate3/icons/technology-event.svg +15 -0
  127. package/assets/archimate3/icons/technology-function.svg +14 -0
  128. package/assets/archimate3/icons/technology-interaction.svg +18 -0
  129. package/assets/archimate3/icons/technology-interface.svg +16 -0
  130. package/assets/archimate3/icons/technology-process.svg +14 -0
  131. package/assets/archimate3/icons/technology-service.svg +14 -0
  132. package/assets/archimate3/icons/value-stream.svg +11 -0
  133. package/assets/archimate3/icons/value.svg +11 -0
  134. package/assets/archimate3/icons/work-package.svg +12 -0
  135. package/assets/archimate4/archimate4-element-shapes.ttl +404 -0
  136. package/assets/archimate4/archimate4-metamodel.ttl +179 -0
  137. package/assets/archimate4/archimate4-notation.ttl +1147 -0
  138. package/assets/archimate4/archimate4-onto.ttl +1559 -0
  139. package/assets/archimate4/archimate4-presentation-contexts.ttl +60 -0
  140. package/assets/archimate4/archimate4-principle-shapes.ttl +893 -0
  141. package/assets/archimate4/archimate4-questions.ttl +1224 -0
  142. package/assets/archimate4/archimate4-reference-data.ttl +56 -0
  143. package/assets/archimate4/archimate4-relationship-shapes.ttl +16920 -0
  144. package/assets/archimate4/archimate4-relationship-tables.ttl +3200 -0
  145. package/assets/archimate4/archimate4-tax.ttl +749 -0
  146. package/assets/archimate4/archimate4-viewpoint-shapes.ttl +55 -0
  147. package/assets/archimate4/archimate4-viewpoints.ttl +777 -0
  148. package/assets/archimate4/icons/and-junction.svg +3 -0
  149. package/assets/archimate4/icons/application-component.svg +18 -0
  150. package/assets/archimate4/icons/application-interface.svg +16 -0
  151. package/assets/archimate4/icons/artifact.svg +16 -0
  152. package/assets/archimate4/icons/assessment.svg +17 -0
  153. package/assets/archimate4/icons/business-actor.svg +22 -0
  154. package/assets/archimate4/icons/business-interface.svg +16 -0
  155. package/assets/archimate4/icons/business-object.svg +14 -0
  156. package/assets/archimate4/icons/capability.svg +40 -0
  157. package/assets/archimate4/icons/collaboration.svg +21 -0
  158. package/assets/archimate4/icons/communication-network.svg +18 -0
  159. package/assets/archimate4/icons/course-of-action.svg +20 -0
  160. package/assets/archimate4/icons/data-object.svg +14 -0
  161. package/assets/archimate4/icons/deliverable.svg +11 -0
  162. package/assets/archimate4/icons/device.svg +18 -0
  163. package/assets/archimate4/icons/distribution-network.svg +19 -0
  164. package/assets/archimate4/icons/driver.svg +24 -0
  165. package/assets/archimate4/icons/equipment.svg +31 -0
  166. package/assets/archimate4/icons/event.svg +15 -0
  167. package/assets/archimate4/icons/facility.svg +16 -0
  168. package/assets/archimate4/icons/function.svg +13 -0
  169. package/assets/archimate4/icons/glyphs/activity.svg +3 -0
  170. package/assets/archimate4/icons/glyphs/actor.svg +14 -0
  171. package/assets/archimate4/icons/glyphs/application-component.svg +12 -0
  172. package/assets/archimate4/icons/glyphs/artifact.svg +9 -0
  173. package/assets/archimate4/icons/glyphs/assessment.svg +9 -0
  174. package/assets/archimate4/icons/glyphs/capability.svg +32 -0
  175. package/assets/archimate4/icons/glyphs/cloud-gear.svg +3 -0
  176. package/assets/archimate4/icons/glyphs/collaboration.svg +15 -0
  177. package/assets/archimate4/icons/glyphs/communication-network.svg +12 -0
  178. package/assets/archimate4/icons/glyphs/constraint.svg +10 -0
  179. package/assets/archimate4/icons/glyphs/contract.svg +5 -0
  180. package/assets/archimate4/icons/glyphs/course-of-action.svg +12 -0
  181. package/assets/archimate4/icons/glyphs/data-object.svg +4 -0
  182. package/assets/archimate4/icons/glyphs/deliverable.svg +3 -0
  183. package/assets/archimate4/icons/glyphs/device.svg +10 -0
  184. package/assets/archimate4/icons/glyphs/distribution-network.svg +11 -0
  185. package/assets/archimate4/icons/glyphs/driver.svg +16 -0
  186. package/assets/archimate4/icons/glyphs/equipment.svg +22 -0
  187. package/assets/archimate4/icons/glyphs/event.svg +6 -0
  188. package/assets/archimate4/icons/glyphs/facility.svg +7 -0
  189. package/assets/archimate4/icons/glyphs/function.svg +6 -0
  190. package/assets/archimate4/icons/glyphs/gap.svg +14 -0
  191. package/assets/archimate4/icons/glyphs/goal.svg +10 -0
  192. package/assets/archimate4/icons/glyphs/grouping.svg +4 -0
  193. package/assets/archimate4/icons/glyphs/interaction.svg +10 -0
  194. package/assets/archimate4/icons/glyphs/interface.svg +8 -0
  195. package/assets/archimate4/icons/glyphs/location.svg +6 -0
  196. package/assets/archimate4/icons/glyphs/material.svg +12 -0
  197. package/assets/archimate4/icons/glyphs/meaning.svg +3 -0
  198. package/assets/archimate4/icons/glyphs/node.svg +8 -0
  199. package/assets/archimate4/icons/glyphs/object.svg +4 -0
  200. package/assets/archimate4/icons/glyphs/outcome.svg +16 -0
  201. package/assets/archimate4/icons/glyphs/path.svg +10 -0
  202. package/assets/archimate4/icons/glyphs/person-silhouette.svg +3 -0
  203. package/assets/archimate4/icons/glyphs/plateau.svg +8 -0
  204. package/assets/archimate4/icons/glyphs/principle.svg +12 -0
  205. package/assets/archimate4/icons/glyphs/process.svg +6 -0
  206. package/assets/archimate4/icons/glyphs/product.svg +4 -0
  207. package/assets/archimate4/icons/glyphs/representation.svg +4 -0
  208. package/assets/archimate4/icons/glyphs/requirement.svg +6 -0
  209. package/assets/archimate4/icons/glyphs/resource.svg +14 -0
  210. package/assets/archimate4/icons/glyphs/role.svg +6 -0
  211. package/assets/archimate4/icons/glyphs/service.svg +6 -0
  212. package/assets/archimate4/icons/glyphs/stakeholder.svg +6 -0
  213. package/assets/archimate4/icons/glyphs/system-software.svg +14 -0
  214. package/assets/archimate4/icons/glyphs/value-stream.svg +3 -0
  215. package/assets/archimate4/icons/glyphs/value.svg +3 -0
  216. package/assets/archimate4/icons/glyphs/work-package.svg +4 -0
  217. package/assets/archimate4/icons/goal.svg +18 -0
  218. package/assets/archimate4/icons/grouping.svg +12 -0
  219. package/assets/archimate4/icons/location.svg +14 -0
  220. package/assets/archimate4/icons/material.svg +21 -0
  221. package/assets/archimate4/icons/meaning.svg +11 -0
  222. package/assets/archimate4/icons/node.svg +14 -0
  223. package/assets/archimate4/icons/or-junction.svg +3 -0
  224. package/assets/archimate4/icons/outcome.svg +25 -0
  225. package/assets/archimate4/icons/path.svg +18 -0
  226. package/assets/archimate4/icons/plateau.svg +16 -0
  227. package/assets/archimate4/icons/principle.svg +21 -0
  228. package/assets/archimate4/icons/process.svg +15 -0
  229. package/assets/archimate4/icons/product.svg +12 -0
  230. package/assets/archimate4/icons/requirement.svg +14 -0
  231. package/assets/archimate4/icons/resource.svg +23 -0
  232. package/assets/archimate4/icons/role.svg +16 -0
  233. package/assets/archimate4/icons/service.svg +13 -0
  234. package/assets/archimate4/icons/stakeholder.svg +15 -0
  235. package/assets/archimate4/icons/system-software.svg +22 -0
  236. package/assets/archimate4/icons/technology-interface.svg +16 -0
  237. package/assets/archimate4/icons/value-stream.svg +11 -0
  238. package/assets/archimate4/icons/value.svg +11 -0
  239. package/assets/archimate4/icons/work-package.svg +12 -0
  240. package/assets/basic/basic-metamodel.ttl +100 -0
  241. package/assets/basic/basic-notation-bubble.ttl +175 -0
  242. package/assets/basic/basic-notation.ttl +172 -0
  243. package/assets/basic/basic-onto.ttl +171 -0
  244. package/assets/basic/basic-presentation-contexts.ttl +70 -0
  245. package/assets/basic/basic-tax.ttl +130 -0
  246. package/assets/basic/icons/aggregation.svg +7 -0
  247. package/assets/basic/icons/association.svg +6 -0
  248. package/assets/basic/icons/element.svg +5 -0
  249. package/assets/basic/icons/glyphs/aggregation.svg +6 -0
  250. package/assets/basic/icons/glyphs/association.svg +5 -0
  251. package/assets/basic/icons/glyphs/element.svg +5 -0
  252. package/assets/basic/icons/glyphs/relationship.svg +5 -0
  253. package/assets/basic/icons/relationship.svg +7 -0
  254. package/assets/basic/notation-bubble/icons/aggregation.svg +7 -0
  255. package/assets/basic/notation-bubble/icons/association.svg +6 -0
  256. package/assets/basic/notation-bubble/icons/element.svg +5 -0
  257. package/assets/basic/notation-bubble/icons/glyphs/aggregation.svg +6 -0
  258. package/assets/basic/notation-bubble/icons/glyphs/association.svg +5 -0
  259. package/assets/basic/notation-bubble/icons/glyphs/element.svg +5 -0
  260. package/assets/basic/notation-bubble/icons/glyphs/relationship.svg +5 -0
  261. package/assets/basic/notation-bubble/icons/relationship.svg +7 -0
  262. package/assets/catalog.ttl +7302 -0
  263. package/assets/core/core-notation.ttl +131 -0
  264. package/assets/core/core-onto.ttl +2811 -0
  265. package/assets/core/core-questions.ttl +957 -0
  266. package/assets/core/core-shapes.ttl +915 -0
  267. package/assets/core/core-vis-onto.ttl +1408 -0
  268. package/assets/core/core-vis-shapes.ttl +840 -0
  269. package/assets/core-vis/markers/circle-dot.svg +3 -0
  270. package/assets/core-vis/markers/closed-arrowhead.svg +3 -0
  271. package/assets/core-vis/markers/filled-diamond.svg +3 -0
  272. package/assets/core-vis/markers/half-arrowhead.svg +3 -0
  273. package/assets/core-vis/markers/hollow-arrowhead.svg +3 -0
  274. package/assets/core-vis/markers/hollow-diamond.svg +3 -0
  275. package/assets/core-vis/markers/open-arrowhead.svg +3 -0
  276. package/fixtures/interoperability/archimate4-demo.trig +259 -0
  277. package/fixtures/interoperability/expected-findings.json +26 -0
  278. package/fixtures/interoperability/shop-seed.ttl +225 -0
  279. package/package.json +136 -4
  280. package/scripts/sync-assets.mjs +252 -0
  281. package/src/conformance.ts +66 -0
  282. package/src/import-export/model-io.ts +426 -0
  283. package/src/index.ts +11 -0
  284. package/src/metamodel-manager/asset-sources.ts +754 -0
  285. package/src/metamodel-manager/bundled-assets.ts +599 -0
  286. package/src/metamodel-manager/catalogue.ts +114 -0
  287. package/src/metamodel-manager/class-hierarchy.ts +155 -0
  288. package/src/metamodel-manager/index.ts +65 -0
  289. package/src/metamodel-manager/interfaces.ts +422 -0
  290. package/src/metamodel-manager/metamodel-completeness.ts +162 -0
  291. package/src/metamodel-manager/metamodel-loader.ts +864 -0
  292. package/src/metamodel-manager/notation-resolver.ts +284 -0
  293. package/src/metamodel-manager/notation.ts +659 -0
  294. package/src/metamodel-manager/palette-generator.ts +882 -0
  295. package/src/metamodel-manager/property-shapes.ts +290 -0
  296. package/src/metamodel-manager/taxonomy.ts +904 -0
  297. package/src/metamodel-manager/type-guide.ts +241 -0
  298. package/src/metamodel-manager/viewpoint-manager.ts +147 -0
  299. package/src/model-manager/appearance.ts +389 -0
  300. package/src/model-manager/cascade.ts +246 -0
  301. package/src/model-manager/clipboard.ts +566 -0
  302. package/src/model-manager/context-names.ts +108 -0
  303. package/src/model-manager/custom-properties.ts +549 -0
  304. package/src/model-manager/derivations.ts +166 -0
  305. package/src/model-manager/direct-permissions.ts +182 -0
  306. package/src/model-manager/drawing-order.ts +119 -0
  307. package/src/model-manager/element-manager.ts +69 -0
  308. package/src/model-manager/element-pictures.ts +118 -0
  309. package/src/model-manager/field-names.ts +42 -0
  310. package/src/model-manager/folders.ts +354 -0
  311. package/src/model-manager/grid.ts +6 -0
  312. package/src/model-manager/index.ts +43 -0
  313. package/src/model-manager/interfaces.ts +417 -0
  314. package/src/model-manager/iri-conformance.ts +183 -0
  315. package/src/model-manager/label-expression.ts +233 -0
  316. package/src/model-manager/legacy-migration.ts +200 -0
  317. package/src/model-manager/missing-references.ts +86 -0
  318. package/src/model-manager/model-diff-text.ts +150 -0
  319. package/src/model-manager/model-diff.ts +534 -0
  320. package/src/model-manager/model-merge.ts +1160 -0
  321. package/src/model-manager/model-namespace.ts +199 -0
  322. package/src/model-manager/model-operations.ts +132 -0
  323. package/src/model-manager/model-queries.ts +616 -0
  324. package/src/model-manager/model-session.ts +759 -0
  325. package/src/model-manager/multiplicity.ts +74 -0
  326. package/src/model-manager/nested-resources.ts +145 -0
  327. package/src/model-manager/own-metamodel.ts +157 -0
  328. package/src/model-manager/placement-copy.ts +116 -0
  329. package/src/model-manager/property-catalog.ts +787 -0
  330. package/src/model-manager/proposal-order.ts +203 -0
  331. package/src/model-manager/provenance.ts +396 -0
  332. package/src/model-manager/questions.ts +470 -0
  333. package/src/model-manager/rdf-scope.ts +97 -0
  334. package/src/model-manager/relationship-graph.ts +462 -0
  335. package/src/model-manager/relationship-manager.ts +962 -0
  336. package/src/model-manager/relationship-table.ts +189 -0
  337. package/src/model-manager/relationship-validity.ts +261 -0
  338. package/src/model-manager/resource-edits.ts +28 -0
  339. package/src/model-manager/short-hash.ts +104 -0
  340. package/src/model-manager/snapshot-lines.ts +88 -0
  341. package/src/model-manager/version-history.ts +205 -0
  342. package/src/model-manager/view-from-results.ts +81 -0
  343. package/src/model-manager/view-manager.ts +1410 -0
  344. package/src/model-manager/vocabulary.ts +279 -0
  345. package/src/rdf-engine/finding-shape.ts +23 -0
  346. package/src/rdf-engine/graph-scope.ts +163 -0
  347. package/src/rdf-engine/index.ts +7 -0
  348. package/src/rdf-engine/interfaces.ts +144 -0
  349. package/src/rdf-engine/iri.ts +203 -0
  350. package/src/rdf-engine/localized-text.ts +13 -0
  351. package/src/rdf-engine/namespaces.ts +41 -0
  352. package/src/rdf-engine/observable-store.ts +631 -0
  353. package/src/rdf-engine/rdf-store.ts +508 -0
  354. package/src/rdf-engine/shacl-validator.ts +602 -0
  355. package/src/rdf-engine/shape-reach.ts +140 -0
  356. package/src/rdf-engine/shape-switches.ts +165 -0
  357. package/src/rdf-engine/single-valued.ts +219 -0
  358. package/src/rdf-engine/sparql-constraints.ts +334 -0
  359. package/src/rdf-engine/term-codec.ts +51 -0
  360. package/src/rdf-engine/ttl-parser.ts +51 -0
  361. package/src/rdf-engine/ttl-serializer.ts +79 -0
  362. package/src/rdf-engine/turtle-writer.ts +284 -0
  363. package/src/rdf-engine/validation-engine.ts +682 -0
  364. package/src/rdf-engine/validation-service.ts +184 -0
  365. package/src/rdf-engine/validation.worker.ts +47 -0
@@ -0,0 +1,1160 @@
1
+ /**
2
+ * Three-way merge of a model: a common version (base) and two versions made
3
+ * from it (ours, theirs) give one model with both sets of changes, and the
4
+ * conflicts between them as data — never as `<<<<<<<` markers in a file, which
5
+ * would leave it unreadable to every RDF tool, la-gram included.
6
+ *
7
+ * ## What is merged
8
+ *
9
+ * Snapshots as {@link snapshotOf} makes them: the model as la-gram holds it, one
10
+ * canonical N-Triples line per triple. A file from Git becomes one with
11
+ * {@link snapshotOfText}, which reads it as opening it does — every graph into
12
+ * the model — so a TriG file's DD-15 graphs are not lost: the merged model is
13
+ * saved like any other, and the save partitions it again.
14
+ *
15
+ * ## How
16
+ *
17
+ * Every changed triple is merged in one of these units, the first that applies:
18
+ *
19
+ * 1. **A deleted concept** — something that has triples in base and none on one
20
+ * side — conflicts when the other side *added* a triple about it or pointing
21
+ * to it: changed it, related something to it, placed it in a view, filed it
22
+ * in a folder. Removals on the other side agree with a deletion, so deleting
23
+ * on both sides, or deleting a relationship the other side's deletion also
24
+ * took, merges cleanly. While the conflict is open the concept is kept: the
25
+ * deletion is undone, with what went with it (its relationships, nodes,
26
+ * links, routes) where those can come back whole.
27
+ * 2. **A line's route** — `arch-vis:points` and every list cell and point reached
28
+ * from it — and **a node's bounds** — the four `arch-vis:bounds-*` — each
29
+ * merge as a whole. Merged triple by triple, two reroutes of one line would
30
+ * make a route neither person drew, and a move on one side and a resize on
31
+ * the other a box neither made.
32
+ * 3. **A relationship's connection** — its types, `arch:source`, `arch:target`,
33
+ * `rdf:reifies`, the triple it reifies and the qualified predicate from its
34
+ * source — and **a concept's types** merge as a whole too: a retarget or a
35
+ * retype changes several triples that only make sense together. They are
36
+ * reported as conflicts of a single value.
37
+ * 4. **A single value** — a property that takes one value, or one per language
38
+ * (`rdf-engine/single-valued.ts`, shared with the room).
39
+ * 5. **Everything else**, triple by triple: kept when either side added it,
40
+ * dropped when either side removed it.
41
+ *
42
+ * A unit changed on one side only takes that side's version; changed alike on
43
+ * both, that version; changed differently, it is a conflict and the merged
44
+ * model holds base's version — neither side's change wins unseen, the model
45
+ * stays as valid as base was, and the result is the same whichever side is
46
+ * "ours".
47
+ *
48
+ * ## A model moved to another namespace
49
+ *
50
+ * Moving a model renames every IRI in it, so merged as they are, a move on one
51
+ * side and an edit on the other read as "everything deleted on one side". A
52
+ * merge therefore first looks for a move — the model under another IRI than
53
+ * base's, `{to}model` — and moves base and the other side after it into the
54
+ * mover's namespace (`vann:preferredNamespaceUri`, else derived from the
55
+ * model's IRI), keeping every local part, as moving it in la-gram does
56
+ * (`planNamespaceChange`; DD-41, scenario S7). Both sides moved it alike: base
57
+ * is moved. Each to a namespace of its own: {@link NamespaceConflict}, not
58
+ * merged.
59
+ *
60
+ * Then, on the merged model:
61
+ *
62
+ * - **Two placements**: both sides placed the same element (or drew the same
63
+ * relationship) in the same view, each with a node of its own. An element
64
+ * may be placed in a view more than once, so the merged model keeps both,
65
+ * with what each side drew at it; the conflict offers to keep only one — two
66
+ * people placing the same element at once most likely meant it once.
67
+ * - **The provenance of edits** (Req 9.16): a concept each side changed names
68
+ * each side's editing activity; it keeps the one that ended later, as its
69
+ * `prov:generatedAtTime` and `dcterms:modified` are the later of the two
70
+ * (`latest`, never a conflict), and an editing activity no concept names any
71
+ * more goes, with a person or a la-gram version nothing names
72
+ * ({@link settleEditProvenance}).
73
+ * - **Count limits** broken by the combination: each side added a value where
74
+ * the shapes allow two, or each removed a different one of the values a
75
+ * shape requires. Checked with the in-app SHACL validator ({@link shaclCountCheck}),
76
+ * on the nodes both sides changed, and reported only where neither side alone
77
+ * breaks the limit.
78
+ *
79
+ * ## Resolving
80
+ *
81
+ * A conflict names the lines of the merged model that stand for it (`held`) and,
82
+ * for each side, the lines that replace them ({@link applyChoice}). For a
83
+ * deleted concept, the deleting side's lines remove it with everything the other
84
+ * side hung on it — its new relationships to it, its new nodes for it and their
85
+ * links — so nothing is left pointing at nothing.
86
+ *
87
+ * ## Blank nodes
88
+ *
89
+ * Their labels are not kept between files, so a triple about a blank node in
90
+ * one version does not match the same triple in another: it shows as removed
91
+ * and added, and both sides' copies end up in the merged model. Models made in
92
+ * la-gram have none; a save to Git warns about an imported model that has.
93
+ */
94
+
95
+ import { DataFactory, Parser as N3Parser, Store as N3Store } from 'n3';
96
+ import type { Quad, Term } from '@rdfjs/types';
97
+ import { NAMESPACES } from '../rdf-engine/namespaces.js';
98
+ import { ensureNamespace } from '../rdf-engine/iri.js';
99
+ import { SingleValued } from '../rdf-engine/single-valued.js';
100
+ import type { RdfShaclValidator } from '../rdf-engine/shacl-validator.js';
101
+ import { detectFormat } from '../metamodel-manager/asset-sources.js';
102
+ import { parseModelText } from '../import-export/model-io.js';
103
+ import { derivedNamespace } from './model-namespace.js';
104
+ import { diffSnapshots, snapshotOf } from './version-history.js';
105
+ import { BOUNDS_PREDICATES, IRI } from './vocabulary.js';
106
+ import { iriOf, literalValue, parseLine, predicateOf, subjectOf, type Line } from './snapshot-lines.js';
107
+ import { LA_GRAM_HOME } from './provenance.js';
108
+
109
+ /** One of the two versions merged into base. */
110
+ export type MergeSide = 'ours' | 'theirs';
111
+
112
+ /** What a conflict is about. */
113
+ export type MergeConflictKind = 'deleted' | 'placement' | 'value' | 'bounds' | 'route' | 'count';
114
+
115
+ /** A conflict, as data: what it is about, and the lines each choice gives. */
116
+ export interface MergeConflict {
117
+ kind: MergeConflictKind;
118
+ /**
119
+ * What it is about, as IRIs (a blank node as `_:label`): a value's, bounds' or
120
+ * route's subject; the deleted concepts kept for now; the two nodes or links
121
+ * of a placement; the focus node of a count.
122
+ */
123
+ subjects: string[];
124
+ /** The property: a value's, a count's. */
125
+ predicate?: string;
126
+ /** A value's language, for a property that takes one per language (`''`: none). */
127
+ language?: string;
128
+ /** Which side deleted the concepts (`deleted`). */
129
+ deletedBy?: MergeSide;
130
+ /** The validator's message (`count`). */
131
+ message?: string;
132
+ /** Lines of the merged snapshot that stand for this conflict until it is resolved. */
133
+ held: string[];
134
+ /** For each side, the lines that replace {@link held} when that side's version is chosen. */
135
+ options: Record<MergeSide, string[]>;
136
+ }
137
+
138
+ /** The merged snapshot, and what is left to decide. */
139
+ export interface MergeResult {
140
+ merged: string[];
141
+ conflicts: MergeConflict[];
142
+ /**
143
+ * The model was moved to another namespace — on one side, or alike on both —
144
+ * and base and the other side were moved after it before merging. Absent when
145
+ * nothing had to be moved, a side left as base included.
146
+ */
147
+ moved?: NamespaceMove;
148
+ }
149
+
150
+ /** A model's IRI and namespace, as a snapshot has them. */
151
+ export interface SnapshotModel {
152
+ /** The `arch:Model`. */
153
+ model: string;
154
+ /** Its `vann:preferredNamespaceUri`, else the namespace derived from its IRI (`model-namespace.ts`). */
155
+ namespace: string;
156
+ }
157
+
158
+ /** A move of the model to another namespace, found by a merge. */
159
+ export interface NamespaceMove {
160
+ /** Base's namespace. */
161
+ from: string;
162
+ /** The namespace it was moved to. */
163
+ to: string;
164
+ /** Who moved it: one side, or both alike. */
165
+ by: MergeSide | 'both';
166
+ }
167
+
168
+ /**
169
+ * Both sides moved the model, each to a namespace of its own (each renamed it
170
+ * otherwise): there is no one namespace to merge into, so the versions are not
171
+ * merged until one side follows the other.
172
+ */
173
+ export class NamespaceConflict extends Error {
174
+ constructor(
175
+ readonly base: SnapshotModel,
176
+ readonly ours: SnapshotModel,
177
+ readonly theirs: SnapshotModel,
178
+ ) {
179
+ const name = (m: SnapshotModel) => (ours.namespace !== theirs.namespace ? m.namespace : m.model);
180
+ super(`Both sides moved the model, ours to ${name(ours)} and theirs to ${name(theirs)}: move one to the other's namespace, then merge again`);
181
+ this.name = 'NamespaceConflict';
182
+ }
183
+ }
184
+
185
+ /** A count limit a snapshot breaks at a node. */
186
+ export interface CountFinding {
187
+ /** The node, as an N-Triples term (`<iri>`, `_:label`). */
188
+ focus: string;
189
+ /** The property path's IRI, or `''` for a path that is not a single property. */
190
+ path: string;
191
+ /** The SHACL constraint component. */
192
+ component: string;
193
+ message: string;
194
+ }
195
+
196
+ /** Find count-limit results for these nodes (N-Triples terms) of a snapshot. */
197
+ export type CountCheck = (snapshot: readonly string[], focus: readonly string[]) => CountFinding[];
198
+
199
+ /** Options for {@link mergeSnapshots}. */
200
+ export interface MergeOptions {
201
+ /** Which properties take one value; the built-in rules when absent. */
202
+ singleValued?: SingleValued;
203
+ /** Checks count limits; without it they are not looked for. */
204
+ counts?: CountCheck;
205
+ }
206
+
207
+ const SIDES: readonly MergeSide[] = ['ours', 'theirs'];
208
+ const other = (side: MergeSide): MergeSide => (side === 'ours' ? 'theirs' : 'ours');
209
+
210
+ const RDF_TYPE = IRI.rdfType;
211
+ const NIL = `<${IRI.rdfNil}>`;
212
+ const BOUNDS = new Set<string>(BOUNDS_PREDICATES);
213
+ /** A subject naming something with one of these cannot be without it: a relationship its ends, a node its element and view, a link its relationship and ends. */
214
+ const REQUIRES = new Set<string>([
215
+ IRI.source,
216
+ IRI.target,
217
+ IRI.legacyRelSource,
218
+ IRI.legacyRelTarget,
219
+ IRI.archElement,
220
+ IRI.archRelationship,
221
+ IRI.visView,
222
+ IRI.visSource,
223
+ IRI.visTarget,
224
+ ]);
225
+ /** What a subject names with one of these is part of it: a link's route cells and label, a cell's point and next cell. */
226
+ const OWNS = new Set<string>([IRI.points, IRI.rdfFirst, IRI.rdfRest, IRI.visLabel]);
227
+ const LINK_ENDS = new Set<string>([IRI.visSource, IRI.visTarget]);
228
+ /** A relationship's own lines that say what it connects, and how. */
229
+ const CONNECTION = new Set<string>([RDF_TYPE, IRI.source, IRI.target, IRI.reifies]);
230
+ /** What makes a subject a relationship. */
231
+ const RELATIONSHIP_MARKS = new Set<string>([IRI.source, IRI.target, IRI.reifies]);
232
+ const KIND_ORDER: readonly MergeConflictKind[] = ['deleted', 'placement', 'value', 'bounds', 'route', 'count'];
233
+ const COUNT_COMPONENTS = new Set(
234
+ ['MinCount', 'MaxCount', 'QualifiedMinCount', 'QualifiedMaxCount'].map((c) => `${NAMESPACES.sh}${c}ConstraintComponent`),
235
+ );
236
+
237
+ /**
238
+ * Merge `ours` and `theirs`, both made from `base`. All three are snapshots
239
+ * ({@link snapshotOf}); so is the result.
240
+ *
241
+ * @throws NamespaceConflict when the sides moved the model to different namespaces.
242
+ */
243
+ export function mergeSnapshots(
244
+ base: readonly string[],
245
+ ours: readonly string[],
246
+ theirs: readonly string[],
247
+ options: MergeOptions = {},
248
+ ): MergeResult {
249
+ const o = new Set(ours);
250
+ const t = new Set(theirs);
251
+ if (sameSet(o, t)) return { merged: sortedOf(o), conflicts: [] };
252
+ const b = new Set(base);
253
+ if (sameSet(b, o)) return { merged: sortedOf(t), conflicts: [] };
254
+ if (sameSet(b, t)) return { merged: sortedOf(o), conflicts: [] };
255
+ const aligned = alignNamespaces(base, ours, theirs);
256
+ if (aligned) return { ...mergeSnapshots(aligned.base, aligned.ours, aligned.theirs, options), moved: aligned.moved };
257
+ const result = new ThreeWay(b, o, t, options).run();
258
+ return { ...result, merged: settleEditProvenance(result.merged) };
259
+ }
260
+
261
+ const PROV_GENERATED_BY = NAMESPACES.prov + 'wasGeneratedBy';
262
+ const PROV_ENDED = NAMESPACES.prov + 'endedAtTime';
263
+ const PROV_ASSOCIATED = NAMESPACES.prov + 'wasAssociatedWith';
264
+
265
+ /**
266
+ * The provenance of edits after a merge: a concept named by two editing activities — one each side — keeps the
267
+ * one that ended later; then la-gram's activities no concept names go, and the people and la-gram versions no
268
+ * remaining line names. A converter's run is not la-gram's, and stays (`model-manager/provenance.ts`).
269
+ */
270
+ export function settleEditProvenance(lines: readonly string[]): string[] {
271
+ const generatedBy = new Map<string, string[]>();
272
+ const ended = new Map<string, string>();
273
+ const associated = new Map<string, string[]>();
274
+ for (const line of lines) {
275
+ const p = predicateOf(line);
276
+ if (p === PROV_GENERATED_BY) push(generatedBy, subjectOf(line), line);
277
+ else if (p === PROV_ENDED) ended.set(subjectOf(line), parseLine(line).o);
278
+ else if (p === PROV_ASSOCIATED) push(associated, subjectOf(line), parseLine(line).o);
279
+ }
280
+ const drop = new Set<string>();
281
+ for (const named of generatedBy.values()) {
282
+ if (named.length < 2) continue;
283
+ const endOf = (line: string) => ended.get(parseLine(line).o) ?? '';
284
+ const kept = named.reduce((a, b) => (endOf(b) > endOf(a) ? b : a));
285
+ for (const line of named) if (line !== kept) drop.add(line);
286
+ }
287
+ if (drop.size === 0) return [...lines];
288
+ const named = new Set([...generatedBy.values()].flat().filter((l) => !drop.has(l)).map((l) => parseLine(l).o));
289
+ const laGram = (term: string) => term.startsWith(`<${LA_GRAM_HOME}`);
290
+ const gone = new Set<string>();
291
+ for (const [activity, agents] of associated) {
292
+ if (!named.has(activity) && agents.some(laGram)) gone.add(activity);
293
+ }
294
+ let kept = lines.filter((l) => !drop.has(l) && !gone.has(subjectOf(l)));
295
+ // People and la-gram versions only the dropped activities named.
296
+ const stillNamed = new Set(kept.flatMap((l) => parseLine(l).refs));
297
+ const orphans = new Set(
298
+ [...gone].flatMap((a) => associated.get(a) ?? []).filter((agent) => !stillNamed.has(agent)),
299
+ );
300
+ if (orphans.size > 0) kept = kept.filter((l) => !orphans.has(subjectOf(l)));
301
+ return kept;
302
+ }
303
+
304
+ /** The merged snapshot with one conflict resolved to one side's version. */
305
+ export function applyChoice(merged: readonly string[], conflict: MergeConflict, side: MergeSide): string[] {
306
+ const result = new Set(merged);
307
+ for (const line of conflict.held) result.delete(line);
308
+ for (const line of conflict.options[side]) result.add(line);
309
+ return sortedOf(result);
310
+ }
311
+
312
+ /**
313
+ * A file's model as a snapshot, read as opening the file reads it: by its
314
+ * name's extension, every graph into the model.
315
+ */
316
+ export function snapshotOfText(text: string, fileName: string): string[] {
317
+ return snapshotOf(parseModelText(text, detectFormat(null, fileName)));
318
+ }
319
+
320
+ /**
321
+ * A {@link CountCheck} by the in-app SHACL validator: `shapes` against the
322
+ * focus nodes, their triples, the triples pointing at them and the types of
323
+ * what they name, with `context` — the class hierarchy and the types of
324
+ * referenced metamodel resources, as validating the model is given them.
325
+ */
326
+ export function shaclCountCheck(validator: RdfShaclValidator, shapes: Quad[], context: Quad[] = []): CountCheck {
327
+ return (snapshot, focus) => {
328
+ if (focus.length === 0 || shapes.length === 0) return [];
329
+ const nodes = new Set(focus);
330
+ const near: string[] = [];
331
+ const named = new Set<string>();
332
+ for (const line of snapshot) {
333
+ const { s, refs } = parseLine(line);
334
+ if (nodes.has(s)) {
335
+ near.push(line);
336
+ for (const ref of refs) named.add(ref);
337
+ } else if (refs.some((r) => nodes.has(r))) near.push(line);
338
+ }
339
+ for (const line of snapshot) {
340
+ const { s, p } = parseLine(line);
341
+ if (p === RDF_TYPE && named.has(s) && !nodes.has(s)) near.push(line);
342
+ }
343
+ const data = new N3Store([...quadsOfSnapshot(near), ...context] as never[]);
344
+ const report = validator.validateNodes(data, shapes, focus.map(termOf));
345
+ const findings: CountFinding[] = [];
346
+ for (const result of report.results) {
347
+ const component = result.sourceConstraintComponent?.value ?? '';
348
+ if (!COUNT_COMPONENTS.has(component)) continue;
349
+ const value = result.focusNode.value;
350
+ const path = result.resultPath.value;
351
+ findings.push({
352
+ focus: nodes.has(`_:${value}`) ? `_:${value}` : `<${value}>`,
353
+ path: /^[a-z][a-z0-9+.-]*:/i.test(path) ? path : '',
354
+ component,
355
+ message: result.message,
356
+ });
357
+ }
358
+ return findings;
359
+ };
360
+ }
361
+
362
+ // ── A model moved to another namespace ────────────────────────────────────
363
+
364
+ const MODEL_TYPE = `<${IRI.Model}>`;
365
+ const VANN_URI = NAMESPACES.vann + 'preferredNamespaceUri';
366
+
367
+ /** The model a snapshot is of, and its namespace; `undefined` without exactly one `arch:Model`. */
368
+ export function snapshotModel(lines: readonly string[]): SnapshotModel | undefined {
369
+ const models: string[] = [];
370
+ const declared = new Map<string, string>();
371
+ for (const line of lines) {
372
+ const p = predicateOf(line);
373
+ if (p === RDF_TYPE) {
374
+ if (line.endsWith(` ${MODEL_TYPE} .`)) models.push(subjectOf(line));
375
+ } else if (p === VANN_URI) {
376
+ const s = subjectOf(line);
377
+ const value = literalValue(parseLine(line).o)?.trim();
378
+ // The first, as lines sort, when a model states more than one.
379
+ if (value && !declared.has(s)) declared.set(s, value);
380
+ }
381
+ }
382
+ if (models.length !== 1 || !models[0]!.startsWith('<')) return undefined;
383
+ const model = iriOf(models[0]!);
384
+ const uri = declared.get(models[0]!);
385
+ return { model, namespace: uri ? ensureNamespace(uri) : derivedNamespace(model) };
386
+ }
387
+
388
+ /** Base and the sides, moved after the side that moved the model; `undefined` when neither did. */
389
+ function alignNamespaces(
390
+ base: readonly string[],
391
+ ours: readonly string[],
392
+ theirs: readonly string[],
393
+ ): { base: string[]; ours: string[]; theirs: string[]; moved: NamespaceMove } | undefined {
394
+ const b = snapshotModel(base);
395
+ const o = snapshotModel(ours);
396
+ const t = snapshotModel(theirs);
397
+ if (!b || !o || !t) return undefined;
398
+ // A move renames the model (`{to}model`). A namespace set without moving the IRIs only
399
+ // changes where new ones are minted: its statement merges as any other value.
400
+ const moved: Record<MergeSide, boolean> = { ours: o.model !== b.model, theirs: t.model !== b.model };
401
+ if (!moved.ours && !moved.theirs) return undefined;
402
+ if (moved.ours && moved.theirs && o.model !== t.model) throw new NamespaceConflict(b, o, t);
403
+ const to = moved.ours ? o : t;
404
+ const movers = SIDES.filter((side) => moved[side]).map((side) => (side === 'ours' ? ours : theirs));
405
+ // What a mover still has, its move left alone: a vocabulary's term in the old namespace.
406
+ const kept = new Set<string>();
407
+ for (const lines of movers) {
408
+ for (const line of lines) {
409
+ const { s, p, refs } = parseLine(line);
410
+ kept.add(iriOf(s));
411
+ kept.add(p);
412
+ for (const ref of refs) kept.add(iriOf(ref));
413
+ }
414
+ }
415
+ const declaration = movers[0]!.filter((line) => predicateOf(line) === VANN_URI && subjectOf(line) === `<${to.model}>`);
416
+ const move = (lines: readonly string[]) => moveLines(lines, b, to, kept, declaration);
417
+ return {
418
+ base: move(base),
419
+ ours: moved.ours ? [...ours] : move(ours),
420
+ theirs: moved.theirs ? [...theirs] : move(theirs),
421
+ moved: { from: b.namespace, to: to.namespace, by: moved.ours && moved.theirs ? 'both' : moved.ours ? 'ours' : 'theirs' },
422
+ };
423
+ }
424
+
425
+ /**
426
+ * Lines moved from one model's namespace to another's, as moving the model in
427
+ * la-gram moves them (`planNamespaceChange`): the model to its new IRI, every
428
+ * other IRI under the old namespace — inside a triple term too — to the same
429
+ * local part under the new one, unless it is `kept`; the model's
430
+ * `vann:preferredNamespaceUri` replaced by `declaration`.
431
+ */
432
+ function moveLines(
433
+ lines: readonly string[],
434
+ from: SnapshotModel,
435
+ to: SnapshotModel,
436
+ kept: ReadonlySet<string>,
437
+ declaration: readonly string[],
438
+ ): string[] {
439
+ const renamed = (iri: string): string => {
440
+ if (iri === from.model) return to.model;
441
+ if (kept.has(iri) || !iri.startsWith(from.namespace) || iri.length === from.namespace.length) return iri;
442
+ return `${to.namespace}${iri.slice(from.namespace.length)}`;
443
+ };
444
+ const term = (t: Term): Term => {
445
+ if (t.termType === 'NamedNode') {
446
+ const next = renamed(t.value);
447
+ return next === t.value ? t : (DataFactory.namedNode(next) as unknown as Term);
448
+ }
449
+ if (t.termType === 'Quad') {
450
+ const inner = t as unknown as Quad;
451
+ return DataFactory.quad(term(inner.subject) as never, term(inner.predicate) as never, term(inner.object) as never) as unknown as Term;
452
+ }
453
+ return t;
454
+ };
455
+ const quads = quadsOfSnapshot(lines)
456
+ .map((q) => DataFactory.quad(term(q.subject) as never, term(q.predicate) as never, term(q.object) as never) as unknown as Quad)
457
+ .filter((q) => !(q.subject.value === to.model && q.predicate.value === VANN_URI));
458
+ return sortedOf(new Set([...snapshotOf(quads), ...declaration]));
459
+ }
460
+
461
+ // ── The merge ─────────────────────────────────────────────────────────────
462
+
463
+ /** A unit merged as a whole. */
464
+ type Unit =
465
+ | { kind: 'route'; subject: string }
466
+ | { kind: 'bounds'; subject: string }
467
+ /** A relationship's kind and ends: its types, `arch:source`/`arch:target`, `rdf:reifies`, the triple it reifies, the qualified predicate to it. */
468
+ | { kind: 'connection'; subject: string }
469
+ /** A concept's types. */
470
+ | { kind: 'types'; subject: string }
471
+ /** `latest`: changed differently on each side, the later value is taken (`dcterms:modified`). */
472
+ | { kind: 'value'; subject: string; predicate: string; language?: string; latest?: boolean };
473
+
474
+ /** A deletion kept for now, until the person decides. */
475
+ interface PendingDeletion {
476
+ deletedBy: MergeSide;
477
+ /** The deleted subjects kept. */
478
+ subjects: string[];
479
+ /** They, and what the other side hung on them. */
480
+ scope: Set<string>;
481
+ }
482
+
483
+ const EMPTY: readonly string[] = [];
484
+
485
+ /** One version's lines, with its triples by subject. */
486
+ class Version {
487
+ private index?: Map<string, string[]>;
488
+
489
+ constructor(readonly lines: Set<string>) {}
490
+
491
+ has(line: string): boolean {
492
+ return this.lines.has(line);
493
+ }
494
+
495
+ of(subject: string): readonly string[] {
496
+ return this.bySubject().get(subject) ?? EMPTY;
497
+ }
498
+
499
+ hasSubject(subject: string): boolean {
500
+ return this.bySubject().has(subject);
501
+ }
502
+
503
+ add(lines: Iterable<string>): void {
504
+ for (const line of lines) {
505
+ if (this.lines.has(line)) continue;
506
+ this.lines.add(line);
507
+ if (this.index) push(this.index, subjectOf(line), line);
508
+ }
509
+ }
510
+
511
+ private bySubject(): Map<string, string[]> {
512
+ if (!this.index) {
513
+ this.index = new Map();
514
+ for (const line of this.lines) push(this.index, subjectOf(line), line);
515
+ }
516
+ return this.index;
517
+ }
518
+ }
519
+
520
+ class ThreeWay {
521
+ private readonly rules: SingleValued;
522
+ private readonly base: Version;
523
+ private readonly side: Record<MergeSide, Version>;
524
+ /** Each side's lines as given, before deletions were undone. */
525
+ private readonly given: Record<MergeSide, ReadonlySet<string>>;
526
+ private readonly added: Record<MergeSide, string[]>;
527
+ private readonly removed: Record<MergeSide, Set<string>>;
528
+ /** What owns a list cell, point or label node (by `OWNS`), in base and in what was added. */
529
+ private readonly ownersInBase = new Map<string, Array<{ parent: string; via: string }>>();
530
+ private readonly ownersAdded = new Map<string, Array<{ parent: string; via: string }>>();
531
+ /** The relationships reifying a triple, by the triple's line; and the triples a relationship reifies. */
532
+ private readonly reifiers = new Map<string, Set<string>>();
533
+ private readonly reified = new Map<string, Set<string>>();
534
+ private readonly relationships = new Map<string, boolean>();
535
+ private readonly lines = new Map<string, Line>();
536
+ private readonly conflicts: MergeConflict[] = [];
537
+ private merged = new Set<string>();
538
+
539
+ constructor(
540
+ base: Set<string>,
541
+ ours: Set<string>,
542
+ theirs: Set<string>,
543
+ private readonly options: MergeOptions,
544
+ ) {
545
+ this.rules = options.singleValued ?? SingleValued.builtIn();
546
+ this.base = new Version(base);
547
+ this.given = { ours, theirs };
548
+ this.side = { ours: new Version(new Set(ours)), theirs: new Version(new Set(theirs)) };
549
+ const baseLines = [...base];
550
+ const diff = { ours: diffSnapshots(baseLines, [...ours]), theirs: diffSnapshots(baseLines, [...theirs]) };
551
+ this.added = { ours: diff.ours.added, theirs: diff.theirs.added };
552
+ this.removed = { ours: new Set(diff.ours.removed), theirs: new Set(diff.theirs.removed) };
553
+ }
554
+
555
+ run(): MergeResult {
556
+ this.readStructure();
557
+ const deletions = SIDES.flatMap((side) => this.keepDeleted(side));
558
+ this.merged = new Set(this.base.lines);
559
+ this.mergeChanges();
560
+ this.recordDeletions(deletions);
561
+ const placed = new Set<string>();
562
+ this.placements(IRI.archElement, placed);
563
+ this.placements(IRI.archRelationship, placed);
564
+ if (this.options.counts) this.countLimits(this.options.counts);
565
+ return { merged: sortedOf(this.merged), conflicts: this.conflicts.sort(byConflict) };
566
+ }
567
+
568
+ private parse(line: string): Line {
569
+ let parsed = this.lines.get(line);
570
+ if (!parsed) {
571
+ parsed = parseLine(line);
572
+ this.lines.set(line, parsed);
573
+ }
574
+ return parsed;
575
+ }
576
+
577
+ /** The subject and every node the object names. */
578
+ private nodesOf(line: string): string[] {
579
+ const { s, refs } = this.parse(line);
580
+ return [s, ...refs];
581
+ }
582
+
583
+ /**
584
+ * Who owns what, by `OWNS`, and which triples relationships reify: in base,
585
+ * and in what either side added.
586
+ */
587
+ private readStructure(): void {
588
+ const read = (lines: Iterable<string>, into: Map<string, Array<{ parent: string; via: string }>>) => {
589
+ for (const line of lines) {
590
+ const p = predicateOf(line);
591
+ if (p === IRI.reifies) {
592
+ const { s, refs } = this.parse(line);
593
+ if (refs.length !== 3) continue;
594
+ const reified = `${refs[0]} ${refs[1]} ${refs[2]} .`;
595
+ const set = this.reifiers.get(reified) ?? new Set<string>();
596
+ set.add(s);
597
+ this.reifiers.set(reified, set);
598
+ const triples = this.reified.get(s) ?? new Set<string>();
599
+ triples.add(reified);
600
+ this.reified.set(s, triples);
601
+ continue;
602
+ }
603
+ if (!OWNS.has(p)) continue;
604
+ const { s, refs } = this.parse(line);
605
+ for (const ref of refs) push(into, ref, { parent: s, via: p });
606
+ }
607
+ };
608
+ read(this.base.lines, this.ownersInBase);
609
+ for (const side of SIDES) read(this.added[side], this.ownersAdded);
610
+ }
611
+
612
+ // ── 1. Deleted concepts ──────────────────────────────────────────────
613
+
614
+ /**
615
+ * Undo `side`'s deletions that the other side added to: put back, on `side`,
616
+ * the base triples of what is kept. What is kept: the deleted subjects the
617
+ * other side's additions name; what those need (their element, view, ends —
618
+ * `REQUIRES`) and are made of (`OWNS`, both ways); and what was deleted with
619
+ * them that needs them and can come back whole.
620
+ */
621
+ private keepDeleted(side: MergeSide): PendingDeletion[] {
622
+ const mine = this.side[side];
623
+ const deleted = new Set<string>();
624
+ for (const line of this.removed[side]) {
625
+ const s = subjectOf(line);
626
+ if (mine.hasSubject(s) || deleted.has(s)) continue;
627
+ // A cell or point of a route whose line is still there: the route merges as a whole.
628
+ const link = this.routeOf(s);
629
+ if (link && mine.hasSubject(link)) continue;
630
+ deleted.add(s);
631
+ }
632
+ if (deleted.size === 0) return [];
633
+
634
+ const seeds: string[][] = [];
635
+ for (const line of this.added[other(side)]) {
636
+ if (mine.has(line)) continue;
637
+ const hit = this.nodesOf(line).filter((n) => deleted.has(n));
638
+ if (hit.length > 0) seeds.push(hit);
639
+ }
640
+ if (seeds.length === 0) return [];
641
+
642
+ const kept = this.keptOf(deleted, seeds.flat());
643
+ const back: string[] = [];
644
+ for (const line of this.removed[side]) {
645
+ const nodes = this.nodesOf(line);
646
+ if (nodes.some((n) => kept.has(n)) && nodes.every((n) => !deleted.has(n) || kept.has(n))) back.push(line);
647
+ }
648
+ mine.add(back);
649
+ for (const line of back) this.removed[side].delete(line);
650
+
651
+ // One conflict per group of kept subjects that base connects (or one added line names together).
652
+ const groups = new UnionFind();
653
+ for (const s of kept) {
654
+ groups.add(s);
655
+ for (const line of this.base.of(s)) for (const ref of this.parse(line).refs) if (kept.has(ref)) groups.union(s, ref);
656
+ }
657
+ for (const hit of seeds) for (const n of hit.slice(1)) groups.union(hit[0], n);
658
+ return groups.sets().map((subjects) => ({
659
+ deletedBy: side,
660
+ // The concepts, not their parts (route cells and points, label nodes).
661
+ subjects: subjects.filter((s) => !(this.ownersInBase.get(s) ?? []).some((o) => kept.has(o.parent))).sort(),
662
+ scope: this.hungOn(other(side), subjects),
663
+ }));
664
+ }
665
+
666
+ /** The deleted subjects to keep, from those named. */
667
+ private keptOf(deleted: ReadonlySet<string>, seeds: readonly string[]): Set<string> {
668
+ const kept = new Set<string>();
669
+ const queue: string[] = [];
670
+ const keep = (n: string) => {
671
+ if (deleted.has(n) && !kept.has(n)) {
672
+ kept.add(n);
673
+ queue.push(n);
674
+ }
675
+ };
676
+ const needs = new Map<string, string[]>();
677
+ const needsOf = (s: string) => {
678
+ let list = needs.get(s);
679
+ if (!list) {
680
+ list = this.base.of(s).flatMap((line) => (REQUIRES.has(this.parse(line).p) ? this.parse(line).refs : []));
681
+ needs.set(s, list);
682
+ }
683
+ return list;
684
+ };
685
+ seeds.forEach(keep);
686
+ for (;;) {
687
+ while (queue.length > 0) {
688
+ const s = queue.pop() as string;
689
+ for (const line of this.base.of(s)) {
690
+ const { p, refs } = this.parse(line);
691
+ if (REQUIRES.has(p) || OWNS.has(p)) refs.forEach(keep);
692
+ }
693
+ for (const { parent } of this.ownersInBase.get(s) ?? []) keep(parent);
694
+ }
695
+ let grew = false;
696
+ for (const d of deleted) {
697
+ if (kept.has(d)) continue;
698
+ const list = needsOf(d);
699
+ if (list.some((n) => kept.has(n)) && list.every((n) => !deleted.has(n) || kept.has(n))) {
700
+ keep(d);
701
+ grew = true;
702
+ }
703
+ }
704
+ if (!grew) return kept;
705
+ }
706
+ }
707
+
708
+ /**
709
+ * `subjects`, and what `side` made that hangs on them: its new subjects that
710
+ * need one of them (`REQUIRES`) — a relationship to it, a node for it, a link
711
+ * of those — and their parts.
712
+ */
713
+ private hungOn(side: MergeSide, subjects: readonly string[]): Set<string> {
714
+ const scope = new Set(subjects);
715
+ const isNew = (s: string) => !this.base.hasSubject(s) && this.side[side].hasSubject(s);
716
+ for (let grew = true; grew; ) {
717
+ grew = false;
718
+ for (const line of this.added[side]) {
719
+ const { s, p, refs } = this.parse(line);
720
+ if (scope.has(s)) {
721
+ if (OWNS.has(p)) {
722
+ for (const ref of refs) {
723
+ if (isNew(ref) && !scope.has(ref)) {
724
+ scope.add(ref);
725
+ grew = true;
726
+ }
727
+ }
728
+ }
729
+ } else if (REQUIRES.has(p) && isNew(s) && refs.some((r) => scope.has(r))) {
730
+ scope.add(s);
731
+ grew = true;
732
+ }
733
+ }
734
+ }
735
+ return scope;
736
+ }
737
+
738
+ /** Record the deletions kept for now, with their lines in the merged model and on each side. */
739
+ private recordDeletions(deletions: PendingDeletion[]): void {
740
+ if (deletions.length === 0) return;
741
+ // Which deletions each node is in scope of; then one pass over each set of lines.
742
+ const scopes = new Map<string, number[]>();
743
+ deletions.forEach((deletion, i) => {
744
+ for (const n of deletion.scope) push(scopes, n, i);
745
+ });
746
+ const touching = (lines: Iterable<string>) => {
747
+ const out = deletions.map(() => [] as string[]);
748
+ for (const line of lines) {
749
+ const { s, refs } = parseLine(line);
750
+ const own = scopes.get(s);
751
+ const named = refs.flatMap((r) => scopes.get(r) ?? []);
752
+ if (!own && named.length === 0) continue;
753
+ for (const i of new Set([...(own ?? []), ...named])) out[i].push(line);
754
+ }
755
+ return out.map((list) => list.sort());
756
+ };
757
+ const held = touching(this.merged);
758
+ const given = { ours: touching(this.given.ours), theirs: touching(this.given.theirs) };
759
+ deletions.forEach((deletion, i) => {
760
+ const subjects = deletion.subjects.filter((s) => held[i].some((line) => subjectOf(line) === s));
761
+ if (subjects.length === 0) return;
762
+ const deleting = given[deletion.deletedBy][i];
763
+ this.conflicts.push({
764
+ kind: 'deleted',
765
+ subjects: subjects.map(iriOf),
766
+ deletedBy: deletion.deletedBy,
767
+ held: held[i],
768
+ options: deletion.deletedBy === 'ours' ? { ours: deleting, theirs: held[i] } : { ours: held[i], theirs: deleting },
769
+ });
770
+ });
771
+ }
772
+
773
+ // ── 2–4. Units, single values, triples ───────────────────────────────
774
+
775
+ private mergeChanges(): void {
776
+ const units = new Map<string, Unit>();
777
+ const changed = new Set<string>();
778
+ for (const side of SIDES) {
779
+ for (const line of this.added[side]) changed.add(line);
780
+ for (const line of this.removed[side]) changed.add(line);
781
+ }
782
+ for (const line of changed) {
783
+ const unit = this.unitOf(line);
784
+ if (unit) {
785
+ units.set(unitKey(unit), unit);
786
+ continue;
787
+ }
788
+ const present = this.base.has(line)
789
+ ? this.side.ours.has(line) && this.side.theirs.has(line)
790
+ : this.side.ours.has(line) || this.side.theirs.has(line);
791
+ if (present) this.merged.add(line);
792
+ else this.merged.delete(line);
793
+ }
794
+ for (const unit of units.values()) this.mergeUnit(unit);
795
+ }
796
+
797
+ /** The unit a changed line merges in, or `undefined` for one merged on its own. */
798
+ private unitOf(line: string): Unit | undefined {
799
+ const { s, p, lang } = this.parse(line);
800
+ if (p === IRI.points) return { kind: 'route', subject: s };
801
+ const link = this.routeOf(s);
802
+ if (link) return { kind: 'route', subject: link };
803
+ if (BOUNDS.has(p)) return { kind: 'bounds', subject: s };
804
+ const relationship = this.connectionOf(line);
805
+ if (relationship) return { kind: 'connection', subject: relationship };
806
+ if (p === RDF_TYPE) return { kind: 'types', subject: s };
807
+ if (!this.rules.mayLimit(p)) return undefined;
808
+ const limit = this.rules.limitOf(p, () => this.typesOf(s));
809
+ if (!limit) return undefined;
810
+ return {
811
+ kind: 'value',
812
+ subject: s,
813
+ predicate: p,
814
+ ...(limit === 'one-per-language' ? { language: lang } : {}),
815
+ ...(limit === 'latest' ? { latest: true } : {}),
816
+ };
817
+ }
818
+
819
+ /**
820
+ * The relationship whose connection a line is part of: one of its own
821
+ * `CONNECTION` lines, the triple it reifies, or the qualified predicate from
822
+ * its source to it.
823
+ */
824
+ private connectionOf(line: string): string | undefined {
825
+ const { s, p, refs } = this.parse(line);
826
+ if (CONNECTION.has(p) && this.isRelationship(s)) return s;
827
+ const reifier = this.reifiers.get(line);
828
+ if (reifier) return [...reifier].sort()[0];
829
+ const o = refs.length === 1 ? refs[0] : undefined;
830
+ if (o && this.isRelationship(o) && this.sourcesOf(o).has(s)) return o;
831
+ return undefined;
832
+ }
833
+
834
+ private isRelationship(subject: string): boolean {
835
+ let known = this.relationships.get(subject);
836
+ if (known === undefined) {
837
+ known = [this.base, this.side.ours, this.side.theirs].some((v) => v.of(subject).some((l) => RELATIONSHIP_MARKS.has(this.parse(l).p)));
838
+ this.relationships.set(subject, known);
839
+ }
840
+ return known;
841
+ }
842
+
843
+ /** A relationship's sources in any version. */
844
+ private sourcesOf(relationship: string): Set<string> {
845
+ const sources = new Set<string>();
846
+ for (const v of [this.base, this.side.ours, this.side.theirs]) {
847
+ for (const l of v.of(relationship)) {
848
+ const { p, o } = this.parse(l);
849
+ if (p === IRI.source) sources.add(o);
850
+ }
851
+ }
852
+ return sources;
853
+ }
854
+
855
+ /** The link whose route a list cell or point is part of. */
856
+ private routeOf(term: string): string | undefined {
857
+ const seen = new Set<string>();
858
+ let current = term;
859
+ for (;;) {
860
+ if (seen.has(current)) return undefined;
861
+ seen.add(current);
862
+ const owners = [...(this.ownersInBase.get(current) ?? []), ...(this.ownersAdded.get(current) ?? [])];
863
+ const owner = owners.find((o) => o.via !== IRI.visLabel);
864
+ if (!owner) return undefined;
865
+ if (owner.via === IRI.points) return owner.parent;
866
+ current = owner.parent;
867
+ }
868
+ }
869
+
870
+ /** A subject's types in any of the three versions. */
871
+ private typesOf(subject: string): string[] {
872
+ const types = new Set<string>();
873
+ for (const version of [this.base, this.side.ours, this.side.theirs]) {
874
+ for (const line of version.of(subject)) {
875
+ const { p, o } = this.parse(line);
876
+ if (p === RDF_TYPE && o.startsWith('<')) types.add(o.slice(1, -1));
877
+ }
878
+ }
879
+ return [...types];
880
+ }
881
+
882
+ private contentOf(unit: Unit, version: Version): string[] {
883
+ if (unit.kind === 'route') return this.routeIn(version, unit.subject);
884
+ if (unit.kind === 'connection') return this.connectionIn(version, unit.subject);
885
+ const lines = version.of(unit.subject);
886
+ if (unit.kind === 'bounds') return lines.filter((line) => BOUNDS.has(this.parse(line).p)).sort();
887
+ if (unit.kind === 'types') return lines.filter((line) => this.parse(line).p === RDF_TYPE).sort();
888
+ const { predicate, language } = unit;
889
+ return lines
890
+ .filter((line) => {
891
+ const { p, lang } = this.parse(line);
892
+ return p === predicate && (language === undefined || lang === language);
893
+ })
894
+ .sort();
895
+ }
896
+
897
+ /**
898
+ * A relationship's connection in a version: the version's lines that
899
+ * {@link connectionOf} gives to it — so a triple it reifies counts where the
900
+ * version still has it, with or without the `rdf:reifies` saying so.
901
+ */
902
+ private connectionIn(version: Version, relationship: string): string[] {
903
+ const out = version.of(relationship).filter((line) => CONNECTION.has(this.parse(line).p));
904
+ for (const triple of this.reified.get(relationship) ?? []) {
905
+ if (version.has(triple) && this.connectionOf(triple) === relationship) out.push(triple);
906
+ }
907
+ for (const source of this.sourcesOf(relationship)) {
908
+ for (const line of version.of(source)) {
909
+ if (this.parse(line).o === relationship && this.connectionOf(line) === relationship) out.push(line);
910
+ }
911
+ }
912
+ return [...new Set(out)].sort();
913
+ }
914
+
915
+ /** A link's route in a version: its `arch-vis:points`, and every cell and point reached from it. */
916
+ private routeIn(version: Version, link: string): string[] {
917
+ const out: string[] = [];
918
+ const seen = new Set<string>();
919
+ for (const line of version.of(link)) {
920
+ const { p, o } = this.parse(line);
921
+ if (p !== IRI.points) continue;
922
+ out.push(line);
923
+ let cell: string | undefined = o;
924
+ while (cell && cell !== NIL && !seen.has(cell)) {
925
+ seen.add(cell);
926
+ let next: string | undefined;
927
+ for (const cellLine of version.of(cell)) {
928
+ out.push(cellLine);
929
+ const parsed = this.parse(cellLine);
930
+ if (parsed.p === IRI.rdfFirst && !seen.has(parsed.o)) {
931
+ seen.add(parsed.o);
932
+ out.push(...version.of(parsed.o));
933
+ } else if (parsed.p === IRI.rdfRest) next = parsed.o;
934
+ }
935
+ cell = next;
936
+ }
937
+ }
938
+ return [...new Set(out)].sort();
939
+ }
940
+
941
+ private mergeUnit(unit: Unit): void {
942
+ const base = this.contentOf(unit, this.base);
943
+ const ours = this.contentOf(unit, this.side.ours);
944
+ const theirs = this.contentOf(unit, this.side.theirs);
945
+ let result: string[];
946
+ if (sameList(ours, base)) result = theirs;
947
+ else if (sameList(theirs, base) || sameList(ours, theirs)) result = ours;
948
+ else if (unit.kind === 'value' && unit.latest) result = latestOf(ours) >= latestOf(theirs) ? ours : theirs;
949
+ else {
950
+ result = base;
951
+ const predicate =
952
+ unit.kind === 'value' ? unit.predicate : unit.kind === 'types' ? RDF_TYPE : unit.kind === 'connection' ? differingEnd(ours, theirs) : undefined;
953
+ this.conflicts.push({
954
+ kind: unit.kind === 'route' || unit.kind === 'bounds' ? unit.kind : 'value',
955
+ subjects: [iriOf(unit.subject)],
956
+ ...(predicate ? { predicate } : {}),
957
+ ...(unit.kind === 'value' && unit.language !== undefined ? { language: unit.language } : {}),
958
+ held: base,
959
+ options: { ours, theirs },
960
+ });
961
+ }
962
+ for (const line of base) this.merged.delete(line);
963
+ for (const line of result) this.merged.add(line);
964
+ }
965
+
966
+ // ── Two placements ───────────────────────────────────────────────────
967
+
968
+ /**
969
+ * Both sides placed the same concept in the same view anew (`via`: a node's
970
+ * `arch-vis:archElement`, a link's `arch-vis:archRelationship`). Both are
971
+ * kept, each with what its side drew at it; the conflict offers each alone.
972
+ */
973
+ private placements(via: string, placed: Set<string>): void {
974
+ // By concept and view: the node or link each side added there ('' for more than one).
975
+ const fresh: Record<MergeSide, Map<string, { concept: string; element: string }>> = { ours: new Map(), theirs: new Map() };
976
+ for (const side of SIDES) {
977
+ for (const line of this.added[side]) {
978
+ const { s, p, refs } = this.parse(line);
979
+ if (p !== via || this.base.hasSubject(s) || placed.has(s)) continue;
980
+ const view = this.side[side].of(s).find((l) => this.parse(l).p === IRI.visView);
981
+ if (!view) continue;
982
+ const key = `${refs[0]} ${this.parse(view).o}`;
983
+ const before = fresh[side].get(key);
984
+ // A side that placed it twice did so itself; not the merge's doing.
985
+ fresh[side].set(key, { concept: refs[0], element: before === undefined || before.element === s ? s : '' });
986
+ }
987
+ }
988
+ for (const [key, { concept, element: ours }] of fresh.ours) {
989
+ const theirs = fresh.theirs.get(key)?.element;
990
+ if (!ours || !theirs || ours === theirs) continue;
991
+ if (!this.merged.has(`${ours} <${via}> ${concept} .`) || !this.merged.has(`${theirs} <${via}> ${concept} .`)) continue;
992
+ const options = { ours: this.drawnAt('ours', ours), theirs: this.drawnAt('theirs', theirs) };
993
+ // Held: both, as merged — picking a side keeps that one alone.
994
+ const held = [...new Set([...options.ours, ...options.theirs])].sort();
995
+ for (const line of held) placed.add(subjectOf(line));
996
+ this.conflicts.push({ kind: 'placement', subjects: [ours, theirs].map(iriOf).sort(), held, options });
997
+ }
998
+ }
999
+
1000
+ /**
1001
+ * What `side` drew at a node or link it added: the lines about it, its parts,
1002
+ * and the links it added that end at it (with their parts) — the lines
1003
+ * pointing at any of them, and the `arch:inView` it added for what they draw
1004
+ * there (`view-manager.ts` writes it with the node or link).
1005
+ */
1006
+ private drawnAt(side: MergeSide, element: string): string[] {
1007
+ const scope = new Set([element]);
1008
+ const isNew = (s: string) => !this.base.hasSubject(s) && this.side[side].hasSubject(s);
1009
+ for (let grew = true; grew; ) {
1010
+ grew = false;
1011
+ for (const line of this.added[side]) {
1012
+ const { s, p, refs } = this.parse(line);
1013
+ const reach = scope.has(s)
1014
+ ? OWNS.has(p)
1015
+ ? refs.filter((r) => isNew(r) && !scope.has(r))
1016
+ : []
1017
+ : LINK_ENDS.has(p) && isNew(s) && refs.some((r) => scope.has(r))
1018
+ ? [s]
1019
+ : [];
1020
+ for (const n of reach) scope.add(n);
1021
+ if (reach.length > 0) grew = true;
1022
+ }
1023
+ }
1024
+ // What they draw, and where: an `arch:inView` the side added for it goes with them.
1025
+ const shown = new Set<string>();
1026
+ for (const line of this.added[side]) {
1027
+ const { s, p, o } = this.parse(line);
1028
+ if (scope.has(s) && (p === IRI.archElement || p === IRI.archRelationship)) {
1029
+ const view = this.side[side].of(s).find((l) => this.parse(l).p === IRI.visView);
1030
+ if (view) shown.add(`${o} <${IRI.inView}> ${this.parse(view).o} .`);
1031
+ }
1032
+ }
1033
+ return this.added[side].filter((line) => shown.has(line) || this.nodesOf(line).some((n) => scope.has(n))).sort();
1034
+ }
1035
+
1036
+ // ── Count limits ─────────────────────────────────────────────────────
1037
+
1038
+ private countLimits(check: CountCheck): void {
1039
+ const touched = (side: MergeSide) => {
1040
+ const nodes = new Set<string>();
1041
+ for (const line of [...this.added[side], ...this.removed[side]]) for (const n of this.nodesOf(line)) nodes.add(n);
1042
+ return nodes;
1043
+ };
1044
+ const ours = touched('ours');
1045
+ const isSubject = (n: string) => [this.base, this.side.ours, this.side.theirs].some((v) => v.hasSubject(n));
1046
+ const focus = [...touched('theirs')].filter((n) => ours.has(n) && isSubject(n)).sort();
1047
+ if (focus.length === 0) return;
1048
+ const merged = sortedOf(this.merged);
1049
+ const found = check(merged, focus);
1050
+ if (found.length === 0) return;
1051
+ const key = (f: CountFinding) => `${f.focus} ${f.path} ${f.component}`;
1052
+ const alone = new Set([...check(sortedOf(this.given.ours), focus), ...check(sortedOf(this.given.theirs), focus)].map(key));
1053
+ const seen = new Set<string>();
1054
+ for (const finding of found) {
1055
+ const k = key(finding);
1056
+ if (alone.has(k) || seen.has(k)) continue;
1057
+ seen.add(k);
1058
+ const values = (lines: Iterable<string>) =>
1059
+ finding.path ? [...lines].filter((l) => subjectOf(l) === finding.focus && this.parse(l).p === finding.path).sort() : [];
1060
+ const candidates = [...this.base.of(finding.focus), ...this.side.ours.of(finding.focus), ...this.side.theirs.of(finding.focus)];
1061
+ this.conflicts.push({
1062
+ kind: 'count',
1063
+ subjects: [iriOf(finding.focus)],
1064
+ ...(finding.path ? { predicate: finding.path } : {}),
1065
+ message: finding.message,
1066
+ held: values(new Set(candidates.filter((l) => this.merged.has(l)))),
1067
+ options: { ours: values(this.side.ours.of(finding.focus)), theirs: values(this.side.theirs.of(finding.focus)) },
1068
+ });
1069
+ }
1070
+ }
1071
+ }
1072
+
1073
+ // ── Helpers ───────────────────────────────────────────────────────────────
1074
+
1075
+ function termOf(term: string): Term {
1076
+ return (term.startsWith('_:') ? DataFactory.blankNode(term.slice(2)) : DataFactory.namedNode(iriOf(term))) as unknown as Term;
1077
+ }
1078
+
1079
+ /**
1080
+ * Snapshot lines back as quads, blank-node labels as they are — so they match
1081
+ * the quads of the store the snapshot was taken from.
1082
+ */
1083
+ export function quadsOfSnapshot(lines: readonly string[]): Quad[] {
1084
+ if (lines.length === 0) return [];
1085
+ return new N3Parser({ format: 'N-Triples', blankNodePrefix: '' }).parse(lines.join('\n')) as unknown as Quad[];
1086
+ }
1087
+
1088
+ /** A side's latest value: its greatest line — `xsd:dateTime`s in one form sort as they fall in time. */
1089
+ function latestOf(lines: readonly string[]): string {
1090
+ return lines.reduce((max, line) => (line > max ? line : max), '');
1091
+ }
1092
+
1093
+ /** Which of a relationship's ends two connections differ in (its type when neither). */
1094
+ function differingEnd(a: readonly string[], b: readonly string[]): string {
1095
+ const of = (lines: readonly string[], p: string) => lines.filter((l) => predicateOf(l) === p).join('\n');
1096
+ return [IRI.source, IRI.target].find((p) => of(a, p) !== of(b, p)) ?? RDF_TYPE;
1097
+ }
1098
+
1099
+ function unitKey(unit: Unit): string {
1100
+ if (unit.kind !== 'value') return `${unit.kind} ${unit.subject}`;
1101
+ return `value ${unit.subject} ${unit.predicate} ${unit.language ?? '*'}`;
1102
+ }
1103
+
1104
+ function byConflict(a: MergeConflict, b: MergeConflict): number {
1105
+ const key = (c: MergeConflict) => [c.subjects.join(' '), c.predicate ?? '', c.language ?? '', c.message ?? ''].join('\u0000');
1106
+ return KIND_ORDER.indexOf(a.kind) - KIND_ORDER.indexOf(b.kind) || (key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0);
1107
+ }
1108
+
1109
+ function push<K, V>(map: Map<K, V[]>, key: K, value: V): void {
1110
+ const list = map.get(key);
1111
+ if (list) list.push(value);
1112
+ else map.set(key, [value]);
1113
+ }
1114
+
1115
+ function sameSet(a: ReadonlySet<string>, b: ReadonlySet<string>): boolean {
1116
+ if (a.size !== b.size) return false;
1117
+ for (const x of a) if (!b.has(x)) return false;
1118
+ return true;
1119
+ }
1120
+
1121
+ function sameList(a: readonly string[], b: readonly string[]): boolean {
1122
+ return a.length === b.length && a.every((x, i) => x === b[i]);
1123
+ }
1124
+
1125
+ function sortedOf(lines: Iterable<string>): string[] {
1126
+ return [...lines].sort();
1127
+ }
1128
+
1129
+ /** Disjoint sets of strings. */
1130
+ class UnionFind {
1131
+ private readonly parent = new Map<string, string>();
1132
+
1133
+ add(x: string): void {
1134
+ if (!this.parent.has(x)) this.parent.set(x, x);
1135
+ }
1136
+
1137
+ find(x: string): string {
1138
+ this.add(x);
1139
+ let root = x;
1140
+ while (this.parent.get(root) !== root) root = this.parent.get(root) as string;
1141
+ for (let n = x; n !== root; ) {
1142
+ const next = this.parent.get(n) as string;
1143
+ this.parent.set(n, root);
1144
+ n = next;
1145
+ }
1146
+ return root;
1147
+ }
1148
+
1149
+ union(a: string, b: string): void {
1150
+ const ra = this.find(a);
1151
+ const rb = this.find(b);
1152
+ if (ra !== rb) this.parent.set(ra < rb ? rb : ra, ra < rb ? ra : rb);
1153
+ }
1154
+
1155
+ sets(): string[][] {
1156
+ const groups = new Map<string, string[]>();
1157
+ for (const x of this.parent.keys()) push(groups, this.find(x), x);
1158
+ return [...groups.values()];
1159
+ }
1160
+ }