@dxos/echo 0.8.4-main.c1de068 → 0.8.4-main.c4373fc

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 (315) hide show
  1. package/README.md +1 -1
  2. package/dist/lib/browser/chunk-MWLA34S5.mjs +3843 -0
  3. package/dist/lib/browser/chunk-MWLA34S5.mjs.map +7 -0
  4. package/dist/lib/browser/chunk-OAZJQHVO.mjs +453 -0
  5. package/dist/lib/browser/chunk-OAZJQHVO.mjs.map +7 -0
  6. package/dist/lib/browser/chunk-ORIE2FMS.mjs +514 -0
  7. package/dist/lib/browser/chunk-ORIE2FMS.mjs.map +7 -0
  8. package/dist/lib/browser/index.mjs +26 -5
  9. package/dist/lib/browser/internal/index.mjs +326 -0
  10. package/dist/lib/browser/internal/index.mjs.map +7 -0
  11. package/dist/lib/browser/meta.json +1 -1
  12. package/dist/lib/browser/query/index.mjs +23 -0
  13. package/dist/lib/browser/query/index.mjs.map +7 -0
  14. package/dist/lib/browser/testing/index.mjs +260 -32
  15. package/dist/lib/browser/testing/index.mjs.map +4 -4
  16. package/dist/lib/node-esm/chunk-AXWVDOP7.mjs +453 -0
  17. package/dist/lib/node-esm/chunk-AXWVDOP7.mjs.map +7 -0
  18. package/dist/lib/node-esm/chunk-L4PBAJDP.mjs +514 -0
  19. package/dist/lib/node-esm/chunk-L4PBAJDP.mjs.map +7 -0
  20. package/dist/lib/node-esm/chunk-YTNLFBIK.mjs +3843 -0
  21. package/dist/lib/node-esm/chunk-YTNLFBIK.mjs.map +7 -0
  22. package/dist/lib/node-esm/index.mjs +26 -5
  23. package/dist/lib/node-esm/internal/index.mjs +326 -0
  24. package/dist/lib/node-esm/internal/index.mjs.map +7 -0
  25. package/dist/lib/node-esm/meta.json +1 -1
  26. package/dist/lib/node-esm/query/index.mjs +23 -0
  27. package/dist/lib/node-esm/query/index.mjs.map +7 -0
  28. package/dist/lib/node-esm/testing/index.mjs +260 -32
  29. package/dist/lib/node-esm/testing/index.mjs.map +4 -4
  30. package/dist/types/src/Obj.d.ts +111 -17
  31. package/dist/types/src/Obj.d.ts.map +1 -1
  32. package/dist/types/src/Ref.d.ts +1 -1
  33. package/dist/types/src/Ref.d.ts.map +1 -1
  34. package/dist/types/src/Relation.d.ts +11 -8
  35. package/dist/types/src/Relation.d.ts.map +1 -1
  36. package/dist/types/src/Type.d.ts +17 -18
  37. package/dist/types/src/Type.d.ts.map +1 -1
  38. package/dist/types/src/errors.d.ts +72 -0
  39. package/dist/types/src/errors.d.ts.map +1 -0
  40. package/dist/types/src/index.d.ts +3 -1
  41. package/dist/types/src/index.d.ts.map +1 -1
  42. package/dist/types/src/internal/ast/annotation-helper.d.ts +8 -0
  43. package/dist/types/src/internal/ast/annotation-helper.d.ts.map +1 -0
  44. package/dist/types/src/internal/ast/annotations.d.ts +119 -0
  45. package/dist/types/src/internal/ast/annotations.d.ts.map +1 -0
  46. package/dist/types/src/internal/ast/annotations.test.d.ts +2 -0
  47. package/dist/types/src/internal/ast/annotations.test.d.ts.map +1 -0
  48. package/dist/types/src/internal/ast/entity-kind.d.ts +10 -0
  49. package/dist/types/src/internal/ast/entity-kind.d.ts.map +1 -0
  50. package/dist/types/src/internal/ast/index.d.ts +5 -0
  51. package/dist/types/src/internal/ast/index.d.ts.map +1 -0
  52. package/dist/types/src/internal/ast/types.d.ts +6 -0
  53. package/dist/types/src/internal/ast/types.d.ts.map +1 -0
  54. package/dist/types/src/internal/formats/date.d.ts +63 -0
  55. package/dist/types/src/internal/formats/date.d.ts.map +1 -0
  56. package/dist/types/src/internal/formats/date.test.d.ts +2 -0
  57. package/dist/types/src/internal/formats/date.test.d.ts.map +1 -0
  58. package/dist/types/src/internal/formats/format.d.ts +30 -0
  59. package/dist/types/src/internal/formats/format.d.ts.map +1 -0
  60. package/dist/types/src/internal/formats/format.test.d.ts +2 -0
  61. package/dist/types/src/internal/formats/format.test.d.ts.map +1 -0
  62. package/dist/types/src/internal/formats/index.d.ts +8 -0
  63. package/dist/types/src/internal/formats/index.d.ts.map +1 -0
  64. package/dist/types/src/internal/formats/number.d.ts +31 -0
  65. package/dist/types/src/internal/formats/number.d.ts.map +1 -0
  66. package/dist/types/src/internal/formats/object.d.ts +35 -0
  67. package/dist/types/src/internal/formats/object.d.ts.map +1 -0
  68. package/dist/types/src/internal/formats/select.d.ts +11 -0
  69. package/dist/types/src/internal/formats/select.d.ts.map +1 -0
  70. package/dist/types/src/internal/formats/string.d.ts +38 -0
  71. package/dist/types/src/internal/formats/string.d.ts.map +1 -0
  72. package/dist/types/src/internal/formats/types.d.ts +68 -0
  73. package/dist/types/src/internal/formats/types.d.ts.map +1 -0
  74. package/dist/types/src/internal/index.d.ts +15 -0
  75. package/dist/types/src/internal/index.d.ts.map +1 -0
  76. package/dist/types/src/internal/json/annotations.d.ts +19 -0
  77. package/dist/types/src/internal/json/annotations.d.ts.map +1 -0
  78. package/dist/types/src/internal/json/effect-schema.test.d.ts +2 -0
  79. package/dist/types/src/internal/json/effect-schema.test.d.ts.map +1 -0
  80. package/dist/types/src/internal/json/index.d.ts +2 -0
  81. package/dist/types/src/internal/json/index.d.ts.map +1 -0
  82. package/dist/types/src/internal/json/json-schema.d.ts +32 -0
  83. package/dist/types/src/internal/json/json-schema.d.ts.map +1 -0
  84. package/dist/types/src/internal/json/json-schema.test.d.ts +2 -0
  85. package/dist/types/src/internal/json/json-schema.test.d.ts.map +1 -0
  86. package/dist/types/src/internal/json-schema/index.d.ts +3 -0
  87. package/dist/types/src/internal/json-schema/index.d.ts.map +1 -0
  88. package/dist/types/src/internal/json-schema/json-schema-normalize.d.ts +7 -0
  89. package/dist/types/src/internal/json-schema/json-schema-normalize.d.ts.map +1 -0
  90. package/dist/types/src/internal/json-schema/json-schema-type.d.ts +250 -0
  91. package/dist/types/src/internal/json-schema/json-schema-type.d.ts.map +1 -0
  92. package/dist/types/src/internal/object/accessors.d.ts +29 -0
  93. package/dist/types/src/internal/object/accessors.d.ts.map +1 -0
  94. package/dist/types/src/internal/object/common.d.ts +18 -0
  95. package/dist/types/src/internal/object/common.d.ts.map +1 -0
  96. package/dist/types/src/internal/object/create.d.ts +40 -0
  97. package/dist/types/src/internal/object/create.d.ts.map +1 -0
  98. package/dist/types/src/internal/object/create.test.d.ts +2 -0
  99. package/dist/types/src/internal/object/create.test.d.ts.map +1 -0
  100. package/dist/types/src/internal/object/deleted.d.ts +6 -0
  101. package/dist/types/src/internal/object/deleted.d.ts.map +1 -0
  102. package/dist/types/src/internal/object/entity.d.ts +22 -0
  103. package/dist/types/src/internal/object/entity.d.ts.map +1 -0
  104. package/dist/types/src/internal/object/expando.d.ts +14 -0
  105. package/dist/types/src/internal/object/expando.d.ts.map +1 -0
  106. package/dist/types/src/internal/object/ids.d.ts +6 -0
  107. package/dist/types/src/internal/object/ids.d.ts.map +1 -0
  108. package/dist/types/src/internal/object/index.d.ts +17 -0
  109. package/dist/types/src/internal/object/index.d.ts.map +1 -0
  110. package/dist/types/src/internal/object/inspect.d.ts +2 -0
  111. package/dist/types/src/internal/object/inspect.d.ts.map +1 -0
  112. package/dist/types/src/internal/object/json-serializer.d.ts +32 -0
  113. package/dist/types/src/internal/object/json-serializer.d.ts.map +1 -0
  114. package/dist/types/src/internal/object/json-serializer.test.d.ts +2 -0
  115. package/dist/types/src/internal/object/json-serializer.test.d.ts.map +1 -0
  116. package/dist/types/src/internal/object/meta.d.ts +31 -0
  117. package/dist/types/src/internal/object/meta.d.ts.map +1 -0
  118. package/dist/types/src/internal/object/model.d.ts +117 -0
  119. package/dist/types/src/internal/object/model.d.ts.map +1 -0
  120. package/dist/types/src/internal/object/relation.d.ts +17 -0
  121. package/dist/types/src/internal/object/relation.d.ts.map +1 -0
  122. package/dist/types/src/internal/object/schema-validator.d.ts +15 -0
  123. package/dist/types/src/internal/object/schema-validator.d.ts.map +1 -0
  124. package/dist/types/src/internal/object/schema-validator.test.d.ts +2 -0
  125. package/dist/types/src/internal/object/schema-validator.test.d.ts.map +1 -0
  126. package/dist/types/src/internal/object/typed-object.d.ts +31 -0
  127. package/dist/types/src/internal/object/typed-object.d.ts.map +1 -0
  128. package/dist/types/src/internal/object/typed-object.test.d.ts +2 -0
  129. package/dist/types/src/internal/object/typed-object.test.d.ts.map +1 -0
  130. package/dist/types/src/internal/object/typed-relation.d.ts +32 -0
  131. package/dist/types/src/internal/object/typed-relation.d.ts.map +1 -0
  132. package/dist/types/src/internal/object/typename.d.ts +15 -0
  133. package/dist/types/src/internal/object/typename.d.ts.map +1 -0
  134. package/dist/types/src/internal/object/version.d.ts +14 -0
  135. package/dist/types/src/internal/object/version.d.ts.map +1 -0
  136. package/dist/types/src/internal/projection/compose.d.ts +6 -0
  137. package/dist/types/src/internal/projection/compose.d.ts.map +1 -0
  138. package/dist/types/src/internal/projection/compose.test.d.ts +2 -0
  139. package/dist/types/src/internal/projection/compose.test.d.ts.map +1 -0
  140. package/dist/types/src/internal/projection/index.d.ts +2 -0
  141. package/dist/types/src/internal/projection/index.d.ts.map +1 -0
  142. package/dist/types/src/internal/proxy/handler.test.d.ts +2 -0
  143. package/dist/types/src/internal/proxy/handler.test.d.ts.map +1 -0
  144. package/dist/types/src/internal/proxy/reactive-object.d.ts +15 -0
  145. package/dist/types/src/internal/proxy/reactive-object.d.ts.map +1 -0
  146. package/dist/types/src/internal/proxy/schema.test.d.ts +2 -0
  147. package/dist/types/src/internal/proxy/schema.test.d.ts.map +1 -0
  148. package/dist/types/src/internal/proxy/typed-handler.d.ts +44 -0
  149. package/dist/types/src/internal/proxy/typed-handler.d.ts.map +1 -0
  150. package/dist/types/src/internal/proxy/typed-handler.test.d.ts +2 -0
  151. package/dist/types/src/internal/proxy/typed-handler.test.d.ts.map +1 -0
  152. package/dist/types/src/internal/proxy/typed-object.test.d.ts +2 -0
  153. package/dist/types/src/internal/proxy/typed-object.test.d.ts.map +1 -0
  154. package/dist/types/src/internal/query/index.d.ts +2 -0
  155. package/dist/types/src/internal/query/index.d.ts.map +1 -0
  156. package/dist/types/src/internal/query/query.d.ts +17 -0
  157. package/dist/types/src/internal/query/query.d.ts.map +1 -0
  158. package/dist/types/src/internal/ref/index.d.ts +3 -0
  159. package/dist/types/src/internal/ref/index.d.ts.map +1 -0
  160. package/dist/types/src/internal/ref/ref-array.d.ts +21 -0
  161. package/dist/types/src/internal/ref/ref-array.d.ts.map +1 -0
  162. package/dist/types/src/internal/ref/ref.d.ts +206 -0
  163. package/dist/types/src/internal/ref/ref.d.ts.map +1 -0
  164. package/dist/types/src/internal/ref/ref.test.d.ts +2 -0
  165. package/dist/types/src/internal/ref/ref.test.d.ts.map +1 -0
  166. package/dist/types/src/internal/schema/echo-schema.d.ts +168 -0
  167. package/dist/types/src/internal/schema/echo-schema.d.ts.map +1 -0
  168. package/dist/types/src/internal/schema/index.d.ts +7 -0
  169. package/dist/types/src/internal/schema/index.d.ts.map +1 -0
  170. package/dist/types/src/internal/schema/manipulation.d.ts +10 -0
  171. package/dist/types/src/internal/schema/manipulation.d.ts.map +1 -0
  172. package/dist/types/src/internal/schema/runtime-schema-registry.d.ts +18 -0
  173. package/dist/types/src/internal/schema/runtime-schema-registry.d.ts.map +1 -0
  174. package/dist/types/src/internal/schema/snapshot.d.ts +6 -0
  175. package/dist/types/src/internal/schema/snapshot.d.ts.map +1 -0
  176. package/dist/types/src/internal/schema/stored-schema.d.ts +13 -0
  177. package/dist/types/src/internal/schema/stored-schema.d.ts.map +1 -0
  178. package/dist/types/src/internal/testing/index.d.ts +3 -0
  179. package/dist/types/src/internal/testing/index.d.ts.map +1 -0
  180. package/dist/types/src/internal/testing/types.d.ts +455 -0
  181. package/dist/types/src/internal/testing/types.d.ts.map +1 -0
  182. package/dist/types/src/internal/testing/utils.d.ts +10 -0
  183. package/dist/types/src/internal/testing/utils.d.ts.map +1 -0
  184. package/dist/types/src/internal/types/index.d.ts +3 -0
  185. package/dist/types/src/internal/types/index.d.ts.map +1 -0
  186. package/dist/types/src/internal/types/types.d.ts +79 -0
  187. package/dist/types/src/internal/types/types.d.ts.map +1 -0
  188. package/dist/types/src/internal/types/types.test.d.ts +2 -0
  189. package/dist/types/src/internal/types/types.test.d.ts.map +1 -0
  190. package/dist/types/src/internal/types/util.d.ts +5 -0
  191. package/dist/types/src/internal/types/util.d.ts.map +1 -0
  192. package/dist/types/src/query/index.d.ts +2 -1
  193. package/dist/types/src/query/index.d.ts.map +1 -1
  194. package/dist/types/src/query/{dsl.d.ts → query.d.ts} +44 -15
  195. package/dist/types/src/query/query.d.ts.map +1 -0
  196. package/dist/types/src/query/query.test.d.ts +2 -0
  197. package/dist/types/src/query/query.test.d.ts.map +1 -0
  198. package/dist/types/src/query/tag.d.ts +18 -0
  199. package/dist/types/src/query/tag.d.ts.map +1 -0
  200. package/dist/types/src/testing/echo-schema.d.ts +7 -0
  201. package/dist/types/src/testing/echo-schema.d.ts.map +1 -0
  202. package/dist/types/src/testing/index.d.ts +2 -0
  203. package/dist/types/src/testing/index.d.ts.map +1 -1
  204. package/dist/types/src/testing/types.d.ts +18 -18
  205. package/dist/types/src/testing/types.d.ts.map +1 -1
  206. package/dist/types/tsconfig.tsbuildinfo +1 -1
  207. package/package.json +34 -16
  208. package/src/Obj.ts +250 -27
  209. package/src/Ref.ts +1 -2
  210. package/src/Relation.ts +25 -13
  211. package/src/Type.ts +32 -31
  212. package/src/errors.ts +18 -0
  213. package/src/index.ts +4 -1
  214. package/src/internal/ast/annotation-helper.ts +22 -0
  215. package/src/internal/ast/annotations.test.ts +98 -0
  216. package/src/internal/ast/annotations.ts +212 -0
  217. package/src/internal/ast/entity-kind.ts +15 -0
  218. package/src/internal/ast/index.ts +8 -0
  219. package/src/internal/ast/types.ts +17 -0
  220. package/src/internal/formats/date.test.ts +56 -0
  221. package/src/internal/formats/date.ts +217 -0
  222. package/src/internal/formats/format.test.ts +77 -0
  223. package/src/internal/formats/format.ts +52 -0
  224. package/src/internal/formats/index.ts +12 -0
  225. package/src/internal/formats/number.ts +89 -0
  226. package/src/internal/formats/object.ts +80 -0
  227. package/src/internal/formats/select.ts +16 -0
  228. package/src/internal/formats/string.ts +76 -0
  229. package/src/internal/formats/types.ts +175 -0
  230. package/src/internal/index.ts +22 -0
  231. package/src/internal/json/annotations.ts +50 -0
  232. package/src/internal/json/effect-schema.test.ts +143 -0
  233. package/src/internal/json/index.ts +5 -0
  234. package/src/internal/json/json-schema.test.ts +726 -0
  235. package/src/internal/json/json-schema.ts +548 -0
  236. package/src/internal/json-schema/index.ts +6 -0
  237. package/src/internal/json-schema/json-schema-normalize.ts +109 -0
  238. package/src/internal/json-schema/json-schema-type.ts +403 -0
  239. package/src/internal/object/accessors.ts +115 -0
  240. package/src/internal/object/common.ts +76 -0
  241. package/src/internal/object/create.test.ts +118 -0
  242. package/src/internal/object/create.ts +96 -0
  243. package/src/internal/object/deleted.ts +19 -0
  244. package/src/internal/object/entity.ts +204 -0
  245. package/src/internal/object/expando.ts +21 -0
  246. package/src/internal/object/ids.ts +12 -0
  247. package/src/internal/object/index.ts +20 -0
  248. package/src/internal/object/inspect.ts +48 -0
  249. package/src/internal/object/json-serializer.test.ts +99 -0
  250. package/src/internal/object/json-serializer.ts +225 -0
  251. package/src/internal/object/meta.ts +62 -0
  252. package/src/internal/object/model.ts +170 -0
  253. package/src/internal/object/relation.ts +24 -0
  254. package/src/internal/object/schema-validator.test.ts +186 -0
  255. package/src/internal/object/schema-validator.ts +241 -0
  256. package/src/internal/object/typed-object.test.ts +34 -0
  257. package/src/internal/object/typed-object.ts +81 -0
  258. package/src/internal/object/typed-relation.ts +85 -0
  259. package/src/internal/object/typename.ts +61 -0
  260. package/src/internal/object/version.ts +22 -0
  261. package/src/internal/projection/compose.test.ts +43 -0
  262. package/src/internal/projection/compose.ts +36 -0
  263. package/src/internal/projection/index.ts +5 -0
  264. package/src/internal/proxy/handler.test.ts +163 -0
  265. package/src/internal/proxy/reactive-object.ts +108 -0
  266. package/src/internal/proxy/schema.test.ts +136 -0
  267. package/src/internal/proxy/typed-handler.test.ts +102 -0
  268. package/src/internal/proxy/typed-handler.ts +228 -0
  269. package/src/internal/proxy/typed-object.test.ts +100 -0
  270. package/src/internal/query/index.ts +5 -0
  271. package/src/internal/query/query.ts +23 -0
  272. package/src/internal/ref/index.ts +6 -0
  273. package/src/internal/ref/ref-array.ts +39 -0
  274. package/src/internal/ref/ref.test.ts +100 -0
  275. package/src/internal/ref/ref.ts +521 -0
  276. package/src/internal/schema/echo-schema.ts +383 -0
  277. package/src/internal/schema/index.ts +10 -0
  278. package/src/internal/schema/manipulation.ts +86 -0
  279. package/src/internal/schema/runtime-schema-registry.ts +78 -0
  280. package/src/internal/schema/snapshot.ts +25 -0
  281. package/src/internal/schema/stored-schema.ts +26 -0
  282. package/src/internal/testing/index.ts +6 -0
  283. package/src/internal/testing/types.ts +211 -0
  284. package/src/internal/testing/utils.ts +54 -0
  285. package/src/internal/types/index.ts +6 -0
  286. package/src/internal/types/types.test.ts +48 -0
  287. package/src/internal/types/types.ts +176 -0
  288. package/src/internal/types/util.ts +9 -0
  289. package/src/query/index.ts +2 -1
  290. package/src/query/{dsl.test.ts → query.test.ts} +41 -2
  291. package/src/query/{dsl.ts → query.ts} +170 -32
  292. package/src/query/tag.ts +35 -0
  293. package/src/test/api.test.ts +17 -10
  294. package/src/testing/echo-schema.ts +39 -0
  295. package/src/testing/index.ts +2 -0
  296. package/src/testing/types.ts +1 -1
  297. package/dist/lib/browser/chunk-EUA7CM23.mjs +0 -619
  298. package/dist/lib/browser/chunk-EUA7CM23.mjs.map +0 -7
  299. package/dist/lib/node-esm/chunk-IV6BWGHK.mjs +0 -619
  300. package/dist/lib/node-esm/chunk-IV6BWGHK.mjs.map +0 -7
  301. package/dist/types/src/experimental/database.d.ts +0 -8
  302. package/dist/types/src/experimental/database.d.ts.map +0 -1
  303. package/dist/types/src/experimental/index.d.ts +0 -1
  304. package/dist/types/src/experimental/index.d.ts.map +0 -1
  305. package/dist/types/src/experimental/queue.d.ts +0 -8
  306. package/dist/types/src/experimental/queue.d.ts.map +0 -1
  307. package/dist/types/src/experimental/space.d.ts +0 -8
  308. package/dist/types/src/experimental/space.d.ts.map +0 -1
  309. package/dist/types/src/query/dsl.d.ts.map +0 -1
  310. package/dist/types/src/query/dsl.test.d.ts +0 -2
  311. package/dist/types/src/query/dsl.test.d.ts.map +0 -1
  312. package/src/experimental/database.ts +0 -11
  313. package/src/experimental/index.ts +0 -7
  314. package/src/experimental/queue.ts +0 -11
  315. package/src/experimental/space.ts +0 -11
