@dxos/echo 0.9.1-main.c7dcc2e112 → 0.9.1-staging.ee54ba693a

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 (278) hide show
  1. package/dist/lib/neutral/Annotation.mjs +22 -8
  2. package/dist/lib/neutral/Database.mjs +3 -3
  3. package/dist/lib/neutral/Entity.mjs +11 -11
  4. package/dist/lib/neutral/Err.mjs +7 -3
  5. package/dist/lib/neutral/Feed.mjs +15 -19
  6. package/dist/lib/neutral/Filter.mjs +13 -11
  7. package/dist/lib/neutral/Format.mjs +3 -7
  8. package/dist/lib/neutral/JsonSchema.mjs +7 -7
  9. package/dist/lib/neutral/Migration.mjs +11 -11
  10. package/dist/lib/neutral/Obj.mjs +15 -13
  11. package/dist/lib/neutral/Order.mjs +1 -1
  12. package/dist/lib/neutral/Query.mjs +17 -17
  13. package/dist/lib/neutral/QueryResult.mjs +1 -1
  14. package/dist/lib/neutral/Ref.mjs +6 -6
  15. package/dist/lib/neutral/Registry.mjs +1 -1
  16. package/dist/lib/neutral/Relation.mjs +12 -12
  17. package/dist/lib/neutral/Tag.mjs +15 -15
  18. package/dist/lib/neutral/Text.mjs +25 -0
  19. package/dist/lib/neutral/Text.mjs.map +7 -0
  20. package/dist/lib/neutral/Type.mjs +10 -10
  21. package/dist/lib/neutral/chunk-2HKGAQM4.mjs +1394 -0
  22. package/dist/lib/neutral/chunk-2HKGAQM4.mjs.map +7 -0
  23. package/dist/lib/neutral/{chunk-O6BH7EPN.mjs → chunk-2ZHECXUR.mjs} +5 -4
  24. package/dist/lib/neutral/chunk-2ZHECXUR.mjs.map +7 -0
  25. package/dist/lib/neutral/{chunk-AFANXSGV.mjs → chunk-3KTE2Y7Q.mjs} +20 -20
  26. package/dist/lib/neutral/chunk-3KTE2Y7Q.mjs.map +7 -0
  27. package/dist/lib/neutral/{chunk-WZ32BF53.mjs → chunk-3TN2VMI4.mjs} +49 -37
  28. package/dist/lib/neutral/chunk-3TN2VMI4.mjs.map +7 -0
  29. package/dist/lib/neutral/{chunk-E7IOTOZD.mjs → chunk-42L4HJ3Z.mjs} +11 -15
  30. package/dist/lib/neutral/chunk-42L4HJ3Z.mjs.map +7 -0
  31. package/dist/lib/neutral/{chunk-K3S7D5PR.mjs → chunk-4A2NWKRJ.mjs} +5 -5
  32. package/dist/lib/neutral/chunk-ACFAOTKJ.mjs +1531 -0
  33. package/dist/lib/neutral/chunk-ACFAOTKJ.mjs.map +7 -0
  34. package/dist/lib/neutral/{chunk-Z3WMRRAZ.mjs → chunk-BEFR7LEA.mjs} +11 -9
  35. package/dist/lib/neutral/{chunk-Z3WMRRAZ.mjs.map → chunk-BEFR7LEA.mjs.map} +1 -1
  36. package/dist/lib/neutral/{chunk-6M2Z6WBH.mjs → chunk-BXIKXT7Q.mjs} +2 -6
  37. package/dist/lib/neutral/{chunk-6M2Z6WBH.mjs.map → chunk-BXIKXT7Q.mjs.map} +1 -1
  38. package/dist/lib/neutral/{chunk-3JXQUMUI.mjs → chunk-C57XMMBY.mjs} +21 -20
  39. package/dist/lib/neutral/chunk-C57XMMBY.mjs.map +7 -0
  40. package/dist/lib/neutral/{chunk-JZ6LFQU5.mjs → chunk-C62JYFAD.mjs} +82 -8
  41. package/dist/lib/neutral/chunk-C62JYFAD.mjs.map +7 -0
  42. package/dist/lib/neutral/{chunk-TF5BSLF6.mjs → chunk-FSGX2R62.mjs} +3 -3
  43. package/dist/lib/neutral/chunk-FSGX2R62.mjs.map +7 -0
  44. package/dist/lib/neutral/{chunk-6CEISA3V.mjs → chunk-HBXT3GSB.mjs} +29 -15
  45. package/dist/lib/neutral/chunk-HBXT3GSB.mjs.map +7 -0
  46. package/dist/lib/neutral/{chunk-WU3GIANS.mjs → chunk-IQR45HAD.mjs} +1 -1
  47. package/dist/lib/neutral/chunk-IQR45HAD.mjs.map +7 -0
  48. package/dist/lib/neutral/{chunk-TFEWTY5A.mjs → chunk-KCBW4BR6.mjs} +4 -8
  49. package/dist/lib/neutral/chunk-KCBW4BR6.mjs.map +7 -0
  50. package/dist/lib/neutral/{chunk-4TPQZPLY.mjs → chunk-L3E5IXAE.mjs} +198 -30
  51. package/dist/lib/neutral/chunk-L3E5IXAE.mjs.map +7 -0
  52. package/dist/lib/neutral/{chunk-EVK6XBXO.mjs → chunk-PRC4FEKJ.mjs} +2 -2
  53. package/dist/lib/neutral/chunk-PRC4FEKJ.mjs.map +7 -0
  54. package/dist/lib/neutral/{chunk-NOL7O3BL.mjs → chunk-SCT6FFCR.mjs} +9 -4
  55. package/dist/lib/neutral/chunk-SCT6FFCR.mjs.map +7 -0
  56. package/dist/lib/neutral/{chunk-BBFJWWAV.mjs → chunk-TOCVVFK2.mjs} +26 -2
  57. package/dist/lib/neutral/chunk-TOCVVFK2.mjs.map +7 -0
  58. package/dist/lib/neutral/{chunk-A53NTBHE.mjs → chunk-U53LSQQA.mjs} +3 -3
  59. package/dist/lib/neutral/{chunk-A53NTBHE.mjs.map → chunk-U53LSQQA.mjs.map} +1 -1
  60. package/dist/lib/neutral/{chunk-PLDMJJJC.mjs → chunk-UGFFV2FR.mjs} +2 -2
  61. package/dist/lib/neutral/{chunk-35INCYOE.mjs → chunk-UWLP4RFM.mjs} +1 -1
  62. package/dist/lib/neutral/chunk-UWLP4RFM.mjs.map +7 -0
  63. package/dist/lib/neutral/{chunk-SZ5WB6HF.mjs → chunk-UZHCQ6NI.mjs} +13 -11
  64. package/dist/lib/neutral/{chunk-SZ5WB6HF.mjs.map → chunk-UZHCQ6NI.mjs.map} +3 -3
  65. package/dist/lib/neutral/{chunk-L3OBWBV2.mjs → chunk-WKIT2YY5.mjs} +2 -2
  66. package/dist/lib/neutral/{chunk-HGWQR5KH.mjs → chunk-XB6ISRAO.mjs} +27 -15
  67. package/dist/lib/neutral/chunk-XB6ISRAO.mjs.map +7 -0
  68. package/dist/lib/neutral/chunk-XXL42WCB.mjs +84 -0
  69. package/dist/lib/neutral/chunk-XXL42WCB.mjs.map +7 -0
  70. package/dist/lib/neutral/{chunk-5GAIWRQB.mjs → chunk-XXWK4J53.mjs} +27 -42
  71. package/dist/lib/neutral/chunk-XXWK4J53.mjs.map +7 -0
  72. package/dist/lib/neutral/index.mjs +30 -26
  73. package/dist/lib/neutral/internal/index.mjs +91 -69
  74. package/dist/lib/neutral/meta.json +1 -1
  75. package/dist/lib/neutral/testing/index.mjs +79 -60
  76. package/dist/lib/neutral/testing/index.mjs.map +3 -3
  77. package/dist/types/src/Annotation.d.ts +35 -1
  78. package/dist/types/src/Annotation.d.ts.map +1 -1
  79. package/dist/types/src/Collection.d.ts +9 -8
  80. package/dist/types/src/Collection.d.ts.map +1 -1
  81. package/dist/types/src/Database.d.ts +16 -0
  82. package/dist/types/src/Database.d.ts.map +1 -1
  83. package/dist/types/src/Dataset.d.ts +1 -16
  84. package/dist/types/src/Dataset.d.ts.map +1 -1
  85. package/dist/types/src/Err.d.ts +67 -0
  86. package/dist/types/src/Err.d.ts.map +1 -1
  87. package/dist/types/src/Feed.d.ts +56 -80
  88. package/dist/types/src/Feed.d.ts.map +1 -1
  89. package/dist/types/src/Filter.d.ts +9 -1
  90. package/dist/types/src/Filter.d.ts.map +1 -1
  91. package/dist/types/src/Hypergraph.d.ts +2 -9
  92. package/dist/types/src/Hypergraph.d.ts.map +1 -1
  93. package/dist/types/src/Migration.d.ts +1 -1
  94. package/dist/types/src/Migration.d.ts.map +1 -1
  95. package/dist/types/src/Obj.d.ts +31 -6
  96. package/dist/types/src/Obj.d.ts.map +1 -1
  97. package/dist/types/src/Order.d.ts +1 -1
  98. package/dist/types/src/Order.d.ts.map +1 -1
  99. package/dist/types/src/Query.d.ts +1 -1
  100. package/dist/types/src/Query.d.ts.map +1 -1
  101. package/dist/types/src/QueryResult.d.ts +2 -2
  102. package/dist/types/src/QueryResult.d.ts.map +1 -1
  103. package/dist/types/src/Ref.d.ts +8 -4
  104. package/dist/types/src/Ref.d.ts.map +1 -1
  105. package/dist/types/src/Registry.d.ts +1 -1
  106. package/dist/types/src/Relation.d.ts.map +1 -1
  107. package/dist/types/src/Tag.d.ts +11 -13
  108. package/dist/types/src/Tag.d.ts.map +1 -1
  109. package/dist/types/src/Text.d.ts +41 -0
  110. package/dist/types/src/Text.d.ts.map +1 -0
  111. package/dist/types/src/Text.test.d.ts +2 -0
  112. package/dist/types/src/Text.test.d.ts.map +1 -0
  113. package/dist/types/src/Type.d.ts +33 -20
  114. package/dist/types/src/Type.d.ts.map +1 -1
  115. package/dist/types/src/View.d.ts +8 -9
  116. package/dist/types/src/View.d.ts.map +1 -1
  117. package/dist/types/src/index.d.ts +1 -0
  118. package/dist/types/src/index.d.ts.map +1 -1
  119. package/dist/types/src/internal/Annotation/annotations.d.ts +9 -0
  120. package/dist/types/src/internal/Annotation/annotations.d.ts.map +1 -1
  121. package/dist/types/src/internal/Annotation/atoms.d.ts +14 -0
  122. package/dist/types/src/internal/Annotation/atoms.d.ts.map +1 -0
  123. package/dist/types/src/internal/Annotation/entity-dictionary.d.ts +13 -0
  124. package/dist/types/src/internal/Annotation/entity-dictionary.d.ts.map +1 -1
  125. package/dist/types/src/internal/Entity/api.d.ts.map +1 -1
  126. package/dist/types/src/internal/Entity/guard.d.ts.map +1 -1
  127. package/dist/types/src/internal/Entity/model.d.ts +1 -1
  128. package/dist/types/src/internal/Entity/model.d.ts.map +1 -1
  129. package/dist/types/src/internal/Entity/object.d.ts +5 -1
  130. package/dist/types/src/internal/Entity/object.d.ts.map +1 -1
  131. package/dist/types/src/internal/Entity/relation.d.ts +7 -0
  132. package/dist/types/src/internal/Entity/relation.d.ts.map +1 -1
  133. package/dist/types/src/internal/Entity/type-uri.d.ts.map +1 -1
  134. package/dist/types/src/internal/Filter/index.d.ts +2 -0
  135. package/dist/types/src/internal/Filter/index.d.ts.map +1 -0
  136. package/dist/types/src/internal/Filter/match.d.ts +22 -0
  137. package/dist/types/src/internal/Filter/match.d.ts.map +1 -0
  138. package/dist/types/src/internal/Format/format.d.ts +0 -2
  139. package/dist/types/src/internal/Format/format.d.ts.map +1 -1
  140. package/dist/types/src/internal/Format/index.d.ts +2 -2
  141. package/dist/types/src/internal/Format/index.d.ts.map +1 -1
  142. package/dist/types/src/internal/Format/string.d.ts +0 -8
  143. package/dist/types/src/internal/Format/string.d.ts.map +1 -1
  144. package/dist/types/src/internal/Format/types.d.ts +2 -1
  145. package/dist/types/src/internal/Format/types.d.ts.map +1 -1
  146. package/dist/types/src/internal/Obj/atoms.d.ts +7 -3
  147. package/dist/types/src/internal/Obj/atoms.d.ts.map +1 -1
  148. package/dist/types/src/internal/Obj/clone.d.ts +2 -1
  149. package/dist/types/src/internal/Obj/clone.d.ts.map +1 -1
  150. package/dist/types/src/internal/Obj/create-object.d.ts +3 -4
  151. package/dist/types/src/internal/Obj/create-object.d.ts.map +1 -1
  152. package/dist/types/src/internal/Obj/json-serializer.d.ts.map +1 -1
  153. package/dist/types/src/internal/Query/index.d.ts +1 -0
  154. package/dist/types/src/internal/Query/index.d.ts.map +1 -1
  155. package/dist/types/src/internal/Query/query-result-effect.d.ts +9 -0
  156. package/dist/types/src/internal/Query/query-result-effect.d.ts.map +1 -0
  157. package/dist/types/src/internal/Ref/atoms.d.ts +1 -2
  158. package/dist/types/src/internal/Ref/atoms.d.ts.map +1 -1
  159. package/dist/types/src/internal/Ref/ref.d.ts +13 -6
  160. package/dist/types/src/internal/Ref/ref.d.ts.map +1 -1
  161. package/dist/types/src/internal/common/atom-snapshot.d.ts +8 -0
  162. package/dist/types/src/internal/common/atom-snapshot.d.ts.map +1 -0
  163. package/dist/types/src/internal/common/proxy/make-object.d.ts.map +1 -1
  164. package/dist/types/src/internal/common/proxy/proxy-types.d.ts +12 -0
  165. package/dist/types/src/internal/common/proxy/proxy-types.d.ts.map +1 -1
  166. package/dist/types/src/internal/common/proxy/proxy-utils.d.ts +25 -0
  167. package/dist/types/src/internal/common/proxy/proxy-utils.d.ts.map +1 -1
  168. package/dist/types/src/internal/common/proxy/schema-validator.d.ts +5 -0
  169. package/dist/types/src/internal/common/proxy/schema-validator.d.ts.map +1 -1
  170. package/dist/types/src/internal/common/proxy/typed-handler.d.ts +17 -0
  171. package/dist/types/src/internal/common/proxy/typed-handler.d.ts.map +1 -1
  172. package/dist/types/src/internal/common/types/entity.d.ts +4 -4
  173. package/dist/types/src/internal/common/types/entity.d.ts.map +1 -1
  174. package/dist/types/src/internal/common/types/meta.d.ts +2 -4
  175. package/dist/types/src/internal/common/types/meta.d.ts.map +1 -1
  176. package/dist/types/src/internal/index.d.ts +1 -0
  177. package/dist/types/src/internal/index.d.ts.map +1 -1
  178. package/dist/types/src/testing/test-schema.d.ts +42 -171
  179. package/dist/types/src/testing/test-schema.d.ts.map +1 -1
  180. package/dist/types/tsconfig.tsbuildinfo +1 -1
  181. package/package.json +20 -13
  182. package/src/Annotation.test.ts +257 -10
  183. package/src/Annotation.ts +55 -6
  184. package/src/Collection.ts +10 -12
  185. package/src/Database.ts +22 -20
  186. package/src/Err.ts +22 -0
  187. package/src/Feed.ts +114 -141
  188. package/src/Filter.test.ts +38 -0
  189. package/src/Filter.ts +17 -3
  190. package/src/Hypergraph.ts +2 -11
  191. package/src/Migration.ts +1 -1
  192. package/src/Obj.test.ts +92 -12
  193. package/src/Obj.ts +36 -5
  194. package/src/Order.ts +3 -3
  195. package/src/Query.test.ts +2 -2
  196. package/src/Query.ts +16 -16
  197. package/src/QueryResult.ts +2 -2
  198. package/src/Ref.ts +12 -4
  199. package/src/Registry.ts +1 -1
  200. package/src/Relation.ts +1 -1
  201. package/src/Tag.ts +12 -16
  202. package/src/Text.test.ts +186 -0
  203. package/src/Text.ts +116 -0
  204. package/src/Type.test.ts +52 -24
  205. package/src/Type.ts +69 -31
  206. package/src/View.ts +22 -30
  207. package/src/index.ts +1 -1
  208. package/src/internal/Annotation/annotations.ts +15 -2
  209. package/src/internal/Annotation/atoms.ts +107 -0
  210. package/src/internal/Annotation/entity-dictionary.ts +40 -37
  211. package/src/internal/Entity/api.ts +1 -1
  212. package/src/internal/Entity/guard.ts +2 -1
  213. package/src/internal/Entity/model.ts +2 -2
  214. package/src/internal/Entity/object.ts +14 -1
  215. package/src/internal/Entity/relation.ts +19 -0
  216. package/src/internal/Entity/type-uri.ts +3 -1
  217. package/src/internal/Filter/index.ts +5 -0
  218. package/src/internal/Filter/match.ts +284 -0
  219. package/src/internal/Format/format.ts +0 -2
  220. package/src/internal/Format/index.ts +2 -2
  221. package/src/internal/Format/string.ts +0 -12
  222. package/src/internal/Format/types.ts +4 -2
  223. package/src/internal/JsonSchema/json-schema.test.ts +82 -54
  224. package/src/internal/Obj/atoms.ts +31 -18
  225. package/src/internal/Obj/clone.ts +61 -20
  226. package/src/internal/Obj/create-object.test.ts +3 -3
  227. package/src/internal/Obj/create-object.ts +3 -4
  228. package/src/internal/Obj/inspect.ts +1 -1
  229. package/src/internal/Obj/json-serializer.test.ts +7 -5
  230. package/src/internal/Obj/json-serializer.ts +1 -1
  231. package/src/internal/Obj/schema-validator.test.ts +53 -0
  232. package/src/internal/Obj/set-value.test.ts +29 -19
  233. package/src/internal/Query/index.ts +1 -0
  234. package/src/internal/Query/query-result-effect.ts +35 -0
  235. package/src/internal/Ref/atoms.ts +23 -3
  236. package/src/internal/Ref/ref.test.ts +8 -8
  237. package/src/internal/Ref/ref.ts +26 -20
  238. package/src/internal/common/atom-snapshot.ts +19 -0
  239. package/src/internal/common/proxy/make-object.ts +1 -1
  240. package/src/internal/common/proxy/proxy-types.ts +20 -0
  241. package/src/internal/common/proxy/proxy-utils.ts +37 -1
  242. package/src/internal/common/proxy/reactive-array.ts +3 -3
  243. package/src/internal/common/proxy/reactive.test.ts +1 -1
  244. package/src/internal/common/proxy/schema-validator.ts +181 -8
  245. package/src/internal/common/proxy/typed-handler.ts +254 -76
  246. package/src/internal/common/types/entity.ts +15 -7
  247. package/src/internal/index.ts +1 -0
  248. package/src/testing/test-schema.ts +75 -90
  249. package/dist/lib/neutral/chunk-35INCYOE.mjs.map +0 -7
  250. package/dist/lib/neutral/chunk-3JXQUMUI.mjs.map +0 -7
  251. package/dist/lib/neutral/chunk-4TPQZPLY.mjs.map +0 -7
  252. package/dist/lib/neutral/chunk-5GAIWRQB.mjs.map +0 -7
  253. package/dist/lib/neutral/chunk-6CEISA3V.mjs.map +0 -7
  254. package/dist/lib/neutral/chunk-AFANXSGV.mjs.map +0 -7
  255. package/dist/lib/neutral/chunk-BBFJWWAV.mjs.map +0 -7
  256. package/dist/lib/neutral/chunk-E7IOTOZD.mjs.map +0 -7
  257. package/dist/lib/neutral/chunk-EVK6XBXO.mjs.map +0 -7
  258. package/dist/lib/neutral/chunk-HGWQR5KH.mjs.map +0 -7
  259. package/dist/lib/neutral/chunk-JZ6LFQU5.mjs.map +0 -7
  260. package/dist/lib/neutral/chunk-NOL7O3BL.mjs.map +0 -7
  261. package/dist/lib/neutral/chunk-O6BH7EPN.mjs.map +0 -7
  262. package/dist/lib/neutral/chunk-TF5BSLF6.mjs.map +0 -7
  263. package/dist/lib/neutral/chunk-TFEWTY5A.mjs.map +0 -7
  264. package/dist/lib/neutral/chunk-VQYL2OQF.mjs +0 -2353
  265. package/dist/lib/neutral/chunk-VQYL2OQF.mjs.map +0 -7
  266. package/dist/lib/neutral/chunk-WU3GIANS.mjs.map +0 -7
  267. package/dist/lib/neutral/chunk-WZ32BF53.mjs.map +0 -7
  268. package/dist/lib/neutral/chunk-X3NUUON4.mjs +0 -184
  269. package/dist/lib/neutral/chunk-X3NUUON4.mjs.map +0 -7
  270. package/dist/types/src/exemplars.test.d.ts +0 -2
  271. package/dist/types/src/exemplars.test.d.ts.map +0 -1
  272. package/dist/types/src/hierarchy.test.d.ts +0 -2
  273. package/dist/types/src/hierarchy.test.d.ts.map +0 -1
  274. package/src/exemplars.test.ts +0 -21
  275. package/src/hierarchy.test.ts +0 -33
  276. /package/dist/lib/neutral/{chunk-K3S7D5PR.mjs.map → chunk-4A2NWKRJ.mjs.map} +0 -0
  277. /package/dist/lib/neutral/{chunk-PLDMJJJC.mjs.map → chunk-UGFFV2FR.mjs.map} +0 -0
  278. /package/dist/lib/neutral/{chunk-L3OBWBV2.mjs.map → chunk-WKIT2YY5.mjs.map} +0 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/internal/Format/types.ts", "../../../src/internal/Format/date.ts", "../../../src/internal/Format/number.ts", "../../../src/internal/Format/object.ts", "../../../src/internal/Format/string.ts", "../../../src/internal/Format/format.ts", "../../../src/internal/Format/select.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Function from 'effect/Function';\nimport type * as JSONSchema from 'effect/JSONSchema';\nimport * as Option from 'effect/Option';\nimport * as SchemaAST from 'effect/SchemaAST';\n\nimport { createAnnotationHelper } from '../Annotation';\nimport { type JsonSchemaType } from '../JsonSchema';\n\n// TODO(burdon): Rename PropertyType.\nexport type ScalarType =\n | JSONSchema.JsonSchema7Object\n | JSONSchema.JsonSchema7String\n | JSONSchema.JsonSchema7Number\n | JSONSchema.JsonSchema7Boolean\n | JSONSchema.JsonSchema7Ref;\n\n// TODO(burdon): Rename ValueType and change to disciminated union.\n// export type ValueType = 'array' | 'object' | 'string' | 'number' | 'boolean' | 'ref';\nexport enum TypeEnum {\n Array = 'array', // TODO(burdon): Remove?\n Object = 'object',\n String = 'string',\n Number = 'number',\n Boolean = 'boolean',\n Ref = 'ref',\n}\n\n// TODO(burdon): Ref?\nexport const getTypeEnum = (property: JsonSchemaType): TypeEnum | undefined => {\n switch (property.type) {\n case 'array':\n return TypeEnum.Array;\n case 'object':\n return TypeEnum.Object;\n case 'string':\n return TypeEnum.String;\n case 'number':\n return TypeEnum.Number;\n case 'boolean':\n return TypeEnum.Boolean;\n default:\n return undefined;\n }\n};\n\n/**\n * https://json-schema.org/understanding-json-schema/reference/schema\n * https://json-schema.org/understanding-json-schema/reference/string#built-in-formats\n */\nexport const FormatAnnotationId = Symbol.for('@dxos/schema/annotation/Format');\n\nexport const FormatAnnotation = createAnnotationHelper<TypeFormat>(FormatAnnotationId);\n\n/** @deprecated */\nexport const getFormatAnnotation = (node: SchemaAST.AST): TypeFormat | undefined =>\n Function.pipe(SchemaAST.getAnnotation<TypeFormat>(FormatAnnotationId)(node), Option.getOrUndefined);\n\n// TODO(burdon): Rename Format; Change to discriminated union?\nexport enum TypeFormat {\n None = 'none',\n\n //\n // Scalar\n //\n\n String = 'string',\n Number = 'number',\n Boolean = 'boolean',\n Ref = 'ref',\n\n //\n // { type: 'string' }\n //\n\n DID = 'did', // Users, etc.\n DXN = 'dxn',\n Email = 'email',\n Formula = 'formula', // Spreadsheet (Excel, Google Sheets, etc.) formula.\n Hostname = 'hostname',\n JSON = 'json',\n Markdown = 'markdown',\n Password = 'password',\n Regex = 'regex',\n SingleSelect = 'single-select',\n Text = 'text',\n MultiSelect = 'multi-select',\n URL = 'url',\n UUID = 'uuid',\n\n //\n // { type: 'number' }\n //\n\n Currency = 'currency',\n Integer = 'integer',\n Percent = 'percent',\n Timestamp = 'timestamp',\n\n //\n // { type: 'date' }\n //\n\n DateTime = 'date-time',\n Date = 'date',\n Time = 'time',\n Duration = 'duration',\n\n //\n // { type: 'object' }\n //\n\n GeoPoint = 'lnglat',\n}\n\nexport const FormatEnums = Object.values(TypeFormat).sort();\n\nexport const PropertyKind = {\n type: TypeEnum,\n format: TypeFormat,\n};\n\n/**\n * Default formats\n */\nexport const typeToFormat: Partial<Record<TypeEnum, TypeFormat>> = {\n [TypeEnum.String]: TypeFormat.String,\n [TypeEnum.Number]: TypeFormat.Number,\n [TypeEnum.Boolean]: TypeFormat.Boolean,\n};\n\n/**\n * Map of format to type.\n */\nexport const formatToType: Record<TypeFormat, TypeEnum> = {\n [TypeFormat.None]: TypeEnum.String,\n [TypeFormat.String]: TypeEnum.String,\n [TypeFormat.Number]: TypeEnum.Number,\n [TypeFormat.Boolean]: TypeEnum.Boolean,\n [TypeFormat.Ref]: TypeEnum.Ref,\n\n // Strings\n [TypeFormat.DID]: TypeEnum.String,\n [TypeFormat.DXN]: TypeEnum.String,\n [TypeFormat.Email]: TypeEnum.String,\n [TypeFormat.Formula]: TypeEnum.String,\n [TypeFormat.Hostname]: TypeEnum.String,\n [TypeFormat.JSON]: TypeEnum.String,\n [TypeFormat.Markdown]: TypeEnum.String,\n [TypeFormat.Password]: TypeEnum.String,\n [TypeFormat.Regex]: TypeEnum.String,\n [TypeFormat.URL]: TypeEnum.String,\n [TypeFormat.UUID]: TypeEnum.String,\n [TypeFormat.SingleSelect]: TypeEnum.String,\n [TypeFormat.Text]: TypeEnum.String,\n [TypeFormat.MultiSelect]: TypeEnum.Object,\n\n // Dates\n [TypeFormat.Date]: TypeEnum.String,\n [TypeFormat.DateTime]: TypeEnum.String,\n [TypeFormat.Duration]: TypeEnum.String,\n [TypeFormat.Time]: TypeEnum.String,\n\n // Numbers\n [TypeFormat.Currency]: TypeEnum.Number,\n [TypeFormat.Integer]: TypeEnum.Number,\n [TypeFormat.Percent]: TypeEnum.Number,\n [TypeFormat.Timestamp]: TypeEnum.Number,\n\n // Objects\n [TypeFormat.GeoPoint]: TypeEnum.Array,\n};\n\n/**\n * Allowed value options for select.\n */\nexport const OptionsAnnotationId = Symbol.for('@dxos/schema/annotation/Options');\n\n// TODO(wittjosiah): Reconcile with `SelectOption`.\nexport type Options = string | number;\nexport const OptionsAnnotation = createAnnotationHelper<Options[]>(OptionsAnnotationId);\n\n/** @deprecated */\nexport const getOptionsAnnotation = (node: SchemaAST.AST): Options[] | undefined =>\n Function.pipe(SchemaAST.getAnnotation<Options[]>(OptionsAnnotationId)(node), Option.getOrUndefined);\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\nimport * as SchemaAST from 'effect/SchemaAST';\n\nimport { FormatAnnotation, TypeFormat } from './types';\n\n/**\n * Datetime values should be stored as ISO strings or unix numbers (ms) in UTC.\n *\n * NOTE: HyperFormula uses Excel's time format (null date 1900/01/01)\n * It can be configured to use a different parser via `parseDateTime`.\n * https://hyperformula.handsontable.com/guide/date-and-time-handling.html#date-and-time-handling\n * https://github.com/handsontable/hyperformula/blob/master/src/DateTimeHelper.ts\n */\n\n// TODO(burdon): Annotations not present in JSON.\n// TODO(burdon): Timezone.\n// TODO(burdon): Format for timestamp (Unix UTC or ISO 8601)?\n// TODO(burdon): Refs\n// - https://www.npmjs.com/package/numfmt\n// - https://date-fns.org/docs/Getting-Started\n// - https://github.com/date-fns/tz\n\n/**\n * Simple date compatible with HF.\n */\nexport const SimpleDate = Schema.Struct({\n year: Schema.Number.pipe(Schema.between(1900, 9999)),\n month: Schema.Number.pipe(Schema.between(1, 12)),\n day: Schema.Number.pipe(Schema.between(1, 31)),\n});\n\nexport type SimpleDate = Schema.Schema.Type<typeof SimpleDate>;\n\nexport const toSimpleDate = (date: Date): SimpleDate => ({\n year: date.getUTCFullYear(),\n month: date.getUTCMonth() + 1,\n day: date.getUTCDate(),\n});\n\n/**\n * Simple time compatible with HF.\n */\nexport const SimpleTime = Schema.Struct({\n hours: Schema.Number.pipe(Schema.between(0, 23)),\n minutes: Schema.Number.pipe(Schema.between(0, 59)),\n seconds: Schema.Number.pipe(Schema.between(0, 59)),\n});\n\nexport type SimpleTime = Schema.Schema.Type<typeof SimpleTime>;\n\nexport const toSimpleTime = (date: Date): SimpleTime => ({\n hours: date.getUTCHours(),\n minutes: date.getUTCSeconds(),\n seconds: date.getUTCSeconds(),\n});\n\n/**\n * Simple date-time compatible with HF.\n */\nexport const SimpleDateTime = Schema.extend(SimpleDate, SimpleTime);\n\nexport type SimpleDateTime = Schema.Schema.Type<typeof SimpleDateTime>;\n\nexport const toSimpleDateTime = (date: Date): SimpleDateTime => ({\n ...toSimpleDate(date),\n ...toSimpleTime(date),\n});\n\n/**\n * https://effect.website/docs/guides/schema/transformations#date-transformations\n */\n\n// TODO(burdon): Consider if transformations should be supported with Automerge.\n\n/**\n * Format: 2018-11-13\n */\nexport const DateOnly = /* Schema.transformOrFail(Schema.String, SimpleDate, {\n strict: true,\n decode: (str, _, ast) => {\n if (!isValidDateFormat(str)) {\n return ParseResult.fail(new ParseResult.Type(ast, str, 'Expected YYYY-MM-DD format'));\n }\n if (!isValidDate(str)) {\n return ParseResult.fail(new ParseResult.Type(ast, str, 'Invalid date'));\n }\n\n const [year, month, day] = str.split('-').map(Number);\n return ParseResult.succeed({ year, month, day });\n },\n encode: (date) => {\n return ParseResult.succeed(\n [\n date.year.toString().padStart(4, '0'),\n date.month.toString().padStart(2, '0'),\n date.day.toString().padStart(2, '0'),\n ].join('-'),\n );\n },\n}) */ Schema.String.pipe(\n FormatAnnotation.set(TypeFormat.Date),\n Schema.annotations({\n description: 'Valid date in ISO format',\n }),\n);\n\n/**\n * Format: 20:20:39+00:00\n */\nexport const TimeOnly = /* Schema.transformOrFail(Schema.String, SimpleTime, {\n strict: true,\n decode: (str, _, ast) => {\n if (!isValidTimeFormat(str)) {\n return ParseResult.fail(new ParseResult.Type(ast, str, 'Expected HH:mm:ss format'));\n }\n\n const [hours, minutes, seconds] = str.split(':').map(Number);\n return ParseResult.succeed({ hours, minutes, seconds });\n },\n encode: (time) => {\n return ParseResult.succeed(\n [\n time.hours.toString().padStart(2, '0'),\n time.minutes.toString().padStart(2, '0'),\n time.seconds.toString().padStart(2, '0'),\n ].join(':'),\n );\n },\n}) */ Schema.String.pipe(\n FormatAnnotation.set(TypeFormat.Time),\n Schema.annotations({\n description: 'Valid time in ISO format',\n }),\n);\n\n/**\n * Format: 2018-11-13T20:20:39+00:00\n */\nexport const DateTime = /* Schema.transformOrFail(Schema.String, SimpleDateTime, {\n strict: false,\n decode: (str, _, ast) => {\n const [date, time] = str.split('T');\n if (!isValidDateFormat(date)) {\n return ParseResult.fail(new ParseResult.Type(ast, date, 'Expected YYYY-MM-DD format'));\n }\n if (!isValidDate(date)) {\n return ParseResult.fail(new ParseResult.Type(ast, date, 'Invalid date'));\n }\n if (!isValidTimeFormat(time)) {\n return ParseResult.fail(new ParseResult.Type(ast, str, 'Expected HH:mm:ss format'));\n }\n\n const [year, month, day] = date.split('-').map(Number);\n const [hours, minutes, seconds] = time.split(':').map(Number);\n return ParseResult.succeed({ year, month, day, hours, minutes, seconds });\n },\n encode: (datetime) => {\n return ParseResult.succeed(\n [\n [\n datetime.year.toString().padStart(4, '0'),\n datetime.month.toString().padStart(2, '0'),\n datetime.day.toString().padStart(2, '0'),\n ].join('-'),\n [\n datetime.hours.toString().padStart(2, '0'),\n datetime.minutes.toString().padStart(2, '0'),\n datetime.seconds.toString().padStart(2, '0'),\n ].join(':'),\n ].join('T'),\n );\n },\n}) */ Schema.String.pipe(\n FormatAnnotation.set(TypeFormat.DateTime),\n Schema.annotations({\n description: 'Valid date and time in ISO format',\n }),\n);\n\n/**\n * https://datatracker.ietf.org/doc/html/rfc3339#appendix-A\n */\n// TODO(burdon): Define duration type.\nexport const Duration = Schema.String.pipe(\n FormatAnnotation.set(TypeFormat.Duration),\n Schema.annotations({\n description: 'Duration in ISO 8601 format',\n [SchemaAST.ExamplesAnnotationId]: ['1h', '3D'],\n }),\n);\n\n//\n// Utils\n//\n\n// YYYY-MM-DD\nconst DATE_REGEX = /^\\d{4}-\\d{2}-\\d{2}$/;\n\nconst _isValidDateFormat = (str: string) => DATE_REGEX.test(str);\n\nconst _isValidDate = (str: string) => {\n const date = new Date(str);\n return !isNaN(date.getTime()) && date.toISOString().startsWith(str);\n};\n\n// HH:mm:ss\nconst TIME_REGEX = /^([01]\\d|2[0-3]):([0-5]\\d):([0-5]\\d)$/;\n\nconst _isValidTimeFormat = (str: string) => TIME_REGEX.test(str);\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport { FormatAnnotation, TypeFormat } from './types';\n\nconst encodeMultipleOf = (divisor: number) => 1 / Math.pow(10, divisor);\n\nconst encodeMultiple =\n <A extends number>(divisor?: number) =>\n <I, R>(self: Schema.Schema<A, I, R>) =>\n divisor === undefined || divisor === 0 ? self : self.pipe(Schema.multipleOf(encodeMultipleOf(divisor)));\n\n/**\n * Convert number of digits to multipleOf annotation.\n */\nexport const DecimalPrecision = Schema.transform(Schema.Number, Schema.Number, {\n strict: true,\n encode: (value) => encodeMultipleOf(value),\n decode: (value) => Math.log10(1 / value),\n}).annotations({\n title: 'Number of digits',\n});\n\nexport const CurrencyAnnotationId = Symbol.for('@dxos/schema/annotation/Currency');\n\nexport type CurrencyAnnotation = {\n decimals?: number;\n code?: string;\n};\n\n/**\n * ISO 4217 currency code.\n */\nexport const Currency = ({ decimals, code }: CurrencyAnnotation = { decimals: 2 }) =>\n Schema.Number.pipe(\n encodeMultiple(decimals),\n FormatAnnotation.set(TypeFormat.Currency),\n Schema.annotations({\n title: 'Currency',\n description: 'Currency value',\n ...(code ? { [CurrencyAnnotationId]: code.toUpperCase() } : {}),\n }),\n );\n\nexport type PercentAnnotation = {\n decimals?: number;\n};\n\n/**\n * Integer.\n */\nexport const Integer = () =>\n Schema.Number.pipe(\n Schema.int(),\n FormatAnnotation.set(TypeFormat.Integer),\n Schema.annotations({\n title: 'Integer',\n description: 'Integer value',\n }),\n );\n\n/**\n * Percent.\n */\n// TODO(burdon): Define min/max (e.g., 0, 1).\nexport const Percent = ({ decimals }: PercentAnnotation = { decimals: 2 }) =>\n Schema.Number.pipe(\n encodeMultiple(decimals),\n FormatAnnotation.set(TypeFormat.Percent),\n Schema.annotations({\n title: 'Percent',\n description: 'Percentage value',\n }),\n );\n\n/**\n * Unix timestamp.\n * https://en.wikipedia.org/wiki/Unix_time\n */\nexport const Timestamp = Schema.Number.pipe(\n FormatAnnotation.set(TypeFormat.Timestamp),\n Schema.annotations({\n title: 'Timestamp',\n description: 'Unix timestamp',\n }),\n);\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport { clamp } from '@dxos/util';\n\nimport { FormatAnnotation, TypeFormat } from './types';\n\n/**\n * GeoJSON Format\n * https://datatracker.ietf.org/doc/html/rfc7946\n * https://datatracker.ietf.org/doc/html/rfc7946#section-3.1.1\n * https://en.wikipedia.org/wiki/Geographic_coordinate_system\n * https://geojson.org\n * {\n * \"type\": \"Point\",\n * \"coordinates\": [0, 51.47] // [longitude, latitude]\n * }\n * Note: optional third element for altitude.\n */\n/** Decimal places retained for stored coordinates (~1.1cm at the equator). */\nexport const GEO_PRECISION = 7;\n\nconst roundCoordinate = (value: number): number => {\n const factor = 10 ** GEO_PRECISION;\n return Math.round(value * factor) / factor;\n};\n\n/** Longitude/latitude clamped to range and rounded to {@link GEO_PRECISION} decimal places. */\nconst Coordinate = (min: number, max: number, title: string) =>\n Schema.transform(Schema.Number.pipe(Schema.clamp(min, max)), Schema.Number, {\n strict: true,\n decode: roundCoordinate,\n encode: roundCoordinate,\n }).annotations({ title });\n\nexport const GeoPoint = Schema.Tuple(\n Coordinate(-180, 180, 'Longitude'),\n Coordinate(-90, 90, 'Latitude'),\n Schema.optionalElement(Schema.Number).annotations({\n title: 'Height ASL (m)',\n }),\n).pipe(\n FormatAnnotation.set(TypeFormat.GeoPoint),\n Schema.annotations({\n title: 'GeoPoint',\n description: 'GeoJSON Position',\n }),\n);\n\nexport type GeoPoint = Schema.Schema.Type<typeof GeoPoint>;\n\nexport type GeoLocation = {\n longitude: number;\n latitude: number;\n height?: number;\n};\n\n/**\n * Geolocation utilities for working with GeoPoint format.\n */\nexport namespace GeoLocation {\n /**\n * Convert latitude and longitude to GeoPoint (GeoJSON format [longitude, latitude, height?]).\n * Clamps values to valid ranges: latitude [-90, 90], longitude [-180, 180].\n */\n export const toGeoPoint = ({ longitude, latitude, height }: GeoLocation): GeoPoint => {\n // TODO(ZaymonFC): Use schema validation instead of doing this manually.\n // Clamp + round to match the `Format.GeoPoint` decode/encode path so both produce identical tuples.\n const clampedLongitude = roundCoordinate(clamp(longitude, -180, 180));\n const clampedLatitude = roundCoordinate(clamp(latitude, -90, 90));\n return height !== undefined ? [clampedLongitude, clampedLatitude, height] : [clampedLongitude, clampedLatitude];\n };\n\n /**\n * Extract latitude and longitude from GeoPoint (GeoJSON format [longitude, latitude, height?]).\n */\n export const fromGeoPoint = (geoPoint: GeoPoint | undefined): GeoLocation => {\n if (!geoPoint) {\n return { longitude: 0, latitude: 0 };\n }\n\n const result: GeoLocation = {\n longitude: geoPoint[0],\n latitude: geoPoint[1],\n };\n\n // Add height if defined.\n if (geoPoint[2] !== undefined) {\n result.height = geoPoint[2];\n }\n\n return result;\n };\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\nimport * as SchemaAST from 'effect/SchemaAST';\n\nimport { FormatAnnotation, TypeFormat } from './types';\n\n/**\n * Email address (RFC 5321)\n * https://datatracker.ietf.org/doc/html/rfc5321#section-4.1.2\n */\nexport const Email = Schema.String.pipe(\n Schema.pattern(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/),\n FormatAnnotation.set(TypeFormat.Email),\n Schema.annotations({\n title: 'Email',\n description: 'Email address',\n }),\n);\n\n/**\n *\n */\n// TODO(burdon): Implement.\nexport const Formula = Schema.String.pipe(FormatAnnotation.set(TypeFormat.Formula));\n\n/**\n *\n */\n// TODO(burdon): Implement.\nexport const Hostname = Schema.String.pipe(FormatAnnotation.set(TypeFormat.Hostname));\n\n/**\n * Regex\n * https://json-schema.org/understanding-json-schema/reference/regular_expressions\n * https://ecma-international.org/publications-and-standards/standards/ecma-262\n */\n// TODO(burdon): Implement.\nexport const Regex = Schema.String.pipe(FormatAnnotation.set(TypeFormat.Regex));\n\n/**\n * Multi-line text.\n */\nexport const Text = Schema.String.pipe(FormatAnnotation.set(TypeFormat.Text));\n\n/**\n * https://datatracker.ietf.org/doc/html/rfc3986#section-1.1.3\n */\nexport const URL = Schema.String.pipe(\n Schema.pattern(/^(\\w+?:\\/\\/)?([\\da-z.-]+)\\.([a-z.]{2,6})([/\\w .-]*)*\\/?$/i),\n FormatAnnotation.set(TypeFormat.URL),\n Schema.annotations({\n title: 'URL',\n description: 'URL',\n }),\n);\n\n/**\n * UUID (RFC 4122)\n * https://datatracker.ietf.org/doc/html/rfc4122\n */\nexport const UUID = Schema.UUID.pipe(\n FormatAnnotation.set(TypeFormat.UUID),\n Schema.annotations({\n [SchemaAST.ExamplesAnnotationId]: ['3e4666bf-d5e5-4aa7-b8ce-cefe41c7568a'],\n }),\n);\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport * as Keys from '@dxos/keys';\n\nimport * as DateUtil from './date';\nimport * as NumberUtil from './number';\nimport * as ObjectUtil from './object';\nimport * as StringUtil from './string';\nimport { TypeFormat as TypeFormat$ } from './types';\n\n// TODO(burdon): Media encoding.\n// - https://json-schema.org/understanding-json-schema/reference/non_json_data\n\n/**\n * Formats.\n * https://json-schema.org/understanding-json-schema/reference/string#built-in-formats\n * NOTE: A JSON Schema validator will ignore any format type that it does not understand.\n */\n// TODO(burdon): Add fields for `examples`, `message`, etc.\nexport namespace Format {\n export import TypeFormat = TypeFormat$;\n\n // String\n export const DXN = Keys.DXN.Schema;\n export const Email = StringUtil.Email;\n export const Formula = StringUtil.Formula;\n export const Hostname = StringUtil.Hostname;\n export const Regex = StringUtil.Regex;\n export const URL = StringUtil.URL;\n export const UUID = Schema.UUID;\n\n // Numbers\n // TODO(burdon): BigInt.\n export const Currency = NumberUtil.Currency;\n export const Integer = NumberUtil.Integer;\n export const Percent = NumberUtil.Percent;\n export const Timestamp = NumberUtil.Timestamp;\n\n // Dates and times\n export const Date = DateUtil.DateOnly;\n export const DateTime = DateUtil.DateTime;\n export const Duration = DateUtil.Duration;\n export const Time = DateUtil.TimeOnly;\n\n // Objects\n export const GeoPoint = ObjectUtil.GeoPoint;\n export type GeoPoint = ObjectUtil.GeoPoint; // TODO(burdon): Export types.\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\n/**\n * Schema for a single select option. Used to define choices in a {single|multi}-select field.\n */\nexport const SelectOption = Schema.Struct({\n /** Stable identifier for the option. */\n id: Schema.NonEmptyString,\n title: Schema.String,\n /** Color palette used for visual styling. */\n color: Schema.String,\n});\n\nexport type SelectOption = Schema.Schema.Type<typeof SelectOption>;\n"],
