@dxos/echo 0.8.4-main.e098934 → 0.8.4-main.e8ec1fe

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