@@ -0,0 +1,3843 @@
1
+ import "@dxos/node-std/globals";
2
+ var __defProp = Object.defineProperty;
3
+ var __export = (target, all) => {
4
+ for (var name in all)
5
+ __defProp(target, name, { get: all[name], enumerable: true });
6
+ };
7
+
8
+ // src/internal/index.ts
9
+ import { JsonPath as JsonPath2, splitJsonPath as splitJsonPath2, JsonProp } from "@dxos/effect";
10
+ import { ObjectId as ObjectId9 } from "@dxos/keys";
11
+ import { ForeignKey as ForeignKey2 } from "@dxos/echo-protocol";
12
+
13
+ // src/internal/ast/annotations.ts
14
+ import * as Function from "effect/Function";
15
+ import * as Option from "effect/Option";
16
+ import * as Schema2 from "effect/Schema";
17
+ import * as SchemaAST2 from "effect/SchemaAST";
18
+ import { assertArgument } from "@dxos/invariant";
19
+ import { DXN } from "@dxos/keys";
20
+
21
+ // src/internal/ast/annotation-helper.ts
22
+ import * as SchemaAST from "effect/SchemaAST";
23
+ var createAnnotationHelper = (id) => {
24
+ return {
25
+ get: (schema) => SchemaAST.getAnnotation(schema.ast, id),
26
+ set: (value) => (schema) => schema.annotations({
27
+ [id]: value
28
+ })
29
+ };
30
+ };
31
+
32
+ // src/internal/ast/entity-kind.ts
33
+ import * as Schema from "effect/Schema";
34
+ var EntityKind = /* @__PURE__ */ (function(EntityKind2) {
35
+ EntityKind2["Object"] = "object";
36
+ EntityKind2["Relation"] = "relation";
37
+ return EntityKind2;
38
+ })({});
39
+ var EntityKindSchema = Schema.Enums(EntityKind);
40
+
41
+ // src/internal/ast/annotations.ts
42
+ var unwrapOptional = (property) => {
43
+ if (!property.isOptional || !SchemaAST2.isUnion(property.type)) {
44
+ return property;
45
+ }
46
+ return property.type.types[0];
47
+ };
48
+ var TypeIdentifierAnnotationId = Symbol.for("@dxos/schema/annotation/TypeIdentifier");
49
+ var getTypeIdentifierAnnotation = (schema) => Function.flow(SchemaAST2.getAnnotation(TypeIdentifierAnnotationId), Option.getOrElse(() => void 0))(schema.ast);
50
+ var TypeAnnotationId = Symbol.for("@dxos/schema/annotation/Type");
51
+ var Typename = Schema2.String.pipe(Schema2.pattern(/^[a-zA-Z]\w+\.[a-zA-Z]\w{1,}\/[\w/_-]+$/));
52
+ var SchemaVersion = Schema2.String.pipe(Schema2.pattern(/^\d+.\d+.\d+$/));
53
+ var TypeAnnotation = Schema2.Struct({
54
+ kind: Schema2.Enums(EntityKind),
55
+ typename: Typename,
56
+ version: SchemaVersion,
57
+ /**
58
+ * If this is a relation, the schema of the source object.
59
+ * Must be present if entity kind is {@link EntityKind.Relation}.
60
+ */
61
+ sourceSchema: Schema2.optional(DXN.Schema),
62
+ /**
63
+ * If this is a relation, the schema of the target object.
64
+ * Must be present if entity kind is {@link EntityKind.Relation}.
65
+ */
66
+ targetSchema: Schema2.optional(DXN.Schema)
67
+ });
68
+ var getTypeAnnotation = (schema) => {
69
+ assertArgument(schema != null && schema.ast != null, "schema", "invalid schema");
70
+ return Function.flow(SchemaAST2.getAnnotation(TypeAnnotationId), Option.getOrElse(() => void 0))(schema.ast);
71
+ };
72
+ var getEntityKind = (schema) => getTypeAnnotation(schema)?.kind;
73
+ var getSchemaTypename = (schema) => getTypeAnnotation(schema)?.typename;
74
+ var getSchemaVersion = (schema) => getTypeAnnotation(schema)?.version;
75
+ var PropertyMetaAnnotationId = Symbol.for("@dxos/schema/annotation/PropertyMeta");
76
+ var PropertyMeta = (name, value) => {
77
+ return (self) => {
78
+ const existingMeta = self.ast.annotations[PropertyMetaAnnotationId];
79
+ return self.annotations({
80
+ [PropertyMetaAnnotationId]: {
81
+ ...existingMeta,
82
+ [name]: value
83
+ }
84
+ });
85
+ };
86
+ };
87
+ var getPropertyMetaAnnotation = (prop, name) => Function.pipe(SchemaAST2.getAnnotation(PropertyMetaAnnotationId)(prop.type), Option.map((meta) => meta[name]), Option.getOrElse(() => void 0));
88
+ var ReferenceAnnotationId = Symbol.for("@dxos/schema/annotation/Reference");
89
+ var getReferenceAnnotation = (schema) => Function.pipe(SchemaAST2.getAnnotation(ReferenceAnnotationId)(schema.ast), Option.getOrElse(() => void 0));
90
+ var SchemaMetaSymbol = Symbol.for("@dxos/schema/SchemaMeta");
91
+ var ViewAnnotationId = Symbol.for("@dxos/schema/annotation/View");
92
+ var ViewAnnotation = createAnnotationHelper(ViewAnnotationId);
93
+ var LabelAnnotationId = Symbol.for("@dxos/schema/annotation/Label");
94
+ var LabelAnnotation = createAnnotationHelper(LabelAnnotationId);
95
+ var FieldLookupAnnotationId = Symbol.for("@dxos/schema/annotation/FieldLookup");
96
+ var GeneratorAnnotationId = Symbol.for("@dxos/schema/annotation/Generator");
97
+ var GeneratorAnnotation = createAnnotationHelper(GeneratorAnnotationId);
98
+ var getSchemaDXN = (schema) => {
99
+ assertArgument(Schema2.isSchema(schema), "schema", "invalid schema");
100
+ const id = getTypeIdentifierAnnotation(schema);
101
+ if (id) {
102
+ return DXN.parse(id);
103
+ }
104
+ const objectAnnotation = getTypeAnnotation(schema);
105
+ if (!objectAnnotation) {
106
+ return void 0;
107
+ }
108
+ return DXN.fromTypenameAndVersion(objectAnnotation.typename, objectAnnotation.version);
109
+ };
110
+
111
+ // src/internal/ast/types.ts
112
+ var FIELD_PATH_ANNOTATION = "path";
113
+ var FieldPath = (path) => PropertyMeta(FIELD_PATH_ANNOTATION, path);
114
+
115
+ // src/internal/formats/number.ts
116
+ import * as Schema3 from "effect/Schema";
117
+
118
+ // src/internal/formats/types.ts
119
+ import * as Function2 from "effect/Function";
120
+ import * as Option2 from "effect/Option";
121
+ import * as SchemaAST3 from "effect/SchemaAST";
122
+ var TypeEnum = /* @__PURE__ */ (function(TypeEnum2) {
123
+ TypeEnum2["Array"] = "array";
124
+ TypeEnum2["Object"] = "object";
125
+ TypeEnum2["String"] = "string";
126
+ TypeEnum2["Number"] = "number";
127
+ TypeEnum2["Boolean"] = "boolean";
128
+ TypeEnum2["Ref"] = "ref";
129
+ return TypeEnum2;
130
+ })({});
131
+ var getTypeEnum = (property) => {
132
+ switch (property.type) {
133
+ case "array":
134
+ return "array";
135
+ case "object":
136
+ return "object";
137
+ case "string":
138
+ return "string";
139
+ case "number":
140
+ return "number";
141
+ case "boolean":
142
+ return "boolean";
143
+ default:
144
+ return void 0;
145
+ }
146
+ };
147
+ var FormatAnnotationId = Symbol.for("@dxos/schema/annotation/Format");
148
+ var FormatAnnotation = createAnnotationHelper(FormatAnnotationId);
149
+ var getFormatAnnotation = (node) => Function2.pipe(SchemaAST3.getAnnotation(FormatAnnotationId)(node), Option2.getOrUndefined);
150
+ var FormatEnum = /* @__PURE__ */ (function(FormatEnum2) {
151
+ FormatEnum2["None"] = "none";
152
+ FormatEnum2["String"] = "string";
153
+ FormatEnum2["Number"] = "number";
154
+ FormatEnum2["Boolean"] = "boolean";
155
+ FormatEnum2["Ref"] = "ref";
156
+ FormatEnum2["DID"] = "did";
157
+ FormatEnum2["DXN"] = "dxn";
158
+ FormatEnum2["Email"] = "email";
159
+ FormatEnum2["Formula"] = "formula";
160
+ FormatEnum2["Hostname"] = "hostname";
161
+ FormatEnum2["JSON"] = "json";
162
+ FormatEnum2["Markdown"] = "markdown";
163
+ FormatEnum2["Regex"] = "regex";
164
+ FormatEnum2["SingleSelect"] = "single-select";
165
+ FormatEnum2["MultiSelect"] = "multi-select";
166
+ FormatEnum2["URL"] = "url";
167
+ FormatEnum2["UUID"] = "uuid";
168
+ FormatEnum2["Currency"] = "currency";
169
+ FormatEnum2["Integer"] = "integer";
170
+ FormatEnum2["Percent"] = "percent";
171
+ FormatEnum2["Timestamp"] = "timestamp";
172
+ FormatEnum2["DateTime"] = "date-time";
173
+ FormatEnum2["Date"] = "date";
174
+ FormatEnum2["Time"] = "time";
175
+ FormatEnum2["Duration"] = "duration";
176
+ FormatEnum2["GeoPoint"] = "lnglat";
177
+ return FormatEnum2;
178
+ })({});
179
+ var FormatEnums = Object.values(FormatEnum).sort();
180
+ var PropertyKind = {
181
+ type: TypeEnum,
182
+ format: FormatEnum
183
+ };
184
+ var typeToFormat = {
185
+ ["string"]: "string",
186
+ ["number"]: "number",
187
+ ["boolean"]: "boolean"
188
+ };
189
+ var formatToType = {
190
+ ["none"]: void 0,
191
+ ["string"]: "string",
192
+ ["number"]: "number",
193
+ ["boolean"]: "boolean",
194
+ ["ref"]: "ref",
195
+ ["did"]: "string",
196
+ ["dxn"]: "string",
197
+ ["email"]: "string",
198
+ ["formula"]: "string",
199
+ ["hostname"]: "string",
200
+ ["json"]: "string",
201
+ ["markdown"]: "string",
202
+ ["regex"]: "string",
203
+ ["url"]: "string",
204
+ ["uuid"]: "string",
205
+ ["single-select"]: "string",
206
+ ["multi-select"]: "object",
207
+ ["date"]: "string",
208
+ ["date-time"]: "string",
209
+ ["duration"]: "string",
210
+ ["time"]: "string",
211
+ ["currency"]: "number",
212
+ ["integer"]: "number",
213
+ ["percent"]: "number",
214
+ ["timestamp"]: "number",
215
+ ["lnglat"]: "array"
216
+ };
217
+ var OptionsAnnotationId = Symbol.for("@dxos/schema/annotation/Options");
218
+ var getOptionsAnnotation = (node) => Function2.pipe(SchemaAST3.getAnnotation(OptionsAnnotationId)(node), Option2.getOrUndefined);
219
+
220
+ // src/internal/formats/number.ts
221
+ var encodeMultipleOf = (divisor) => 1 / Math.pow(10, divisor);
222
+ var encodeMultiple = (divisor) => (self) => divisor === void 0 || divisor === 0 ? self : self.pipe(Schema3.multipleOf(encodeMultipleOf(divisor)));
223
+ var DecimalPrecision = Schema3.transform(Schema3.Number, Schema3.Number, {
224
+ strict: true,
225
+ encode: (value) => encodeMultipleOf(value),
226
+ decode: (value) => Math.log10(1 / value)
227
+ }).annotations({
228
+ title: "Number of digits"
229
+ });
230
+ var CurrencyAnnotationId = Symbol.for("@dxos/schema/annotation/Currency");
231
+ var Currency = ({ decimals, code } = {
232
+ decimals: 2
233
+ }) => Schema3.Number.pipe(encodeMultiple(decimals), FormatAnnotation.set(FormatEnum.Currency), Schema3.annotations({
234
+ title: "Currency",
235
+ description: "Currency value",
236
+ ...code ? {
237
+ [CurrencyAnnotationId]: code.toUpperCase()
238
+ } : {}
239
+ }));
240
+ var Integer = () => Schema3.Number.pipe(Schema3.int(), FormatAnnotation.set(FormatEnum.Integer), Schema3.annotations({
241
+ title: "Integer",
242
+ description: "Integer value"
243
+ }));
244
+ var Percent = ({ decimals } = {
245
+ decimals: 2
246
+ }) => Schema3.Number.pipe(encodeMultiple(decimals), FormatAnnotation.set(FormatEnum.Percent), Schema3.annotations({
247
+ title: "Percent",
248
+ description: "Percentage value"
249
+ }));
250
+ var Timestamp = Schema3.Number.pipe(FormatAnnotation.set(FormatEnum.Timestamp), Schema3.annotations({
251
+ title: "Timestamp",
252
+ description: "Unix timestamp"
253
+ }));
254
+
255
+ // src/internal/formats/object.ts
256
+ import * as Schema4 from "effect/Schema";
257
+ import { clamp as clamp2 } from "@dxos/util";
258
+ var GeoPoint = Schema4.Tuple(Schema4.Number.pipe(Schema4.annotations({
259
+ title: "Longitude"
260
+ }), Schema4.clamp(-180, 180), Schema4.multipleOf(1e-5)), Schema4.Number.pipe(Schema4.annotations({
261
+ title: "Latitude"
262
+ }), Schema4.clamp(-90, 90), Schema4.multipleOf(1e-5)), Schema4.optionalElement(Schema4.Number).annotations({
263
+ title: "Height ASL (m)"
264
+ })).pipe(FormatAnnotation.set(FormatEnum.GeoPoint), Schema4.annotations({
265
+ title: "GeoPoint",
266
+ description: "GeoJSON Position"
267
+ }));
268
+ (function(GeoLocation2) {
269
+ GeoLocation2.toGeoPoint = ({ longitude, latitude, height }) => {
270
+ const clampedLongitude = clamp2(longitude, -180, 180);
271
+ const clampedLatitude = clamp2(latitude, -90, 90);
272
+ return height !== void 0 ? [
273
+ clampedLongitude,
274
+ clampedLatitude,
275
+ height
276
+ ] : [
277
+ clampedLongitude,
278
+ clampedLatitude
279
+ ];
280
+ };
281
+ GeoLocation2.fromGeoPoint = (geoPoint) => {
282
+ if (!geoPoint) {
283
+ return {
284
+ longitude: 0,
285
+ latitude: 0
286
+ };
287
+ }
288
+ const result = {
289
+ longitude: geoPoint[0],
290
+ latitude: geoPoint[1]
291
+ };
292
+ if (geoPoint[2] !== void 0) {
293
+ result.height = geoPoint[2];
294
+ }
295
+ return result;
296
+ };
297
+ })(GeoLocation || (GeoLocation = {}));
298
+ var GeoLocation;
299
+
300
+ // src/internal/formats/format.ts
301
+ import * as Schema7 from "effect/Schema";
302
+ import * as Keys from "@dxos/keys";
303
+
304
+ // src/internal/formats/date.ts
305
+ import * as Schema5 from "effect/Schema";
306
+ import * as SchemaAST4 from "effect/SchemaAST";
307
+ var SimpleDate = Schema5.Struct({
308
+ year: Schema5.Number.pipe(Schema5.between(1900, 9999)),
309
+ month: Schema5.Number.pipe(Schema5.between(1, 12)),
310
+ day: Schema5.Number.pipe(Schema5.between(1, 31))
311
+ });
312
+ var SimpleTime = Schema5.Struct({
313
+ hours: Schema5.Number.pipe(Schema5.between(0, 23)),
314
+ minutes: Schema5.Number.pipe(Schema5.between(0, 59)),
315
+ seconds: Schema5.Number.pipe(Schema5.between(0, 59))
316
+ });
317
+ var SimpleDateTime = Schema5.extend(SimpleDate, SimpleTime);
318
+ var DateOnly = (
319
+ /* Schema.transformOrFail(Schema.String, SimpleDate, {
320
+ strict: true,
321
+ decode: (str, _, ast) => {
322
+ if (!isValidDateFormat(str)) {
323
+ return ParseResult.fail(new ParseResult.Type(ast, str, 'Expected YYYY-MM-DD format'));
324
+ }
325
+ if (!isValidDate(str)) {
326
+ return ParseResult.fail(new ParseResult.Type(ast, str, 'Invalid date'));
327
+ }
328
+
329
+ const [year, month, day] = str.split('-').map(Number);
330
+ return ParseResult.succeed({ year, month, day });
331
+ },
332
+ encode: (date) => {
333
+ return ParseResult.succeed(
334
+ [
335
+ date.year.toString().padStart(4, '0'),
336
+ date.month.toString().padStart(2, '0'),
337
+ date.day.toString().padStart(2, '0'),
338
+ ].join('-'),
339
+ );
340
+ },
341
+ }) */
342
+ Schema5.String.pipe(FormatAnnotation.set(FormatEnum.Date), Schema5.annotations({
343
+ title: "Date",
344
+ description: "Valid date in ISO format"
345
+ }))
346
+ );
347
+ var TimeOnly = (
348
+ /* Schema.transformOrFail(Schema.String, SimpleTime, {
349
+ strict: true,
350
+ decode: (str, _, ast) => {
351
+ if (!isValidTimeFormat(str)) {
352
+ return ParseResult.fail(new ParseResult.Type(ast, str, 'Expected HH:mm:ss format'));
353
+ }
354
+
355
+ const [hours, minutes, seconds] = str.split(':').map(Number);
356
+ return ParseResult.succeed({ hours, minutes, seconds });
357
+ },
358
+ encode: (time) => {
359
+ return ParseResult.succeed(
360
+ [
361
+ time.hours.toString().padStart(2, '0'),
362
+ time.minutes.toString().padStart(2, '0'),
363
+ time.seconds.toString().padStart(2, '0'),
364
+ ].join(':'),
365
+ );
366
+ },
367
+ }) */
368
+ Schema5.String.pipe(FormatAnnotation.set(FormatEnum.Time), Schema5.annotations({
369
+ title: "Time",
370
+ description: "Valid time in ISO format"
371
+ }))
372
+ );
373
+ var DateTime = (
374
+ /* Schema.transformOrFail(Schema.String, SimpleDateTime, {
375
+ strict: false,
376
+ decode: (str, _, ast) => {
377
+ const [date, time] = str.split('T');
378
+ if (!isValidDateFormat(date)) {
379
+ return ParseResult.fail(new ParseResult.Type(ast, date, 'Expected YYYY-MM-DD format'));
380
+ }
381
+ if (!isValidDate(date)) {
382
+ return ParseResult.fail(new ParseResult.Type(ast, date, 'Invalid date'));
383
+ }
384
+ if (!isValidTimeFormat(time)) {
385
+ return ParseResult.fail(new ParseResult.Type(ast, str, 'Expected HH:mm:ss format'));
386
+ }
387
+
388
+ const [year, month, day] = date.split('-').map(Number);
389
+ const [hours, minutes, seconds] = time.split(':').map(Number);
390
+ return ParseResult.succeed({ year, month, day, hours, minutes, seconds });
391
+ },
392
+ encode: (datetime) => {
393
+ return ParseResult.succeed(
394
+ [
395
+ [
396
+ datetime.year.toString().padStart(4, '0'),
397
+ datetime.month.toString().padStart(2, '0'),
398
+ datetime.day.toString().padStart(2, '0'),
399
+ ].join('-'),
400
+ [
401
+ datetime.hours.toString().padStart(2, '0'),
402
+ datetime.minutes.toString().padStart(2, '0'),
403
+ datetime.seconds.toString().padStart(2, '0'),
404
+ ].join(':'),
405
+ ].join('T'),
406
+ );
407
+ },
408
+ }) */
409
+ Schema5.String.pipe(FormatAnnotation.set(FormatEnum.DateTime), Schema5.annotations({
410
+ title: "DateTime",
411
+ description: "Valid date and time in ISO format"
412
+ }))
413
+ );
414
+ var Duration = Schema5.String.pipe(FormatAnnotation.set(FormatEnum.Duration), Schema5.annotations({
415
+ title: "Duration",
416
+ description: "Duration in ISO 8601 format",
417
+ [SchemaAST4.ExamplesAnnotationId]: [
418
+ "1h",
419
+ "3D"
420
+ ]
421
+ }));
422
+
423
+ // src/internal/formats/string.ts
424
+ import * as Schema6 from "effect/Schema";
425
+ import * as SchemaAST5 from "effect/SchemaAST";
426
+ var Email = Schema6.String.pipe(Schema6.pattern(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/), FormatAnnotation.set(FormatEnum.Email), Schema6.annotations({
427
+ title: "Email",
428
+ description: "Email address"
429
+ }));
430
+ var Formula = Schema6.String.pipe(FormatAnnotation.set(FormatEnum.Formula));
431
+ var Hostname = Schema6.String.pipe(FormatAnnotation.set(FormatEnum.Hostname));
432
+ var JSON = Schema6.String.pipe(FormatAnnotation.set(FormatEnum.JSON));
433
+ var Markdown = Schema6.String.pipe(FormatAnnotation.set(FormatEnum.Markdown));
434
+ var Regex = Schema6.String.pipe(FormatAnnotation.set(FormatEnum.Regex));
435
+ var URL = Schema6.String.pipe(Schema6.pattern(/^(\w+?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([/\w .-]*)*\/?$/i), FormatAnnotation.set(FormatEnum.URL), Schema6.annotations({
436
+ title: "URL",
437
+ description: "URL"
438
+ }));
439
+ var UUID2 = Schema6.UUID.pipe(FormatAnnotation.set(FormatEnum.UUID), Schema6.annotations({
440
+ [SchemaAST5.ExamplesAnnotationId]: [
441
+ "3e4666bf-d5e5-4aa7-b8ce-cefe41c7568a"
442
+ ]
443
+ }));
444
+
445
+ // src/internal/formats/format.ts
446
+ (function(Format2) {
447
+ Format2.DXN = Keys.DXN.Schema;
448
+ Format2.Email = Email;
449
+ Format2.Formula = Formula;
450
+ Format2.Hostname = Hostname;
451
+ Format2.JSON = JSON;
452
+ Format2.Markdown = Markdown;
453
+ Format2.Regex = Regex;
454
+ Format2.URL = URL;
455
+ Format2.UUID = Schema7.UUID;
456
+ Format2.Currency = Currency;
457
+ Format2.Integer = Integer;
458
+ Format2.Percent = Percent;
459
+ Format2.Timestamp = Timestamp;
460
+ Format2.DateTime = DateTime;
461
+ Format2.Date = DateOnly;
462
+ Format2.Time = TimeOnly;
463
+ Format2.Duration = Duration;
464
+ Format2.GeoPoint = GeoPoint;
465
+ })(Format || (Format = {}));
466
+ var Format;
467
+
468
+ // src/internal/formats/select.ts
469
+ import * as Schema8 from "effect/Schema";
470
+ var SelectOptionSchema = Schema8.Struct({
471
+ /** Stable identifier for the option. */
472
+ id: Schema8.NonEmptyString,
473
+ title: Schema8.String,
474
+ /** Color palette used for visual styling. */
475
+ color: Schema8.String
476
+ }).pipe(Schema8.mutable);
477
+
478
+ // src/internal/json/json-schema.ts
479
+ import * as Array4 from "effect/Array";
480
+ import * as Function3 from "effect/Function";
481
+ import * as JSONSchema from "effect/JSONSchema";
482
+ import * as Option5 from "effect/Option";
483
+ import * as Schema20 from "effect/Schema";
484
+ import * as SchemaAST10 from "effect/SchemaAST";
485
+ import { raise as raise4 } from "@dxos/debug";
486
+ import { mapAst } from "@dxos/effect";
487
+ import { invariant as invariant11 } from "@dxos/invariant";
488
+ import { DXN as DXN10, ObjectId as ObjectId7 } from "@dxos/keys";
489
+ import { log } from "@dxos/log";
490
+ import { clearUndefined, orderKeys, removeProperties } from "@dxos/util";
491
+
492
+ // src/internal/json-schema/json-schema-type.ts
493
+ import * as Schema9 from "effect/Schema";
494
+ import { JsonPath } from "@dxos/effect";
495
+ var SimpleTypes = Schema9.Literal("array", "boolean", "integer", "null", "number", "object", "string");
496
+ var NonNegativeInteger = Schema9.Number.pipe(Schema9.greaterThanOrEqualTo(0));
497
+ var StringArray = Schema9.Array(Schema9.String).pipe(Schema9.mutable);
498
+ var JsonSchemaOrBoolean = Schema9.Union(Schema9.suspend(() => JsonSchemaType), Schema9.Boolean);
499
+ var JsonSchemaEchoAnnotations = Schema9.Struct({
500
+ /**
501
+ * Label for this schema.
502
+ * Mapped from {@link LabelAnnotationId}.
503
+ */
504
+ labelProp: Schema9.optional(Schema9.Union(JsonPath, Schema9.Array(JsonPath))),
505
+ /**
506
+ * Generator function for this schema.
507
+ * Mapped from {@link GeneratorAnnotationId}.
508
+ */
509
+ generator: Schema9.optional(Schema9.Union(Schema9.String, Schema9.Tuple(Schema9.String, Schema9.Number))),
510
+ /**
511
+ * {@link PropertyMeta} annotations get serialized here.
512
+ */
513
+ meta: Schema9.optional(Schema9.Record({
514
+ key: Schema9.String,
515
+ value: Schema9.Any
516
+ }).pipe(Schema9.mutable)),
517
+ /**
518
+ * @deprecated
519
+ */
520
+ // TODO(dmaretskyi): We risk old schema not passing validation due to the extra fields. Remove when we are sure this is safe
521
+ type: Schema9.optional(Schema9.Struct({
522
+ typename: Schema9.String,
523
+ version: Schema9.String,
524
+ // Not used.
525
+ schemaId: Schema9.optional(Schema9.String)
526
+ }).pipe(Schema9.mutable)),
527
+ /**
528
+ * @deprecated Superseded by `meta`.
529
+ */
530
+ annotations: Schema9.optional(Schema9.Record({
531
+ key: Schema9.String,
532
+ value: Schema9.Any
533
+ }).pipe(Schema9.mutable))
534
+ }).pipe(Schema9.mutable);
535
+ var _JsonSchemaType = Schema9.Struct({
536
+ /**
537
+ * Identifier for this schema.
538
+ * This schema might be referenced by $ref clause in other schemas.
539
+ */
540
+ // TODO(dmaretskyi): Specify how the ids are generated.
541
+ // TODO(dmaretskyi): For type dxns, should this include the version?
542
+ $id: Schema9.optional(Schema9.String),
543
+ /**
544
+ * Schema of this schema.
545
+ * Set to "https://json-schema.org/draft-07/schema".
546
+ */
547
+ $schema: Schema9.optional(Schema9.String),
548
+ /**
549
+ * Reference to another schema.
550
+ */
551
+ $ref: Schema9.optional(Schema9.String),
552
+ /**
553
+ * Comments are ignored when interpreting the schema.
554
+ */
555
+ $comment: Schema9.optional(Schema9.String),
556
+ /**
557
+ * Defines whether this schema is an object schema or a relation schema.
558
+ */
559
+ entityKind: Schema9.optional(EntityKindSchema),
560
+ /**
561
+ * Typename of this schema.
562
+ * Only on schema representing an ECHO object.
563
+ *
564
+ * @example 'example.com/type/MyType'
565
+ */
566
+ typename: Schema9.optional(Schema9.String),
567
+ /**
568
+ * Version of this schema.
569
+ * Custom dialect for ECHO.
570
+ */
571
+ version: Schema9.optional(Schema9.String),
572
+ /**
573
+ * Target of this relation.
574
+ * Only for relation schemas.
575
+ * The referenced schema must be an object schema.
576
+ */
577
+ relationTarget: Schema9.optional(Schema9.suspend(() => JsonSchemaType)),
578
+ /**
579
+ * Source of this relation.
580
+ * Only for relation schemas.
581
+ * The referenced schema must be an object schema.
582
+ */
583
+ relationSource: Schema9.optional(Schema9.suspend(() => JsonSchemaType)),
584
+ /**
585
+ * Title of this schema.
586
+ */
587
+ title: Schema9.optional(Schema9.String),
588
+ /**
589
+ * Description of this schema.
590
+ */
591
+ description: Schema9.optional(Schema9.String),
592
+ /**
593
+ * Whether this schema is read-only.
594
+ */
595
+ readOnly: Schema9.optional(Schema9.Boolean),
596
+ /**
597
+ * Whether this schema is write-only.
598
+ */
599
+ writeOnly: Schema9.optional(Schema9.Boolean),
600
+ /**
601
+ * Examples of instances of this schema.
602
+ */
603
+ examples: Schema9.optional(Schema9.Array(Schema9.Any)),
604
+ /**
605
+ * Default value for this schema.
606
+ */
607
+ default: Schema9.optional(Schema9.Any),
608
+ /**
609
+ * This schema only matches values that are equal to this value.
610
+ */
611
+ const: Schema9.optional(Schema9.Any),
612
+ /**
613
+ * This schema only matches one of the values in this array.
614
+ */
615
+ enum: Schema9.optional(Schema9.Array(Schema9.Any)),
616
+ /**
617
+ * Base type of the schema.
618
+ */
619
+ type: Schema9.optional(Schema9.Union(SimpleTypes, Schema9.Array(SimpleTypes))),
620
+ //
621
+ // Numbers.
622
+ //
623
+ multipleOf: Schema9.optional(Schema9.Number.pipe(Schema9.greaterThan(0))),
624
+ maximum: Schema9.optional(Schema9.Number),
625
+ exclusiveMaximum: Schema9.optional(Schema9.Number),
626
+ minimum: Schema9.optional(Schema9.Number),
627
+ exclusiveMinimum: Schema9.optional(Schema9.Number),
628
+ //
629
+ // Strings.
630
+ //
631
+ maxLength: Schema9.optional(NonNegativeInteger),
632
+ /**
633
+ * Regex pattern for strings.
634
+ */
635
+ pattern: Schema9.optional(Schema9.String.pipe(FormatAnnotation.set(FormatEnum.Regex))),
636
+ /**
637
+ * Serialized from {@link FormatAnnotationId}.
638
+ */
639
+ format: Schema9.optional(Schema9.String),
640
+ //
641
+ // Arrays
642
+ //
643
+ minLength: Schema9.optional(NonNegativeInteger),
644
+ items: Schema9.optional(Schema9.Union(Schema9.suspend(() => JsonSchemaType), Schema9.Array(Schema9.suspend(() => JsonSchemaType)))),
645
+ additionalItems: Schema9.optional(Schema9.Union(Schema9.suspend(() => JsonSchemaType), Schema9.Boolean)),
646
+ maxItems: Schema9.optional(NonNegativeInteger),
647
+ minItems: Schema9.optional(NonNegativeInteger),
648
+ uniqueItems: Schema9.optional(Schema9.Boolean),
649
+ contains: Schema9.optional(Schema9.suspend(() => JsonSchemaType)),
650
+ //
651
+ // Objects
652
+ //
653
+ maxProperties: Schema9.optional(NonNegativeInteger),
654
+ minProperties: Schema9.optional(NonNegativeInteger),
655
+ required: Schema9.optional(StringArray),
656
+ /**
657
+ * Non-standard JSON Schema extension.
658
+ * Defines the order of properties in the object.
659
+ * The unmentioned properties are placed at the end.
660
+ *
661
+ * Related: https://github.com/json-schema/json-schema/issues/119
662
+ */
663
+ propertyOrder: Schema9.optional(StringArray),
664
+ additionalProperties: Schema9.optional(JsonSchemaOrBoolean),
665
+ properties: Schema9.optional(Schema9.Record({
666
+ key: Schema9.String,
667
+ value: Schema9.suspend(() => JsonSchemaType)
668
+ }).pipe(Schema9.mutable)),
669
+ patternProperties: Schema9.optional(Schema9.Record({
670
+ key: Schema9.String,
671
+ value: Schema9.suspend(() => JsonSchemaType)
672
+ }).pipe(Schema9.mutable)),
673
+ propertyNames: Schema9.optional(Schema9.suspend(() => JsonSchemaType)),
674
+ definitions: Schema9.optional(Schema9.mutable(Schema9.Record({
675
+ key: Schema9.String,
676
+ value: Schema9.suspend(() => JsonSchemaType)
677
+ }))),
678
+ dependencies: Schema9.optional(Schema9.Record({
679
+ key: Schema9.String,
680
+ value: Schema9.suspend(() => Schema9.Union(Schema9.String, StringArray, JsonSchemaType)).annotations({
681
+ identifier: "dependency",
682
+ description: "Dependency"
683
+ })
684
+ })),
685
+ contentMediaType: Schema9.optional(Schema9.String),
686
+ contentEncoding: Schema9.optional(Schema9.String),
687
+ if: Schema9.optional(Schema9.suspend(() => JsonSchemaType)),
688
+ then: Schema9.optional(Schema9.suspend(() => JsonSchemaType)),
689
+ else: Schema9.optional(Schema9.suspend(() => JsonSchemaType)),
690
+ allOf: Schema9.optional(Schema9.Array(Schema9.suspend(() => JsonSchemaType))),
691
+ anyOf: Schema9.optional(Schema9.Array(Schema9.suspend(() => JsonSchemaType))),
692
+ oneOf: Schema9.optional(Schema9.Array(Schema9.suspend(() => JsonSchemaType))),
693
+ not: Schema9.optional(Schema9.suspend(() => JsonSchemaType)),
694
+ $defs: Schema9.optional(Schema9.mutable(Schema9.Record({
695
+ key: Schema9.String,
696
+ value: Schema9.suspend(() => JsonSchemaType)
697
+ }))),
698
+ //
699
+ // ECHO extensions.
700
+ //
701
+ currency: Schema9.optional(Schema9.String),
702
+ reference: Schema9.optional(Schema9.mutable(Schema9.Struct({
703
+ schema: Schema9.suspend(() => JsonSchemaType),
704
+ schemaVersion: Schema9.optional(Schema9.String),
705
+ schemaObject: Schema9.optional(Schema9.String)
706
+ }))),
707
+ /**
708
+ * ECHO-specific annotations.
709
+ */
710
+ // TODO(dmaretskyi): Since we are adding a lot of new extensions to the JSON Schema, it is safer to namespace them here.
711
+ annotations: Schema9.optional(Schema9.mutable(JsonSchemaEchoAnnotations)),
712
+ /**
713
+ * @deprecated Use `annotations` instead.
714
+ */
715
+ echo: Schema9.optional(Schema9.mutable(JsonSchemaEchoAnnotations))
716
+ }).annotations({
717
+ identifier: "jsonSchema",
718
+ description: "JSON Schema"
719
+ });
720
+ var JsonSchemaFields = Object.keys(_JsonSchemaType.fields);
721
+ var JsonSchemaType = _JsonSchemaType.pipe(Schema9.mutable);
722
+ var getSchemaProperty = (schema, property) => {
723
+ return schema.properties?.[property];
724
+ };
725
+ var setSchemaProperty = (schema, property, value) => {
726
+ var _schema;
727
+ (_schema = schema).properties ?? (_schema.properties = {});
728
+ schema.properties[property] = value;
729
+ return schema;
730
+ };
731
+ var ECHO_ANNOTATIONS_NS_DEPRECATED_KEY = "echo";
732
+ var ECHO_ANNOTATIONS_NS_KEY = "annotations";
733
+ var getNormalizedEchoAnnotations = (obj) => {
734
+ if (obj[ECHO_ANNOTATIONS_NS_KEY] != null && obj[ECHO_ANNOTATIONS_NS_DEPRECATED_KEY] != null) {
735
+ return normalizeEchoAnnotations({
736
+ ...obj[ECHO_ANNOTATIONS_NS_DEPRECATED_KEY],
737
+ ...obj[ECHO_ANNOTATIONS_NS_KEY]
738
+ });
739
+ } else if (obj[ECHO_ANNOTATIONS_NS_KEY] != null) {
740
+ return normalizeEchoAnnotations(obj[ECHO_ANNOTATIONS_NS_KEY]);
741
+ } else if (obj[ECHO_ANNOTATIONS_NS_DEPRECATED_KEY] != null) {
742
+ return normalizeEchoAnnotations(obj[ECHO_ANNOTATIONS_NS_DEPRECATED_KEY]);
743
+ } else {
744
+ return void 0;
745
+ }
746
+ };
747
+ var normalizeEchoAnnotations = (obj) => {
748
+ if (!obj.annotations) {
749
+ return obj;
750
+ } else {
751
+ const res = {
752
+ ...obj,
753
+ meta: {
754
+ ...obj.annotations,
755
+ ...obj.meta ?? {}
756
+ }
757
+ };
758
+ delete res.annotations;
759
+ return res;
760
+ }
761
+ };
762
+
763
+ // src/internal/json-schema/json-schema-normalize.ts
764
+ var normalizeSchema = (schema) => {
765
+ const copy = structuredClone(schema);
766
+ go(copy);
767
+ return copy;
768
+ };
769
+ var go = (schema) => {
770
+ if (typeof schema !== "object" || schema === null) {
771
+ return;
772
+ }
773
+ if (schema.exclusiveMaximum === true) {
774
+ schema.exclusiveMaximum = schema.maximum;
775
+ delete schema.exclusiveMaximum;
776
+ } else if (schema.exclusiveMaximum === false) {
777
+ delete schema.exclusiveMaximum;
778
+ }
779
+ if (schema.exclusiveMinimum === true) {
780
+ schema.exclusiveMinimum = schema.minimum;
781
+ delete schema.exclusiveMinimum;
782
+ } else if (schema.exclusiveMinimum === false) {
783
+ delete schema.exclusiveMinimum;
784
+ }
785
+ for (const key of Object.keys(schema)) {
786
+ if (!JsonSchemaFields.includes(key)) {
787
+ delete schema[key];
788
+ }
789
+ }
790
+ if (schema.properties) {
791
+ goOnRecord(schema.properties);
792
+ }
793
+ if (schema.patternProperties) {
794
+ goOnRecord(schema.patternProperties);
795
+ }
796
+ if (schema.propertyNames) {
797
+ go(schema.propertyNames);
798
+ }
799
+ if (schema.definitions) {
800
+ goOnRecord(schema.definitions);
801
+ }
802
+ if (schema.items) {
803
+ maybeGoOnArray(schema.items);
804
+ }
805
+ if (schema.additionalItems) {
806
+ maybeGoOnArray(schema.additionalItems);
807
+ }
808
+ if (schema.contains) {
809
+ go(schema.contains);
810
+ }
811
+ if (schema.if) {
812
+ go(schema.if);
813
+ }
814
+ if (schema.then) {
815
+ go(schema.then);
816
+ }
817
+ if (schema.else) {
818
+ go(schema.else);
819
+ }
820
+ if (schema.allOf) {
821
+ maybeGoOnArray(schema.allOf);
822
+ }
823
+ if (schema.anyOf) {
824
+ maybeGoOnArray(schema.anyOf);
825
+ }
826
+ if (schema.oneOf) {
827
+ maybeGoOnArray(schema.oneOf);
828
+ }
829
+ if (schema.not) {
830
+ go(schema.not);
831
+ }
832
+ if (schema.$defs) {
833
+ goOnRecord(schema.$defs);
834
+ }
835
+ if (schema.reference) {
836
+ go(schema.reference.schema);
837
+ }
838
+ };
839
+ var maybeGoOnArray = (value) => {
840
+ if (Array.isArray(value)) {
841
+ for (const item of value) {
842
+ go(item);
843
+ }
844
+ } else if (typeof value === "object" && value !== null) {
845
+ go(value);
846
+ }
847
+ };
848
+ var goOnRecord = (record) => {
849
+ for (const key of Object.keys(record)) {
850
+ go(record[key]);
851
+ }
852
+ };
853
+
854
+ // src/internal/object/common.ts
855
+ import * as Schema11 from "effect/Schema";
856
+
857
+ // src/internal/object/typename.ts
858
+ import { invariant as invariant3 } from "@dxos/invariant";
859
+ import { DXN as DXN5 } from "@dxos/keys";
860
+
861
+ // src/internal/object/accessors.ts
862
+ import * as Option3 from "effect/Option";
863
+ import * as Schema10 from "effect/Schema";
864
+ import { getField } from "@dxos/effect";
865
+ import { assertArgument as assertArgument2, invariant as invariant2 } from "@dxos/invariant";
866
+ import { DXN as DXN4, ObjectId as ObjectId2 } from "@dxos/keys";
867
+ import { assumeType as assumeType2 } from "@dxos/util";
868
+
869
+ // src/internal/object/model.ts
870
+ import { invariant } from "@dxos/invariant";
871
+ import { DXN as DXN3, ObjectId } from "@dxos/keys";
872
+ import { assumeType } from "@dxos/util";
873
+ var __dxlog_file = "/__w/dxos/dxos/packages/core/echo/echo/src/internal/object/model.ts";
874
+ var EntityKindId = Symbol("@dxos/echo/EntityKind");
875
+ var SelfDXNId = Symbol("@dxos/echo/DXN");
876
+ var ATTR_SELF_DXN = "@dxn";
877
+ var TypeId = Symbol("@dxos/echo/Type");
878
+ var ATTR_TYPE = "@type";
879
+ var SchemaId = Symbol("@dxos/echo/Schema");
880
+ var DeletedId = Symbol("@dxos/echo/Deleted");
881
+ var ATTR_DELETED = "@deleted";
882
+ var MetaId = Symbol("@dxos/echo/Meta");
883
+ var ATTR_META = "@meta";
884
+ var RelationSourceDXNId = Symbol("@dxos/echo/RelationSourceDXN");
885
+ var ATTR_RELATION_SOURCE = "@relationSource";
886
+ var RelationTargetDXNId = Symbol("@dxos/echo/RelationTargetDXN");
887
+ var ATTR_RELATION_TARGET = "@relationTarget";
888
+ var RelationSourceId = Symbol("@dxos/echo/RelationSource");
889
+ var RelationTargetId = Symbol("@dxos/echo/RelationTarget");
890
+ var ObjectVersionId = Symbol("@dxos/echo/ObjectVersion");
891
+ function assertObjectModelShape(obj) {
892
+ invariant(typeof obj === "object" && obj !== null, "Invalid object model: not an object", {
893
+ F: __dxlog_file,
894
+ L: 156,
895
+ S: this,
896
+ A: [
897
+ "typeof obj === 'object' && obj !== null",
898
+ "'Invalid object model: not an object'"
899
+ ]
900
+ });
901
+ assumeType(obj);
902
+ invariant(ObjectId.isValid(obj.id), "Invalid object model: invalid id", {
903
+ F: __dxlog_file,
904
+ L: 158,
905
+ S: this,
906
+ A: [
907
+ "ObjectId.isValid(obj.id)",
908
+ "'Invalid object model: invalid id'"
909
+ ]
910
+ });
911
+ invariant(obj[TypeId] === void 0 || obj[TypeId] instanceof DXN3, "Invalid object model: invalid type", {
912
+ F: __dxlog_file,
913
+ L: 159,
914
+ S: this,
915
+ A: [
916
+ "obj[TypeId] === undefined || obj[TypeId] instanceof DXN",
917
+ "'Invalid object model: invalid type'"
918
+ ]
919
+ });
920
+ invariant(obj[EntityKindId] === EntityKind.Object || obj[EntityKindId] === EntityKind.Relation, "Invalid object model: invalid entity kind", {
921
+ F: __dxlog_file,
922
+ L: 160,
923
+ S: this,
924
+ A: [
925
+ "obj[EntityKindId] === EntityKind.Object || obj[EntityKindId] === EntityKind.Relation",
926
+ "'Invalid object model: invalid entity kind'"
927
+ ]
928
+ });
929
+ if (obj[EntityKindId] === EntityKind.Relation) {
930
+ invariant(obj[RelationSourceDXNId] instanceof DXN3, "Invalid object model: invalid relation source", {
931
+ F: __dxlog_file,
932
+ L: 165,
933
+ S: this,
934
+ A: [
935
+ "obj[RelationSourceDXNId] instanceof DXN",
936
+ "'Invalid object model: invalid relation source'"
937
+ ]
938
+ });
939
+ invariant(obj[RelationTargetDXNId] instanceof DXN3, "Invalid object model: invalid relation target", {
940
+ F: __dxlog_file,
941
+ L: 166,
942
+ S: this,
943
+ A: [
944
+ "obj[RelationTargetDXNId] instanceof DXN",
945
+ "'Invalid object model: invalid relation target'"
946
+ ]
947
+ });
948
+ invariant(!(obj[RelationSourceId] instanceof DXN3), "Invalid object model: source pointer is a DXN", {
949
+ F: __dxlog_file,
950
+ L: 167,
951
+ S: this,
952
+ A: [
953
+ "!(obj[RelationSourceId] instanceof DXN)",
954
+ "'Invalid object model: source pointer is a DXN'"
955
+ ]
956
+ });
957
+ invariant(!(obj[RelationTargetId] instanceof DXN3), "Invalid object model: target pointer is a DXN", {
958
+ F: __dxlog_file,
959
+ L: 168,
960
+ S: this,
961
+ A: [
962
+ "!(obj[RelationTargetId] instanceof DXN)",
963
+ "'Invalid object model: target pointer is a DXN'"
964
+ ]
965
+ });
966
+ }
967
+ }
968
+
969
+ // src/internal/object/accessors.ts
970
+ var __dxlog_file2 = "/__w/dxos/dxos/packages/core/echo/echo/src/internal/object/accessors.ts";
971
+ var getObjectDXN = (object) => {
972
+ invariant2(!Schema10.isSchema(object), "schema not allowed in this function", {
973
+ F: __dxlog_file2,
974
+ L: 26,
975
+ S: void 0,
976
+ A: [
977
+ "!Schema.isSchema(object)",
978
+ "'schema not allowed in this function'"
979
+ ]
980
+ });
981
+ assertArgument2(typeof object === "object" && object != null, "object", "expected object");
982
+ assumeType2(object);
983
+ if (object[SelfDXNId]) {
984
+ invariant2(object[SelfDXNId] instanceof DXN4, "Invalid object model: invalid self dxn", {
985
+ F: __dxlog_file2,
986
+ L: 31,
987
+ S: void 0,
988
+ A: [
989
+ "object[SelfDXNId] instanceof DXN",
990
+ "'Invalid object model: invalid self dxn'"
991
+ ]
992
+ });
993
+ return object[SelfDXNId];
994
+ }
995
+ if (!ObjectId2.isValid(object.id)) {
996
+ throw new TypeError("Object id is not valid.");
997
+ }
998
+ return DXN4.fromLocalObjectId(object.id);
999
+ };
1000
+ var getSchema = (obj) => {
1001
+ if (obj) {
1002
+ return obj[SchemaId];
1003
+ }
1004
+ };
1005
+ var setSchema = (obj, schema) => {
1006
+ Object.defineProperty(obj, SchemaId, {
1007
+ value: schema,
1008
+ writable: false,
1009
+ enumerable: false,
1010
+ configurable: false
1011
+ });
1012
+ };
1013
+ var getLabelForObject = (obj) => {
1014
+ const schema = getSchema(obj);
1015
+ if (schema) {
1016
+ return getLabel(schema, obj);
1017
+ }
1018
+ };
1019
+ var getLabel = (schema, object) => {
1020
+ const annotation = LabelAnnotation.get(schema).pipe(Option3.getOrElse(() => [
1021
+ "name"
1022
+ ]));
1023
+ for (const accessor of annotation) {
1024
+ assertArgument2(typeof accessor === "string", "accessor", "Label annotation must be a string or an array of strings");
1025
+ const value = getField(object, accessor);
1026
+ switch (typeof value) {
1027
+ case "string":
1028
+ case "number":
1029
+ case "boolean":
1030
+ case "bigint":
1031
+ case "symbol":
1032
+ return value.toString();
1033
+ case "undefined":
1034
+ case "object":
1035
+ case "function":
1036
+ continue;
1037
+ }
1038
+ }
1039
+ return void 0;
1040
+ };
1041
+ var setLabel = (schema, object, label) => {
1042
+ const annotation = LabelAnnotation.get(schema).pipe(Option3.map((field) => field[0]), Option3.getOrElse(() => "name"));
1043
+ object[annotation] = label;
1044
+ };
1045
+
1046
+ // src/internal/object/typename.ts
1047
+ var __dxlog_file3 = "/__w/dxos/dxos/packages/core/echo/echo/src/internal/object/typename.ts";
1048
+ var getTypename = (obj) => {
1049
+ const schema = getSchema(obj);
1050
+ if (schema != null) {
1051
+ return getSchemaTypename(schema);
1052
+ } else {
1053
+ const type = getType(obj);
1054
+ return type?.asTypeDXN()?.type;
1055
+ }
1056
+ };
1057
+ var setTypename = (obj, typename) => {
1058
+ invariant3(typename instanceof DXN5, "Invalid type.", {
1059
+ F: __dxlog_file3,
1060
+ L: 35,
1061
+ S: void 0,
1062
+ A: [
1063
+ "typename instanceof DXN",
1064
+ "'Invalid type.'"
1065
+ ]
1066
+ });
1067
+ Object.defineProperty(obj, TypeId, {
1068
+ value: typename,
1069
+ writable: false,
1070
+ enumerable: false,
1071
+ configurable: false
1072
+ });
1073
+ };
1074
+ var getType = (obj) => {
1075
+ if (!obj) {
1076
+ return void 0;
1077
+ }
1078
+ const type = obj[TypeId];
1079
+ if (!type) {
1080
+ return void 0;
1081
+ }
1082
+ invariant3(type instanceof DXN5, "Invalid object.", {
1083
+ F: __dxlog_file3,
1084
+ L: 59,
1085
+ S: void 0,
1086
+ A: [
1087
+ "type instanceof DXN",
1088
+ "'Invalid object.'"
1089
+ ]
1090
+ });
1091
+ return type;
1092
+ };
1093
+
1094
+ // src/internal/object/common.ts
1095
+ function _define_property(obj, key, value) {
1096
+ if (key in obj) {
1097
+ Object.defineProperty(obj, key, {
1098
+ value,
1099
+ enumerable: true,
1100
+ configurable: true,
1101
+ writable: true
1102
+ });
1103
+ } else {
1104
+ obj[key] = value;
1105
+ }
1106
+ return obj;
1107
+ }
1108
+ var makeTypedEntityClass = (typename, version, baseSchema) => {
1109
+ let _Schema_TypeId2;
1110
+ var _class;
1111
+ return _Schema_TypeId2 = Schema11.TypeId, _class = class {
1112
+ // TODO(burdon): Comment required.
1113
+ static [Symbol.hasInstance](obj) {
1114
+ return obj != null && getTypename(obj) === typename;
1115
+ }
1116
+ // TODO(burdon): Throw APIError.
1117
+ constructor() {
1118
+ throw new Error("Use live(Typename, { ...fields }) to instantiate an object.");
1119
+ }
1120
+ }, // Implement TypedObject properties.
1121
+ _define_property(_class, "typename", typename), _define_property(_class, "version", version), // Implement Schema.Schema properties.
1122
+ // TODO(burdon): Comment required.
1123
+ _define_property(_class, _Schema_TypeId2, schemaVariance), _define_property(_class, "ast", baseSchema.ast), _define_property(_class, "annotations", baseSchema.annotations.bind(baseSchema)), _define_property(_class, "pipe", baseSchema.pipe.bind(baseSchema)), _class;
1124
+ };
1125
+ var schemaVariance = {
1126
+ _A: (_) => _,
1127
+ _I: (_) => _,
1128
+ _R: (_) => _
1129
+ };
1130
+
1131
+ // src/internal/object/create.ts
1132
+ import { raise as raise2 } from "@dxos/debug";
1133
+ import { assertArgument as assertArgument5, failedInvariant } from "@dxos/invariant";
1134
+ import { ObjectId as ObjectId5 } from "@dxos/keys";
1135
+ import { defineHiddenProperty as defineHiddenProperty2 } from "@dxos/live-object";
1136
+
1137
+ // src/internal/object/inspect.ts
1138
+ import { inspectCustom } from "@dxos/debug";
1139
+ var attachedTypedObjectInspector = (obj) => {
1140
+ const descriptor = Object.getOwnPropertyDescriptor(obj, inspectCustom);
1141
+ if (descriptor) {
1142
+ return;
1143
+ }
1144
+ Object.defineProperty(obj, inspectCustom, {
1145
+ value: typedObjectInspectFunction,
1146
+ writable: false,
1147
+ enumerable: false,
1148
+ configurable: true
1149
+ });
1150
+ };
1151
+ var typedObjectInspectFunction = function(depth, options, inspect) {
1152
+ const { id, ...props } = this;
1153
+ return inspect({
1154
+ id,
1155
+ [ATTR_TYPE]: getType(this),
1156
+ ...props,
1157
+ [ATTR_META]: this[MetaId]
1158
+ }, options);
1159
+ };
1160
+
1161
+ // src/internal/object/json-serializer.ts
1162
+ import * as Schema14 from "effect/Schema";
1163
+ import { raise } from "@dxos/debug";
1164
+ import { isEncodedReference } from "@dxos/echo-protocol";
1165
+ import { assertArgument as assertArgument4, invariant as invariant6 } from "@dxos/invariant";
1166
+ import { DXN as DXN7, ObjectId as ObjectId4 } from "@dxos/keys";
1167
+ import { defineHiddenProperty } from "@dxos/live-object";
1168
+ import { assumeType as assumeType3, deepMapValues, visitValues } from "@dxos/util";
1169
+
1170
+ // src/internal/ref/ref.ts
1171
+ import * as Effect from "effect/Effect";
1172
+ import * as Option4 from "effect/Option";
1173
+ import * as ParseResult from "effect/ParseResult";
1174
+ import * as Schema12 from "effect/Schema";
1175
+ import * as SchemaAST6 from "effect/SchemaAST";
1176
+ import { Reference } from "@dxos/echo-protocol";
1177
+ import { compositeRuntime } from "@dxos/echo-signals/runtime";
1178
+ import { assertArgument as assertArgument3, invariant as invariant4 } from "@dxos/invariant";
1179
+ import { DXN as DXN6, ObjectId as ObjectId3 } from "@dxos/keys";
1180
+ function _check_private_redeclaration(obj, privateCollection) {
1181
+ if (privateCollection.has(obj)) {
1182
+ throw new TypeError("Cannot initialize the same private elements twice on an object");
1183
+ }
1184
+ }
1185
+ function _class_apply_descriptor_get(receiver, descriptor) {
1186
+ if (descriptor.get) {
1187
+ return descriptor.get.call(receiver);
1188
+ }
1189
+ return descriptor.value;
1190
+ }
1191
+ function _class_apply_descriptor_set(receiver, descriptor, value) {
1192
+ if (descriptor.set) {
1193
+ descriptor.set.call(receiver, value);
1194
+ } else {
1195
+ if (!descriptor.writable) {
1196
+ throw new TypeError("attempted to set read only private field");
1197
+ }
1198
+ descriptor.value = value;
1199
+ }
1200
+ }
1201
+ function _class_extract_field_descriptor(receiver, privateMap, action) {
1202
+ if (!privateMap.has(receiver)) {
1203
+ throw new TypeError("attempted to " + action + " private field on non-instance");
1204
+ }
1205
+ return privateMap.get(receiver);
1206
+ }
1207
+ function _class_private_field_get(receiver, privateMap) {
1208
+ var descriptor = _class_extract_field_descriptor(receiver, privateMap, "get");
1209
+ return _class_apply_descriptor_get(receiver, descriptor);
1210
+ }
1211
+ function _class_private_field_init(obj, privateMap, value) {
1212
+ _check_private_redeclaration(obj, privateMap);
1213
+ privateMap.set(obj, value);
1214
+ }
1215
+ function _class_private_field_set(receiver, privateMap, value) {
1216
+ var descriptor = _class_extract_field_descriptor(receiver, privateMap, "set");
1217
+ _class_apply_descriptor_set(receiver, descriptor, value);
1218
+ return value;
1219
+ }
1220
+ function _define_property2(obj, key, value) {
1221
+ if (key in obj) {
1222
+ Object.defineProperty(obj, key, {
1223
+ value,
1224
+ enumerable: true,
1225
+ configurable: true,
1226
+ writable: true
1227
+ });
1228
+ } else {
1229
+ obj[key] = value;
1230
+ }
1231
+ return obj;
1232
+ }
1233
+ var __dxlog_file4 = "/__w/dxos/dxos/packages/core/echo/echo/src/internal/ref/ref.ts";
1234
+ var JSON_SCHEMA_ECHO_REF_ID = "/schemas/echo/ref";
1235
+ var getSchemaReference = (property) => {
1236
+ const { $id, reference: { schema: { $ref } = {} } = {} } = property;
1237
+ if ($id === JSON_SCHEMA_ECHO_REF_ID && $ref) {
1238
+ return {
1239
+ typename: DXN6.parse($ref).typename
1240
+ };
1241
+ }
1242
+ };
1243
+ var createSchemaReference = (typename) => {
1244
+ return {
1245
+ $id: JSON_SCHEMA_ECHO_REF_ID,
1246
+ reference: {
1247
+ schema: {
1248
+ $ref: DXN6.fromTypename(typename).toString()
1249
+ }
1250
+ }
1251
+ };
1252
+ };
1253
+ var getReferenceAst = (ast) => {
1254
+ if (ast._tag !== "Declaration" || !ast.annotations[ReferenceAnnotationId]) {
1255
+ return void 0;
1256
+ }
1257
+ return {
1258
+ typename: ast.annotations[ReferenceAnnotationId].typename,
1259
+ version: ast.annotations[ReferenceAnnotationId].version
1260
+ };
1261
+ };
1262
+ var RefTypeId = Symbol("@dxos/echo/internal/Ref");
1263
+ var Ref = (schema) => {
1264
+ assertArgument3(Schema12.isSchema(schema), "schema", "Must call with an instance of effect-schema");
1265
+ const annotation = getTypeAnnotation(schema);
1266
+ if (annotation == null) {
1267
+ throw new Error("Reference target must be an ECHO schema.");
1268
+ }
1269
+ return createEchoReferenceSchema(getTypeIdentifierAnnotation(schema), annotation.typename, annotation.version, getSchemaExpectedName(schema.ast));
1270
+ };
1271
+ Ref.isRef = (obj) => {
1272
+ return obj && typeof obj === "object" && RefTypeId in obj;
1273
+ };
1274
+ Ref.hasObjectId = (id) => (ref) => ref.dxn.isLocalObjectId() && ref.dxn.parts[1] === id;
1275
+ Ref.isRefSchema = (schema) => {
1276
+ return Ref.isRefSchemaAST(schema.ast);
1277
+ };
1278
+ Ref.isRefSchemaAST = (ast) => {
1279
+ return SchemaAST6.getAnnotation(ast, ReferenceAnnotationId).pipe(Option4.isSome);
1280
+ };
1281
+ Ref.make = (obj) => {
1282
+ if (typeof obj !== "object" || obj === null) {
1283
+ throw new TypeError("Expected: ECHO object.");
1284
+ }
1285
+ const id = obj.id;
1286
+ invariant4(ObjectId3.isValid(id), "Invalid object ID", {
1287
+ F: __dxlog_file4,
1288
+ L: 219,
1289
+ S: void 0,
1290
+ A: [
1291
+ "ObjectId.isValid(id)",
1292
+ "'Invalid object ID'"
1293
+ ]
1294
+ });
1295
+ const dxn = Reference.localObjectReference(id).toDXN();
1296
+ return new RefImpl(dxn, obj);
1297
+ };
1298
+ Ref.fromDXN = (dxn) => {
1299
+ assertArgument3(dxn instanceof DXN6, "dxn", "Expected DXN");
1300
+ return new RefImpl(dxn);
1301
+ };
1302
+ var createEchoReferenceSchema = (echoId, typename, version, schemaName) => {
1303
+ if (!echoId && !typename) {
1304
+ throw new TypeError("Either echoId or typename must be provided.");
1305
+ }
1306
+ const referenceInfo = {
1307
+ schema: {
1308
+ // TODO(dmaretskyi): Include version?
1309
+ $ref: echoId ?? DXN6.fromTypename(typename).toString()
1310
+ },
1311
+ schemaVersion: version
1312
+ };
1313
+ const refSchema = Schema12.declare([], {
1314
+ encode: () => {
1315
+ return (value) => {
1316
+ return Effect.succeed({
1317
+ "/": value.dxn.toString()
1318
+ });
1319
+ };
1320
+ },
1321
+ decode: () => {
1322
+ return (value) => {
1323
+ if (Ref.isRef(value)) {
1324
+ return Effect.succeed(value);
1325
+ }
1326
+ if (typeof value !== "object" || value == null || typeof value["/"] !== "string") {
1327
+ return Effect.fail(new ParseResult.Unexpected(value, "reference"));
1328
+ }
1329
+ return Effect.succeed(Ref.fromDXN(DXN6.parse(value["/"])));
1330
+ };
1331
+ }
1332
+ }, {
1333
+ jsonSchema: {
1334
+ // TODO(dmaretskyi): We should remove `$id` and keep `$ref` with a fully qualified name.
1335
+ $id: JSON_SCHEMA_ECHO_REF_ID,
1336
+ $ref: JSON_SCHEMA_ECHO_REF_ID,
1337
+ reference: referenceInfo
1338
+ },
1339
+ [ReferenceAnnotationId]: {
1340
+ typename: typename ?? "",
1341
+ version
1342
+ }
1343
+ });
1344
+ return refSchema;
1345
+ };
1346
+ var getSchemaExpectedName = (ast) => {
1347
+ return SchemaAST6.getIdentifierAnnotation(ast).pipe(Option4.orElse(() => SchemaAST6.getTitleAnnotation(ast)), Option4.orElse(() => SchemaAST6.getDescriptionAnnotation(ast)), Option4.getOrElse(() => void 0));
1348
+ };
1349
+ var _dxn = /* @__PURE__ */ new WeakMap();
1350
+ var _resolver = /* @__PURE__ */ new WeakMap();
1351
+ var _signal = /* @__PURE__ */ new WeakMap();
1352
+ var _target = /* @__PURE__ */ new WeakMap();
1353
+ var _resolverCallback = /* @__PURE__ */ new WeakMap();
1354
+ var _RefTypeId = RefTypeId;
1355
+ var RefImpl = class _RefImpl {
1356
+ /**
1357
+ * @inheritdoc
1358
+ */
1359
+ get dxn() {
1360
+ return _class_private_field_get(this, _dxn);
1361
+ }
1362
+ /**
1363
+ * @inheritdoc
1364
+ */
1365
+ get target() {
1366
+ _class_private_field_get(this, _signal).notifyRead();
1367
+ if (_class_private_field_get(this, _target)) {
1368
+ return _class_private_field_get(this, _target);
1369
+ }
1370
+ invariant4(_class_private_field_get(this, _resolver), "Resolver is not set", {
1371
+ F: __dxlog_file4,
1372
+ L: 368,
1373
+ S: this,
1374
+ A: [
1375
+ "this.#resolver",
1376
+ "'Resolver is not set'"
1377
+ ]
1378
+ });
1379
+ return _class_private_field_get(this, _resolver).resolveSync(_class_private_field_get(this, _dxn), true, _class_private_field_get(this, _resolverCallback));
1380
+ }
1381
+ /**
1382
+ * @inheritdoc
1383
+ */
1384
+ async load() {
1385
+ if (_class_private_field_get(this, _target)) {
1386
+ return _class_private_field_get(this, _target);
1387
+ }
1388
+ invariant4(_class_private_field_get(this, _resolver), "Resolver is not set", {
1389
+ F: __dxlog_file4,
1390
+ L: 379,
1391
+ S: this,
1392
+ A: [
1393
+ "this.#resolver",
1394
+ "'Resolver is not set'"
1395
+ ]
1396
+ });
1397
+ const obj = await _class_private_field_get(this, _resolver).resolve(_class_private_field_get(this, _dxn));
1398
+ if (obj == null) {
1399
+ throw new Error("Object not found");
1400
+ }
1401
+ return obj;
1402
+ }
1403
+ /**
1404
+ * @inheritdoc
1405
+ */
1406
+ async tryLoad() {
1407
+ invariant4(_class_private_field_get(this, _resolver), "Resolver is not set", {
1408
+ F: __dxlog_file4,
1409
+ L: 391,
1410
+ S: this,
1411
+ A: [
1412
+ "this.#resolver",
1413
+ "'Resolver is not set'"
1414
+ ]
1415
+ });
1416
+ return await _class_private_field_get(this, _resolver).resolve(_class_private_field_get(this, _dxn));
1417
+ }
1418
+ /**
1419
+ * Do not inline the target object in the reference.
1420
+ * Makes .target unavailable unless the reference is connected to a database context.
1421
+ * Clones the reference object.
1422
+ */
1423
+ noInline() {
1424
+ const ref = new _RefImpl(_class_private_field_get(this, _dxn), void 0);
1425
+ _class_private_field_set(ref, _resolver, _class_private_field_get(this, _resolver));
1426
+ return ref;
1427
+ }
1428
+ encode() {
1429
+ return {
1430
+ "/": _class_private_field_get(this, _dxn).toString(),
1431
+ ..._class_private_field_get(this, _target) ? {
1432
+ target: _class_private_field_get(this, _target)
1433
+ } : {}
1434
+ };
1435
+ }
1436
+ /**
1437
+ * Serializes the reference to a JSON object.
1438
+ * The serialization format is compatible with the IPLD-style encoded references.
1439
+ * When a reference has a saved target (i.e. the target or object holding the reference is not in the database),
1440
+ * the target is included in the serialized object.
1441
+ */
1442
+ toJSON() {
1443
+ return this.encode();
1444
+ }
1445
+ toString() {
1446
+ if (_class_private_field_get(this, _target)) {
1447
+ return `Ref(${_class_private_field_get(this, _target).toString()})`;
1448
+ }
1449
+ return `Ref(${_class_private_field_get(this, _dxn).toString()})`;
1450
+ }
1451
+ /**
1452
+ * Internal method to set the resolver.
1453
+ * @internal
1454
+ */
1455
+ _setResolver(resolver) {
1456
+ _class_private_field_set(this, _resolver, resolver);
1457
+ }
1458
+ /**
1459
+ * Internal method to get the saved target.
1460
+ * Not the same as `target` which is resolved from the resolver.
1461
+ * @internal
1462
+ */
1463
+ _getSavedTarget() {
1464
+ return _class_private_field_get(this, _target);
1465
+ }
1466
+ constructor(dxn, target) {
1467
+ _class_private_field_init(this, _dxn, {
1468
+ writable: true,
1469
+ value: void 0
1470
+ });
1471
+ _class_private_field_init(this, _resolver, {
1472
+ writable: true,
1473
+ value: void 0
1474
+ });
1475
+ _class_private_field_init(this, _signal, {
1476
+ writable: true,
1477
+ value: compositeRuntime.createSignal()
1478
+ });
1479
+ _class_private_field_init(this, _target, {
1480
+ writable: true,
1481
+ value: void 0
1482
+ });
1483
+ _class_private_field_init(this, _resolverCallback, {
1484
+ writable: true,
1485
+ value: () => {
1486
+ _class_private_field_get(this, _signal).notifyWrite();
1487
+ }
1488
+ });
1489
+ _define_property2(this, _RefTypeId, refVariance);
1490
+ _class_private_field_set(this, _dxn, dxn);
1491
+ _class_private_field_set(this, _target, target);
1492
+ }
1493
+ };
1494
+ var setRefResolver = (ref, resolver) => {
1495
+ invariant4(ref instanceof RefImpl, "Ref is not an instance of RefImpl", {
1496
+ F: __dxlog_file4,
1497
+ L: 455,
1498
+ S: void 0,
1499
+ A: [
1500
+ "ref instanceof RefImpl",
1501
+ "'Ref is not an instance of RefImpl'"
1502
+ ]
1503
+ });
1504
+ ref._setResolver(resolver);
1505
+ };
1506
+ var getRefSavedTarget = (ref) => {
1507
+ invariant4(ref instanceof RefImpl, "Ref is not an instance of RefImpl", {
1508
+ F: __dxlog_file4,
1509
+ L: 463,
1510
+ S: void 0,
1511
+ A: [
1512
+ "ref instanceof RefImpl",
1513
+ "'Ref is not an instance of RefImpl'"
1514
+ ]
1515
+ });
1516
+ return ref._getSavedTarget();
1517
+ };
1518
+ var refVariance = {
1519
+ _T: null
1520
+ };
1521
+ var refFromEncodedReference = (encodedReference, resolver) => {
1522
+ const dxn = DXN6.parse(encodedReference["/"]);
1523
+ const ref = new RefImpl(dxn);
1524
+ if (resolver) {
1525
+ setRefResolver(ref, resolver);
1526
+ }
1527
+ return ref;
1528
+ };
1529
+ var StaticRefResolver = class {
1530
+ addObject(obj) {
1531
+ this.objects.set(obj.id, obj);
1532
+ return this;
1533
+ }
1534
+ addSchema(schema) {
1535
+ const dxn = getSchemaDXN(schema);
1536
+ invariant4(dxn, "Schema has no DXN", {
1537
+ F: __dxlog_file4,
1538
+ L: 495,
1539
+ S: this,
1540
+ A: [
1541
+ "dxn",
1542
+ "'Schema has no DXN'"
1543
+ ]
1544
+ });
1545
+ this.schemas.set(dxn.toString(), schema);
1546
+ return this;
1547
+ }
1548
+ resolveSync(dxn, _load, _onLoad) {
1549
+ const id = dxn?.asEchoDXN()?.echoId;
1550
+ if (id == null) {
1551
+ return void 0;
1552
+ }
1553
+ return this.objects.get(id);
1554
+ }
1555
+ async resolve(dxn) {
1556
+ const id = dxn?.asEchoDXN()?.echoId;
1557
+ if (id == null) {
1558
+ return void 0;
1559
+ }
1560
+ return this.objects.get(id);
1561
+ }
1562
+ async resolveSchema(dxn) {
1563
+ return this.schemas.get(dxn.toString());
1564
+ }
1565
+ constructor() {
1566
+ _define_property2(this, "objects", /* @__PURE__ */ new Map());
1567
+ _define_property2(this, "schemas", /* @__PURE__ */ new Map());
1568
+ }
1569
+ };
1570
+
1571
+ // src/internal/ref/ref-array.ts
1572
+ import { isNonNullable } from "@dxos/util";
1573
+ var RefArray = Object.freeze({
1574
+ /**
1575
+ * @returns all resolved targets.
1576
+ */
1577
+ targets: (refs) => {
1578
+ return refs.map((ref) => ref.target).filter(isNonNullable);
1579
+ },
1580
+ /**
1581
+ * Load all referenced objects.
1582
+ */
1583
+ loadAll: (refs) => {
1584
+ return Promise.all(refs.map((ref) => ref.load()));
1585
+ },
1586
+ /**
1587
+ * Removes the ref with the given id.
1588
+ */
1589
+ removeById: (refs, id) => {
1590
+ const index = refs.findIndex(Ref.hasObjectId(id));
1591
+ if (index >= 0) {
1592
+ refs.splice(index, 1);
1593
+ }
1594
+ }
1595
+ });
1596
+
1597
+ // src/internal/object/meta.ts
1598
+ import * as Schema13 from "effect/Schema";
1599
+ import { ForeignKey } from "@dxos/echo-protocol";
1600
+ import { invariant as invariant5 } from "@dxos/invariant";
1601
+ import { intersection } from "@dxos/util";
1602
+ var __dxlog_file5 = "/__w/dxos/dxos/packages/core/echo/echo/src/internal/object/meta.ts";
1603
+ var ObjectMetaSchema = Schema13.mutable(Schema13.Struct({
1604
+ keys: Schema13.mutable(Schema13.Array(ForeignKey)),
1605
+ /**
1606
+ * A set of tags.
1607
+ * Tags are arbitrary application-defined strings.
1608
+ * ECHO makes no assumptions about the tag structure.
1609
+ */
1610
+ // TODO(dmaretskyi): Has to be optional for compatibility with old data.
1611
+ // Defaulting to an empty array is possible but requires a bit more work.
1612
+ tags: Schema13.optional(Schema13.mutable(Schema13.Array(Schema13.String)))
1613
+ }));
1614
+ var foreignKey = (source, id) => ({
1615
+ source,
1616
+ id
1617
+ });
1618
+ var foreignKeyEquals = (a, b) => a.source === b.source && a.id === b.id;
1619
+ var getObjectMeta = (obj) => {
1620
+ return getMeta(obj);
1621
+ };
1622
+ var getMeta = (obj) => {
1623
+ const metadata = obj[MetaId];
1624
+ invariant5(metadata, "ObjectMeta not found.", {
1625
+ F: __dxlog_file5,
1626
+ L: 56,
1627
+ S: void 0,
1628
+ A: [
1629
+ "metadata",
1630
+ "'ObjectMeta not found.'"
1631
+ ]
1632
+ });
1633
+ return metadata;
1634
+ };
1635
+ var compareForeignKeys = (a, b) => intersection(getMeta(a).keys, getMeta(b).keys, foreignKeyEquals).length > 0;
1636
+
1637
+ // src/internal/object/json-serializer.ts
1638
+ var __dxlog_file6 = "/__w/dxos/dxos/packages/core/echo/echo/src/internal/object/json-serializer.ts";
1639
+ var objectToJSON = (obj) => {
1640
+ const typename = getType(obj)?.toString();
1641
+ invariant6(typename && typeof typename === "string", void 0, {
1642
+ F: __dxlog_file6,
1643
+ L: 50,
1644
+ S: void 0,
1645
+ A: [
1646
+ "typename && typeof typename === 'string'",
1647
+ ""
1648
+ ]
1649
+ });
1650
+ return typedJsonSerializer.call(obj);
1651
+ };
1652
+ var objectFromJSON = async (jsonData, { refResolver, dxn } = {}) => {
1653
+ assumeType3(jsonData);
1654
+ assertArgument4(typeof jsonData === "object" && jsonData !== null, "jsonData", "expect object");
1655
+ assertArgument4(typeof jsonData[ATTR_TYPE] === "string", "jsonData[ATTR_TYPE]", "expected object to have a type");
1656
+ assertArgument4(typeof jsonData.id === "string", "jsonData.id", "expected object to have an id");
1657
+ const type = DXN7.parse(jsonData[ATTR_TYPE]);
1658
+ const schema = await refResolver?.resolveSchema(type);
1659
+ invariant6(schema === void 0 || Schema14.isSchema(schema), void 0, {
1660
+ F: __dxlog_file6,
1661
+ L: 72,
1662
+ S: void 0,
1663
+ A: [
1664
+ "schema === undefined || Schema.isSchema(schema)",
1665
+ ""
1666
+ ]
1667
+ });
1668
+ let obj;
1669
+ if (schema != null) {
1670
+ obj = await schema.pipe(Schema14.decodeUnknownPromise)(jsonData);
1671
+ if (refResolver) {
1672
+ setRefResolverOnData(obj, refResolver);
1673
+ }
1674
+ } else {
1675
+ obj = decodeGeneric(jsonData, {
1676
+ refResolver
1677
+ });
1678
+ }
1679
+ invariant6(ObjectId4.isValid(obj.id), "Invalid object id", {
1680
+ F: __dxlog_file6,
1681
+ L: 84,
1682
+ S: void 0,
1683
+ A: [
1684
+ "ObjectId.isValid(obj.id)",
1685
+ "'Invalid object id'"
1686
+ ]
1687
+ });
1688
+ setTypename(obj, type);
1689
+ if (schema) {
1690
+ setSchema(obj, schema);
1691
+ }
1692
+ const isRelation = typeof jsonData[ATTR_RELATION_SOURCE] === "string" || typeof jsonData[ATTR_RELATION_TARGET] === "string";
1693
+ if (isRelation) {
1694
+ const sourceDxn = DXN7.parse(jsonData[ATTR_RELATION_SOURCE] ?? raise(new TypeError("Missing relation source")));
1695
+ const targetDxn = DXN7.parse(jsonData[ATTR_RELATION_TARGET] ?? raise(new TypeError("Missing relation target")));
1696
+ const source = await refResolver?.resolve(sourceDxn);
1697
+ const target = await refResolver?.resolve(targetDxn);
1698
+ defineHiddenProperty(obj, EntityKindId, EntityKind.Relation);
1699
+ defineHiddenProperty(obj, RelationSourceDXNId, sourceDxn);
1700
+ defineHiddenProperty(obj, RelationTargetDXNId, targetDxn);
1701
+ defineHiddenProperty(obj, RelationSourceId, source);
1702
+ defineHiddenProperty(obj, RelationTargetId, target);
1703
+ } else {
1704
+ defineHiddenProperty(obj, EntityKindId, EntityKind.Object);
1705
+ }
1706
+ if (typeof jsonData[ATTR_META] === "object") {
1707
+ const meta = await ObjectMetaSchema.pipe(Schema14.decodeUnknownPromise)(jsonData[ATTR_META]);
1708
+ invariant6(Array.isArray(meta.keys), void 0, {
1709
+ F: __dxlog_file6,
1710
+ L: 114,
1711
+ S: void 0,
1712
+ A: [
1713
+ "Array.isArray(meta.keys)",
1714
+ ""
1715
+ ]
1716
+ });
1717
+ defineHiddenProperty(obj, MetaId, meta);
1718
+ }
1719
+ if (dxn) {
1720
+ defineHiddenProperty(obj, SelfDXNId, dxn);
1721
+ }
1722
+ assertObjectModelShape(obj);
1723
+ invariant6(obj[ATTR_TYPE] === void 0, "Invalid object model", {
1724
+ F: __dxlog_file6,
1725
+ L: 124,
1726
+ S: void 0,
1727
+ A: [
1728
+ "(obj as any)[ATTR_TYPE] === undefined",
1729
+ "'Invalid object model'"
1730
+ ]
1731
+ });
1732
+ invariant6(obj[ATTR_SELF_DXN] === void 0, "Invalid object model", {
1733
+ F: __dxlog_file6,
1734
+ L: 125,
1735
+ S: void 0,
1736
+ A: [
1737
+ "(obj as any)[ATTR_SELF_DXN] === undefined",
1738
+ "'Invalid object model'"
1739
+ ]
1740
+ });
1741
+ invariant6(obj[ATTR_DELETED] === void 0, "Invalid object model", {
1742
+ F: __dxlog_file6,
1743
+ L: 126,
1744
+ S: void 0,
1745
+ A: [
1746
+ "(obj as any)[ATTR_DELETED] === undefined",
1747
+ "'Invalid object model'"
1748
+ ]
1749
+ });
1750
+ invariant6(obj[ATTR_RELATION_SOURCE] === void 0, "Invalid object model", {
1751
+ F: __dxlog_file6,
1752
+ L: 127,
1753
+ S: void 0,
1754
+ A: [
1755
+ "(obj as any)[ATTR_RELATION_SOURCE] === undefined",
1756
+ "'Invalid object model'"
1757
+ ]
1758
+ });
1759
+ invariant6(obj[ATTR_RELATION_TARGET] === void 0, "Invalid object model", {
1760
+ F: __dxlog_file6,
1761
+ L: 128,
1762
+ S: void 0,
1763
+ A: [
1764
+ "(obj as any)[ATTR_RELATION_TARGET] === undefined",
1765
+ "'Invalid object model'"
1766
+ ]
1767
+ });
1768
+ invariant6(obj[ATTR_META] === void 0, "Invalid object model", {
1769
+ F: __dxlog_file6,
1770
+ L: 129,
1771
+ S: void 0,
1772
+ A: [
1773
+ "(obj as any)[ATTR_META] === undefined",
1774
+ "'Invalid object model'"
1775
+ ]
1776
+ });
1777
+ return obj;
1778
+ };
1779
+ var decodeGeneric = (jsonData, options) => {
1780
+ const { [ATTR_TYPE]: _type, [ATTR_META]: _meta, [ATTR_DELETED]: _deleted, [ATTR_RELATION_SOURCE]: _relationSource, [ATTR_RELATION_TARGET]: _relationTarget, [ATTR_SELF_DXN]: _selfDxn, ...props } = jsonData;
1781
+ return deepMapValues(props, (value, recurse) => {
1782
+ if (isEncodedReference(value)) {
1783
+ return refFromEncodedReference(value, options.refResolver);
1784
+ }
1785
+ return recurse(value);
1786
+ });
1787
+ };
1788
+ var setRefResolverOnData = (obj, refResolver) => {
1789
+ const go2 = (value) => {
1790
+ if (Ref.isRef(value)) {
1791
+ setRefResolver(value, refResolver);
1792
+ } else {
1793
+ visitValues(value, go2);
1794
+ }
1795
+ };
1796
+ go2(obj);
1797
+ };
1798
+ var attachTypedJsonSerializer = (obj) => {
1799
+ const descriptor = Object.getOwnPropertyDescriptor(obj, "toJSON");
1800
+ if (descriptor) {
1801
+ return;
1802
+ }
1803
+ Object.defineProperty(obj, "toJSON", {
1804
+ value: typedJsonSerializer,
1805
+ writable: false,
1806
+ enumerable: false,
1807
+ // Setting `configurable` to false breaks proxy invariants, should be fixable.
1808
+ configurable: true
1809
+ });
1810
+ };
1811
+ var typedJsonSerializer = function() {
1812
+ const { id, ...rest } = this;
1813
+ const result = {
1814
+ id
1815
+ };
1816
+ if (this[TypeId]) {
1817
+ result[ATTR_TYPE] = this[TypeId].toString();
1818
+ }
1819
+ if (this[SelfDXNId]) {
1820
+ result[ATTR_SELF_DXN] = this[SelfDXNId].toString();
1821
+ }
1822
+ if (this[RelationSourceDXNId]) {
1823
+ const sourceDXN = this[RelationSourceDXNId];
1824
+ invariant6(sourceDXN instanceof DXN7, void 0, {
1825
+ F: __dxlog_file6,
1826
+ L: 196,
1827
+ S: this,
1828
+ A: [
1829
+ "sourceDXN instanceof DXN",
1830
+ ""
1831
+ ]
1832
+ });
1833
+ result[ATTR_RELATION_SOURCE] = sourceDXN.toString();
1834
+ }
1835
+ if (this[RelationTargetDXNId]) {
1836
+ const targetDXN = this[RelationTargetDXNId];
1837
+ invariant6(targetDXN instanceof DXN7, void 0, {
1838
+ F: __dxlog_file6,
1839
+ L: 201,
1840
+ S: this,
1841
+ A: [
1842
+ "targetDXN instanceof DXN",
1843
+ ""
1844
+ ]
1845
+ });
1846
+ result[ATTR_RELATION_TARGET] = targetDXN.toString();
1847
+ }
1848
+ if (this[MetaId]) {
1849
+ result[ATTR_META] = serializeMeta(this[MetaId]);
1850
+ }
1851
+ Object.assign(result, serializeData(rest));
1852
+ return result;
1853
+ };
1854
+ var serializeData = (data) => {
1855
+ return deepMapValues(data, (value, recurse) => {
1856
+ if (Ref.isRef(value)) {
1857
+ return value.noInline().encode();
1858
+ }
1859
+ return recurse(value);
1860
+ });
1861
+ };
1862
+ var serializeMeta = (meta) => {
1863
+ return deepMapValues(meta, (value, recurse) => recurse(value));
1864
+ };
1865
+
1866
+ // src/internal/object/create.ts
1867
+ var create = (schema, data) => {
1868
+ const annotation = getTypeAnnotation(schema);
1869
+ if (!annotation) {
1870
+ throw new Error("Schema is not an object schema");
1871
+ }
1872
+ assertArgument5(!("@type" in data), "data", "@type is not allowed");
1873
+ assertArgument5(!(RelationSourceDXNId in data), "data", "Relation source DXN is not allowed in the constructor");
1874
+ assertArgument5(!(RelationTargetDXNId in data), "data", "Relation target DXN is not allowed in the constructor");
1875
+ assertArgument5(RelationSourceId in data === RelationTargetId in data, "data", "Relation source and target must be provided together");
1876
+ const obj = {
1877
+ ...data,
1878
+ id: data.id ?? ObjectId5.random()
1879
+ };
1880
+ const kind = RelationSourceId in data ? EntityKind.Relation : EntityKind.Object;
1881
+ defineHiddenProperty2(obj, EntityKindId, kind);
1882
+ setTypename(obj, getSchemaDXN(schema) ?? failedInvariant("Missing schema DXN"));
1883
+ setSchema(obj, schema);
1884
+ attachTypedJsonSerializer(obj);
1885
+ attachedTypedObjectInspector(obj);
1886
+ defineHiddenProperty2(obj, MetaId, {
1887
+ keys: []
1888
+ });
1889
+ if (kind === EntityKind.Relation) {
1890
+ const sourceDXN = getObjectDXN(data[RelationSourceId]) ?? raise2(new Error("Unresolved relation source"));
1891
+ const targetDXN = getObjectDXN(data[RelationTargetId]) ?? raise2(new Error("Unresolved relation target"));
1892
+ defineHiddenProperty2(obj, RelationSourceDXNId, sourceDXN);
1893
+ defineHiddenProperty2(obj, RelationTargetDXNId, targetDXN);
1894
+ }
1895
+ assertObjectModelShape(obj);
1896
+ return obj;
1897
+ };
1898
+
1899
+ // src/internal/object/entity.ts
1900
+ import * as Schema15 from "effect/Schema";
1901
+ import * as SchemaAST7 from "effect/SchemaAST";
1902
+ import { raise as raise3 } from "@dxos/debug";
1903
+ import { invariant as invariant7 } from "@dxos/invariant";
1904
+ import { DXN as DXN8 } from "@dxos/keys";
1905
+ function _define_property3(obj, key, value) {
1906
+ if (key in obj) {
1907
+ Object.defineProperty(obj, key, {
1908
+ value,
1909
+ enumerable: true,
1910
+ configurable: true,
1911
+ writable: true
1912
+ });
1913
+ } else {
1914
+ obj[key] = value;
1915
+ }
1916
+ return obj;
1917
+ }
1918
+ var __dxlog_file7 = "/__w/dxos/dxos/packages/core/echo/echo/src/internal/object/entity.ts";
1919
+ var EchoObject = ({ typename, version }) => {
1920
+ return (self) => {
1921
+ invariant7(typeof TypeAnnotationId === "symbol", "Sanity.", {
1922
+ F: __dxlog_file7,
1923
+ L: 59,
1924
+ S: void 0,
1925
+ A: [
1926
+ "typeof TypeAnnotationId === 'symbol'",
1927
+ "'Sanity.'"
1928
+ ]
1929
+ });
1930
+ invariant7(SchemaAST7.isTypeLiteral(self.ast), "Schema must be a TypeLiteral.", {
1931
+ F: __dxlog_file7,
1932
+ L: 60,
1933
+ S: void 0,
1934
+ A: [
1935
+ "SchemaAST.isTypeLiteral(self.ast)",
1936
+ "'Schema must be a TypeLiteral.'"
1937
+ ]
1938
+ });
1939
+ const schemaWithId = Schema15.extend(Schema15.mutable(self), Schema15.Struct({
1940
+ id: Schema15.String
1941
+ }));
1942
+ const ast = SchemaAST7.annotations(schemaWithId.ast, {
1943
+ // TODO(dmaretskyi): `extend` kills the annotations.
1944
+ ...self.ast.annotations,
1945
+ [TypeAnnotationId]: {
1946
+ kind: EntityKind.Object,
1947
+ typename,
1948
+ version
1949
+ }
1950
+ });
1951
+ return makeEchoObjectSchema(
1952
+ /* self.fields, */
1953
+ ast,
1954
+ typename,
1955
+ version
1956
+ );
1957
+ };
1958
+ };
1959
+ var EchoRelation = (options) => {
1960
+ const sourceDXN = getDXNForRelationSchemaRef(options.source);
1961
+ const targetDXN = getDXNForRelationSchemaRef(options.target);
1962
+ if (getEntityKind(options.source) !== EntityKind.Object) {
1963
+ raise3(new Error("Source schema must be an echo object schema."));
1964
+ }
1965
+ if (getEntityKind(options.target) !== EntityKind.Object) {
1966
+ raise3(new Error("Target schema must be an echo object schema."));
1967
+ }
1968
+ return (self) => {
1969
+ invariant7(SchemaAST7.isTypeLiteral(self.ast), "Schema must be a TypeLiteral.", {
1970
+ F: __dxlog_file7,
1971
+ L: 100,
1972
+ S: void 0,
1973
+ A: [
1974
+ "SchemaAST.isTypeLiteral(self.ast)",
1975
+ "'Schema must be a TypeLiteral.'"
1976
+ ]
1977
+ });
1978
+ const schemaWithId = Schema15.extend(Schema15.mutable(self), Schema15.Struct({
1979
+ id: Schema15.String
1980
+ }));
1981
+ const ast = SchemaAST7.annotations(schemaWithId.ast, {
1982
+ // TODO(dmaretskyi): `extend` kills the annotations.
1983
+ ...self.ast.annotations,
1984
+ [TypeAnnotationId]: {
1985
+ kind: EntityKind.Relation,
1986
+ typename: options.typename,
1987
+ version: options.version,
1988
+ sourceSchema: sourceDXN,
1989
+ targetSchema: targetDXN
1990
+ }
1991
+ });
1992
+ return makeEchoObjectSchema(
1993
+ /* self.fields, */
1994
+ ast,
1995
+ options.typename,
1996
+ options.version
1997
+ );
1998
+ };
1999
+ };
2000
+ var getDXNForRelationSchemaRef = (schema) => {
2001
+ const identifier = getTypeIdentifierAnnotation(schema);
2002
+ if (identifier) {
2003
+ return identifier;
2004
+ }
2005
+ const typename = getSchemaTypename(schema);
2006
+ if (!typename) {
2007
+ throw new Error("Schema must have a typename");
2008
+ }
2009
+ return DXN8.fromTypename(typename).toString();
2010
+ };
2011
+ var makeEchoObjectSchema = (ast, typename, version) => {
2012
+ var _Schema_make, _EchoObjectSchemaClass;
2013
+ return _EchoObjectSchemaClass = class EchoObjectSchemaClass extends (_Schema_make = Schema15.make(ast)) {
2014
+ static annotations(annotations7) {
2015
+ const schema = Schema15.make(ast).annotations(annotations7);
2016
+ return makeEchoObjectSchema(
2017
+ /* fields, */
2018
+ schema.ast,
2019
+ typename,
2020
+ version
2021
+ );
2022
+ }
2023
+ // static make(
2024
+ // props: RequiredKeys<Schema.TypeLiteral.Constructor<Fields, []>> extends never
2025
+ // ? void | Simplify<Schema.TypeLiteral.Constructor<Fields, []>>
2026
+ // : Simplify<Schema.TypeLiteral.Constructor<Fields, []>>,
2027
+ // options?: MakeOptions,
2028
+ // ): Simplify<Schema.TypeLiteral.Type<Fields, []>> {
2029
+ // const propsWithDefaults: any = _lazilyMergeDefaults(fields, { ...(props as any) });
2030
+ // return _getDisableValidationMakeOption(options)
2031
+ // ? propsWithDefaults
2032
+ // : ParseResult.validateSync(this)(propsWithDefaults);
2033
+ // }
2034
+ static instanceOf(value) {
2035
+ return Schema15.is(this)(value);
2036
+ }
2037
+ }, _define_property3(_EchoObjectSchemaClass, "typename", typename), _define_property3(_EchoObjectSchemaClass, "version", version), _EchoObjectSchemaClass;
2038
+ };
2039
+
2040
+ // src/internal/object/expando.ts
2041
+ import * as Schema16 from "effect/Schema";
2042
+ var EXPANDO_TYPENAME = "dxos.org/type/Expando";
2043
+ var ExpandoSchema = Schema16.Struct({}, {
2044
+ key: Schema16.String,
2045
+ value: Schema16.Any
2046
+ }).pipe(EchoObject({
2047
+ typename: EXPANDO_TYPENAME,
2048
+ version: "0.1.0"
2049
+ }));
2050
+ var Expando = ExpandoSchema;
2051
+
2052
+ // src/internal/object/ids.ts
2053
+ import { DXN as DXN9, ObjectId as ObjectId6, QueueSubspaceTags, SpaceId } from "@dxos/keys";
2054
+ var createQueueDXN = (spaceId = SpaceId.random(), queueId = ObjectId6.random()) => new DXN9(DXN9.kind.QUEUE, [
2055
+ QueueSubspaceTags.DATA,
2056
+ spaceId,
2057
+ queueId
2058
+ ]);
2059
+
2060
+ // src/internal/object/typed-object.ts
2061
+ import * as Schema17 from "effect/Schema";
2062
+ import { invariant as invariant8 } from "@dxos/invariant";
2063
+ var __dxlog_file8 = "/__w/dxos/dxos/packages/core/echo/echo/src/internal/object/typed-object.ts";
2064
+ var TypedObject = ({ typename: typenameParam, version: versionParam, disableValidation }) => {
2065
+ const typename = Typename.make(typenameParam, {
2066
+ disableValidation
2067
+ });
2068
+ const version = SchemaVersion.make(versionParam, {
2069
+ disableValidation
2070
+ });
2071
+ return (fields, options) => {
2072
+ const schema = options?.record ? Schema17.Struct(fields, {
2073
+ key: Schema17.String,
2074
+ value: Schema17.Any
2075
+ }) : Schema17.Struct(fields);
2076
+ const typeSchema = Schema17.extend(Schema17.mutable(options?.partial ? Schema17.partial(schema) : schema), Schema17.Struct({
2077
+ id: Schema17.String
2078
+ }));
2079
+ invariant8(typeof EntityKind.Object === "string", void 0, {
2080
+ F: __dxlog_file8,
2081
+ L: 69,
2082
+ S: void 0,
2083
+ A: [
2084
+ "typeof EntityKind.Object === 'string'",
2085
+ ""
2086
+ ]
2087
+ });
2088
+ const annotatedSchema = typeSchema.annotations({
2089
+ [TypeAnnotationId]: {
2090
+ kind: EntityKind.Object,
2091
+ typename,
2092
+ version
2093
+ }
2094
+ });
2095
+ return class TypedObject extends makeTypedEntityClass(typename, version, annotatedSchema) {
2096
+ };
2097
+ };
2098
+ };
2099
+
2100
+ // src/internal/object/typed-relation.ts
2101
+ import * as Schema18 from "effect/Schema";
2102
+ import { invariant as invariant9 } from "@dxos/invariant";
2103
+ var __dxlog_file9 = "/__w/dxos/dxos/packages/core/echo/echo/src/internal/object/typed-relation.ts";
2104
+ var TypedRelation = ({ typename: typenameParam, version: versionParam, disableValidation }) => {
2105
+ const typename = Typename.make(typenameParam, {
2106
+ disableValidation
2107
+ });
2108
+ const version = SchemaVersion.make(versionParam, {
2109
+ disableValidation
2110
+ });
2111
+ return (fields, options) => {
2112
+ const schema = options?.record ? Schema18.Struct(fields, {
2113
+ key: Schema18.String,
2114
+ value: Schema18.Any
2115
+ }) : Schema18.Struct(fields);
2116
+ const typeSchema = Schema18.extend(Schema18.mutable(options?.partial ? Schema18.partial(schema) : schema), Schema18.Struct({
2117
+ id: Schema18.String
2118
+ }));
2119
+ invariant9(typeof EntityKind.Relation === "string", void 0, {
2120
+ F: __dxlog_file9,
2121
+ L: 73,
2122
+ S: void 0,
2123
+ A: [
2124
+ "typeof EntityKind.Relation === 'string'",
2125
+ ""
2126
+ ]
2127
+ });
2128
+ const annotatedSchema = typeSchema.annotations({
2129
+ [TypeAnnotationId]: {
2130
+ kind: EntityKind.Relation,
2131
+ typename,
2132
+ version
2133
+ }
2134
+ });
2135
+ return class TypedRelation extends makeTypedEntityClass(typename, version, annotatedSchema) {
2136
+ };
2137
+ };
2138
+ };
2139
+
2140
+ // src/internal/object/deleted.ts
2141
+ var isDeleted = (obj) => {
2142
+ if (obj[DeletedId] === void 0) {
2143
+ return false;
2144
+ }
2145
+ return obj[DeletedId] ?? false;
2146
+ };
2147
+
2148
+ // src/internal/object/schema-validator.ts
2149
+ import * as Schema19 from "effect/Schema";
2150
+ import * as SchemaAST8 from "effect/SchemaAST";
2151
+ import { invariant as invariant10 } from "@dxos/invariant";
2152
+ var __dxlog_file10 = "/__w/dxos/dxos/packages/core/echo/echo/src/internal/object/schema-validator.ts";
2153
+ var SchemaValidator = class {
2154
+ /**
2155
+ * Recursively check that schema specifies constructions we can handle.
2156
+ * Validates there are no ambiguous discriminated union types.
2157
+ */
2158
+ static validateSchema(schema) {
2159
+ const visitAll = (nodes) => nodes.forEach((node) => this.validateSchema(Schema19.make(node)));
2160
+ if (SchemaAST8.isUnion(schema.ast)) {
2161
+ const typeAstList = schema.ast.types.filter((type) => SchemaAST8.isTypeLiteral(type));
2162
+ if (typeAstList.length > 1) {
2163
+ getTypeDiscriminators(typeAstList);
2164
+ }
2165
+ visitAll(typeAstList);
2166
+ } else if (SchemaAST8.isTupleType(schema.ast)) {
2167
+ const positionalTypes = schema.ast.elements.map((t) => t.type);
2168
+ const allTypes = positionalTypes.concat(schema.ast.rest.map((t) => t.type));
2169
+ visitAll(allTypes);
2170
+ } else if (SchemaAST8.isTypeLiteral(schema.ast)) {
2171
+ visitAll(SchemaAST8.getPropertySignatures(schema.ast).map((p) => p.type));
2172
+ }
2173
+ }
2174
+ static hasTypeAnnotation(rootObjectSchema, property, annotation) {
2175
+ try {
2176
+ let type = this.getPropertySchema(rootObjectSchema, [
2177
+ property
2178
+ ]);
2179
+ if (SchemaAST8.isTupleType(type.ast)) {
2180
+ type = this.getPropertySchema(rootObjectSchema, [
2181
+ property,
2182
+ "0"
2183
+ ]);
2184
+ }
2185
+ return type.ast.annotations[annotation] != null;
2186
+ } catch (err) {
2187
+ return false;
2188
+ }
2189
+ }
2190
+ static getPropertySchema(rootObjectSchema, propertyPath, getProperty = () => null) {
2191
+ let schema = rootObjectSchema;
2192
+ for (let i = 0; i < propertyPath.length; i++) {
2193
+ const propertyName = propertyPath[i];
2194
+ const tupleAst = unwrapArray(schema.ast);
2195
+ if (tupleAst != null) {
2196
+ schema = getArrayElementSchema(tupleAst, propertyName);
2197
+ } else {
2198
+ const propertyType = getPropertyType(schema.ast, propertyName.toString(), (propertyName2) => getProperty([
2199
+ ...propertyPath.slice(0, i),
2200
+ propertyName2
2201
+ ]));
2202
+ if (propertyType == null) {
2203
+ throw new TypeError(`unknown property: ${String(propertyName)} on object. Path: ${propertyPath}`);
2204
+ }
2205
+ schema = Schema19.make(propertyType).annotations(propertyType.annotations);
2206
+ }
2207
+ }
2208
+ return schema;
2209
+ }
2210
+ static getTargetPropertySchema(target, prop) {
2211
+ const schema = target[SchemaId];
2212
+ invariant10(schema, "target has no schema", {
2213
+ F: __dxlog_file10,
2214
+ L: 82,
2215
+ S: this,
2216
+ A: [
2217
+ "schema",
2218
+ "'target has no schema'"
2219
+ ]
2220
+ });
2221
+ const arrayAst = unwrapArray(schema.ast);
2222
+ if (arrayAst != null) {
2223
+ return getArrayElementSchema(arrayAst, prop);
2224
+ }
2225
+ const propertyType = getPropertyType(schema.ast, prop.toString(), (prop2) => target[prop2]);
2226
+ if (propertyType == null) {
2227
+ return Schema19.Any;
2228
+ }
2229
+ invariant10(propertyType, `invalid property: ${prop.toString()}`, {
2230
+ F: __dxlog_file10,
2231
+ L: 93,
2232
+ S: this,
2233
+ A: [
2234
+ "propertyType",
2235
+ "`invalid property: ${prop.toString()}`"
2236
+ ]
2237
+ });
2238
+ return Schema19.make(propertyType);
2239
+ }
2240
+ };
2241
+ var getArrayElementSchema = (tupleAst, property) => {
2242
+ const elementIndex = typeof property === "string" ? parseInt(property, 10) : Number.NaN;
2243
+ if (Number.isNaN(elementIndex)) {
2244
+ invariant10(property === "length", `invalid array property: ${String(property)}`, {
2245
+ F: __dxlog_file10,
2246
+ L: 109,
2247
+ S: void 0,
2248
+ A: [
2249
+ "property === 'length'",
2250
+ "`invalid array property: ${String(property)}`"
2251
+ ]
2252
+ });
2253
+ return Schema19.Number;
2254
+ }
2255
+ if (elementIndex < tupleAst.elements.length) {
2256
+ const elementType = tupleAst.elements[elementIndex].type;
2257
+ return Schema19.make(elementType).annotations(elementType.annotations);
2258
+ }
2259
+ const restType = tupleAst.rest;
2260
+ return Schema19.make(restType[0].type).annotations(restType[0].annotations);
2261
+ };
2262
+ var flattenUnion = (typeAst) => SchemaAST8.isUnion(typeAst) ? typeAst.types.flatMap(flattenUnion) : [
2263
+ typeAst
2264
+ ];
2265
+ var getProperties = (typeAst, getTargetPropertyFn) => {
2266
+ const astCandidates = flattenUnion(typeAst);
2267
+ const typeAstList = astCandidates.filter((type) => SchemaAST8.isTypeLiteral(type));
2268
+ if (typeAstList.length === 0) {
2269
+ return [];
2270
+ }
2271
+ if (typeAstList.length === 1) {
2272
+ return SchemaAST8.getPropertySignatures(typeAstList[0]);
2273
+ }
2274
+ const typeDiscriminators = getTypeDiscriminators(typeAstList);
2275
+ const targetPropertyValue = getTargetPropertyFn(String(typeDiscriminators[0].name));
2276
+ const typeIndex = typeDiscriminators.findIndex((p) => targetPropertyValue === p.type.literal);
2277
+ invariant10(typeIndex !== -1, "discriminator field not set on target", {
2278
+ F: __dxlog_file10,
2279
+ L: 140,
2280
+ S: void 0,
2281
+ A: [
2282
+ "typeIndex !== -1",
2283
+ "'discriminator field not set on target'"
2284
+ ]
2285
+ });
2286
+ return SchemaAST8.getPropertySignatures(typeAstList[typeIndex]);
2287
+ };
2288
+ var getPropertyType = (ast, propertyName, getTargetPropertyFn) => {
2289
+ const anyOrObject = unwrapAst(ast, (candidate) => SchemaAST8.isAnyKeyword(candidate) || SchemaAST8.isObjectKeyword(candidate));
2290
+ if (anyOrObject != null) {
2291
+ return ast;
2292
+ }
2293
+ const typeOrDiscriminatedUnion = unwrapAst(ast, (t) => {
2294
+ return SchemaAST8.isTypeLiteral(t) || SchemaAST8.isUnion(t) && t.types.some((t2) => SchemaAST8.isTypeLiteral(t2));
2295
+ });
2296
+ if (typeOrDiscriminatedUnion == null) {
2297
+ return null;
2298
+ }
2299
+ const targetProperty = getProperties(typeOrDiscriminatedUnion, getTargetPropertyFn).find((p) => p.name === propertyName);
2300
+ if (targetProperty != null) {
2301
+ return unwrapAst(targetProperty.type);
2302
+ }
2303
+ const indexSignatureType = unwrapAst(ast, SchemaAST8.isTypeLiteral);
2304
+ if (indexSignatureType && SchemaAST8.isTypeLiteral(indexSignatureType) && indexSignatureType.indexSignatures.length > 0) {
2305
+ return unwrapAst(indexSignatureType.indexSignatures[0].type);
2306
+ }
2307
+ return null;
2308
+ };
2309
+ var getTypeDiscriminators = (typeAstList) => {
2310
+ const discriminatorPropCandidates = typeAstList.flatMap(SchemaAST8.getPropertySignatures).filter((p) => SchemaAST8.isLiteral(p.type));
2311
+ const propertyName = discriminatorPropCandidates[0].name;
2312
+ const isValidDiscriminator = discriminatorPropCandidates.every((p) => p.name === propertyName && !p.isOptional);
2313
+ const everyTypeHasDiscriminator = discriminatorPropCandidates.length === typeAstList.length;
2314
+ const isDiscriminatedUnion = isValidDiscriminator && everyTypeHasDiscriminator;
2315
+ invariant10(isDiscriminatedUnion, "type ambiguity: every type in a union must have a single unique-literal field", {
2316
+ F: __dxlog_file10,
2317
+ L: 191,
2318
+ S: void 0,
2319
+ A: [
2320
+ "isDiscriminatedUnion",
2321
+ "'type ambiguity: every type in a union must have a single unique-literal field'"
2322
+ ]
2323
+ });
2324
+ return discriminatorPropCandidates;
2325
+ };
2326
+ var unwrapAst = (rootAst, predicate) => {
2327
+ let ast = rootAst;
2328
+ while (ast != null) {
2329
+ if (predicate?.(ast)) {
2330
+ return ast;
2331
+ }
2332
+ if (SchemaAST8.isUnion(ast)) {
2333
+ const next = ast.types.find((t) => predicate != null && predicate(t) || SchemaAST8.isSuspend(t));
2334
+ if (next != null) {
2335
+ ast = next;
2336
+ continue;
2337
+ }
2338
+ }
2339
+ if (SchemaAST8.isSuspend(ast)) {
2340
+ ast = ast.f();
2341
+ } else {
2342
+ return predicate == null ? ast : null;
2343
+ }
2344
+ }
2345
+ return null;
2346
+ };
2347
+ var unwrapArray = (ast) => unwrapAst(ast, SchemaAST8.isTupleType);
2348
+ var checkIdNotPresentOnSchema = (schema) => {
2349
+ invariant10(SchemaAST8.isTypeLiteral(schema.ast), void 0, {
2350
+ F: __dxlog_file10,
2351
+ L: 234,
2352
+ S: void 0,
2353
+ A: [
2354
+ "SchemaAST.isTypeLiteral(schema.ast)",
2355
+ ""
2356
+ ]
2357
+ });
2358
+ const idProperty = SchemaAST8.getPropertySignatures(schema.ast).find((prop) => prop.name === "id");
2359
+ if (idProperty != null) {
2360
+ throw new Error('"id" property name is reserved');
2361
+ }
2362
+ };
2363
+
2364
+ // src/internal/object/version.ts
2365
+ var VersionTypeId = Symbol("@dxos/echo/Version");
2366
+
2367
+ // src/internal/json/annotations.ts
2368
+ import * as SchemaAST9 from "effect/SchemaAST";
2369
+ var CustomAnnotations = {
2370
+ format: FormatAnnotationId,
2371
+ currency: CurrencyAnnotationId
2372
+ };
2373
+ var DecodedAnnotations = {
2374
+ title: SchemaAST9.TitleAnnotationId,
2375
+ description: SchemaAST9.DescriptionAnnotationId
2376
+ };
2377
+ var EchoAnnotations = {
2378
+ // TODO(dmaretskyi): `FieldLookupAnnotationId` might go here, but lets remove it entirely and use LabelAnnotation instead.
2379
+ meta: PropertyMetaAnnotationId,
2380
+ generator: GeneratorAnnotationId,
2381
+ labelProp: LabelAnnotationId
2382
+ };
2383
+
2384
+ // src/internal/json/json-schema.ts
2385
+ var __dxlog_file11 = "/__w/dxos/dxos/packages/core/echo/echo/src/internal/json/json-schema.ts";
2386
+ var createJsonSchema = (schema = Schema20.Struct({})) => {
2387
+ const jsonSchema = _toJsonSchema(schema);
2388
+ jsonSchema.type = "object";
2389
+ delete jsonSchema.anyOf;
2390
+ return jsonSchema;
2391
+ };
2392
+ var PropType = /* @__PURE__ */ (function(PropType2) {
2393
+ PropType2[PropType2["NONE"] = 0] = "NONE";
2394
+ PropType2[PropType2["STRING"] = 1] = "STRING";
2395
+ PropType2[PropType2["NUMBER"] = 2] = "NUMBER";
2396
+ PropType2[PropType2["BOOLEAN"] = 3] = "BOOLEAN";
2397
+ PropType2[PropType2["DATE"] = 4] = "DATE";
2398
+ PropType2[PropType2["REF"] = 5] = "REF";
2399
+ PropType2[PropType2["RECORD"] = 6] = "RECORD";
2400
+ PropType2[PropType2["ENUM"] = 7] = "ENUM";
2401
+ return PropType2;
2402
+ })({});
2403
+ var toPropType = (type) => {
2404
+ switch (type) {
2405
+ case 1:
2406
+ return "string";
2407
+ case 2:
2408
+ return "number";
2409
+ case 3:
2410
+ return "boolean";
2411
+ case 4:
2412
+ return "date";
2413
+ case 5:
2414
+ return "ref";
2415
+ case 6:
2416
+ return "object";
2417
+ default:
2418
+ throw new Error(`Invalid type: ${type}`);
2419
+ }
2420
+ };
2421
+ var JSON_SCHEMA_URL = "http://json-schema.org/draft-07/schema#";
2422
+ var toJsonSchema = (schema, options = {}) => {
2423
+ let jsonSchema = _toJsonSchema(schema);
2424
+ if (options.strict) {
2425
+ jsonSchema = removeProperties(jsonSchema, (key, value) => {
2426
+ if (key === "$id" && value === "/schemas/any") {
2427
+ return true;
2428
+ }
2429
+ if (key === "$ref" && value === "#/$defs/dependency") {
2430
+ return true;
2431
+ }
2432
+ if (key === "$ref" && value === "#/$defs/jsonSchema") {
2433
+ return true;
2434
+ }
2435
+ return false;
2436
+ });
2437
+ }
2438
+ return jsonSchema;
2439
+ };
2440
+ var _toJsonSchema = (schema) => {
2441
+ invariant11(schema, void 0, {
2442
+ F: __dxlog_file11,
2443
+ L: 117,
2444
+ S: void 0,
2445
+ A: [
2446
+ "schema",
2447
+ ""
2448
+ ]
2449
+ });
2450
+ const withRefinements = withEchoRefinements(schema.ast, "#");
2451
+ let jsonSchema = JSONSchema.fromAST(withRefinements, {
2452
+ definitions: {}
2453
+ });
2454
+ jsonSchema.$schema = JSON_SCHEMA_URL;
2455
+ if (jsonSchema.properties && "id" in jsonSchema.properties) {
2456
+ jsonSchema.properties = orderKeys(jsonSchema.properties, [
2457
+ "id"
2458
+ ]);
2459
+ }
2460
+ const echoIdentifier = getTypeIdentifierAnnotation(schema);
2461
+ if (echoIdentifier) {
2462
+ jsonSchema.$id = echoIdentifier;
2463
+ }
2464
+ const objectAnnotation = getTypeAnnotation(schema);
2465
+ if (objectAnnotation) {
2466
+ if (!jsonSchema.$id) {
2467
+ jsonSchema.$id = DXN10.fromTypename(objectAnnotation.typename).toString();
2468
+ }
2469
+ jsonSchema.entityKind = objectAnnotation.kind;
2470
+ jsonSchema.version = objectAnnotation.version;
2471
+ jsonSchema.typename = objectAnnotation.typename;
2472
+ if (jsonSchema.entityKind === EntityKind.Relation) {
2473
+ jsonSchema.relationTarget = {
2474
+ $ref: objectAnnotation.sourceSchema
2475
+ };
2476
+ jsonSchema.relationSource = {
2477
+ $ref: objectAnnotation.targetSchema
2478
+ };
2479
+ }
2480
+ }
2481
+ jsonSchema = orderKeys(jsonSchema, [
2482
+ "$schema",
2483
+ "$id",
2484
+ "entityKind",
2485
+ "typename",
2486
+ "version",
2487
+ "relationTarget",
2488
+ "relationSource",
2489
+ "type",
2490
+ "enum",
2491
+ "properties",
2492
+ "required",
2493
+ "propertyOrder",
2494
+ "items",
2495
+ "additionalProperties",
2496
+ "anyOf",
2497
+ "oneOf"
2498
+ ]);
2499
+ return jsonSchema;
2500
+ };
2501
+ var withEchoRefinements = (ast, path, suspendCache = /* @__PURE__ */ new Map()) => {
2502
+ if (path) {
2503
+ suspendCache.set(ast, path);
2504
+ }
2505
+ let recursiveResult;
2506
+ if (SchemaAST10.isSuspend(ast)) {
2507
+ const suspendedAst = ast.f();
2508
+ const cachedPath = suspendCache.get(suspendedAst);
2509
+ if (cachedPath) {
2510
+ recursiveResult = new SchemaAST10.Suspend(() => withEchoRefinements(suspendedAst, path, suspendCache), {
2511
+ [SchemaAST10.JSONSchemaAnnotationId]: {
2512
+ $ref: cachedPath
2513
+ }
2514
+ });
2515
+ } else {
2516
+ const jsonSchema = _toJsonSchema(Schema20.make(suspendedAst));
2517
+ recursiveResult = new SchemaAST10.Suspend(() => withEchoRefinements(suspendedAst, path, suspendCache), {
2518
+ [SchemaAST10.JSONSchemaAnnotationId]: jsonSchema
2519
+ });
2520
+ }
2521
+ } else if (SchemaAST10.isTypeLiteral(ast)) {
2522
+ recursiveResult = mapAst(ast, (ast2, key) => withEchoRefinements(ast2, path && typeof key === "string" ? `${path}/${key}` : void 0, suspendCache));
2523
+ recursiveResult = addJsonSchemaFields(recursiveResult, {
2524
+ propertyOrder: [
2525
+ ...ast.propertySignatures.map((p) => p.name)
2526
+ ]
2527
+ });
2528
+ } else if (SchemaAST10.isUndefinedKeyword(ast)) {
2529
+ return ast;
2530
+ } else {
2531
+ recursiveResult = mapAst(ast, (ast2, key) => withEchoRefinements(ast2, path && (typeof key === "string" || typeof key === "number") ? `${path}/${key}` : void 0, suspendCache));
2532
+ }
2533
+ const annotationFields = annotations_toJsonSchemaFields(ast.annotations);
2534
+ if (Object.keys(annotationFields).length === 0) {
2535
+ return recursiveResult;
2536
+ } else {
2537
+ return addJsonSchemaFields(recursiveResult, annotationFields);
2538
+ }
2539
+ };
2540
+ var toEffectSchema = (root, _defs) => {
2541
+ const defs = root.$defs ? {
2542
+ ..._defs,
2543
+ ...root.$defs
2544
+ } : _defs ?? {};
2545
+ if ("type" in root && root.type === "object") {
2546
+ return objectToEffectSchema(root, defs);
2547
+ }
2548
+ let result = Schema20.Unknown;
2549
+ if ("$ref" in root) {
2550
+ switch (root.$ref) {
2551
+ case "/schemas/echo/ref": {
2552
+ result = refToEffectSchema(root);
2553
+ break;
2554
+ }
2555
+ }
2556
+ } else if ("$id" in root) {
2557
+ switch (root.$id) {
2558
+ case "/schemas/any": {
2559
+ result = anyToEffectSchema(root);
2560
+ break;
2561
+ }
2562
+ case "/schemas/unknown": {
2563
+ result = Schema20.Unknown;
2564
+ break;
2565
+ }
2566
+ case "/schemas/{}":
2567
+ case "/schemas/object": {
2568
+ result = Schema20.Object;
2569
+ break;
2570
+ }
2571
+ // Custom ECHO object reference.
2572
+ case "/schemas/echo/ref": {
2573
+ result = refToEffectSchema(root);
2574
+ break;
2575
+ }
2576
+ }
2577
+ } else if ("enum" in root) {
2578
+ result = Schema20.Union(...root.enum.map((e) => Schema20.Literal(e)));
2579
+ } else if ("oneOf" in root) {
2580
+ result = Schema20.Union(...root.oneOf.map((v) => toEffectSchema(v, defs)));
2581
+ } else if ("anyOf" in root) {
2582
+ result = Schema20.Union(...root.anyOf.map((v) => toEffectSchema(v, defs)));
2583
+ } else if ("allOf" in root) {
2584
+ if (root.allOf.length === 1) {
2585
+ result = toEffectSchema(root.allOf[0], defs);
2586
+ } else {
2587
+ log.warn("allOf with multiple schemas is not supported", void 0, {
2588
+ F: __dxlog_file11,
2589
+ L: 288,
2590
+ S: void 0,
2591
+ C: (f, a) => f(...a)
2592
+ });
2593
+ result = Schema20.Unknown;
2594
+ }
2595
+ } else if ("type" in root) {
2596
+ switch (root.type) {
2597
+ case "string": {
2598
+ result = Schema20.String;
2599
+ if (root.pattern) {
2600
+ result = result.pipe(Schema20.pattern(new RegExp(root.pattern)));
2601
+ }
2602
+ break;
2603
+ }
2604
+ case "number": {
2605
+ result = Schema20.Number;
2606
+ break;
2607
+ }
2608
+ case "integer": {
2609
+ result = Schema20.Number.pipe(Schema20.int());
2610
+ break;
2611
+ }
2612
+ case "boolean": {
2613
+ result = Schema20.Boolean;
2614
+ break;
2615
+ }
2616
+ case "array": {
2617
+ if (Array4.isArray(root.items)) {
2618
+ const [required, optional6] = Function3.pipe(root.items, Array4.map((v) => toEffectSchema(v, defs)), Array4.splitAt(root.minItems ?? root.items.length));
2619
+ result = Schema20.Tuple(...required, ...optional6.map(Schema20.optionalElement));
2620
+ } else {
2621
+ invariant11(root.items, void 0, {
2622
+ F: __dxlog_file11,
2623
+ L: 321,
2624
+ S: void 0,
2625
+ A: [
2626
+ "root.items",
2627
+ ""
2628
+ ]
2629
+ });
2630
+ const items = root.items;
2631
+ result = Array4.isArray(items) ? Schema20.Tuple(...items.map((v) => toEffectSchema(v, defs))) : Schema20.Array(toEffectSchema(items, defs));
2632
+ }
2633
+ break;
2634
+ }
2635
+ case "null": {
2636
+ result = Schema20.Null;
2637
+ break;
2638
+ }
2639
+ }
2640
+ } else if ("$ref" in root) {
2641
+ const refSegments = root.$ref.split("/");
2642
+ const jsonSchema = defs[refSegments[refSegments.length - 1]];
2643
+ invariant11(jsonSchema, `missing definition for ${root.$ref}`, {
2644
+ F: __dxlog_file11,
2645
+ L: 337,
2646
+ S: void 0,
2647
+ A: [
2648
+ "jsonSchema",
2649
+ "`missing definition for ${root.$ref}`"
2650
+ ]
2651
+ });
2652
+ result = toEffectSchema(jsonSchema, defs).pipe(Schema20.annotations({
2653
+ identifier: refSegments[refSegments.length - 1]
2654
+ }));
2655
+ }
2656
+ const annotations7 = jsonSchemaFieldsToAnnotations(root);
2657
+ result = result.annotations(annotations7);
2658
+ return result;
2659
+ };
2660
+ var objectToEffectSchema = (root, defs) => {
2661
+ invariant11("type" in root && root.type === "object", `not an object: ${root}`, {
2662
+ F: __dxlog_file11,
2663
+ L: 352,
2664
+ S: void 0,
2665
+ A: [
2666
+ "'type' in root && root.type === 'object'",
2667
+ "`not an object: ${root}`"
2668
+ ]
2669
+ });
2670
+ const echoRefinement = root[ECHO_ANNOTATIONS_NS_DEPRECATED_KEY];
2671
+ const isEchoObject = echoRefinement != null || "$id" in root && typeof root.$id === "string" && root.$id.startsWith("dxn:");
2672
+ let fields = {};
2673
+ const propertyList = Object.entries(root.properties ?? {});
2674
+ let immutableIdField;
2675
+ for (const [key, value] of propertyList) {
2676
+ if (isEchoObject && key === "id") {
2677
+ immutableIdField = toEffectSchema(value, defs);
2678
+ } else {
2679
+ fields[key] = root.required?.includes(key) ? toEffectSchema(value, defs) : Schema20.optional(toEffectSchema(value, defs));
2680
+ }
2681
+ }
2682
+ if (root.propertyOrder) {
2683
+ fields = orderKeys(fields, root.propertyOrder);
2684
+ }
2685
+ let schema;
2686
+ if (root.patternProperties) {
2687
+ invariant11(propertyList.length === 0, "pattern properties mixed with regular properties are not supported", {
2688
+ F: __dxlog_file11,
2689
+ L: 378,
2690
+ S: void 0,
2691
+ A: [
2692
+ "propertyList.length === 0",
2693
+ "'pattern properties mixed with regular properties are not supported'"
2694
+ ]
2695
+ });
2696
+ invariant11(Object.keys(root.patternProperties).length === 1 && Object.keys(root.patternProperties)[0] === "", "only one pattern property is supported", {
2697
+ F: __dxlog_file11,
2698
+ L: 379,
2699
+ S: void 0,
2700
+ A: [
2701
+ "Object.keys(root.patternProperties).length === 1 && Object.keys(root.patternProperties)[0] === ''",
2702
+ "'only one pattern property is supported'"
2703
+ ]
2704
+ });
2705
+ schema = Schema20.Record({
2706
+ key: Schema20.String,
2707
+ value: toEffectSchema(root.patternProperties[""], defs)
2708
+ });
2709
+ } else if (typeof root.additionalProperties !== "object") {
2710
+ schema = Schema20.Struct(fields);
2711
+ } else {
2712
+ const indexValue = toEffectSchema(root.additionalProperties, defs);
2713
+ if (propertyList.length > 0) {
2714
+ schema = Schema20.Struct(fields, {
2715
+ key: Schema20.String,
2716
+ value: indexValue
2717
+ });
2718
+ } else {
2719
+ schema = Schema20.Record({
2720
+ key: Schema20.String,
2721
+ value: indexValue
2722
+ });
2723
+ }
2724
+ }
2725
+ if (immutableIdField) {
2726
+ schema = Schema20.extend(Schema20.mutable(schema), Schema20.Struct({
2727
+ id: immutableIdField
2728
+ }));
2729
+ }
2730
+ const annotations7 = jsonSchemaFieldsToAnnotations(root);
2731
+ return schema.annotations(annotations7);
2732
+ };
2733
+ var anyToEffectSchema = (root) => {
2734
+ const echoRefinement = root[ECHO_ANNOTATIONS_NS_DEPRECATED_KEY];
2735
+ if (echoRefinement?.reference != null) {
2736
+ const echoId = root.$id.startsWith("dxn:echo:") ? root.$id : void 0;
2737
+ return createEchoReferenceSchema(echoId, echoRefinement.reference.typename, echoRefinement.reference.version);
2738
+ }
2739
+ return Schema20.Any;
2740
+ };
2741
+ var refToEffectSchema = (root) => {
2742
+ if (!("reference" in root)) {
2743
+ return Ref(Expando);
2744
+ }
2745
+ const reference = root.reference;
2746
+ if (typeof reference !== "object") {
2747
+ throw new Error("Invalid reference field in ref schema");
2748
+ }
2749
+ const targetSchemaDXN = DXN10.parse(reference.schema.$ref);
2750
+ invariant11(targetSchemaDXN.kind === DXN10.kind.TYPE, void 0, {
2751
+ F: __dxlog_file11,
2752
+ L: 430,
2753
+ S: void 0,
2754
+ A: [
2755
+ "targetSchemaDXN.kind === DXN.kind.TYPE",
2756
+ ""
2757
+ ]
2758
+ });
2759
+ return createEchoReferenceSchema(targetSchemaDXN.toString(), targetSchemaDXN.kind === DXN10.kind.TYPE ? targetSchemaDXN.parts[0] : void 0, reference.schemaVersion);
2760
+ };
2761
+ var annotations_toJsonSchemaFields = (annotations7) => {
2762
+ const schemaFields = {};
2763
+ const echoAnnotations = {};
2764
+ for (const [key, annotationId] of Object.entries(EchoAnnotations)) {
2765
+ if (annotations7[annotationId] != null) {
2766
+ echoAnnotations[key] = annotations7[annotationId];
2767
+ }
2768
+ }
2769
+ if (Object.keys(echoAnnotations).length > 0) {
2770
+ schemaFields[ECHO_ANNOTATIONS_NS_KEY] = echoAnnotations;
2771
+ }
2772
+ const echoIdentifier = annotations7[TypeIdentifierAnnotationId];
2773
+ if (echoIdentifier) {
2774
+ var _schemaFields, _ECHO_ANNOTATIONS_NS_KEY;
2775
+ (_schemaFields = schemaFields)[_ECHO_ANNOTATIONS_NS_KEY = ECHO_ANNOTATIONS_NS_KEY] ?? (_schemaFields[_ECHO_ANNOTATIONS_NS_KEY] = {});
2776
+ schemaFields[ECHO_ANNOTATIONS_NS_KEY].schemaId = echoIdentifier;
2777
+ }
2778
+ for (const [key, annotationId] of Object.entries(CustomAnnotations)) {
2779
+ const value = annotations7[annotationId];
2780
+ if (value != null) {
2781
+ schemaFields[key] = value;
2782
+ }
2783
+ }
2784
+ return schemaFields;
2785
+ };
2786
+ var decodeTypeIdentifierAnnotation = (schema) => {
2787
+ if (schema.$id && schema.$id.startsWith("dxn:echo:")) {
2788
+ return schema.$id;
2789
+ } else if (schema.$id && schema.$id.startsWith("dxn:type:") && schema?.echo?.type?.schemaId) {
2790
+ const id = schema?.echo?.type?.schemaId;
2791
+ if (ObjectId7.isValid(id)) {
2792
+ return DXN10.fromLocalObjectId(id).toString();
2793
+ }
2794
+ }
2795
+ return void 0;
2796
+ };
2797
+ var decodeTypeAnnotation = (schema) => {
2798
+ if (schema.typename) {
2799
+ const annotation = {
2800
+ // TODO(dmaretskyi): Decoding default.
2801
+ kind: schema.entityKind ? Schema20.decodeSync(EntityKindSchema)(schema.entityKind) : EntityKind.Object,
2802
+ typename: schema.typename,
2803
+ version: schema.version ?? "0.1.0"
2804
+ };
2805
+ if (annotation.kind === EntityKind.Relation) {
2806
+ const source = schema.relationSource?.$ref ?? raise4(new Error("Relation source not set"));
2807
+ const target = schema.relationTarget?.$ref ?? raise4(new Error("Relation target not set"));
2808
+ annotation.sourceSchema = DXN10.parse(source).toString();
2809
+ annotation.targetSchema = DXN10.parse(target).toString();
2810
+ }
2811
+ return annotation;
2812
+ }
2813
+ if (!schema.typename && schema?.echo?.type) {
2814
+ return {
2815
+ kind: EntityKind.Object,
2816
+ typename: schema.echo.type.typename,
2817
+ version: schema.echo.type.version
2818
+ };
2819
+ }
2820
+ return void 0;
2821
+ };
2822
+ var jsonSchemaFieldsToAnnotations = (schema) => {
2823
+ const annotations7 = {};
2824
+ const echoAnnotations = getNormalizedEchoAnnotations(schema) ?? {};
2825
+ if (echoAnnotations) {
2826
+ for (const [key, annotationId] of Object.entries(EchoAnnotations)) {
2827
+ if (echoAnnotations[key]) {
2828
+ annotations7[annotationId] = echoAnnotations[key];
2829
+ }
2830
+ }
2831
+ }
2832
+ annotations7[TypeIdentifierAnnotationId] = decodeTypeIdentifierAnnotation(schema);
2833
+ annotations7[TypeAnnotationId] = decodeTypeAnnotation(schema);
2834
+ for (const [key, annotationId] of Object.entries({
2835
+ ...CustomAnnotations,
2836
+ ...DecodedAnnotations
2837
+ })) {
2838
+ if (key in schema) {
2839
+ annotations7[annotationId] = schema[key];
2840
+ }
2841
+ }
2842
+ return clearUndefined(annotations7);
2843
+ };
2844
+ var makeAnnotatedRefinement = (ast, annotations7) => {
2845
+ return new SchemaAST10.Refinement(ast, () => Option5.none(), annotations7);
2846
+ };
2847
+ var addJsonSchemaFields = (ast, schema) => makeAnnotatedRefinement(ast, {
2848
+ [SchemaAST10.JSONSchemaAnnotationId]: schema
2849
+ });
2850
+
2851
+ // src/internal/types/types.ts
2852
+ import * as Schema21 from "effect/Schema";
2853
+ import * as SchemaAST11 from "effect/SchemaAST";
2854
+ import { Reference as Reference2 } from "@dxos/echo-protocol";
2855
+ import { splitJsonPath } from "@dxos/effect";
2856
+ import { DXN as DXN11 } from "@dxos/keys";
2857
+ import { getDeep, setDeep } from "@dxos/util";
2858
+ var RawObject = (schema) => {
2859
+ return Schema21.make(SchemaAST11.omit(schema.ast, [
2860
+ "id"
2861
+ ]));
2862
+ };
2863
+ var splitMeta = (object) => {
2864
+ const meta = object[ATTR_META];
2865
+ delete object[ATTR_META];
2866
+ return {
2867
+ meta,
2868
+ object
2869
+ };
2870
+ };
2871
+ var getValue = (obj, path) => {
2872
+ return getDeep(obj, splitJsonPath(path).map((p) => p.replace(/[[\]]/g, "")));
2873
+ };
2874
+ var setValue = (obj, path, value) => {
2875
+ return setDeep(obj, splitJsonPath(path).map((p) => p.replace(/[[\]]/g, "")), value);
2876
+ };
2877
+ var getTypeReference = (schema) => {
2878
+ if (!schema) {
2879
+ return void 0;
2880
+ }
2881
+ const schemaDXN = getSchemaDXN(schema);
2882
+ if (!schemaDXN) {
2883
+ return void 0;
2884
+ }
2885
+ return Reference2.fromDXN(schemaDXN);
2886
+ };
2887
+ var requireTypeReference = (schema) => {
2888
+ const typeReference = getTypeReference(schema);
2889
+ if (typeReference == null) {
2890
+ throw new Error("Schema must be defined via TypedObject.");
2891
+ }
2892
+ return typeReference;
2893
+ };
2894
+ var isInstanceOf = (schema, object) => {
2895
+ if (object == null) {
2896
+ return false;
2897
+ }
2898
+ const schemaDXN = getSchemaDXN(schema);
2899
+ if (!schemaDXN) {
2900
+ throw new Error("Schema must have an object annotation.");
2901
+ }
2902
+ const type = getType(object);
2903
+ if (type && DXN11.equals(type, schemaDXN)) {
2904
+ return true;
2905
+ }
2906
+ const typename = getTypename(object);
2907
+ if (!typename) {
2908
+ return false;
2909
+ }
2910
+ const typeDXN = schemaDXN.asTypeDXN();
2911
+ if (!typeDXN) {
2912
+ return false;
2913
+ }
2914
+ return typeDXN.type === typename;
2915
+ };
2916
+
2917
+ // src/internal/index.ts
2918
+ import { defineHiddenProperty as defineHiddenProperty5 } from "@dxos/live-object";
2919
+
2920
+ // src/internal/projection/compose.ts
2921
+ import { invariant as invariant15 } from "@dxos/invariant";
2922
+
2923
+ // src/internal/schema/echo-schema.ts
2924
+ import * as Schema24 from "effect/Schema";
2925
+ import * as SchemaAST13 from "effect/SchemaAST";
2926
+ import { invariant as invariant13 } from "@dxos/invariant";
2927
+
2928
+ // src/internal/schema/manipulation.ts
2929
+ import * as Schema22 from "effect/Schema";
2930
+ import * as SchemaAST12 from "effect/SchemaAST";
2931
+ import { invariant as invariant12 } from "@dxos/invariant";
2932
+ var __dxlog_file12 = "/__w/dxos/dxos/packages/core/echo/echo/src/internal/schema/manipulation.ts";
2933
+ var addFieldsToSchema = (schema, fields) => {
2934
+ const schemaExtension = Schema22.partial(Schema22.Struct(fields));
2935
+ return Schema22.extend(schema, schemaExtension).annotations(schema.ast.annotations);
2936
+ };
2937
+ var updateFieldsInSchema = (schema, fields) => {
2938
+ const ast = schema.ast;
2939
+ invariant12(SchemaAST12.isTypeLiteral(ast), void 0, {
2940
+ F: __dxlog_file12,
2941
+ L: 28,
2942
+ S: void 0,
2943
+ A: [
2944
+ "SchemaAST.isTypeLiteral(ast)",
2945
+ ""
2946
+ ]
2947
+ });
2948
+ const updatedProperties = [
2949
+ ...ast.propertySignatures
2950
+ ];
2951
+ const propertiesToUpdate = Schema22.partial(Schema22.Struct(fields)).ast.propertySignatures;
2952
+ for (const property of propertiesToUpdate) {
2953
+ const index = updatedProperties.findIndex((p) => p.name === property.name);
2954
+ if (index !== -1) {
2955
+ updatedProperties[index] = property;
2956
+ } else {
2957
+ updatedProperties.push(property);
2958
+ }
2959
+ }
2960
+ return Schema22.make(new SchemaAST12.TypeLiteral(updatedProperties, ast.indexSignatures, ast.annotations));
2961
+ };
2962
+ var removeFieldsFromSchema = (schema, fieldNames) => {
2963
+ return Schema22.make(SchemaAST12.omit(schema.ast, fieldNames)).annotations(schema.ast.annotations);
2964
+ };
2965
+ var updateFieldNameInSchema = (schema, { before, after }) => {
2966
+ const ast = schema.ast;
2967
+ invariant12(SchemaAST12.isTypeLiteral(ast), void 0, {
2968
+ F: __dxlog_file12,
2969
+ L: 56,
2970
+ S: void 0,
2971
+ A: [
2972
+ "SchemaAST.isTypeLiteral(ast)",
2973
+ ""
2974
+ ]
2975
+ });
2976
+ return Schema22.make(new SchemaAST12.TypeLiteral(ast.propertySignatures.map((p) => p.name === before ? new SchemaAST12.PropertySignature(after, p.type, p.isOptional, p.isReadonly, p.annotations) : p), ast.indexSignatures, ast.annotations));
2977
+ };
2978
+ var setTypenameInSchema = (schema, typename) => {
2979
+ const existingAnnotation = schema.ast.annotations[TypeAnnotationId];
2980
+ invariant12(existingAnnotation, `Missing ${String(TypeAnnotationId)}`, {
2981
+ F: __dxlog_file12,
2982
+ L: 76,
2983
+ S: void 0,
2984
+ A: [
2985
+ "existingAnnotation",
2986
+ "`Missing ${String(TypeAnnotationId)}`"
2987
+ ]
2988
+ });
2989
+ return schema.annotations({
2990
+ ...schema.ast.annotations,
2991
+ [TypeAnnotationId]: {
2992
+ kind: existingAnnotation.kind,
2993
+ typename,
2994
+ version: existingAnnotation.version
2995
+ }
2996
+ });
2997
+ };
2998
+
2999
+ // src/internal/schema/snapshot.ts
3000
+ var getSnapshot = (object) => {
3001
+ if (typeof object !== "object") {
3002
+ return object;
3003
+ }
3004
+ if (Array.isArray(object)) {
3005
+ return object.map(getSnapshot);
3006
+ }
3007
+ const result = {};
3008
+ for (const key in object) {
3009
+ result[key] = getSnapshot(object[key]);
3010
+ }
3011
+ return result;
3012
+ };
3013
+
3014
+ // src/internal/schema/stored-schema.ts
3015
+ import * as Schema23 from "effect/Schema";
3016
+ var StoredSchema = Schema23.Struct({
3017
+ name: Schema23.optional(Schema23.String),
3018
+ typename: Typename,
3019
+ version: SchemaVersion,
3020
+ jsonSchema: JsonSchemaType
3021
+ }).pipe(EchoObject({
3022
+ typename: "dxos.org/type/Schema",
3023
+ version: "0.1.0"
3024
+ }));
3025
+
3026
+ // src/internal/schema/echo-schema.ts
3027
+ function _define_property4(obj, key, value) {
3028
+ if (key in obj) {
3029
+ Object.defineProperty(obj, key, {
3030
+ value,
3031
+ enumerable: true,
3032
+ configurable: true,
3033
+ writable: true
3034
+ });
3035
+ } else {
3036
+ obj[key] = value;
3037
+ }
3038
+ return obj;
3039
+ }
3040
+ var __dxlog_file13 = "/__w/dxos/dxos/packages/core/echo/echo/src/internal/schema/echo-schema.ts";
3041
+ var _Schema_TypeId = Schema24.TypeId;
3042
+ var ImmutableSchema = class {
3043
+ //
3044
+ // Effect Schema (push to abstract base class).
3045
+ //
3046
+ get [_Schema_TypeId]() {
3047
+ return schemaVariance2;
3048
+ }
3049
+ get Type() {
3050
+ return this._schema.Type;
3051
+ }
3052
+ get Encoded() {
3053
+ return this._schema.Encoded;
3054
+ }
3055
+ get Context() {
3056
+ return this._schema.Context;
3057
+ }
3058
+ get ast() {
3059
+ return this._schema.ast;
3060
+ }
3061
+ get annotations() {
3062
+ return this._schema.annotations;
3063
+ }
3064
+ get pipe() {
3065
+ return this._schema.pipe;
3066
+ }
3067
+ //
3068
+ // TypedObject
3069
+ //
3070
+ get typename() {
3071
+ return this._objectAnnotation.typename;
3072
+ }
3073
+ get version() {
3074
+ return this._objectAnnotation.version;
3075
+ }
3076
+ //
3077
+ // BaseSchema
3078
+ //
3079
+ get readonly() {
3080
+ return true;
3081
+ }
3082
+ get snapshot() {
3083
+ return this._schema;
3084
+ }
3085
+ // TODO(burdon): Change from getter since this is expensive.
3086
+ get jsonSchema() {
3087
+ return toJsonSchema(this._schema);
3088
+ }
3089
+ get mutable() {
3090
+ throw new Error("Schema is readonly.");
3091
+ }
3092
+ constructor(_schema) {
3093
+ _define_property4(this, "_schema", void 0);
3094
+ _define_property4(this, "_objectAnnotation", void 0);
3095
+ this._schema = _schema;
3096
+ this._objectAnnotation = getTypeAnnotation(this._schema);
3097
+ invariant13(this._objectAnnotation, void 0, {
3098
+ F: __dxlog_file13,
3099
+ L: 47,
3100
+ S: this,
3101
+ A: [
3102
+ "this._objectAnnotation",
3103
+ ""
3104
+ ]
3105
+ });
3106
+ }
3107
+ };
3108
+ var EchoSchemaConstructor = () => {
3109
+ let _Schema_TypeId2;
3110
+ var _class;
3111
+ return _Schema_TypeId2 = Schema24.TypeId, _class = class {
3112
+ static get _schema() {
3113
+ return Schema24.Union(StoredSchema, Schema24.instanceOf(EchoSchema)).annotations(StoredSchema.ast.annotations);
3114
+ }
3115
+ static get ast() {
3116
+ const schema = this._schema;
3117
+ return schema.ast;
3118
+ }
3119
+ static get annotations() {
3120
+ const schema = this._schema;
3121
+ return schema.annotations.bind(schema);
3122
+ }
3123
+ static get pipe() {
3124
+ const schema = this._schema;
3125
+ return schema.pipe.bind(schema);
3126
+ }
3127
+ }, _define_property4(_class, _Schema_TypeId2, schemaVariance2), _class;
3128
+ };
3129
+ var isMutable = (schema) => {
3130
+ return schema instanceof EchoSchema;
3131
+ };
3132
+ var schemaVariance2 = {
3133
+ _A: (_) => _,
3134
+ _I: (_) => _,
3135
+ _R: (_) => _
3136
+ };
3137
+ var _Schema_TypeId1 = Schema24.TypeId;
3138
+ var _SchemaMetaSymbol = SchemaMetaSymbol;
3139
+ var EchoSchema = class extends EchoSchemaConstructor() {
3140
+ //
3141
+ // Effect Schema (push to abstract base class).
3142
+ //
3143
+ get [_Schema_TypeId1]() {
3144
+ return schemaVariance2;
3145
+ }
3146
+ get Type() {
3147
+ return this._storedSchema;
3148
+ }
3149
+ get Encoded() {
3150
+ return this._storedSchema;
3151
+ }
3152
+ get Context() {
3153
+ const schema = this._getSchema();
3154
+ return schema.Context;
3155
+ }
3156
+ get ast() {
3157
+ const schema = this._getSchema();
3158
+ return schema.ast;
3159
+ }
3160
+ get annotations() {
3161
+ const schema = this._getSchema();
3162
+ return schema.annotations.bind(schema);
3163
+ }
3164
+ get pipe() {
3165
+ const schema = this._getSchema();
3166
+ return schema.pipe.bind(schema);
3167
+ }
3168
+ //
3169
+ // BaseSchema
3170
+ //
3171
+ get typename() {
3172
+ return this._storedSchema.typename;
3173
+ }
3174
+ get version() {
3175
+ return this._storedSchema.version;
3176
+ }
3177
+ get readonly() {
3178
+ return false;
3179
+ }
3180
+ /**
3181
+ * Returns an immutable schema snapshot of the current state of the schema.
3182
+ */
3183
+ get snapshot() {
3184
+ return this._getSchema();
3185
+ }
3186
+ /**
3187
+ * @reactive
3188
+ */
3189
+ get jsonSchema() {
3190
+ return this._storedSchema.jsonSchema;
3191
+ }
3192
+ /**
3193
+ * Returns a mutable schema.
3194
+ */
3195
+ get mutable() {
3196
+ invariant13(!this.readonly, "Schema is not mutable", {
3197
+ F: __dxlog_file13,
3198
+ L: 260,
3199
+ S: this,
3200
+ A: [
3201
+ "!this.readonly",
3202
+ "'Schema is not mutable'"
3203
+ ]
3204
+ });
3205
+ return this;
3206
+ }
3207
+ //
3208
+ // Mutable Schema
3209
+ //
3210
+ /**
3211
+ * Id of the ECHO object containing the schema.
3212
+ */
3213
+ get id() {
3214
+ return this._storedSchema.id;
3215
+ }
3216
+ /**
3217
+ * Short name of the schema.
3218
+ */
3219
+ get name() {
3220
+ return this._storedSchema.name;
3221
+ }
3222
+ get [_SchemaMetaSymbol]() {
3223
+ return {
3224
+ id: this.id,
3225
+ typename: this.typename,
3226
+ version: this._storedSchema.version
3227
+ };
3228
+ }
3229
+ /**
3230
+ * Reference to the underlying stored schema object.
3231
+ */
3232
+ get storedSchema() {
3233
+ return this._storedSchema;
3234
+ }
3235
+ getProperties() {
3236
+ const ast = this._getSchema().ast;
3237
+ invariant13(SchemaAST13.isTypeLiteral(ast), void 0, {
3238
+ F: __dxlog_file13,
3239
+ L: 295,
3240
+ S: this,
3241
+ A: [
3242
+ "SchemaAST.isTypeLiteral(ast)",
3243
+ ""
3244
+ ]
3245
+ });
3246
+ return [
3247
+ ...ast.propertySignatures
3248
+ ].filter((p) => p.name !== "id").map(unwrapOptionality);
3249
+ }
3250
+ //
3251
+ // Mutation methods.
3252
+ // TODO(burdon): Create separate interface for dynamic schema.
3253
+ // TODO(burdon): Deprecate direct manipulation? Use JSONSchema directly.
3254
+ //
3255
+ /**
3256
+ * @throws Error if the schema is readonly.
3257
+ */
3258
+ updateTypename(typename) {
3259
+ const updated = setTypenameInSchema(this._getSchema(), typename);
3260
+ this._storedSchema.typename = typename;
3261
+ this._storedSchema.jsonSchema = toJsonSchema(updated);
3262
+ }
3263
+ /**
3264
+ * @throws Error if the schema is readonly.
3265
+ */
3266
+ addFields(fields) {
3267
+ const extended = addFieldsToSchema(this._getSchema(), fields);
3268
+ this._storedSchema.jsonSchema = toJsonSchema(extended);
3269
+ }
3270
+ /**
3271
+ * @throws Error if the schema is readonly.
3272
+ */
3273
+ updateFields(fields) {
3274
+ const updated = updateFieldsInSchema(this._getSchema(), fields);
3275
+ this._storedSchema.jsonSchema = toJsonSchema(updated);
3276
+ }
3277
+ /**
3278
+ * @throws Error if the schema is readonly.
3279
+ */
3280
+ updateFieldPropertyName({ before, after }) {
3281
+ const renamed = updateFieldNameInSchema(this._getSchema(), {
3282
+ before,
3283
+ after
3284
+ });
3285
+ this._storedSchema.jsonSchema = toJsonSchema(renamed);
3286
+ }
3287
+ /**
3288
+ * @throws Error if the schema is readonly.
3289
+ */
3290
+ removeFields(fieldNames) {
3291
+ const removed = removeFieldsFromSchema(this._getSchema(), fieldNames);
3292
+ this._storedSchema.jsonSchema = toJsonSchema(removed);
3293
+ }
3294
+ //
3295
+ // Internals
3296
+ //
3297
+ /**
3298
+ * Called by EchoSchemaRegistry on update.
3299
+ */
3300
+ _invalidate() {
3301
+ this._isDirty = true;
3302
+ }
3303
+ /**
3304
+ * Rebuilds this schema if it is dirty.
3305
+ */
3306
+ _rebuild() {
3307
+ if (this._isDirty || this._schema == null) {
3308
+ this._schema = toEffectSchema(getSnapshot(this._storedSchema.jsonSchema));
3309
+ this._isDirty = false;
3310
+ }
3311
+ }
3312
+ _getSchema() {
3313
+ this._rebuild();
3314
+ return this._schema;
3315
+ }
3316
+ constructor(_storedSchema) {
3317
+ super(), _define_property4(this, "_storedSchema", void 0), _define_property4(this, "_schema", void 0), _define_property4(this, "_isDirty", void 0), this._storedSchema = _storedSchema, this._isDirty = true;
3318
+ }
3319
+ };
3320
+ var unwrapOptionality = (property) => {
3321
+ if (!SchemaAST13.isUnion(property.type)) {
3322
+ return property;
3323
+ }
3324
+ return {
3325
+ ...property,
3326
+ type: property.type.types.find((type) => !SchemaAST13.isUndefinedKeyword(type))
3327
+ };
3328
+ };
3329
+
3330
+ // src/internal/schema/runtime-schema-registry.ts
3331
+ import { raise as raise5 } from "@dxos/debug";
3332
+ import { invariant as invariant14 } from "@dxos/invariant";
3333
+ import { defaultMap } from "@dxos/util";
3334
+ function _define_property5(obj, key, value) {
3335
+ if (key in obj) {
3336
+ Object.defineProperty(obj, key, {
3337
+ value,
3338
+ enumerable: true,
3339
+ configurable: true,
3340
+ writable: true
3341
+ });
3342
+ } else {
3343
+ obj[key] = value;
3344
+ }
3345
+ return obj;
3346
+ }
3347
+ var __dxlog_file14 = "/__w/dxos/dxos/packages/core/echo/echo/src/internal/schema/runtime-schema-registry.ts";
3348
+ var RuntimeSchemaRegistry = class {
3349
+ get schemas() {
3350
+ return Array.from(this._registry.values()).flat();
3351
+ }
3352
+ hasSchema(schema) {
3353
+ const typename = getSchemaTypename(schema);
3354
+ const version = getSchemaVersion(schema);
3355
+ invariant14(typename, "Invalid schema", {
3356
+ F: __dxlog_file14,
3357
+ L: 34,
3358
+ S: this,
3359
+ A: [
3360
+ "typename",
3361
+ "'Invalid schema'"
3362
+ ]
3363
+ });
3364
+ const schemas = this._registry.get(typename);
3365
+ return schemas?.some((schema2) => getSchemaVersion(schema2) === version) ?? false;
3366
+ }
3367
+ getSchemaByDXN(dxn) {
3368
+ const components = dxn.asTypeDXN();
3369
+ if (!components) {
3370
+ return void 0;
3371
+ }
3372
+ const { type, version } = components;
3373
+ const allSchemas = this._registry.get(type) ?? [];
3374
+ if (version) {
3375
+ return allSchemas.find((s) => getSchemaVersion(s) === version);
3376
+ } else {
3377
+ return allSchemas.sort((a, b) => (getSchemaVersion(a) ?? "0.0.0").localeCompare(getSchemaVersion(b) ?? "0.0.0"))[0];
3378
+ }
3379
+ }
3380
+ /**
3381
+ * @deprecated Use getSchemaByDXN.
3382
+ */
3383
+ getSchema(typename) {
3384
+ return this._registry.get(typename)?.[0];
3385
+ }
3386
+ addSchema(types) {
3387
+ types.forEach((schema) => {
3388
+ const typename = getSchemaTypename(schema) ?? raise5(new TypeError("Schema has no typename"));
3389
+ const version = getSchemaVersion(schema) ?? raise5(new TypeError("Schema has no version"));
3390
+ const versions = defaultMap(this._registry, typename, () => []);
3391
+ if (versions.some((schema2) => getSchemaVersion(schema2) === version)) {
3392
+ throw new Error(`Schema version already registered: ${typename}:${version}`);
3393
+ }
3394
+ versions.push(schema);
3395
+ });
3396
+ }
3397
+ constructor() {
3398
+ _define_property5(this, "_registry", /* @__PURE__ */ new Map());
3399
+ this._registry.set(StoredSchema.typename, [
3400
+ StoredSchema
3401
+ ]);
3402
+ }
3403
+ };
3404
+
3405
+ // src/internal/projection/compose.ts
3406
+ var __dxlog_file15 = "/__w/dxos/dxos/packages/core/echo/echo/src/internal/projection/compose.ts";
3407
+ var composeSchema = (source, target) => {
3408
+ const result = getSnapshot(target);
3409
+ invariant15("type" in result && result.type === "object", "source schema must be an object", {
3410
+ F: __dxlog_file15,
3411
+ L: 17,
3412
+ S: void 0,
3413
+ A: [
3414
+ "'type' in result && result.type === 'object'",
3415
+ "'source schema must be an object'"
3416
+ ]
3417
+ });
3418
+ invariant15("type" in source && source.type === "object", "target schema must be an object", {
3419
+ F: __dxlog_file15,
3420
+ L: 18,
3421
+ S: void 0,
3422
+ A: [
3423
+ "'type' in source && source.type === 'object'",
3424
+ "'target schema must be an object'"
3425
+ ]
3426
+ });
3427
+ for (const prop in result.properties) {
3428
+ const propSchema = source.properties[prop];
3429
+ const annotations7 = propSchema?.annotations?.meta;
3430
+ if (annotations7) {
3431
+ var _result_properties_prop, _result_properties_prop_annotations;
3432
+ (_result_properties_prop = result.properties[prop]).annotations ?? (_result_properties_prop.annotations = {});
3433
+ (_result_properties_prop_annotations = result.properties[prop].annotations).meta ?? (_result_properties_prop_annotations.meta = {});
3434
+ for (const key in annotations7) {
3435
+ var _result_properties_prop_annotations_meta, _key;
3436
+ (_result_properties_prop_annotations_meta = result.properties[prop].annotations.meta)[_key = key] ?? (_result_properties_prop_annotations_meta[_key] = {});
3437
+ Object.assign(result.properties[prop].annotations.meta[key], annotations7[key], {
3438
+ ...result.properties[prop].annotations.meta[key]
3439
+ });
3440
+ }
3441
+ }
3442
+ }
3443
+ return result;
3444
+ };
3445
+
3446
+ // src/internal/proxy/reactive-object.ts
3447
+ import { ObjectId as ObjectId8 } from "@dxos/keys";
3448
+ import { UntypedReactiveHandler, createProxy as createProxy2, defineHiddenProperty as defineHiddenProperty4, isValidProxyTarget as isValidProxyTarget2 } from "@dxos/live-object";
3449
+
3450
+ // src/internal/proxy/typed-handler.ts
3451
+ import * as Schema25 from "effect/Schema";
3452
+ import * as SchemaAST14 from "effect/SchemaAST";
3453
+ import { inspectCustom as inspectCustom2 } from "@dxos/debug";
3454
+ import { compositeRuntime as compositeRuntime2 } from "@dxos/echo-signals/runtime";
3455
+ import { invariant as invariant16 } from "@dxos/invariant";
3456
+ import { ReactiveArray, createProxy, defineHiddenProperty as defineHiddenProperty3, isValidProxyTarget, objectData, symbolIsProxy } from "@dxos/live-object";
3457
+ function _define_property6(obj, key, value) {
3458
+ if (key in obj) {
3459
+ Object.defineProperty(obj, key, {
3460
+ value,
3461
+ enumerable: true,
3462
+ configurable: true,
3463
+ writable: true
3464
+ });
3465
+ } else {
3466
+ obj[key] = value;
3467
+ }
3468
+ return obj;
3469
+ }
3470
+ var __dxlog_file16 = "/__w/dxos/dxos/packages/core/echo/echo/src/internal/proxy/typed-handler.ts";
3471
+ var symbolSignal = Symbol("signal");
3472
+ var symbolPropertySignal = Symbol("property-signal");
3473
+ var TypedReactiveHandler = class {
3474
+ init(target) {
3475
+ invariant16(typeof target === "object" && target !== null, void 0, {
3476
+ F: __dxlog_file16,
3477
+ L: 63,
3478
+ S: this,
3479
+ A: [
3480
+ "typeof target === 'object' && target !== null",
3481
+ ""
3482
+ ]
3483
+ });
3484
+ invariant16(SchemaId in target, "Schema is not defined for the target", {
3485
+ F: __dxlog_file16,
3486
+ L: 64,
3487
+ S: this,
3488
+ A: [
3489
+ "SchemaId in target",
3490
+ "'Schema is not defined for the target'"
3491
+ ]
3492
+ });
3493
+ if (!(symbolSignal in target)) {
3494
+ defineHiddenProperty3(target, symbolSignal, compositeRuntime2.createSignal());
3495
+ defineHiddenProperty3(target, symbolPropertySignal, compositeRuntime2.createSignal());
3496
+ }
3497
+ defineHiddenProperty3(target, DeletedId, false);
3498
+ for (const key of Object.getOwnPropertyNames(target)) {
3499
+ const descriptor = Object.getOwnPropertyDescriptor(target, key);
3500
+ if (descriptor.get) {
3501
+ continue;
3502
+ }
3503
+ }
3504
+ Object.defineProperty(target, inspectCustom2, {
3505
+ enumerable: false,
3506
+ configurable: true,
3507
+ value: this._inspect.bind(target)
3508
+ });
3509
+ }
3510
+ get(target, prop, receiver) {
3511
+ switch (prop) {
3512
+ case objectData: {
3513
+ target[symbolSignal].notifyRead();
3514
+ return toJSON(target);
3515
+ }
3516
+ }
3517
+ if (Object.getOwnPropertyDescriptor(target, prop)?.get) {
3518
+ target[symbolPropertySignal].notifyRead();
3519
+ return Reflect.get(target, prop, receiver);
3520
+ }
3521
+ target[symbolSignal].notifyRead();
3522
+ target[symbolPropertySignal].notifyRead();
3523
+ const value = Reflect.get(target, prop, receiver);
3524
+ if (isValidProxyTarget(value)) {
3525
+ return createProxy(value, this);
3526
+ }
3527
+ return value;
3528
+ }
3529
+ set(target, prop, value, receiver) {
3530
+ if (Array.isArray(value)) {
3531
+ value = ReactiveArray.from(value);
3532
+ }
3533
+ let result = false;
3534
+ compositeRuntime2.batch(() => {
3535
+ const validatedValue = this._validateValue(target, prop, value);
3536
+ result = Reflect.set(target, prop, validatedValue, receiver);
3537
+ target[symbolSignal].notifyWrite();
3538
+ });
3539
+ return result;
3540
+ }
3541
+ ownKeys(target) {
3542
+ target[symbolSignal].notifyRead();
3543
+ target[symbolPropertySignal].notifyRead();
3544
+ return Reflect.ownKeys(target);
3545
+ }
3546
+ defineProperty(target, property, attributes) {
3547
+ const validatedValue = this._validateValue(target, property, attributes.value);
3548
+ const result = Reflect.defineProperty(target, property, {
3549
+ ...attributes,
3550
+ value: validatedValue
3551
+ });
3552
+ target[symbolPropertySignal].notifyWrite();
3553
+ return result;
3554
+ }
3555
+ _validateValue(target, prop, value) {
3556
+ const schema = SchemaValidator.getTargetPropertySchema(target, prop);
3557
+ const _ = Schema25.asserts(schema)(value);
3558
+ if (Array.isArray(value)) {
3559
+ value = new ReactiveArray(...value);
3560
+ }
3561
+ if (isValidProxyTarget(value)) {
3562
+ setSchemaProperties(value, schema);
3563
+ }
3564
+ return value;
3565
+ }
3566
+ _inspect(_, options, inspectFn) {
3567
+ return `Typed ${inspectFn(this, {
3568
+ ...options,
3569
+ compact: true,
3570
+ showHidden: false,
3571
+ customInspect: false
3572
+ })}`;
3573
+ }
3574
+ constructor() {
3575
+ _define_property6(this, "_proxyMap", /* @__PURE__ */ new WeakMap());
3576
+ }
3577
+ };
3578
+ _define_property6(TypedReactiveHandler, "instance", new TypedReactiveHandler());
3579
+ var toJSON = (target) => {
3580
+ return {
3581
+ "@type": "TypedReactiveObject",
3582
+ ...target
3583
+ };
3584
+ };
3585
+ var setSchemaProperties = (obj, schema) => {
3586
+ const schemaType = getSchemaDXN(schema);
3587
+ if (schemaType != null) {
3588
+ defineHiddenProperty3(obj, TypeId, schemaType);
3589
+ }
3590
+ defineHiddenProperty3(obj, SchemaId, schema);
3591
+ for (const key in obj) {
3592
+ if (isValidProxyTarget(obj[key])) {
3593
+ const elementSchema = SchemaValidator.getTargetPropertySchema(obj, key);
3594
+ if (elementSchema != null) {
3595
+ setSchemaProperties(obj[key], elementSchema);
3596
+ }
3597
+ }
3598
+ }
3599
+ };
3600
+ var prepareTypedTarget = (target, schema) => {
3601
+ if (!SchemaAST14.isTypeLiteral(schema.ast)) {
3602
+ throw new Error("schema has to describe an object type");
3603
+ }
3604
+ SchemaValidator.validateSchema(schema);
3605
+ const _ = Schema25.asserts(schema)(target);
3606
+ makeArraysReactive(target);
3607
+ setSchemaProperties(target, schema);
3608
+ };
3609
+ var makeArraysReactive = (target) => {
3610
+ for (const key in target) {
3611
+ if (target[symbolIsProxy]) {
3612
+ continue;
3613
+ }
3614
+ if (Array.isArray(target[key])) {
3615
+ target[key] = ReactiveArray.from(target[key]);
3616
+ }
3617
+ if (typeof target[key] === "object") {
3618
+ makeArraysReactive(target[key]);
3619
+ }
3620
+ }
3621
+ };
3622
+
3623
+ // src/internal/proxy/reactive-object.ts
3624
+ var live = (objOrSchema, obj, meta) => {
3625
+ if (obj && objOrSchema !== Expando) {
3626
+ return createReactiveObject({
3627
+ ...obj
3628
+ }, meta, objOrSchema);
3629
+ } else if (obj && objOrSchema === Expando) {
3630
+ return createReactiveObject({
3631
+ ...obj
3632
+ }, meta, void 0, {
3633
+ expando: true
3634
+ });
3635
+ } else {
3636
+ return createReactiveObject(objOrSchema, meta);
3637
+ }
3638
+ };
3639
+ var createReactiveObject = (obj, meta, schema, options) => {
3640
+ if (!isValidProxyTarget2(obj)) {
3641
+ throw new Error("Value cannot be made into a reactive object.");
3642
+ }
3643
+ if (schema) {
3644
+ const annotation = getTypeAnnotation(schema);
3645
+ const shouldGenerateId = options?.expando || !!annotation;
3646
+ if (shouldGenerateId) {
3647
+ setIdOnTarget(obj);
3648
+ }
3649
+ if (annotation) {
3650
+ defineHiddenProperty4(obj, EntityKindId, annotation.kind);
3651
+ }
3652
+ initMeta(obj, meta);
3653
+ prepareTypedTarget(obj, schema);
3654
+ attachTypedJsonSerializer(obj);
3655
+ return createProxy2(obj, TypedReactiveHandler.instance);
3656
+ } else {
3657
+ if (options?.expando) {
3658
+ setIdOnTarget(obj);
3659
+ }
3660
+ initMeta(obj, meta);
3661
+ return createProxy2(obj, UntypedReactiveHandler.instance);
3662
+ }
3663
+ };
3664
+ var setIdOnTarget = (target) => {
3665
+ if ("id" in target && target.id !== void 0 && target.id !== null) {
3666
+ if (!ObjectId8.isValid(target.id)) {
3667
+ throw new Error("Invalid object id format.");
3668
+ }
3669
+ } else {
3670
+ target.id = ObjectId8.random();
3671
+ }
3672
+ };
3673
+ var initMeta = (obj, meta = {
3674
+ keys: []
3675
+ }) => {
3676
+ prepareTypedTarget(meta, ObjectMetaSchema);
3677
+ defineHiddenProperty4(obj, MetaId, createProxy2(meta, TypedReactiveHandler.instance));
3678
+ };
3679
+
3680
+ export {
3681
+ __export,
3682
+ createAnnotationHelper,
3683
+ EntityKind,
3684
+ EntityKindSchema,
3685
+ unwrapOptional,
3686
+ TypeIdentifierAnnotationId,
3687
+ getTypeIdentifierAnnotation,
3688
+ TypeAnnotationId,
3689
+ Typename,
3690
+ SchemaVersion,
3691
+ TypeAnnotation,
3692
+ getTypeAnnotation,
3693
+ getEntityKind,
3694
+ getSchemaTypename,
3695
+ getSchemaVersion,
3696
+ PropertyMetaAnnotationId,
3697
+ PropertyMeta,
3698
+ getPropertyMetaAnnotation,
3699
+ ReferenceAnnotationId,
3700
+ getReferenceAnnotation,
3701
+ SchemaMetaSymbol,
3702
+ ViewAnnotationId,
3703
+ ViewAnnotation,
3704
+ LabelAnnotationId,
3705
+ LabelAnnotation,
3706
+ FieldLookupAnnotationId,
3707
+ GeneratorAnnotationId,
3708
+ GeneratorAnnotation,
3709
+ getSchemaDXN,
3710
+ FIELD_PATH_ANNOTATION,
3711
+ FieldPath,
3712
+ TypeEnum,
3713
+ getTypeEnum,
3714
+ FormatAnnotationId,
3715
+ FormatAnnotation,
3716
+ getFormatAnnotation,
3717
+ FormatEnum,
3718
+ FormatEnums,
3719
+ PropertyKind,
3720
+ typeToFormat,
3721
+ formatToType,
3722
+ OptionsAnnotationId,
3723
+ getOptionsAnnotation,
3724
+ DecimalPrecision,
3725
+ CurrencyAnnotationId,
3726
+ Currency,
3727
+ GeoPoint,
3728
+ GeoLocation,
3729
+ Email,
3730
+ Formula,
3731
+ Hostname,
3732
+ JSON,
3733
+ Markdown,
3734
+ Regex,
3735
+ URL,
3736
+ UUID2 as UUID,
3737
+ Format,
3738
+ SelectOptionSchema,
3739
+ JsonSchemaEchoAnnotations,
3740
+ JsonSchemaFields,
3741
+ JsonSchemaType,
3742
+ getSchemaProperty,
3743
+ setSchemaProperty,
3744
+ ECHO_ANNOTATIONS_NS_DEPRECATED_KEY,
3745
+ ECHO_ANNOTATIONS_NS_KEY,
3746
+ getNormalizedEchoAnnotations,
3747
+ normalizeSchema,
3748
+ EntityKindId,
3749
+ SelfDXNId,
3750
+ ATTR_SELF_DXN,
3751
+ TypeId,
3752
+ ATTR_TYPE,
3753
+ SchemaId,
3754
+ DeletedId,
3755
+ ATTR_DELETED,
3756
+ MetaId,
3757
+ ATTR_META,
3758
+ RelationSourceDXNId,
3759
+ ATTR_RELATION_SOURCE,
3760
+ RelationTargetDXNId,
3761
+ ATTR_RELATION_TARGET,
3762
+ RelationSourceId,
3763
+ RelationTargetId,
3764
+ ObjectVersionId,
3765
+ assertObjectModelShape,
3766
+ getObjectDXN,
3767
+ getSchema,
3768
+ setSchema,
3769
+ getLabelForObject,
3770
+ getLabel,
3771
+ setLabel,
3772
+ getTypename,
3773
+ setTypename,
3774
+ getType,
3775
+ makeTypedEntityClass,
3776
+ JSON_SCHEMA_ECHO_REF_ID,
3777
+ getSchemaReference,
3778
+ createSchemaReference,
3779
+ getReferenceAst,
3780
+ RefTypeId,
3781
+ Ref,
3782
+ createEchoReferenceSchema,
3783
+ RefImpl,
3784
+ setRefResolver,
3785
+ getRefSavedTarget,
3786
+ refFromEncodedReference,
3787
+ StaticRefResolver,
3788
+ RefArray,
3789
+ ObjectMetaSchema,
3790
+ foreignKey,
3791
+ foreignKeyEquals,
3792
+ getObjectMeta,
3793
+ getMeta,
3794
+ compareForeignKeys,
3795
+ objectToJSON,
3796
+ objectFromJSON,
3797
+ setRefResolverOnData,
3798
+ attachTypedJsonSerializer,
3799
+ create,
3800
+ EchoObject,
3801
+ EchoRelation,
3802
+ EXPANDO_TYPENAME,
3803
+ Expando,
3804
+ createQueueDXN,
3805
+ TypedObject,
3806
+ TypedRelation,
3807
+ isDeleted,
3808
+ SchemaValidator,
3809
+ checkIdNotPresentOnSchema,
3810
+ VersionTypeId,
3811
+ createJsonSchema,
3812
+ PropType,
3813
+ toPropType,
3814
+ toJsonSchema,
3815
+ toEffectSchema,
3816
+ RawObject,
3817
+ splitMeta,
3818
+ getValue,
3819
+ setValue,
3820
+ getTypeReference,
3821
+ requireTypeReference,
3822
+ isInstanceOf,
3823
+ addFieldsToSchema,
3824
+ updateFieldsInSchema,
3825
+ removeFieldsFromSchema,
3826
+ updateFieldNameInSchema,
3827
+ setTypenameInSchema,
3828
+ getSnapshot,
3829
+ StoredSchema,
3830
+ ImmutableSchema,
3831
+ isMutable,
3832
+ EchoSchema,
3833
+ RuntimeSchemaRegistry,
3834
+ composeSchema,
3835
+ live,
3836
+ JsonPath2 as JsonPath,
3837
+ splitJsonPath2 as splitJsonPath,
3838
+ JsonProp,
3839
+ ObjectId9 as ObjectId,
3840
+ ForeignKey2 as ForeignKey,
3841
+ defineHiddenProperty5 as defineHiddenProperty
3842
+ };
3843
+ //# sourceMappingURL=chunk-MWLA34S5.mjs.map