5
+ "mappings": ";;;;;AAIA,YAAYA,cAAc;AAE1B,YAAYC,YAAY;AACxB,YAAYC,eAAe;AAepB,IAAKC,WAAAA,0BAAAA,WAAAA;;;;;;;SAAAA;;AAUL,IAAMC,cAAc,CAACC,aAAAA;AAC1B,UAAQA,SAASC,MAAI;IACnB,KAAK;AACH,aAAA;IACF,KAAK;AACH,aAAA;IACF,KAAK;AACH,aAAA;IACF,KAAK;AACH,aAAA;IACF,KAAK;AACH,aAAA;IACF;AACE,aAAOC;EACX;AACF;AAMO,IAAMC,qBAAqBC,uBAAOC,IAAI,gCAAA;AAEtC,IAAMC,mBAAmBC,uBAAmCJ,kBAAAA;AAG5D,IAAMK,sBAAsB,CAACC,SACzBC,cAAeC,wBAA0BR,kBAAAA,EAAoBM,IAAAA,GAAcG,qBAAc;AAG7F,IAAKC,aAAAA,0BAAAA,aAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;SAAAA;;AAwDL,IAAMC,cAAcC,OAAOC,OAAOH,UAAAA,EAAYI,KAAI;AAElD,IAAMC,eAAe;EAC1BjB,MAAMH;EACNqB,QAAQN;AACV;AAKO,IAAMO,eAAsD;EACjE,CAAA,QAAA,GAAiB;EACjB,CAAA,QAAA,GAAiB;EACjB,CAAA,SAAA,GAAkB;AACpB;AAKO,IAAMC,eAA6C;EACxD,CAAA,MAAA,GAAiB;EACjB,CAAA,QAAA,GAAmB;EACnB,CAAA,QAAA,GAAmB;EACnB,CAAA,SAAA,GAAoB;EACpB,CAAA,KAAA,GAAgB;EAGhB,CAAA,KAAA,GAAgB;EAChB,CAAA,KAAA,GAAgB;EAChB,CAAA,OAAA,GAAkB;EAClB,CAAA,SAAA,GAAoB;EACpB,CAAA,UAAA,GAAqB;EACrB,CAAA,MAAA,GAAiB;EACjB,CAAA,UAAA,GAAqB;EACrB,CAAA,UAAA,GAAqB;EACrB,CAAA,OAAA,G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AOC,KAAKE,iBAAiBC,IAAIC,WAAWO,IAAI,CAAA;AAKpE,IAAMC,MAAab,eAAOC,KACxBC,gBAAQ,2DAAA,GACfC,iBAAiBC,IAAIC,WAAWQ,GAAG,GAC5BP,oBAAY;EACjBC,OAAO;EACPC,aAAa;AACf,CAAA,CAAA;AAOK,IAAMM,QAAcA,aAAKb,KAC9BE,iBAAiBC,IAAIC,WAAWS,IAAI,GAC7BR,oBAAY;EACjB,CAAWS,+BAAoB,GAAG;IAAC;;AACrC,CAAA,CAAA;;;AC/DF,YAAYC,aAAY;AAExB,YAAYC,UAAU;UAiBLC,SAAAA;UACDC,aAAa;UAGdC,MAAWA,SAAIC;UACfC,QAAmBA;UACnBC,UAAqBA;UACrBC,WAAsBA;UACtBC,QAAmBA;UACnBC,MAAiBA;UACjBC,OAAcA;UAIdC,WAAsBA;UACtBC,UAAqBA;UACrBC,UAAqBA;UACrBC,YAAuBA;UAGvBC,OAAgBC;UAChBC,WAAoBA;UACpBC,WAAoBA;UACpBC,OAAgBC;UAGhBC,WAAsBA;AAErC,GA5BiBpB,WAAAA,SAAAA,CAAAA,EAAAA;;;;ACnBjB,YAAYqB,aAAY;AAKjB,IAAMC,eAAsBC,eAAO;;EAExCC,IAAWC;EACXC,OAAcC;;EAEdC,OAAcD;AAChB,CAAA;",
6
+ "names": ["Function", "Option", "SchemaAST", "TypeEnum", "getTypeEnum", "property", "type", "undefined", "FormatAnnotationId", "Symbol", "for", "FormatAnnotation", "createAnnotationHelper", "getFormatAnnotation", "node", "pipe", "getAnnotation", "getOrUndefined", "TypeFormat", "FormatEnums", "Object", "values", "sort", "PropertyKind", "format", "typeToFormat", "formatToType", "OptionsAnnotationId", "OptionsAnnotation", "getOptionsAnnotation", "Schema", "SchemaAST", "SimpleDate", "Struct", "year", "Number", "pipe", "between", "month", "day", "toSimpleDate", "date", "getUTCFullYear", "getUTCMonth", "getUTCDate", "SimpleTime", "hours", "minutes", "seconds", "toSimpleTime", "getUTCHours", "getUTCSeconds", "SimpleDateTime", "extend", "toSimpleDateTime", "DateOnly", "String", "FormatAnnotation", "set", "TypeFormat", "Date", "annotations", "description", "TimeOnly", "Time", "DateTime", "Duration", "ExamplesAnnotationId", "Schema", "encodeMultipleOf", "divisor", "Math", "pow", "encodeMultiple", "self", "undefined", "pipe", "multipleOf", "DecimalPrecision", "transform", "Number", "strict", "encode", "value", "decode", "log10", "annotations", "title", "CurrencyAnnotationId", "Symbol", "for", "Currency", "decimals", "code", "FormatAnnotation", "set", "TypeFormat", "description", "toUpperCase", "Integer", "int", "Percent", "Timestamp", "Schema", "clamp", "GEO_PRECISION", "roundCoordinate", "value", "factor", "Math", "round", "Coordinate", "min", "max", "title", "transform", "Number", "pipe", "clamp", "strict", "decode", "encode", "annotations", "GeoPoint", "Tuple", "optionalElement", "FormatAnnotation", "set", "TypeFormat", "description", "GeoLocation", "toGeoPoint", "longitude", "latitude", "height", "clampedLongitude", "clampedLatitude", "undefined", "fromGeoPoint", "geoPoint", "result", "Schema", "SchemaAST", "Email", "String", "pipe", "pattern", "FormatAnnotation", "set", "TypeFormat", "annotations", "title", "description", "Formula", "Hostname", "Regex", "Text", "URL", "UUID", "ExamplesAnnotationId", "Schema", "Keys", "Format", "TypeFormat", "DXN", "Schema", "Email", "Formula", "Hostname", "Regex", "URL", "UUID", "Currency", "Integer", "Percent", "Timestamp", "Date", "DateOnly", "DateTime", "Duration", "Time", "TimeOnly", "GeoPoint", "Schema", "SelectOption", "Struct", "id", "NonEmptyString", "title", "String", "color"]
7
+ }
@@ -1,13 +1,155 @@
1
1
  import {
2
+ ObjectDeletedId,
2
3
  ReferenceAnnotationId,
3
4
  Service,
4
5
  getSchemaURI,
5
6
  getTypeAnnotation,
6
7
  getTypeIdentifierAnnotation
7
- } from "./chunk-WZ32BF53.mjs";
8
+ } from "./chunk-3TN2VMI4.mjs";
8
9
  import {
9
10
  getStaticTypeSchema
10
- } from "./chunk-O6BH7EPN.mjs";
11
+ } from "./chunk-2ZHECXUR.mjs";
12
+
13
+ // src/internal/common/proxy/proxy-utils.ts
14
+ import { invariant } from "@dxos/invariant";
15
+ var __dxlog_file = "/__w/dxos/dxos/packages/core/echo/echo/src/internal/common/proxy/proxy-utils.ts";
16
+ var symbolIsProxy = /* @__PURE__ */ Symbol.for("@dxos/schema/Proxy");
17
+ var symbolReactivePrototype = /* @__PURE__ */ Symbol.for("@dxos/echo/ReactivePrototype");
18
+ var isProxy = (value) => !!value?.[symbolIsProxy];
19
+ var isReactiveRecord = (value) => {
20
+ const proto = Object.getPrototypeOf(value);
21
+ return proto === Object.prototype || proto != null && !!proto[symbolReactivePrototype];
22
+ };
23
+ var isValidProxyTarget = (value) => {
24
+ if (value == null || value[symbolIsProxy]) {
25
+ return false;
26
+ }
27
+ if (Array.isArray(value)) {
28
+ return true;
29
+ }
30
+ return typeof value === "object" && isReactiveRecord(value);
31
+ };
32
+ var getProxySlot = (proxy) => {
33
+ const value = proxy[symbolIsProxy];
34
+ invariant(value instanceof ProxyHandlerSlot, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 37, S: void 0, A: ["value instanceof ProxyHandlerSlot", ""] });
35
+ return value;
36
+ };
37
+ var getProxyTarget = (proxy) => {
38
+ return getProxySlot(proxy).target;
39
+ };
40
+ var getProxyHandler = (proxy) => {
41
+ return getProxySlot(proxy).handler;
42
+ };
43
+ var normalizeSpliceRange = (length, start, deleteCount) => {
44
+ const safeStart = start < 0 ? Math.max(length + start, 0) : Math.min(start, length);
45
+ const safeDeleteCount = Math.max(0, Math.min(deleteCount, length - safeStart));
46
+ return {
47
+ start: safeStart,
48
+ deleteCount: safeDeleteCount
49
+ };
50
+ };
51
+ var dangerouslySetProxyId = (obj, id) => {
52
+ getProxySlot(obj).target.id = id;
53
+ };
54
+ var createProxy = (target, handler) => {
55
+ const existingProxy = handler._proxyMap.get(target);
56
+ if (existingProxy) {
57
+ return existingProxy;
58
+ }
59
+ const proxy = new Proxy(target, new ProxyHandlerSlot(target, handler));
60
+ handler.init(target);
61
+ handler._proxyMap.set(target, proxy);
62
+ return proxy;
63
+ };
64
+ var ProxyHandlerSlot = class {
65
+ target;
66
+ _handler;
67
+ /**
68
+ * @param target Original object.
69
+ * @param _handler Handles intercepted operations.
70
+ */
71
+ constructor(target, _handler) {
72
+ this.target = target;
73
+ this._handler = _handler;
74
+ }
75
+ get handler() {
76
+ invariant(this._handler, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 100, S: this, A: ["this._handler", ""] });
77
+ return this._handler;
78
+ }
79
+ // TODO(burdon): Requires comment.
80
+ setHandler(handler) {
81
+ this._handler = handler;
82
+ }
83
+ /**
84
+ * Get value.
85
+ */
86
+ get(target, prop, receiver) {
87
+ if (prop === symbolIsProxy) {
88
+ return this;
89
+ }
90
+ if (!this._handler || !this._handler.get) {
91
+ return Reflect.get(target, prop, receiver);
92
+ }
93
+ return this._handler.get(target, prop, receiver);
94
+ }
95
+ static {
96
+ const TRAPS = [
97
+ "apply",
98
+ "construct",
99
+ "defineProperty",
100
+ "deleteProperty",
101
+ "get",
102
+ "getOwnPropertyDescriptor",
103
+ "getPrototypeOf",
104
+ "has",
105
+ "isExtensible",
106
+ "ownKeys",
107
+ "preventExtensions",
108
+ "set",
109
+ "setPrototypeOf"
110
+ ];
111
+ for (const trap of TRAPS) {
112
+ if (trap === "get") {
113
+ continue;
114
+ }
115
+ Object.defineProperty(this.prototype, trap, {
116
+ enumerable: false,
117
+ value: function(...args) {
118
+ if (!this._handler || !this._handler[trap]) {
119
+ return Reflect[trap](...args);
120
+ }
121
+ return this._handler[trap].apply(this._handler, args);
122
+ }
123
+ });
124
+ }
125
+ }
126
+ };
127
+
128
+ // src/internal/common/proxy/symbols.ts
129
+ var EventId = /* @__PURE__ */ Symbol.for("@dxos/live-object/EventId");
130
+ var ChangeId = /* @__PURE__ */ Symbol.for("@dxos/live-object/ChangeId");
131
+
132
+ // src/internal/common/proxy/reactive.ts
133
+ var subscribe = (obj, callback) => {
134
+ if (!isProxy(obj)) {
135
+ return () => {
136
+ };
137
+ }
138
+ const target = getProxyTarget(obj);
139
+ if (target && EventId in target) {
140
+ return target[EventId].on(callback);
141
+ }
142
+ return () => {
143
+ };
144
+ };
145
+ var change = (obj, callback) => {
146
+ const changeFn = obj[ChangeId];
147
+ if (changeFn) {
148
+ changeFn(callback);
149
+ } else {
150
+ callback(obj);
151
+ }
152
+ };
11
153
 
12
154
  // src/internal/Ref/ref.ts
13
155
  import * as Effect from "effect/Effect";
@@ -21,7 +163,7 @@ import * as SchemaAST from "effect/SchemaAST";
21
163
  import { Event } from "@dxos/async";
22
164
  import { inspectCustom } from "@dxos/debug";
23
165
  import { EncodedReference } from "@dxos/echo-protocol";
24
- import { assertArgument, invariant } from "@dxos/invariant";
166
+ import { assertArgument, invariant as invariant2 } from "@dxos/invariant";
25
167
  import { DXN, EID, EntityId } from "@dxos/keys";
26
168
 
27
169
  // src/internal/Ref/atoms.ts
@@ -50,12 +192,25 @@ var loadRefTarget = (ref, get, onTargetAvailable) => {
50
192
  // src/internal/Ref/atoms.ts
51
193
  var refSimpleFamily = Atom.family((ref) => {
52
194
  return Atom.make((get) => {
53
- return loadRefTarget(ref, get, (target) => target);
195
+ let unsubscribeTarget;
196
+ const setupSubscription = (target) => {
197
+ unsubscribeTarget?.();
198
+ unsubscribeTarget = subscribe(target, () => {
199
+ const deleted2 = !!target[ObjectDeletedId];
200
+ get.setSelf(deleted2 ? void 0 : target);
201
+ });
202
+ const deleted = !!target[ObjectDeletedId];
203
+ return deleted ? void 0 : target;
204
+ };
205
+ get.addFinalizer(() => {
206
+ unsubscribeTarget?.();
207
+ });
208
+ return loadRefTarget(ref, get, setupSubscription);
54
209
  });
55
210
  });
56
211
 
57
212
  // src/internal/Ref/ref.ts
58
- var __dxlog_file = "/__w/dxos/dxos/packages/core/echo/echo/src/internal/Ref/ref.ts";
213
+ var __dxlog_file2 = "/__w/dxos/dxos/packages/core/echo/echo/src/internal/Ref/ref.ts";
59
214
  var JSON_SCHEMA_ECHO_REF_ID = "/schemas/echo/ref";
60
215
  var getSchemaReference = (property) => {
61
216
  const { $id, reference: { schema: { $ref } = {} } = {} } = property;
@@ -114,7 +269,7 @@ Ref.make = (obj) => {
114
269
  throw new TypeError("Expected: ECHO object.");
115
270
  }
116
271
  const id = obj.id;
117
- invariant(EntityId.isValid(id), "Invalid object ID", { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 87, S: void 0, A: ["EntityId.isValid(id)", "'Invalid object ID'"] });
272
+ invariant2(EntityId.isValid(id), "Invalid object ID", { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 87, S: void 0, A: ["EntityId.isValid(id)", "'Invalid object ID'"] });
118
273
  const uri = EID.make({
119
274
  entityId: id
120
275
  });
@@ -190,14 +345,15 @@ var makeSettledRequest = (state, result) => ({
190
345
  }
191
346
  });
192
347
  var RefImpl = class _RefImpl {
348
+ [RefTypeId] = refVariance;
193
349
  #uri;
194
- #resolver = void 0;
195
- #resolved = new Event();
196
350
  /**
197
351
  * Target is set when the reference is created from a specific object.
198
352
  * In this case, the target might not be in the database.
199
353
  */
200
354
  #target = void 0;
355
+ #resolver = void 0;
356
+ #resolved = new Event();
201
357
  /**
202
358
  * Callback to issue a reactive notification when object is resolved.
203
359
  */
@@ -217,27 +373,30 @@ var RefImpl = class _RefImpl {
217
373
  /**
218
374
  * @inheritdoc
219
375
  */
220
- get isAvailable() {
221
- return this.#target !== void 0 || this.#resolver !== void 0;
222
- }
223
- /**
224
- * @inheritdoc
225
- */
226
376
  get target() {
227
377
  if (this.#target) {
228
378
  return this.#target;
229
379
  }
230
- invariant(this.#resolver, "Resolver is not set", { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 205, S: this, A: ["this.#resolver", "'Resolver is not set'"] });
380
+ invariant2(this.#resolver, "Resolver is not set", { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 201, S: this, A: ["this.#resolver", "'Resolver is not set'"] });
231
381
  return this.#resolver.resolveSync(this.#uri, true, this.#resolverCallback);
232
382
  }
233
383
  /**
234
384
  * @inheritdoc
235
385
  */
386
+ get isAvailable() {
387
+ return this.#target !== void 0 || this.#resolver !== void 0;
388
+ }
389
+ get atom() {
390
+ return refSimpleFamily(this);
391
+ }
392
+ /**
393
+ * @inheritdoc
394
+ */
236
395
  async load() {
237
396
  if (this.#target) {
238
397
  return this.#target;
239
398
  }
240
- invariant(this.#resolver, "Resolver is not set", { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 214, S: this, A: ["this.#resolver", "'Resolver is not set'"] });
399
+ invariant2(this.#resolver, "Resolver is not set", { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 218, S: this, A: ["this.#resolver", "'Resolver is not set'"] });
241
400
  const obj = await this.#resolver.resolveLegacy(this.#uri);
242
401
  if (obj == null) {
243
402
  throw new Error("Object not found");
@@ -251,7 +410,7 @@ var RefImpl = class _RefImpl {
251
410
  if (this.#target) {
252
411
  return this.#target;
253
412
  }
254
- invariant(this.#resolver, "Resolver is not set", { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 227, S: this, A: ["this.#resolver", "'Resolver is not set'"] });
413
+ invariant2(this.#resolver, "Resolver is not set", { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 231, S: this, A: ["this.#resolver", "'Resolver is not set'"] });
255
414
  return await this.#resolver.resolveLegacy(this.#uri);
256
415
  }
257
416
  /**
@@ -296,7 +455,6 @@ var RefImpl = class _RefImpl {
296
455
  [inspectCustom] = (depth, options, inspect) => {
297
456
  return this.toString();
298
457
  };
299
- [RefTypeId] = refVariance;
300
458
  /**
301
459
  * Effect Hash trait. Required for MutableHashMap-based caches (e.g., Atom.family)
302
460
  * to deduplicate Ref instances that point to the same object.
@@ -310,12 +468,10 @@ var RefImpl = class _RefImpl {
310
468
  [Equal.symbol](that) {
311
469
  return that instanceof _RefImpl && this.#uri === that.uri;
312
470
  }
313
- get atom() {
314
- return refSimpleFamily(this);
471
+ pipe() {
472
+ return Pipeable.pipeArguments(this, arguments);
315
473
  }
316
474
  /**
317
- * Internal method to set the resolver.
318
- *
319
475
  * @internal
320
476
  */
321
477
  _setResolver(resolver) {
@@ -327,16 +483,13 @@ var RefImpl = class _RefImpl {
327
483
  _getSavedTarget() {
328
484
  return this.#target;
329
485
  }
330
- pipe() {
331
- return Pipeable.pipeArguments(this, arguments);
332
- }
333
486
  };
334
487
  var setRefResolver = (ref, resolver) => {
335
- invariant(ref instanceof RefImpl, "Ref is not an instance of RefImpl", { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 304, S: void 0, A: ["ref instanceof RefImpl", "'Ref is not an instance of RefImpl'"] });
488
+ invariant2(ref instanceof RefImpl, "Ref is not an instance of RefImpl", { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 302, S: void 0, A: ["ref instanceof RefImpl", "'Ref is not an instance of RefImpl'"] });
336
489
  ref._setResolver(resolver);
337
490
  };
338
491
  var getRefSavedTarget = (ref) => {
339
- invariant(ref instanceof RefImpl, "Ref is not an instance of RefImpl", { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 310, S: void 0, A: ["ref instanceof RefImpl", "'Ref is not an instance of RefImpl'"] });
492
+ invariant2(ref instanceof RefImpl, "Ref is not an instance of RefImpl", { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 308, S: void 0, A: ["ref instanceof RefImpl", "'Ref is not an instance of RefImpl'"] });
340
493
  return ref._getSavedTarget();
341
494
  };
342
495
  var refVariance = {
@@ -359,9 +512,9 @@ var StaticRefResolver = class {
359
512
  }
360
513
  addSchema(input) {
361
514
  const schema = getStaticTypeSchema(input);
362
- invariant(schema, "Type entity is missing its source schema", { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 335, S: this, A: ["schema", "'Type entity is missing its source schema'"] });
515
+ invariant2(schema, "Type entity is missing its source schema", { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 333, S: this, A: ["schema", "'Type entity is missing its source schema'"] });
363
516
  const uri = getSchemaURI(schema);
364
- invariant(uri, "Schema has no URI", { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 337, S: this, A: ["uri", "'Schema has no URI'"] });
517
+ invariant2(uri, "Schema has no URI", { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 335, S: this, A: ["uri", "'Schema has no URI'"] });
365
518
  this.schemas.set(uri, schema);
366
519
  return this;
367
520
  }
@@ -389,6 +542,21 @@ var StaticRefResolver = class {
389
542
  };
390
543
 
391
544
  export {
545
+ symbolIsProxy,
546
+ symbolReactivePrototype,
547
+ isProxy,
548
+ isReactiveRecord,
549
+ isValidProxyTarget,
550
+ getProxySlot,
551
+ getProxyTarget,
552
+ getProxyHandler,
553
+ normalizeSpliceRange,
554
+ dangerouslySetProxyId,
555
+ createProxy,
556
+ EventId,
557
+ ChangeId,
558
+ subscribe,
559
+ change,
392
560
  loadRefTarget,
393
561
  JSON_SCHEMA_ECHO_REF_ID,
394
562
  getSchemaReference,
@@ -404,4 +572,4 @@ export {
404
572
  refFromEncodedReference,
405
573
  StaticRefResolver
406
574
  };
407
- //# sourceMappingURL=chunk-4TPQZPLY.mjs.map
575
+ //# sourceMappingURL=chunk-L3E5IXAE.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/internal/common/proxy/proxy-utils.ts", "../../../src/internal/common/proxy/symbols.ts", "../../../src/internal/common/proxy/reactive.ts", "../../../src/internal/Ref/ref.ts", "../../../src/internal/Ref/atoms.ts", "../../../src/internal/Ref/utils.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { invariant } from '@dxos/invariant';\n\nimport { type ReactiveHandler } from './proxy-types';\n\nexport const symbolIsProxy = Symbol.for('@dxos/schema/Proxy');\n\n/**\n * Marker placed on a reactive-object behaviour prototype (e.g. the typed handler's\n * `TypedObject` prototype). A record target whose prototype chain carries this marker\n * is a reactive data record — equivalent, for the purposes of the \"plain object\" gates\n * below, to one rooted directly at `Object.prototype`. This lets a handler move its\n * per-object metadata onto an intermediate prototype without those gates mistaking the\n * record for a foreign class instance.\n */\nexport const symbolReactivePrototype = Symbol.for('@dxos/echo/ReactivePrototype');\n\n/**\n * Internal api.\n */\nexport const isProxy = (value: unknown) => !!(value as any)?.[symbolIsProxy];\n\n/**\n * True if `value` is a plain data record — either rooted at `Object.prototype` or carrying\n * a reactive behaviour prototype (see {@link symbolReactivePrototype}).\n */\nexport const isReactiveRecord = (value: any): boolean => {\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || (proto != null && !!proto[symbolReactivePrototype]);\n};\n\nexport const isValidProxyTarget = (value: any): value is object => {\n if (value == null || value[symbolIsProxy]) {\n return false;\n }\n if (Array.isArray(value)) {\n return true;\n }\n\n return typeof value === 'object' && isReactiveRecord(value);\n};\n\n/**\n * @deprecated\n */\nexport const getProxySlot = <T extends object>(proxy: any): ProxyHandlerSlot<T> => {\n const value = (proxy as any)[symbolIsProxy];\n invariant(value instanceof ProxyHandlerSlot);\n return value;\n};\n\nexport const getProxyTarget = <T extends object>(proxy: any): T => {\n return getProxySlot<T>(proxy).target;\n};\n\nexport const getProxyHandler = <T extends object>(proxy: any): ReactiveHandler<T> => {\n return getProxySlot<T>(proxy).handler;\n};\n\n/**\n * Clamp a splice range to `Array.prototype.splice` semantics for a string of the given `length`:\n * a negative `start` counts from the end, a `start` past the end appends, and `deleteCount` is bounded\n * to the remaining characters. Shared by both reactive handlers so the string CRDT API behaves\n * identically across the in-memory and Automerge backends (Automerge's `splice` otherwise throws on\n * out-of-range indices).\n */\nexport const normalizeSpliceRange = (\n length: number,\n start: number,\n deleteCount: number,\n): { start: number; deleteCount: number } => {\n const safeStart = start < 0 ? Math.max(length + start, 0) : Math.min(start, length);\n const safeDeleteCount = Math.max(0, Math.min(deleteCount, length - safeStart));\n return { start: safeStart, deleteCount: safeDeleteCount };\n};\n\n/**\n * Unsafe method to override id for debugging/testing and migration purposes.\n * @deprecated\n */\nexport const dangerouslySetProxyId = <T>(obj: T, id: string) => {\n (getProxySlot(obj).target as any).id = id;\n};\n\n/**\n * Create a reactive proxy object.\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy\n *\n * @param target Object or array. Passing in array will enable array methods.\n * @param handler ReactiveHandler instance.\n */\n// TODO(burdon): Document.\n// TODO(burdon): Tests for low-level functions.\nexport const createProxy = <T extends object>(target: T, handler: ReactiveHandler<T>): T => {\n const existingProxy = handler._proxyMap.get(target);\n if (existingProxy) {\n return existingProxy;\n }\n\n // TODO(dmaretskyi): In the future this should be mutable to allow replacing the handler on-the-fly while maintaining the proxy identity.\n const proxy = new Proxy(target, new ProxyHandlerSlot<T>(target, handler));\n handler.init(target);\n\n // TODO(dmaretskyi): Check if this will actually work; maybe a global WeakMap is better?\n handler._proxyMap.set(target, proxy);\n return proxy;\n};\n\n/**\n * Passed as the handler to the Proxy constructor.\n * Maintains a mutable slot for the actual handler.\n */\nclass ProxyHandlerSlot<T extends object> implements ProxyHandler<T> {\n /**\n * @param target Original object.\n * @param _handler Handles intercepted operations.\n */\n constructor(\n readonly target: T,\n private _handler: ReactiveHandler<T>,\n ) {}\n\n get handler() {\n invariant(this._handler);\n return this._handler;\n }\n\n // TODO(burdon): Requires comment.\n setHandler(handler: ReactiveHandler<T>): void {\n this._handler = handler;\n }\n\n /**\n * Get value.\n */\n get(target: T, prop: string | symbol, receiver: any): any {\n if (prop === symbolIsProxy) {\n return this;\n }\n\n if (!this._handler || !this._handler.get) {\n return Reflect.get(target, prop, receiver);\n }\n\n return this._handler.get(target, prop, receiver);\n }\n\n static {\n const TRAPS: (keyof ProxyHandler<any>)[] = [\n 'apply',\n 'construct',\n 'defineProperty',\n 'deleteProperty',\n 'get',\n 'getOwnPropertyDescriptor',\n 'getPrototypeOf',\n 'has',\n 'isExtensible',\n 'ownKeys',\n 'preventExtensions',\n 'set',\n 'setPrototypeOf',\n ];\n\n for (const trap of TRAPS) {\n if (trap === 'get') {\n continue;\n }\n\n Object.defineProperty(this.prototype, trap, {\n enumerable: false,\n value: function (this: ProxyHandlerSlot<any>, ...args: any[]) {\n // log.info('trap', { trap, args });\n if (!this._handler || !this._handler[trap]) {\n return (Reflect[trap] as Function)(...args);\n }\n\n return (this._handler[trap] as Function).apply(this._handler, args);\n },\n });\n }\n }\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\n// TODO(dmaretskyi): Rename all symbols that are props to end with *Key.\nexport const EventId = Symbol.for('@dxos/live-object/EventId');\nexport const ChangeId = Symbol.for('@dxos/live-object/ChangeId');\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { type RefTypeId } from '../../Ref/ref';\nimport { getProxyTarget, isProxy } from './proxy-utils';\nimport { ChangeId, EventId } from './symbols';\n\n/**\n * Subscribe to changes on a reactive object.\n * @param obj - The reactive object to subscribe to.\n * @param callback - Called when the object changes.\n * @returns Unsubscribe function.\n */\n// TODO(wittjosiah): Consider throwing if obj doesn't have EventId instead of returning no-op.\nexport const subscribe = (obj: unknown, callback: () => void): (() => void) => {\n // Guard against non-reactive inputs (queue-stored typed objects, snapshots, plain shapes\n // with branded symbols) before `getProxyTarget`'s `ProxyHandlerSlot` invariant kicks in.\n // `Obj.isObject` (KindId-based) is satisfied by these inputs, so callers like\n // `Atom.family((obj) => Atom.make((get) => Obj.subscribe(obj, ...)))` legitimately reach\n // here with a non-proxy. Falling back to a no-op preserves the documented contract that\n // values without subscription support get a no-op unsubscribe.\n if (!isProxy(obj)) {\n return () => {};\n }\n const target = getProxyTarget(obj as any);\n if (target && EventId in target) {\n return (target as any)[EventId].on(callback);\n }\n return () => {};\n};\n\n/**\n * Deeply removes readonly modifiers from all properties of T.\n * Inside Obj.update, all properties are fully mutable regardless of schema definition.\n * Ref types are preserved as-is since they are value-like objects that are replaced, not mutated.\n * Primitive types (including branded primitives) are preserved as-is.\n */\nexport type Mutable<T> = T extends string | number | boolean | bigint | symbol | null | undefined\n ? T // Primitives (including branded primitives like JsonPath) stay as-is.\n : T extends { [RefTypeId]: any }\n ? T // Keep Ref types as-is (they're value-like, not mutated in place).\n : T extends object\n ? T extends readonly (infer U)[]\n ? Mutable<U>[]\n : { -readonly [K in keyof T]: Mutable<T[K]> }\n : T;\n\n/**\n * Callback type for the change function.\n */\nexport type ChangeCallback<T> = (mutableObj: Mutable<T>) => void;\n\n/**\n * Perform mutations on a reactive object within a change context.\n *\n * If the object has a change handler (via ChangeId), it will be called with the callback.\n * This allows handlers to implement features like:\n * - Readonly enforcement (mutations only allowed within change context)\n * - Batched notifications (single notification for all mutations in the callback)\n * - Transaction semantics\n *\n * If the object doesn't have a change handler, the callback is called directly.\n *\n * @param obj - The reactive object to mutate.\n * @param callback - Callback that receives a mutable view of the object.\n */\nexport const change = <T>(obj: T, callback: ChangeCallback<T>): void => {\n // Check proxy first (allows handler to intercept), then fall back to target.\n // This order is important for EchoReactiveHandler which handles ChangeId in the proxy trap.\n const changeFn = (obj as any)[ChangeId];\n if (changeFn) {\n changeFn(callback);\n } else {\n callback(obj as Mutable<T>);\n }\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport type * as Atom from '@effect-atom/atom/Atom';\nimport * as Effect from 'effect/Effect';\nimport * as Equal from 'effect/Equal';\nimport * as Hash from 'effect/Hash';\nimport * as Option from 'effect/Option';\nimport * as ParseResult from 'effect/ParseResult';\nimport * as Pipeable from 'effect/Pipeable';\nimport * as Schema from 'effect/Schema';\nimport * as SchemaAST from 'effect/SchemaAST';\nimport type * as Types from 'effect/Types';\n\nimport { Event } from '@dxos/async';\nimport { type CustomInspectFunction, inspectCustom } from '@dxos/debug';\nimport { EncodedReference } from '@dxos/echo-protocol';\nimport { assertArgument, invariant } from '@dxos/invariant';\nimport { DXN, EID, EntityId, type URI } from '@dxos/keys';\n\nimport * as Database from '../../Database';\nimport type * as Type from '../../Type';\nimport {\n ReferenceAnnotationId,\n getSchemaURI,\n getTypeAnnotation,\n getTypeIdentifierAnnotation,\n} from '../Annotation/annotations';\nimport { type AnyEntity, type AnyProperties, type UnknownTypeSchema, getStaticTypeSchema } from '../common/types';\nimport { type JsonSchemaType } from '../JsonSchema';\nimport * as RefAtoms from './atoms';\n\n/**\n * The `$id` and `$ref` fields for an ECHO reference schema.\n */\nexport const JSON_SCHEMA_ECHO_REF_ID = '/schemas/echo/ref';\n\nexport const getSchemaReference = (property: JsonSchemaType): { typename: string } | undefined => {\n const { $id, reference: { schema: { $ref } = {} } = {} } = property;\n if ($id === JSON_SCHEMA_ECHO_REF_ID && $ref) {\n const parsed = DXN.tryMake($ref);\n const typename = parsed ? DXN.getName(parsed) : undefined;\n return typename ? { typename } : undefined;\n }\n};\n\nexport const createSchemaReference = (typename: string): Types.DeepMutable<JsonSchemaType> => {\n return {\n $id: JSON_SCHEMA_ECHO_REF_ID,\n reference: {\n schema: {\n $ref: DXN.make(typename),\n },\n },\n };\n};\n\n/**\n * Runtime type-info for a reference extracted from effect AST.\n */\nexport type RefereneAST = {\n /**\n * Typename of linked schema.\n */\n typename: string;\n\n /**\n * Version of linked schema.\n */\n version: string;\n};\n\nexport const getReferenceAst = (ast: SchemaAST.AST): RefereneAST | undefined => {\n if (ast._tag !== 'Declaration' || !ast.annotations[ReferenceAnnotationId]) {\n return undefined;\n }\n return {\n typename: (ast.annotations[ReferenceAnnotationId] as any).typename,\n version: (ast.annotations[ReferenceAnnotationId] as any).version,\n };\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const RefTypeId: unique symbol = Symbol.for('@dxos/echo/internal/Ref') as any;\n\n/**\n * Reference Schema.\n */\nexport interface RefSchema<T extends AnyEntity> extends Schema.SchemaClass<Ref<T>, EncodedReference> {}\n\n/**\n * Type of the `Ref` function and extra methods attached to it.\n */\nexport interface RefFn {\n // A reference target is a `Type.AnyEntity` entity (the canonical Option B\n // input) or one of the well-known \"any object\" / \"any relation\" branded\n // schemas (`Obj.Unknown` / `Relation.Unknown`). Arbitrary raw schemas are\n // rejected.\n //\n // Referencing a type-kind entity (a meta-schema, e.g. `Type.Type`) yields a\n // reference to a stored schema record; its loaded target is any registered\n // entity (`Type.AnyEntity`), since a stored object/relation schema is itself a\n // `Type.Type` record. Referencing an object/relation type yields a reference\n // to an instance of that type.\n <S extends Type.AnyEntity | UnknownTypeSchema<any, any> = Type.AnyEntity>(\n schema: S,\n ): RefSchema<\n S extends Type.AnyType\n ? Type.AnyEntity\n : S extends Type.AnyObj | Type.AnyRelation\n ? Type.InstanceType<S>\n : S extends UnknownTypeSchema<infer A, any>\n ? A\n : never\n >;\n\n /**\n * @returns True if the object is a reference.\n */\n isRef: (obj: unknown) => obj is Ref<any>;\n\n /**\n * @returns True if the reference points to the given object id.\n */\n hasEntityId: (id: EntityId) => (ref: Ref<any>) => boolean;\n\n /**\n * @returns True if the schema is a reference schema.\n */\n isRefSchema: (schema: Schema.Schema<any, any>) => schema is RefSchema<any>;\n\n /**\n * @returns True if the schema AST is a reference schema.\n */\n isRefSchemaAST: (ast: SchemaAST.AST) => boolean;\n\n /**\n * Constructs a reference that points to the given object.\n */\n // TODO(burdon): Narrow to Obj.Unknown?\n make: <T extends AnyEntity>(object: T) => Ref<T>;\n\n /**\n * Constructs a reference that points to the object specified by the provided URI\n * (either an `echo:` EID for an object reference or a `dxn:` DXN for a type reference).\n */\n fromURI: (uri: URI.URI) => Ref<any>;\n}\n\n/**\n * Schema builder for references.\n */\nexport const Ref: RefFn = (input: any): RefSchema<any> => {\n // `Type.Type` entities carry their source schema on the hidden slot; the\n // branded `Obj.Unknown` / `Relation.Unknown` schemas are used directly.\n const schema = getStaticTypeSchema(input) ?? input;\n assertArgument(Schema.isSchema(schema), 'schema', 'Must call with an instance of effect-schema');\n const annotation = getTypeAnnotation(schema);\n if (annotation == null) {\n throw new Error('Reference target must be an ECHO schema.');\n }\n\n return createEchoReferenceSchema(getTypeIdentifierAnnotation(schema), annotation.typename, annotation.version);\n};\n\n/**\n * Represents materialized reference to a target.\n * This is the data type for the fields marked as ref.\n */\nexport interface Ref<T> extends Pipeable.Pipeable {\n /**\n * Target URI (either an `echo:` EID for an object reference or a `dxn:` DXN for a type reference).\n */\n get uri(): URI.URI;\n\n /**\n * Returns true if the reference has a target available (inlined or resolver set).\n */\n get isAvailable(): boolean;\n\n /**\n * @returns The reference target.\n * May return `undefined` if the object is not loaded in the working set.\n * Accessing this property, even if it returns `undefined` will trigger the object to be loaded to the working set.\n */\n get target(): T | undefined;\n\n /**\n * @returns Promise that will resolves with the target object.\n * Will load the object from disk if it is not present in the working set.\n * Short-circuits immediately when the target is already loaded.\n * @throws If the object is not available locally.\n *\n * @idiom org.dxos.echo.refLoad\n * applies: Resolving a ref inside an async function or Effect handler — guarantees the object is available before proceeding\n * instead-of: `ref.target` — not guaranteed to be defined in async contexts; use `await ref.load()` (or `yield* Database.load(ref)` in Effect) to ensure the target is present\n * uses: {@link load}\n * related: org.dxos.echo-react.useObjectReactive\n */\n load(): Promise<T>;\n\n /**\n * @returns Promise that will resolves with the target object or undefined if the object is not loaded locally.\n */\n\n tryLoad(): Promise<T | undefined>;\n\n /**\n * Subscribe to the ref's resolution event.\n * The callback fires when the target object becomes available in the working set\n * (e.g. when its document is loaded after sibling-client mutation).\n * Note: the resolver only schedules a notification when the target is requested\n * via {@link target} while it is not yet loaded.\n * @returns Function that unsubscribes the callback.\n */\n onResolved(callback: () => void): () => void;\n\n /**\n * Do not inline the target object in the reference.\n * Makes .target unavailable unless the reference is connected to a database context.\n *\n * When serialized with toJSON, the difference is between:\n * `{ \"/\": \"dxn:...\" }`\n * and\n * `{ \"/\": \"dxn:...\", \"target\": { ... } }`\n *\n * Clones the reference object.\n */\n noInline(): Ref<T>;\n\n /**\n * Read-only atom for the ref target.\n * Resolves once when the target loads; does NOT subscribe to target object mutations.\n * Use `Obj.atom(ref)` if you need reactive snapshots that update on every object mutation.\n */\n get atom(): Atom.Atom<T | undefined>;\n\n /**\n * Serializes the reference to a JSON object.\n * The serialization format is compatible with the IPLD-style encoded references.\n * When a reference has a saved target (i.e. the target or object holding the reference is not in the database),\n * the target is included in the serialized object.\n *\n * Examples:\n * `{ \"/\": \"dxn:...\" }`\n * `{ \"/\": \"dxn:...\", \"target\": { ... } }`\n */\n encode(): EncodedReference;\n\n [RefTypeId]: {\n _T: T;\n };\n}\n\nexport declare namespace Ref {\n /**\n * Target of the reference.\n */\n export type Target<R> = R extends Ref<infer U> ? U : never;\n}\n\nRef.isRef = (obj: any): obj is Ref<any> => {\n return obj != null && typeof obj === 'object' && RefTypeId in obj;\n};\n\nRef.hasEntityId = (id: EntityId) => (ref: Ref<any>) => {\n const uri = EID.tryParse(ref.uri);\n return uri !== undefined && EID.isLocal(uri) && EID.getEntityId(uri) === id;\n};\n\nRef.isRefSchema = (schema: Schema.Schema<any, any>): schema is RefSchema<any> => {\n return Ref.isRefSchemaAST(schema.ast);\n};\n\nRef.isRefSchemaAST = (ast: SchemaAST.AST): boolean => {\n return SchemaAST.getAnnotation(ast, ReferenceAnnotationId).pipe(Option.isSome);\n};\n\nRef.make = <T extends AnyProperties>(obj: T): Ref<T> => {\n if (typeof obj !== 'object' || obj === null) {\n throw new TypeError('Expected: ECHO object.');\n }\n\n // TODO(dmaretskyi): Extract to `getObjectEchoUri` function.\n const id = obj.id;\n invariant(EntityId.isValid(id), 'Invalid object ID');\n const uri = EID.make({ entityId: id });\n const ref = new RefImpl(uri, obj);\n return ref;\n};\n\nRef.fromURI = (uri: URI.URI): Ref<any> => {\n assertArgument(typeof uri === 'string', 'uri', 'Expected URI string');\n return new RefImpl(uri);\n};\n\n/**\n * `reference` field on the schema object.\n */\nexport type JsonSchemaReferenceInfo = {\n schema: { $ref: string };\n schemaVersion?: string;\n};\n\n/**\n * @internal\n */\n// TODO(burdon): Move to json schema and make private?\nexport const createEchoReferenceSchema = (\n echoUri: string | undefined,\n typename: string | undefined,\n version: string | undefined,\n): Schema.SchemaClass<Ref<any>, EncodedReference> => {\n if (!echoUri && !typename) {\n throw new TypeError('Either echoUri or typename must be provided.');\n }\n\n const referenceInfo: JsonSchemaReferenceInfo = {\n schema: {\n // TODO(dmaretskyi): Include version?\n $ref: echoUri ?? DXN.make(typename!),\n },\n schemaVersion: version,\n };\n\n // TODO(dmaretskyi): Add name and description.\n const refSchema = Schema.declare<Ref<any>, EncodedReference, []>(\n [],\n {\n encode: () => {\n return (value) =>\n Effect.gen(function* () {\n if (Ref.isRef(value)) {\n return EncodedReference.fromURI((value as Ref<any>).uri);\n } else if (EncodedReference.isEncodedReference(value)) {\n return value;\n }\n throw new Error('Invalid reference');\n });\n },\n decode: () => {\n return (value) =>\n Effect.gen(function* () {\n const dbService = yield* Effect.serviceOption(Database.Service);\n\n // TODO(dmaretskyi): This branch seems to be taken by Schema.is\n if (Ref.isRef(value)) {\n if (Option.isSome(dbService)) {\n return dbService.value.db.makeRef(value.uri);\n } else {\n return value;\n }\n }\n\n if (!EncodedReference.isEncodedReference(value)) {\n return yield* Effect.fail(new ParseResult.Unexpected(value, 'reference'));\n }\n if (Option.isSome(dbService)) {\n return dbService.value.db.makeRef(EncodedReference.toURI(value));\n } else {\n return Ref.fromURI(EncodedReference.toURI(value));\n }\n });\n },\n },\n {\n jsonSchema: {\n // TODO(dmaretskyi): We should remove `$id` and keep `$ref` with a fully qualified name.\n $id: JSON_SCHEMA_ECHO_REF_ID,\n $ref: JSON_SCHEMA_ECHO_REF_ID,\n reference: referenceInfo,\n },\n [ReferenceAnnotationId]: {\n typename: typename ?? '',\n version,\n },\n },\n );\n\n return refSchema;\n};\n\nconst getSchemaExpectedName = (ast: SchemaAST.Annotated): string | undefined => {\n return SchemaAST.getIdentifierAnnotation(ast).pipe(\n Option.orElse(() => SchemaAST.getTitleAnnotation(ast)),\n Option.orElse(() => SchemaAST.getDescriptionAnnotation(ast)),\n Option.getOrElse(() => undefined),\n );\n};\n\n/**\n * Load-source ceiling for a resolution request. Cheaper tiers are always probed first; the\n * ceiling caps how far a request is allowed to reach:\n * - `working-set`: synchronous, in-memory only. A miss settles `unavailable` immediately.\n * - `disk`: probe the working set, then local storage; never the network.\n * - `network`: probe the working set, disk, then fetch from peers.\n *\n * `unavailable` is always relative to the requested ceiling (disk-unavailable ≠ network-unavailable).\n */\nexport type RefSource = 'working-set' | 'disk' | 'network';\n\n/**\n * A stateful, closure-aware handle to an in-flight (or settled) reference resolution.\n *\n * `ready` means the entity is FULLY USABLE: its own body and its strong-dependency closure are all\n * materialized. The body-vs-closure split is internal; `requesting` transparently covers \"a\n * dependency is still loading\".\n */\nexport interface RefResolverRequest {\n /**\n * `pending` is a one-way entry state (never re-entered). `requesting` means the body and/or\n * closure is still loading. `ready` means fully usable. `unavailable` means unreachable at the\n * requested ceiling.\n */\n readonly state: 'pending' | 'requesting' | 'ready' | 'unavailable';\n\n /**\n * Fires (deferred to a microtask) whenever {@link state} changes.\n */\n readonly stateChanged: Event<void>;\n\n /**\n * Synchronous snapshot of the resolved entity; defined iff `state === 'ready'`.\n */\n getResult(): AnyProperties | undefined;\n\n /**\n * Settles when `state ∈ {ready, unavailable}`.\n */\n wait(): Promise<AnyProperties | undefined>;\n\n /**\n * Decrements the refcount on the shared load op(s); cancels the underlying IO at zero.\n */\n abort(): void;\n}\n\nexport interface RefResolver {\n /**\n * Resolve a reference, returning a stateful handle. `source` is a required ceiling; cheaper\n * tiers are always probed first.\n */\n resolve(uri: URI.URI, options: { source: RefSource }): RefResolverRequest;\n\n /**\n * Resolve ref synchronously from the objects in the working set.\n *\n * @param uri\n * @param load If true the resolver should attempt to load the object from disk.\n * @param onLoad Callback to call when the object is loaded.\n * @deprecated Use {@link resolve} with `{ source: 'working-set' }`. Removed in Task 11.\n */\n resolveSync(uri: URI.URI, load: boolean, onLoad?: () => void): AnyProperties | undefined;\n\n /**\n * Resolver ref asynchronously.\n * @deprecated Use {@link resolve} with `{ source: 'network' }`. Removed in Task 11.\n */\n resolveLegacy(uri: URI.URI): Promise<AnyProperties | undefined>;\n\n /**\n * @deprecated Use {@link resolve} + `Type.getSchema`. Removed in Task 11.\n */\n resolveSchema(uri: URI.URI): Promise<Schema.Schema.AnyNoContext | undefined>;\n\n /**\n * Resolve the source `Type.AnyEntity` entity for a type URI. Used by\n * deserialization paths (`Obj.fromJSON`) to set the back-reference accessed\n * via `Obj.getType` / `Entity.getType`. Optional — resolvers that only\n * carry raw schemas may leave this unimplemented; the deserializer falls\n * back to leaving the type entity unset.\n * @deprecated Use {@link resolve}. Removed in Task 11.\n */\n resolveType?(uri: URI.URI): Promise<unknown | undefined>;\n}\n\n/**\n * A settled {@link RefResolverRequest} with a fixed `state` and `result`, used by resolvers\n * whose backends are fully synchronous (e.g. {@link StaticRefResolver}).\n */\nexport const makeSettledRequest = (\n state: RefResolverRequest['state'],\n result: AnyProperties | undefined,\n): RefResolverRequest => ({\n state,\n stateChanged: new Event<void>(),\n getResult: () => (state === 'ready' ? result : undefined),\n wait: async () => (state === 'ready' ? result : undefined),\n abort: () => {},\n});\n\nexport class RefImpl<T> implements Ref<T> {\n [RefTypeId] = refVariance;\n\n #uri: URI.URI;\n\n /**\n * Target is set when the reference is created from a specific object.\n * In this case, the target might not be in the database.\n */\n #target: T | undefined = undefined;\n\n #resolver?: RefResolver = undefined;\n #resolved = new Event<void>();\n\n /**\n * Callback to issue a reactive notification when object is resolved.\n */\n #resolverCallback = () => {\n this.#resolved.emit();\n };\n\n constructor(uri: URI.URI, target?: T) {\n this.#uri = uri;\n this.#target = target;\n }\n\n /**\n * @inheritdoc\n */\n get uri(): URI.URI {\n return this.#uri;\n }\n\n /**\n * @inheritdoc\n */\n get target(): T | undefined {\n if (this.#target) {\n return this.#target;\n }\n\n invariant(this.#resolver, 'Resolver is not set');\n return this.#resolver.resolveSync(this.#uri, true, this.#resolverCallback) as T | undefined;\n }\n\n /**\n * @inheritdoc\n */\n get isAvailable(): boolean {\n return this.#target !== undefined || this.#resolver !== undefined;\n }\n\n get atom(): Atom.Atom<T | undefined> {\n return RefAtoms.refSimpleFamily(this);\n }\n\n /**\n * @inheritdoc\n */\n async load(): Promise<T> {\n if (this.#target) {\n return this.#target;\n }\n invariant(this.#resolver, 'Resolver is not set');\n const obj = await this.#resolver.resolveLegacy(this.#uri);\n if (obj == null) {\n throw new Error('Object not found');\n }\n return obj as T;\n }\n\n /**\n * @inheritdoc\n */\n async tryLoad(): Promise<T | undefined> {\n if (this.#target) {\n return this.#target;\n }\n invariant(this.#resolver, 'Resolver is not set');\n return (await this.#resolver.resolveLegacy(this.#uri)) as T | undefined;\n }\n\n /**\n * @inheritdoc\n */\n onResolved(callback: () => void): () => void {\n return this.#resolved.on(callback);\n }\n\n /**\n * Do not inline the target object in the reference.\n * Makes .target unavailable unless the reference is connected to a database context.\n * Clones the reference object.\n */\n noInline(): RefImpl<T> {\n const ref = new RefImpl<T>(this.#uri, undefined);\n ref.#resolver = this.#resolver;\n return ref;\n }\n\n encode(): EncodedReference {\n return {\n '/': this.#uri,\n ...(this.#target ? { target: this.#target } : {}),\n };\n }\n\n /**\n * Serializes the reference to a JSON object.\n * The serialization format is compatible with the IPLD-style encoded references.\n * When a reference has a saved target (i.e. the target or object holding the reference is not in the database),\n * the target is included in the serialized object.\n */\n toJSON(): EncodedReference {\n return this.encode();\n }\n\n toString(): string {\n if (this.#target) {\n return `Ref(${this.#target.toString()})`;\n }\n\n return `Ref(${this.#uri.toString()})`;\n }\n\n [inspectCustom]: CustomInspectFunction = (depth, options, inspect) => {\n return this.toString();\n };\n\n /**\n * Effect Hash trait. Required for MutableHashMap-based caches (e.g., Atom.family)\n * to deduplicate Ref instances that point to the same object.\n * ECHO proxies return new RefImpl instances on every property access,\n * so without this, each access would create a separate cache entry.\n */\n [Hash.symbol](): number {\n return Hash.hash(this.#uri.toString());\n }\n\n /** Effect Equal trait. See {@link Hash.symbol} for rationale. */\n [Equal.symbol](that: Equal.Equal): boolean {\n return that instanceof RefImpl && this.#uri === that.uri;\n }\n\n pipe() {\n // eslint-disable-next-line prefer-rest-params\n return Pipeable.pipeArguments(this, arguments);\n }\n\n /**\n * @internal\n */\n _setResolver(resolver: RefResolver): void {\n this.#resolver = resolver;\n }\n\n /**\n * @internal\n */\n _getSavedTarget(): T | undefined {\n return this.#target;\n }\n}\n\n/**\n * Internal API for setting the reference resolver.\n */\nexport const setRefResolver = (ref: Ref<any>, resolver: RefResolver) => {\n invariant(ref instanceof RefImpl, 'Ref is not an instance of RefImpl');\n ref._setResolver(resolver);\n};\n\n/**\n * Internal API for getting the saved target on a reference.\n */\nexport const getRefSavedTarget = (ref: Ref<any>): AnyProperties | undefined => {\n invariant(ref instanceof RefImpl, 'Ref is not an instance of RefImpl');\n return ref._getSavedTarget();\n};\n\n// Used to validate reference target type.\nconst refVariance: Ref<any>[typeof RefTypeId] = {\n _T: null as any,\n};\n\nexport const refFromEncodedReference = (encodedReference: EncodedReference, resolver?: RefResolver): Ref<any> => {\n const uri = EncodedReference.toURI(encodedReference);\n const ref = new RefImpl(uri);\n\n // TODO(dmaretskyi): Handle inline target in the encoded reference.\n\n if (resolver) {\n setRefResolver(ref, resolver);\n }\n return ref;\n};\n\nexport class StaticRefResolver implements RefResolver {\n public objects = new Map<EntityId, AnyProperties>();\n public schemas = new Map<URI.URI, Schema.Schema.AnyNoContext>();\n\n addObject(obj: AnyProperties): this {\n this.objects.set(obj.id, obj);\n return this;\n }\n\n addSchema(input: Type.AnyEntity): this {\n const schema = getStaticTypeSchema(input);\n invariant(schema, 'Type entity is missing its source schema');\n const uri = getSchemaURI(schema);\n invariant(uri, 'Schema has no URI');\n this.schemas.set(uri, schema);\n return this;\n }\n\n resolve(uri: URI.URI, _options: { source: RefSource }): RefResolverRequest {\n const obj = this.#lookup(uri);\n return makeSettledRequest(obj ? 'ready' : 'unavailable', obj);\n }\n\n resolveSync(uri: URI.URI, _load: boolean, _onLoad?: () => void): AnyProperties | undefined {\n return this.#lookup(uri);\n }\n\n async resolveLegacy(uri: URI.URI): Promise<AnyProperties | undefined> {\n return this.#lookup(uri);\n }\n\n async resolveSchema(uri: URI.URI): Promise<Schema.Schema.AnyNoContext | undefined> {\n return this.schemas.get(uri);\n }\n\n #lookup(uri: URI.URI): AnyProperties | undefined {\n const echoUri = EID.tryParse(uri);\n const id = echoUri ? EID.getEntityId(echoUri) : undefined;\n if (id == null) {\n return undefined;\n }\n return this.objects.get(id);\n }\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Atom from '@effect-atom/atom/Atom';\n\nimport { subscribe } from '../common/proxy/reactive';\nimport { ObjectDeletedId } from '../common/types/model-symbols';\nimport type { Ref } from './ref';\nimport { loadRefTarget } from './utils';\n\n/**\n * Atom family for ECHO refs.\n * Uses ref reference as key — same ref returns same atom.\n * Subscribes to target object changes and resolves to undefined when the target is deleted.\n */\nexport const refSimpleFamily = Atom.family(<T>(ref: Ref<T>): Atom.Atom<T | undefined> => {\n return Atom.make<T | undefined>((get) => {\n let unsubscribeTarget: (() => void) | undefined;\n\n const setupSubscription = (target: T): T | undefined => {\n // Release any previous subscription before re-subscribing (loadRefTarget may call this more than once).\n // T has no ECHO-proxy constraint at this generic level; `subscribe` and ObjectDeletedId\n // both require the internal proxy shape that cannot be expressed statically here.\n unsubscribeTarget?.();\n unsubscribeTarget = subscribe(target as any, () => {\n const deleted = !!(target as any)[ObjectDeletedId];\n get.setSelf(deleted ? undefined : target);\n });\n const deleted = !!(target as any)[ObjectDeletedId];\n return deleted ? undefined : target;\n };\n\n get.addFinalizer(() => {\n unsubscribeTarget?.();\n });\n\n return loadRefTarget(ref, get, setupSubscription);\n });\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport type * as Atom from '@effect-atom/atom/Atom';\n\nimport type { Ref } from './ref';\n\n/**\n * Internal helper for loading ref targets in atoms.\n * Handles the common pattern of checking for loaded target and triggering async load.\n */\nexport const loadRefTarget = <T, R>(\n ref: Ref<T>,\n get: Atom.Context,\n onTargetAvailable: (target: T) => R,\n): R | undefined => {\n // Accessing `ref.target` registers a resolution callback when the target is\n // not yet loaded, so resolution can be observed via `ref.onResolved` below.\n const currentTarget = ref.target;\n if (currentTarget) {\n return onTargetAvailable(currentTarget);\n }\n\n // Subscribe to the ref's resolution event in case the target loads later.\n const unsubscribe = ref.onResolved(() => {\n const target = ref.target;\n if (target) {\n get.setSelf(onTargetAvailable(target));\n }\n });\n get.addFinalizer(unsubscribe);\n\n // Also try async load (e.g. for objects that need disk loading).\n void ref\n .load()\n .then((loadedTarget) => {\n get.setSelf(onTargetAvailable(loadedTarget));\n })\n .catch(() => {\n // Loading failed; the resolution subscription above will pick up cross-client updates.\n });\n\n return undefined;\n};\n"],
5
+ "mappings": ";;;;;;;;;;;;;AAIA,SAASA,iBAAiB;AAI1B,IAAA,eAAaC;;;;AAuBJC,IAAAA,mBAAiBC,CAAS,UAAKD;AACtC,QAAA,QAAA,OAAA,eAAA,KAAA;AAEF,SAAO,UAAME,OAAAA,aAAsBC,SAAAA,QAAAA,CAAAA,CAAAA,MAAAA,uBAAAA;;IAE/B,qBAAO,CAAA,UAAA;AACT,MAAA,SAAA,QAAA,MAAA,aAAA,GAAA;AACIC,WAAMC;;AAEV,MAAA,MAAA,QAAA,KAAA,GAAA;AAEA,WAAO;EACP;AAEF,SAAA,OAAA,UAAA,YAAA,iBAAA,KAAA;;AAKEP,IAAUK,eAAiBG,CAAAA,UAAAA;AAC3B,QAAA,QAAOH,MAAAA,aAAAA;AACP,YAAA,iBAAA,kBAAA,QAAA,EAAA,YAAA,YAAA,GAAA,cAAA,GAAA,IAAA,GAAA,QAAA,GAAA,CAAA,qCAAA,EAAA,EAAA,CAAA;AAEF,SAAO;;AAEL,IAAA,iBAAA,CAAA,UAAA;AAEF,SAAO,aAAMI,KAAAA,EAAkB;;AAE7B,IAAA,kBAAA,CAAA,UAAA;AAEF,SAAA,aAAA,KAAA,EAAA;;AAaQC,IAAAA,uBAA8BC,CAAAA,QAASC,OAAAA,gBAAaC;AAC1D,QAAA,YAAO,QAAA,IAAA,KAAA,IAAA,SAAA,OAAA,CAAA,IAAA,KAAA,IAAA,OAAA,MAAA;QAAEC,kBAAOC,KAAAA,IAAAA,GAAAA,KAAAA,IAAAA,aAAAA,SAAAA,SAAAA,CAAAA;SAAWH;IAA6B,OAAA;IACxD,aAAA;EAEF;;AAME,IAA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,KAAAA,QAAAA;EACP;AAEF,SAAO;;AAEEY,IAAAA,oBAAAA,MAAyD;EAEhEC,UAAUf,oBAAkB,IAAQ;YAC7BgB,oBAAAA,IAAQC;YACb,KAAW;AACb,SAAA,QAAA,IAAA,IAAA,IAAA,GAAA;AAEAC,WAAUC;;YAERtB,OAAUuB;AACV,UAAMP,SAAMQ,oBAAaD,KAAAA;AACzBvB,IAAAA,WAAUgB,QAAK,4CAAA,EAAA,YAAA,YAAA,GAAAf,eAAA,GAAA,KAAA,GAAA,MAAA,GAAA,CAAA,UAAA,4CAAA,EAAA,CAAA;AACf,UAAKgB,MAAO,aAAUM,MAAAA;AACtB,IAAAvB,WAAO,KAAI,qBAAA,EAAA,YAAA,YAAA,GAAAC,eAAA,GAAA,KAAA,GAAA,MAAA,GAAA,CAAA,OAAA,qBAAA,EAAA,CAAA;AACb,SAAA,QAAA,IAAA,KAAA,MAAA;AAEAwB,WAAoB;;UAElB,KAAOC,UAAAA;AACT,UAAA,MAAA,KAAA,QAAA,GAAA;AAEAC,WAAAA,mBAA0CC,MAAiD,UAAA,eAAA,GAAA;;EAE3F,YAAA,KAAA,OAAA,SAAA;AAEA,WAAMC,KAAAA,QAA0B,GAAsC;;EAEtE,MAAA,cAAA,KAAA;AAEA,WAAMC,KAAAA,QAA0B,GAAmD;;EAEnF,MAAA,cAAA,KAAA;AAEA,WAAoB,KAAA,QAAA,IAAA,GAAA;;UAElB,KAAMC;AACN,UAAIA,UAAY,IAAA,SAAA,GAAA;UACd,KAAOC,UAAAA,IAAAA,YAAAA,OAAAA,IAAAA;AACT,QAAA,MAAA,MAAA;AACA,aAAW;IACb;AACF,WAAA,KAAA,QAAA,IAAA,EAAA;;;",
6
+ "names": ["invariant", "symbolIsProxy", "proto", "prototype", "isValidProxyTarget", "value", "Array", "isArray", "ProxyHandlerSlot", "getProxyHandler", "safeDeleteCount", "Math", "deleteCount", "length", "start", "safeStart", "existingProxy", "handler", "_proxyMap", "set", "_handler", "setHandler", "get", "target", "prop", "receiver", "Object", "trap", "apply", "EventId", "Symbol", "for", "ChangeId", "subscribe", "obj", "callback", "isProxy", "target", "getProxyTarget", "EventId", "on", "change", "changeFn", "ChangeId", "Effect", "Equal", "Hash", "Option", "ParseResult", "Pipeable", "Schema", "SchemaAST", "Event", "inspectCustom", "EncodedReference", "assertArgument", "invariant", "DXN", "EID", "EntityId", "Atom", "loadRefTarget", "ref", "get", "onTargetAvailable", "currentTarget", "target", "unsubscribe", "onResolved", "setSelf", "addFinalizer", "load", "then", "loadedTarget", "catch", "undefined", "refSimpleFamily", "family", "ref", "make", "get", "unsubscribeTarget", "setupSubscription", "target", "subscribe", "deleted", "ObjectDeletedId", "setSelf", "undefined", "addFinalizer", "loadRefTarget", "__dxlog_file", "reference", "$ref", "$id", "JSON_SCHEMA_ECHO_REF_ID", "parsed", "tryMake", "typename", "getName", "undefined", "schema", "version", "annotation", "getTypeAnnotation", "Error", "createEchoReferenceSchema", "isRef", "obj", "hasEntityId", "ref", "uri", "isRefSchema", "isRefSchemaAST", "ast", "make", "TypeError", "EID", "entityId", "id", "fromURI", "RefImpl", "referenceInfo", "schemaVersion", "Effect", "gen", "EncodedReference", "value", "Ref", "dbService", "Option", "isSome", "jsonSchema", "ReferenceAnnotationId", "getSchemaExpectedName", "stateChanged", "Event", "getResult", "wait", "state", "abort", "RefImpl", "target", "invariant", "__dxlog_file", "atom", "obj", "Error", "ref", "encode", "toString", "inspectCustom", "depth", "options", "inspect", "pipe", "_setResolver", "resolver", "_getSavedTarget", "uri", "schemas", "addObject", "objects", "set", "addSchema", "input", "schema", "getSchemaURI", "resolve", "makeSettledRequest", "resolveSync", "_onLoad", "resolveLegacy", "resolveSchema", "id", "undefined"]
7
+ }
@@ -14,7 +14,7 @@ __export(Order_exports, {
14
14
  var OrderClass = class _OrderClass {
15
15
  ast;
16
16
  static "variance" = {};
17
- static is(value) {
17
+ static "is"(value) {
18
18
  return typeof value === "object" && value !== null && "~Order" in value;
19
19
  }
20
20
  constructor(ast) {
@@ -53,4 +53,4 @@ export {
53
53
  created,
54
54
  Order_exports
55
55
  };
56
- //# sourceMappingURL=chunk-EVK6XBXO.mjs.map
56
+ //# sourceMappingURL=chunk-PRC4FEKJ.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/Order.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\n// @import-as-namespace\n\nimport { type QueryAST } from '@dxos/echo-protocol';\n\nexport interface Order<T> {\n // TODO(dmaretskyi): See new effect-schema approach to variance.\n '~Order': { value: T };\n\n 'ast': QueryAST.Order;\n}\n\nexport type Any = Order<any>;\n\nclass OrderClass implements Order<any> {\n private static 'variance': Order<any>['~Order'] = {} as Order<any>['~Order'];\n\n static 'is'(value: unknown): value is Order<any> {\n return typeof value === 'object' && value !== null && '~Order' in value;\n }\n\n 'constructor'(public readonly ast: QueryAST.Order) {}\n\n '~Order' = OrderClass.variance;\n}\n\nexport const natural: Order<any> = new OrderClass({ kind: 'natural' });\nexport const property = <T>(property: keyof T & string, direction: QueryAST.OrderDirection): Order<T> =>\n new OrderClass({\n kind: 'property',\n property,\n direction,\n });\n\n/**\n * Order by relevance rank (for FTS/vector search results).\n * Higher rank = better match. Default direction is 'desc' (best matches first).\n */\nexport const rank = <T>(direction: QueryAST.OrderDirection = 'desc'): Order<T> =>\n new OrderClass({\n kind: 'rank',\n direction,\n });\n\n/**\n * Order by the system `updatedAt` timestamp (last re-indexed). Default direction is 'desc'\n * (most-recently-updated first). Mirrors {@link Filter.updated}.\n */\nexport const updated = <T>(direction: QueryAST.OrderDirection = 'desc'): Order<T> =>\n new OrderClass({\n kind: 'timestamp',\n field: 'updatedAt',\n direction,\n });\n\n/**\n * Order by the system `createdAt` timestamp (first indexed). Default direction is 'desc'\n * (most-recently-created first). Mirrors {@link Filter.created}.\n */\nexport const created = <T>(direction: QueryAST.OrderDirection = 'desc'): Order<T> =>\n new OrderClass({\n kind: 'timestamp',\n field: 'createdAt',\n direction,\n });\n"],
5
+ "mappings": ";;;;;AAAA;;;;;;;;AAiBA,IAAMA,aAAN,MAAMA,YAAAA;;EACJ,OAAe,aAAmC,CAAC;EAEnD,OAAO,KAAKC,OAAqC;AAC/C,WAAO,OAAOA,UAAU,YAAYA,UAAU,QAAQ,YAAYA;EACpE;EAEA,YAA8BC,KAAqB;SAArBA,MAAAA;EAAsB;EAEpD,WAAWF,YAAWG;AACxB;AAEO,IAAMC,UAAsB,IAAIJ,WAAW;EAAEK,MAAM;AAAU,CAAA;AAC7D,IAAMC,WAAW,CAAIA,WAA4BC,cACtD,IAAIP,WAAW;EACbK,MAAM;EACNC,UAAAA;EACAC;AACF,CAAA;AAMK,IAAMC,OAAO,CAAID,YAAqC,WAC3D,IAAIP,WAAW;EACbK,MAAM;EACNE;AACF,CAAA;AAMK,IAAME,UAAU,CAAIF,YAAqC,WAC9D,IAAIP,WAAW;EACbK,MAAM;EACNK,OAAO;EACPH;AACF,CAAA;AAMK,IAAMI,UAAU,CAAIJ,YAAqC,WAC9D,IAAIP,WAAW;EACbK,MAAM;EACNK,OAAO;EACPH;AACF,CAAA;",
6
+ "names": ["OrderClass", "value", "ast", "variance", "natural", "kind", "property", "direction", "rank", "updated", "field", "created"]
7
+ }
@@ -1,13 +1,14 @@
1
1
  import {
2
2
  isRef
3
- } from "./chunk-TF5BSLF6.mjs";
3
+ } from "./chunk-FSGX2R62.mjs";
4
4
  import {
5
+ filterMatchEntity,
5
6
  prettyFilter
6
- } from "./chunk-VQYL2OQF.mjs";
7
+ } from "./chunk-ACFAOTKJ.mjs";
7
8
  import {
8
9
  getTypeURIFromSpecifier,
9
10
  getUri
10
- } from "./chunk-WZ32BF53.mjs";
11
+ } from "./chunk-3TN2VMI4.mjs";
11
12
  import {
12
13
  __export
13
14
  } from "./chunk-J5LGTIGS.mjs";
@@ -40,9 +41,11 @@ __export(Filter_exports, {
40
41
  props: () => props,
41
42
  tag: () => tag,
42
43
  text: () => text,
44
+ toPredicate: () => toPredicate,
43
45
  type: () => type,
44
46
  updated: () => updated
45
47
  });
48
+ import * as Function from "effect/Function";
46
49
  import * as Match from "effect/Match";
47
50
  import * as Schema from "effect/Schema";
48
51
  import * as SchemaAST from "effect/SchemaAST";
@@ -312,6 +315,7 @@ var processPredicate = (predicate) => {
312
315
  );
313
316
  };
314
317
  var pretty = (filter) => prettyFilter(filter.ast);
318
+ var toPredicate = Function.dual(2, (entity, filter) => filterMatchEntity(filter.ast, entity));
315
319
 
316
320
  export {
317
321
  is,
@@ -341,6 +345,7 @@ export {
341
345
  and,
342
346
  or,
343
347
  pretty,
348
+ toPredicate,
344
349
  Filter_exports
345
350
  };
346
- //# sourceMappingURL=chunk-NOL7O3BL.mjs.map
351
+ //# sourceMappingURL=chunk-SCT6FFCR.mjs.map