@dxos/echo 0.10.0 → 0.11.1

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 (274) hide show
  1. package/dist/lib/Annotation.mjs +3 -0
  2. package/dist/lib/Blob.mjs +160 -0
  3. package/dist/lib/Blob.mjs.map +1 -0
  4. package/dist/lib/Database.mjs +2 -0
  5. package/dist/lib/Entity.mjs +231 -0
  6. package/dist/lib/Entity.mjs.map +1 -0
  7. package/dist/lib/Err.mjs +105 -0
  8. package/dist/lib/Err.mjs.map +1 -0
  9. package/dist/lib/Feed.mjs +338 -0
  10. package/dist/lib/Feed.mjs.map +1 -0
  11. package/dist/lib/Filter.mjs +380 -0
  12. package/dist/lib/Filter.mjs.map +1 -0
  13. package/dist/lib/Format.mjs +47 -0
  14. package/dist/lib/Format.mjs.map +1 -0
  15. package/dist/lib/JsonSchema.mjs +21 -0
  16. package/dist/lib/JsonSchema.mjs.map +1 -0
  17. package/dist/lib/Key.mjs +15 -0
  18. package/dist/lib/Key.mjs.map +1 -0
  19. package/dist/lib/Migration.mjs +38 -0
  20. package/dist/lib/Migration.mjs.map +1 -0
  21. package/dist/lib/Obj.mjs +660 -0
  22. package/dist/lib/Obj.mjs.map +1 -0
  23. package/dist/lib/Order.mjs +65 -0
  24. package/dist/lib/Order.mjs.map +1 -0
  25. package/dist/lib/Query.mjs +336 -0
  26. package/dist/lib/Query.mjs.map +1 -0
  27. package/dist/lib/QueryResult.mjs +7 -0
  28. package/dist/lib/QueryResult.mjs.map +1 -0
  29. package/dist/lib/Ref.mjs +44 -0
  30. package/dist/lib/Ref.mjs.map +1 -0
  31. package/dist/lib/Registry.mjs +35 -0
  32. package/dist/lib/Registry.mjs.map +1 -0
  33. package/dist/lib/Relation.mjs +397 -0
  34. package/dist/lib/Relation.mjs.map +1 -0
  35. package/dist/lib/Scope.mjs +51 -0
  36. package/dist/lib/Scope.mjs.map +1 -0
  37. package/dist/lib/Tag.mjs +70 -0
  38. package/dist/lib/Tag.mjs.map +1 -0
  39. package/dist/lib/Text.mjs +82 -0
  40. package/dist/lib/Text.mjs.map +1 -0
  41. package/dist/lib/Type.mjs +371 -0
  42. package/dist/lib/Type.mjs.map +1 -0
  43. package/dist/lib/chunk-Annotation.mjs +221 -0
  44. package/dist/lib/chunk-Annotation.mjs.map +1 -0
  45. package/dist/lib/chunk-Database.mjs +918 -0
  46. package/dist/lib/chunk-Database.mjs.map +1 -0
  47. package/dist/lib/chunk-atom-snapshot.mjs +249 -0
  48. package/dist/lib/chunk-atom-snapshot.mjs.map +1 -0
  49. package/dist/lib/chunk-internal.mjs +2775 -0
  50. package/dist/lib/chunk-internal.mjs.map +1 -0
  51. package/dist/lib/chunk-json-schema.mjs +660 -0
  52. package/dist/lib/chunk-json-schema.mjs.map +1 -0
  53. package/dist/lib/chunk-number.mjs +164 -0
  54. package/dist/lib/chunk-number.mjs.map +1 -0
  55. package/dist/lib/chunk-ref-array.mjs +31 -0
  56. package/dist/lib/chunk-ref-array.mjs.map +1 -0
  57. package/dist/lib/chunk-ref.mjs +590 -0
  58. package/dist/lib/chunk-ref.mjs.map +1 -0
  59. package/dist/lib/chunk-rolldown-runtime.mjs +13 -0
  60. package/dist/lib/chunk-select.mjs +186 -0
  61. package/dist/lib/chunk-select.mjs.map +1 -0
  62. package/dist/lib/chunk-src.mjs +234 -0
  63. package/dist/lib/chunk-src.mjs.map +1 -0
  64. package/dist/lib/chunk-util.mjs +140 -0
  65. package/dist/lib/chunk-util.mjs.map +1 -0
  66. package/dist/lib/index.mjs +24 -0
  67. package/dist/lib/internal.mjs +10 -0
  68. package/dist/lib/testing.mjs +346 -0
  69. package/dist/lib/testing.mjs.map +1 -0
  70. package/dist/types/src/Aggregate.d.ts +86 -0
  71. package/dist/types/src/Aggregate.d.ts.map +1 -0
  72. package/dist/types/src/Blob.d.ts +153 -0
  73. package/dist/types/src/Blob.d.ts.map +1 -0
  74. package/dist/types/src/Blob.test.d.ts +2 -0
  75. package/dist/types/src/Blob.test.d.ts.map +1 -0
  76. package/dist/types/src/Database.d.ts +153 -4
  77. package/dist/types/src/Database.d.ts.map +1 -1
  78. package/dist/types/src/Err.d.ts +116 -0
  79. package/dist/types/src/Err.d.ts.map +1 -1
  80. package/dist/types/src/Feed.d.ts +116 -28
  81. package/dist/types/src/Feed.d.ts.map +1 -1
  82. package/dist/types/src/Feed.test.d.ts +2 -0
  83. package/dist/types/src/Feed.test.d.ts.map +1 -0
  84. package/dist/types/src/Filter.d.ts +14 -6
  85. package/dist/types/src/Filter.d.ts.map +1 -1
  86. package/dist/types/src/Hypergraph.d.ts +18 -0
  87. package/dist/types/src/Hypergraph.d.ts.map +1 -1
  88. package/dist/types/src/Json.d.ts.map +1 -1
  89. package/dist/types/src/Obj.d.ts +14 -1
  90. package/dist/types/src/Obj.d.ts.map +1 -1
  91. package/dist/types/src/Order.d.ts +9 -3
  92. package/dist/types/src/Order.d.ts.map +1 -1
  93. package/dist/types/src/Query.d.ts +107 -26
  94. package/dist/types/src/Query.d.ts.map +1 -1
  95. package/dist/types/src/Relation.d.ts +6 -0
  96. package/dist/types/src/Relation.d.ts.map +1 -1
  97. package/dist/types/src/Type.d.ts.map +1 -1
  98. package/dist/types/src/View.d.ts +1 -1
  99. package/dist/types/src/index.d.ts +2 -0
  100. package/dist/types/src/index.d.ts.map +1 -1
  101. package/dist/types/src/internal/Entity/api.d.ts +6 -0
  102. package/dist/types/src/internal/Entity/api.d.ts.map +1 -1
  103. package/dist/types/src/internal/Entity/model.d.ts +3 -2
  104. package/dist/types/src/internal/Entity/model.d.ts.map +1 -1
  105. package/dist/types/src/internal/Filter/match.d.ts.map +1 -1
  106. package/dist/types/src/internal/JsonSchema/json-schema-type.d.ts +34 -8
  107. package/dist/types/src/internal/JsonSchema/json-schema-type.d.ts.map +1 -1
  108. package/dist/types/src/internal/JsonSchema/json-schema.d.ts.map +1 -1
  109. package/dist/types/src/internal/Obj/atoms.d.ts.map +1 -1
  110. package/dist/types/src/internal/Obj/json-serializer.d.ts.map +1 -1
  111. package/dist/types/src/internal/Query/pretty.d.ts.map +1 -1
  112. package/dist/types/src/internal/Query/query-result-effect.d.ts.map +1 -1
  113. package/dist/types/src/internal/common/proxy/make-object.d.ts +13 -0
  114. package/dist/types/src/internal/common/proxy/make-object.d.ts.map +1 -1
  115. package/dist/types/src/internal/common/proxy/reactive.d.ts.map +1 -1
  116. package/dist/types/src/internal/common/proxy/symbols.d.ts.map +1 -1
  117. package/dist/types/src/internal/common/proxy/typed-handler.d.ts +12 -0
  118. package/dist/types/src/internal/common/proxy/typed-handler.d.ts.map +1 -1
  119. package/dist/types/src/internal/common/types/index.d.ts +1 -0
  120. package/dist/types/src/internal/common/types/index.d.ts.map +1 -1
  121. package/dist/types/src/internal/common/types/model-symbols.d.ts +5 -0
  122. package/dist/types/src/internal/common/types/model-symbols.d.ts.map +1 -1
  123. package/dist/types/src/internal/common/types/projection.d.ts +32 -0
  124. package/dist/types/src/internal/common/types/projection.d.ts.map +1 -0
  125. package/dist/types/tsconfig.tsbuildinfo +1 -1
  126. package/package.json +40 -35
  127. package/src/Aggregate.ts +105 -0
  128. package/src/Blob.test.ts +45 -0
  129. package/src/Blob.ts +205 -0
  130. package/src/Database.ts +207 -17
  131. package/src/Err.ts +36 -0
  132. package/src/Feed.test.ts +188 -0
  133. package/src/Feed.ts +238 -62
  134. package/src/Filter.ts +28 -10
  135. package/src/Hypergraph.ts +18 -0
  136. package/src/Json.ts +1 -0
  137. package/src/Obj.test.ts +2 -2
  138. package/src/Obj.ts +21 -1
  139. package/src/Order.ts +16 -9
  140. package/src/Query.test.ts +319 -2
  141. package/src/Query.ts +165 -51
  142. package/src/Relation.ts +14 -0
  143. package/src/Type.ts +5 -6
  144. package/src/index.ts +2 -0
  145. package/src/internal/Entity/api.ts +11 -1
  146. package/src/internal/Entity/model.ts +3 -0
  147. package/src/internal/Filter/match.ts +30 -1
  148. package/src/internal/JsonSchema/json-schema-type.ts +14 -2
  149. package/src/internal/JsonSchema/json-schema.test.ts +28 -1
  150. package/src/internal/JsonSchema/json-schema.ts +33 -6
  151. package/src/internal/Obj/atoms.ts +4 -2
  152. package/src/internal/Obj/json-serializer.test.ts +162 -2
  153. package/src/internal/Obj/json-serializer.ts +6 -0
  154. package/src/internal/Query/pretty.ts +19 -1
  155. package/src/internal/Query/query-result-effect.ts +2 -4
  156. package/src/internal/Ref/atoms.ts +1 -1
  157. package/src/internal/common/proxy/change-context.ts +1 -1
  158. package/src/internal/common/proxy/make-object.ts +42 -3
  159. package/src/internal/common/proxy/reactive.ts +5 -0
  160. package/src/internal/common/proxy/symbols.ts +1 -0
  161. package/src/internal/common/proxy/typed-handler.ts +71 -29
  162. package/src/internal/common/types/index.ts +1 -0
  163. package/src/internal/common/types/model-symbols.ts +6 -0
  164. package/src/internal/common/types/projection.ts +45 -0
  165. package/src/testing/test-data.ts +14 -14
  166. package/dist/lib/neutral/Annotation.mjs +0 -90
  167. package/dist/lib/neutral/Annotation.mjs.map +0 -7
  168. package/dist/lib/neutral/Database.mjs +0 -42
  169. package/dist/lib/neutral/Database.mjs.map +0 -7
  170. package/dist/lib/neutral/Entity.mjs +0 -76
  171. package/dist/lib/neutral/Entity.mjs.map +0 -7
  172. package/dist/lib/neutral/Err.mjs +0 -16
  173. package/dist/lib/neutral/Err.mjs.map +0 -7
  174. package/dist/lib/neutral/Feed.mjs +0 -50
  175. package/dist/lib/neutral/Feed.mjs.map +0 -7
  176. package/dist/lib/neutral/Filter.mjs +0 -72
  177. package/dist/lib/neutral/Filter.mjs.map +0 -7
  178. package/dist/lib/neutral/Format.mjs +0 -82
  179. package/dist/lib/neutral/Format.mjs.map +0 -7
  180. package/dist/lib/neutral/JsonSchema.mjs +0 -18
  181. package/dist/lib/neutral/JsonSchema.mjs.map +0 -7
  182. package/dist/lib/neutral/Key.mjs +0 -16
  183. package/dist/lib/neutral/Key.mjs.map +0 -7
  184. package/dist/lib/neutral/Migration.mjs +0 -18
  185. package/dist/lib/neutral/Migration.mjs.map +0 -7
  186. package/dist/lib/neutral/Obj.mjs +0 -128
  187. package/dist/lib/neutral/Obj.mjs.map +0 -7
  188. package/dist/lib/neutral/Order.mjs +0 -16
  189. package/dist/lib/neutral/Order.mjs.map +0 -7
  190. package/dist/lib/neutral/Query.mjs +0 -38
  191. package/dist/lib/neutral/Query.mjs.map +0 -7
  192. package/dist/lib/neutral/QueryResult.mjs +0 -2
  193. package/dist/lib/neutral/QueryResult.mjs.map +0 -7
  194. package/dist/lib/neutral/Ref.mjs +0 -25
  195. package/dist/lib/neutral/Ref.mjs.map +0 -7
  196. package/dist/lib/neutral/Registry.mjs +0 -14
  197. package/dist/lib/neutral/Registry.mjs.map +0 -7
  198. package/dist/lib/neutral/Relation.mjs +0 -97
  199. package/dist/lib/neutral/Relation.mjs.map +0 -7
  200. package/dist/lib/neutral/Scope.mjs +0 -12
  201. package/dist/lib/neutral/Scope.mjs.map +0 -7
  202. package/dist/lib/neutral/Tag.mjs +0 -32
  203. package/dist/lib/neutral/Tag.mjs.map +0 -7
  204. package/dist/lib/neutral/Text.mjs +0 -25
  205. package/dist/lib/neutral/Text.mjs.map +0 -7
  206. package/dist/lib/neutral/Type.mjs +0 -65
  207. package/dist/lib/neutral/Type.mjs.map +0 -7
  208. package/dist/lib/neutral/chunk-2HKGAQM4.mjs +0 -1394
  209. package/dist/lib/neutral/chunk-2HKGAQM4.mjs.map +0 -7
  210. package/dist/lib/neutral/chunk-2ZHECXUR.mjs +0 -95
  211. package/dist/lib/neutral/chunk-2ZHECXUR.mjs.map +0 -7
  212. package/dist/lib/neutral/chunk-3KTE2Y7Q.mjs +0 -336
  213. package/dist/lib/neutral/chunk-3KTE2Y7Q.mjs.map +0 -7
  214. package/dist/lib/neutral/chunk-3TN2VMI4.mjs +0 -714
  215. package/dist/lib/neutral/chunk-3TN2VMI4.mjs.map +0 -7
  216. package/dist/lib/neutral/chunk-42L4HJ3Z.mjs +0 -104
  217. package/dist/lib/neutral/chunk-42L4HJ3Z.mjs.map +0 -7
  218. package/dist/lib/neutral/chunk-4A2NWKRJ.mjs +0 -747
  219. package/dist/lib/neutral/chunk-4A2NWKRJ.mjs.map +0 -7
  220. package/dist/lib/neutral/chunk-7LOUAPYZ.mjs +0 -25
  221. package/dist/lib/neutral/chunk-7LOUAPYZ.mjs.map +0 -7
  222. package/dist/lib/neutral/chunk-ACFAOTKJ.mjs +0 -1531
  223. package/dist/lib/neutral/chunk-ACFAOTKJ.mjs.map +0 -7
  224. package/dist/lib/neutral/chunk-BEFR7LEA.mjs +0 -170
  225. package/dist/lib/neutral/chunk-BEFR7LEA.mjs.map +0 -7
  226. package/dist/lib/neutral/chunk-BXIKXT7Q.mjs +0 -89
  227. package/dist/lib/neutral/chunk-BXIKXT7Q.mjs.map +0 -7
  228. package/dist/lib/neutral/chunk-C57XMMBY.mjs +0 -206
  229. package/dist/lib/neutral/chunk-C57XMMBY.mjs.map +0 -7
  230. package/dist/lib/neutral/chunk-C62JYFAD.mjs +0 -183
  231. package/dist/lib/neutral/chunk-C62JYFAD.mjs.map +0 -7
  232. package/dist/lib/neutral/chunk-FSGX2R62.mjs +0 -48
  233. package/dist/lib/neutral/chunk-FSGX2R62.mjs.map +0 -7
  234. package/dist/lib/neutral/chunk-HBXT3GSB.mjs +0 -459
  235. package/dist/lib/neutral/chunk-HBXT3GSB.mjs.map +0 -7
  236. package/dist/lib/neutral/chunk-IQR45HAD.mjs +0 -31
  237. package/dist/lib/neutral/chunk-IQR45HAD.mjs.map +0 -7
  238. package/dist/lib/neutral/chunk-J5LGTIGS.mjs +0 -10
  239. package/dist/lib/neutral/chunk-J5LGTIGS.mjs.map +0 -7
  240. package/dist/lib/neutral/chunk-KCBW4BR6.mjs +0 -424
  241. package/dist/lib/neutral/chunk-KCBW4BR6.mjs.map +0 -7
  242. package/dist/lib/neutral/chunk-L3E5IXAE.mjs +0 -575
  243. package/dist/lib/neutral/chunk-L3E5IXAE.mjs.map +0 -7
  244. package/dist/lib/neutral/chunk-PRC4FEKJ.mjs +0 -56
  245. package/dist/lib/neutral/chunk-PRC4FEKJ.mjs.map +0 -7
  246. package/dist/lib/neutral/chunk-SCT6FFCR.mjs +0 -351
  247. package/dist/lib/neutral/chunk-SCT6FFCR.mjs.map +0 -7
  248. package/dist/lib/neutral/chunk-TOCVVFK2.mjs +0 -75
  249. package/dist/lib/neutral/chunk-TOCVVFK2.mjs.map +0 -7
  250. package/dist/lib/neutral/chunk-U53LSQQA.mjs +0 -41
  251. package/dist/lib/neutral/chunk-U53LSQQA.mjs.map +0 -7
  252. package/dist/lib/neutral/chunk-UGFFV2FR.mjs +0 -27
  253. package/dist/lib/neutral/chunk-UGFFV2FR.mjs.map +0 -7
  254. package/dist/lib/neutral/chunk-UWLP4RFM.mjs +0 -7
  255. package/dist/lib/neutral/chunk-UWLP4RFM.mjs.map +0 -7
  256. package/dist/lib/neutral/chunk-UZHCQ6NI.mjs +0 -283
  257. package/dist/lib/neutral/chunk-UZHCQ6NI.mjs.map +0 -7
  258. package/dist/lib/neutral/chunk-WISOH2XH.mjs +0 -36
  259. package/dist/lib/neutral/chunk-WISOH2XH.mjs.map +0 -7
  260. package/dist/lib/neutral/chunk-WKIT2YY5.mjs +0 -34
  261. package/dist/lib/neutral/chunk-WKIT2YY5.mjs.map +0 -7
  262. package/dist/lib/neutral/chunk-XB6ISRAO.mjs +0 -271
  263. package/dist/lib/neutral/chunk-XB6ISRAO.mjs.map +0 -7
  264. package/dist/lib/neutral/chunk-XXL42WCB.mjs +0 -84
  265. package/dist/lib/neutral/chunk-XXL42WCB.mjs.map +0 -7
  266. package/dist/lib/neutral/chunk-XXWK4J53.mjs +0 -117
  267. package/dist/lib/neutral/chunk-XXWK4J53.mjs.map +0 -7
  268. package/dist/lib/neutral/index.mjs +0 -115
  269. package/dist/lib/neutral/index.mjs.map +0 -7
  270. package/dist/lib/neutral/internal/index.mjs +0 -581
  271. package/dist/lib/neutral/internal/index.mjs.map +0 -7
  272. package/dist/lib/neutral/meta.json +0 -1
  273. package/dist/lib/neutral/testing/index.mjs +0 -477
  274. package/dist/lib/neutral/testing/index.mjs.map +0 -7
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Obj.mjs","names":[],"sources":["../../src/Obj.ts"],"sourcesContent":["//\n// Copyright 2025 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Effect from 'effect/Effect';\nimport * as Equal from 'effect/Equal';\nimport * as Exit from 'effect/Exit';\nimport * as Function from 'effect/Function';\nimport * as Option from 'effect/Option';\nimport * as Schema from 'effect/Schema';\nimport * as Utils from 'effect/Utils';\n\nimport type { ForeignKey } from '@dxos/echo-protocol';\nimport { SchemaEx } from '@dxos/effect';\nimport { assertArgument, invariant } from '@dxos/invariant';\nimport { EntityId, type URI } from '@dxos/keys';\nimport { assumeType, deepMapValues } from '@dxos/util';\n\nimport type * as Database from './Database';\nimport * as Entity from './Entity';\nimport * as Err from './Err';\nimport * as internal from './internal';\nimport { getProxyTarget, isProxy } from './internal/common/proxy/proxy-utils';\nimport * as objInternal from './internal/Obj';\nimport * as Ref from './Ref';\nimport type * as Tag from './Tag';\nimport * as Type from './Type';\n\n/**\n * Base type for all ECHO objects.\n */\ninterface BaseObj extends internal.AnyEntity, Entity.OfKind<typeof Entity.Kind.Object> {}\n\n/**\n * Object type with specific properties.\n */\nexport type OfShape<Props> = BaseObj & Props;\n\n/**\n * Object with no known properties beyond id and kind.\n * Use this when the object's schema/properties are not known.\n * For objects with arbitrary properties, use `Obj.AnyProps`.\n *\n * NOTE: This is a TypeScript type only, not a schema.\n * To validate that a value is an ECHO object, use `Schema.is(Type.Obj)`.\n */\nexport interface Unknown extends BaseObj {}\n\n/**\n * Runtime Effect schema for any ECHO object.\n * Use for validation, parsing, or as a reference target for collections.\n *\n * NOTE: `Schema.is(Type.Obj)` does STRUCTURAL validation only (checks for `id` field).\n * Use `Obj.isObject()` for proper ECHO instance type guards that check the KindId brand.\n *\n * @example\n * ```ts\n * // Structural type guard (accepts any object with id field)\n * if (Schema.is(Type.Obj)(unknownValue)) { ... }\n *\n * // ECHO instance type guard (checks KindId brand)\n * if (Obj.isObject(unknownValue)) { ... }\n *\n * // Reference to any object type\n * class Collection extends Type.makeObject<Collection>(DXN.make('com.example.type.collection', '0.1.0'))(\n * Schema.Struct({ objects: Schema.Array(Ref.Ref(Obj.Unknown)) }),\n * ) {}\n * ```\n */\n// TODO(wittjosiah): Investigate if Schema.filter can validate KindId on ECHO instances.\n// Effect Schema normalizes proxy objects to plain objects before calling filter predicates.\n// Possible approaches: custom Schema.declare, AST manipulation, or upstream contribution.\nexport const Unknown: internal.UnknownTypeSchema<Unknown, typeof Entity.Kind.Object> = Schema.Struct({\n id: Schema.String,\n}).pipe(\n Schema.extend(Schema.Record({ key: Schema.String, value: Schema.Unknown })),\n Schema.annotations({\n [internal.TypeAnnotationId]: {\n kind: Entity.Kind.Object,\n typename: internal.ANY_OBJECT_TYPENAME,\n version: internal.ANY_OBJECT_VERSION,\n },\n }),\n) as unknown as internal.UnknownTypeSchema<Unknown, typeof Entity.Kind.Object>;\n\n/**\n * Object with arbitrary properties.\n *\n * NOTE: Due to how TypeScript works, this type is not assignable to a specific schema type.\n * In that case, use `Obj.instanceOf` to check if an object is of a specific type.\n *\n * Prefer using `Obj.Unknown` when you don't need to access arbitrary properties.\n */\nexport interface Any extends BaseObj, internal.AnyProperties {}\n\n/**\n * Base type for snapshot objects (has SnapshotKindId instead of KindId).\n */\ninterface BaseSnapshot extends internal.AnyEntity {\n readonly [Entity.SnapshotKindId]: typeof Entity.Kind.Object;\n readonly id: EntityId;\n}\n\n/**\n * Immutable snapshot of an ECHO object.\n * Branded with SnapshotKindId (not KindId).\n * Property values are frozen at the time the snapshot was created.\n * Returned by getSnapshot() and hooks like useObject().\n *\n * Snapshots are structurally identical to reactive objects but have a different brand,\n * making them distinguishable at the TypeScript level. Neither is assignable to the other.\n */\nexport type Snapshot<T extends Unknown = Unknown> = Omit<T, Entity.KindId> & BaseSnapshot;\n\n/**\n * JSON-encoded properties for objects.\n */\nexport interface BaseObjJson {\n id: string;\n}\n\n// Factory (not a shared const): each object must get its own `keys`/`tags`/`annotations` containers,\n// otherwise mutating one object's meta would leak into every other object via the shared references.\nconst defaultMeta = (): internal.EntityMeta => ({\n keys: [],\n tags: [],\n annotations: {},\n});\n\n// TODO(burdon): Should we allow the caller to set the id?\n/**\n * Props type for object creation with a given type. Accepts a `Type.AnyObj`\n * entity and derives the instance shape via `Type.InstanceType`. Relation-kind\n * entities are rejected at the type level — use `Relation.MakeProps` for those.\n *\n * When the schema is the unconstrained `Type.AnyObj` (`Obj<unknown>` — e.g. a\n * dynamic type from `schemaRegistry.register`), the instance shape is not\n * statically known, so data props widen to `Record<string, unknown>` and the\n * caller can pass arbitrary fields without a cast.\n */\nexport type MakeProps<S extends Type.AnyObj> = {\n id?: EntityId;\n [Meta]?: Partial<internal.EntityMeta>;\n [Parent]?: Unknown;\n // When the resolved instance has no known data keys, widen to a permissive\n // record (the `Obj<unknown>` case); otherwise use the precise property shape.\n // `[keyof …] extends [never]` is wrapped in tuples so the check is\n // non-distributive — a `never` instance type (e.g. when narrowing collapses\n // the schema) stays a single branch instead of distributing to `never`.\n} & ([keyof Entity.Properties<Type.InstanceType<S>>] extends [never]\n ? Record<string, unknown>\n : Entity.Properties<Type.InstanceType<S>>);\n\n/**\n * Creates a new echo object of the given schema or `Type.Type`.\n *\n * @param typeOrSchema - A static object schema (`Type.makeObject(...)`) or a\n * `Type.Type` entity (e.g. one returned by `db.addType(schemaEntity)`).\n * @param props - Object properties.\n *\n * Meta can be passed as a symbol in `props`.\n *\n * Example:\n * ```ts\n * const obj = Obj.make(Person, { [Obj.Meta]: { keys: [...] }, name: 'John' });\n * ```\n *\n * Note: Only accepts object schemas / object-kind types, not relation schemas.\n * Use `Relation.make` for relations.\n */\nexport function make<T extends Type.AnyObj>(type: T, props: NoInfer<MakeProps<T>>): OfShape<Type.InstanceType<T>>;\nexport function make(input: Type.AnyObj, props: any): OfShape<any> {\n // `Type.Type` entities aren't `Schema.Schema` themselves; derive the Effect\n // Schema via `Type.getSchema(...)`. Pass the entity through to `makeObject`\n // so subsequent schema mutations (`Type.addFields`, etc.) propagate.\n const schema = Type.getSchema(input);\n assertArgument(\n internal.getTypeAnnotation(schema)?.kind === Entity.Kind.Object,\n 'schema',\n 'Expected an object schema',\n );\n\n let meta: internal.EntityMeta | undefined = undefined;\n\n // Set default fields on meta on creation.\n if (props[internal.MetaId] != null) {\n meta = { ...defaultMeta(), ...props[internal.MetaId] };\n delete props[internal.MetaId];\n }\n\n // Filter undefined values (Object.entries only returns string-keyed properties).\n const filterUndefined: any = Object.fromEntries(Object.entries(props).filter(([_, v]) => v !== undefined));\n\n // Copy symbol properties (like ParentId) that Object.entries doesn't include.\n for (const sym of Object.getOwnPropertySymbols(props)) {\n const value = (props as any)[sym];\n if (value !== undefined) {\n filterUndefined[sym] = value;\n }\n }\n\n return internal.makeObject(\n schema,\n filterUndefined,\n {\n ...defaultMeta(),\n ...meta,\n },\n input,\n );\n}\n\n/**\n * Determine if object is an ECHO object.\n */\nexport const isObject = (obj: unknown): obj is Unknown => {\n assumeType<internal.InternalObjectProps>(obj);\n return typeof obj === 'object' && obj !== null && obj[Entity.KindId] === Entity.Kind.Object;\n};\n\nexport const isSnapshot = (obj: unknown): obj is Snapshot => {\n assumeType<internal.InternalObjectProps>(obj);\n return typeof obj === 'object' && obj !== null && (obj as any)[Entity.SnapshotKindId] === Entity.Kind.Object;\n};\n\n/**\n * Subscribe to object updates.\n * The callback is called synchronously when the object is modified.\n * Only accepts reactive objects (not snapshots).\n * @returns Unsubscribe function.\n */\nexport const subscribe = (obj: Unknown, callback: () => void): (() => void) => {\n return internal.subscribe(obj, callback);\n};\n\n//\n// Snapshot\n//\n\n/**\n * Returns an immutable snapshot of an object.\n * The snapshot is branded with SnapshotKindId instead of KindId,\n * making it distinguishable from the reactive object at the type level.\n */\nexport const getSnapshot: <T extends Unknown>(obj: T) => Snapshot<T> = objInternal.getSnapshot as any;\n\n/**\n * Returns the reactive version of an object from the database, given its snapshot.\n * Inverse of `Obj.getSnapshot`.\n *\n * Uses `Obj.getDatabase` internally to get the database from the snapshot,\n * then resolves the reactive object by ID.\n *\n * @param snapshot - A snapshot of the object (from `Obj.getSnapshot`).\n * @returns Effect that succeeds with the reactive object, or fails with `GetReactiveError`.\n * @example\n * ```ts\n * const snapshot = Obj.getSnapshot(obj);\n * const reactive = Obj.getReactive(snapshot).pipe(\n * Effect.runSync\n * );\n * ```\n */\nexport const getReactive = <T extends Unknown>(snapshot: Snapshot<T>): Effect.Effect<T, Err.GetReactiveError> =>\n Effect.gen(function* () {\n const db = internal.getDatabase(snapshot);\n if (!db) {\n return yield* Effect.fail(new Err.GetReactiveError({ reason: 'no-database', snapshotId: snapshot.id }));\n }\n const obj = db.getObjectById(snapshot.id);\n if (!obj) {\n return yield* Effect.fail(new Err.GetReactiveError({ reason: 'object-not-found', snapshotId: snapshot.id }));\n }\n return obj as T;\n });\n\n/**\n * Like `Obj.getReactive` but returns `Option.none()` instead of failing when the object\n * cannot be resolved (no database, object not found).\n *\n * @param snapshot - A snapshot of the object (from `Obj.getSnapshot`).\n * @returns Effect that succeeds with `Option.some(reactive)` or `Option.none()`.\n */\nexport const getReactiveOption = <T extends Unknown>(snapshot: Snapshot<T>): Effect.Effect<Option.Option<T>, never> =>\n getReactive(snapshot).pipe(\n Effect.map(Option.some),\n Effect.catchAll(() => Effect.succeed(Option.none())),\n );\n\n/**\n * Synchronous version of `Obj.getReactive`. Returns the reactive object or throws\n * `GetReactiveError` when the object cannot be resolved (no database, object not found).\n *\n * @param snapshot - A snapshot of the object (from `Obj.getSnapshot`).\n * @returns The reactive object.\n * @throws {Err.GetReactiveError} When the object cannot be resolved.\n */\nexport const getReactiveOrThrow = <T extends Unknown>(snapshot: Snapshot<T>): T =>\n Effect.runSync(getReactive(snapshot));\n\n/**\n * Synchronous version of `Obj.getReactive` that returns `undefined` instead of throwing.\n * Accepts `undefined` input so callers can pass the result of `useObject` directly.\n *\n * @param snapshot - A snapshot of the object (from `Obj.getSnapshot` or `useObject`), or `undefined`.\n * @returns The reactive object, or `undefined` if the snapshot is `undefined` or unresolvable.\n */\nexport const getReactiveOrUndefined = <T extends Unknown>(snapshot: Snapshot<T> | undefined): T | undefined => {\n if (snapshot === undefined) {\n return undefined;\n }\n return Effect.runSyncExit(getReactive(snapshot)).pipe(\n Exit.match({ onSuccess: (value) => value, onFailure: () => undefined }),\n );\n};\n\nexport type CloneOptions = {\n /**\n * Retain the original object's ID.\n * @default false\n */\n retainId?: boolean;\n\n /**\n * Recursively clone referenced objects.\n * - `'parent'`: clone only refs whose target is transitively parented under the clone root (children\n * that cascade-delete with it); shared refs (registry operations, context objects, …) are copied as-is.\n * - `'all'`: clone every referenced object recursively.\n * Omit for a shallow clone (refs copied as-is).\n */\n deep?: 'parent' | 'all';\n};\n\n/**\n * Clones an object or relation.\n * This does not clone referenced objects, only the properties in the object.\n * @returns A new object with the same schema and properties.\n */\nexport const clone: <T extends Unknown>(obj: T, opts?: CloneOptions) => T = objInternal.clone;\n\n//\n// Change\n//\n\n/**\n * Makes all properties mutable recursively.\n * Used to provide a mutable view of an object within `Obj.update`.\n */\nexport type Mutable<T> = internal.Mutable<T>;\n\n/**\n * Perform mutations on an echo object within a controlled context.\n *\n * All mutations within the callback are batched and trigger a single notification\n * when the callback completes. Direct mutations outside of `Obj.update` will throw\n * an error for echo objects.\n *\n * This function also works with nested objects within echo objects (e.g., Template structs)\n * that are reactive at runtime.\n *\n * @param obj - The echo object to mutate. Use `Relation.update` for relations.\n * @param callback - The callback that performs mutations on the object.\n *\n * @example\n * ```ts\n * const person = Obj.make(Person, { name: 'John', age: 25 });\n *\n * // Mutate within Obj.update\n * Obj.update(person, (obj) => {\n * obj.name = 'Jane';\n * obj.age = 30;\n * });\n * // ONE notification fires here\n *\n * // Direct mutation throws\n * person.name = 'Bob'; // Error: Cannot modify outside Obj.update()\n * ```\n *\n * Note: Only accepts objects. Use `Relation.update` for relations.\n */\nexport const update = <T extends Unknown>(obj: T, callback: internal.ChangeCallback<T>): T => {\n internal.change(obj, callback);\n return obj;\n};\n\n/**\n * Get a deeply nested property from an object.\n *\n * Similar to lodash.get and getDeep from @dxos/util.\n * This is the complementary function to setValue.\n * Accepts both reactive objects and snapshots.\n *\n * @param obj - The ECHO object to get the property from.\n * @param path - Path to the property (array of keys).\n * @returns The value at the path, or undefined if not found.\n *\n * @example\n * ```ts\n * const person = Obj.make(Person, {\n * name: 'John',\n * addresses: [{ street: '123 Main St' }]\n * });\n *\n * Obj.getValue(person, ['addresses', 0, 'street']); // '123 Main St'\n * Obj.getValue(person, ['addresses', 1, 'street']); // undefined\n * ```\n */\nexport const getValue = (obj: Unknown | Snapshot, path: readonly (string | number)[]): any => {\n return SchemaEx.getValue(obj, SchemaEx.createJsonPath(path));\n};\n\n/**\n * Set a deeply nested property on an object, using the object's schema to determine\n * whether to initialize nested data as an empty object or array.\n *\n * Similar to lodash.set and setDeep from @dxos/util, but schema-aware.\n * Must be called within an `Obj.update` callback.\n *\n * NOTE: TypeScript's structural typing allows readonly objects to be passed to `Mutable<T>`\n * parameters, so there is no compile-time error. Enforcement is runtime-only.\n *\n * @param obj - The mutable ECHO object to set the property on.\n * @param path - Path to the property (array of keys).\n * @param value - Value to set.\n * @returns The value that was set.\n *\n * @example\n * ```ts\n * const person = Obj.make(Person, { name: 'John' });\n * // Person schema has: addresses: Schema.Array(Address)\n * Obj.update(person, (obj) => {\n * Obj.setValue(obj, ['addresses', 0, 'street'], '123 Main St');\n * });\n * // Creates: person.addresses = [{ street: '123 Main St' }]\n * ```\n */\n// TODO(wittjosiah): Compute possible path values + type value based on generic object type.\nexport const setValue: (obj: Mutable<Unknown>, path: readonly (string | number)[], value: any) => void =\n objInternal.setValue as any;\n\n//\n// Type\n//\n\nexport const ID = EntityId;\nexport type ID = EntityId;\n\n/**\n * Test if an object is an instance of a given object type.\n *\n * @example\n * ```ts\n * const john = Obj.make(Person, { name: 'John' });\n * const isPerson = Obj.instanceOf(Person);\n * if (isPerson(john)) {\n * // john is Person\n * }\n * ```\n *\n * Only accepts `Type.AnyObj` — use `Relation.instanceOf` for relations and\n * `Type.isType(value)` to test for `Type.Type` meta-schema entities.\n */\nexport const instanceOf: {\n // Reject `Type.Type` at the type level — those are meta-schema entities, not\n // object instances. Use `Type.isType(value)` instead.\n <T extends Type.Type>(\n type: T,\n _hint?: never,\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n ..._error: ['ERROR: Obj.instanceOf does not accept Type.Type; use Type.isType(value) instead']\n ): never;\n // Reject relation types — use `Relation.instanceOf` instead.\n <R extends Type.AnyRelation>(\n type: R,\n _hint?: never,\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n ..._error: ['ERROR: Obj.instanceOf does not accept relation types; use Relation.instanceOf instead']\n ): never;\n <S extends Type.AnyObj>(schema: S): (value: unknown) => value is Type.InstanceType<S>;\n <S extends Type.AnyObj>(schema: S, value: unknown): value is Type.InstanceType<S>;\n} = ((...args: [schema: Type.AnyEntity, value?: unknown]) => {\n if (args.length === 1) {\n return (entity: unknown) => internal.isInstanceOf(args[0], entity);\n }\n\n return internal.isInstanceOf(args[0], args[1]);\n}) as any;\n\n/**\n * Test if a snapshot is an instance of a schema.\n * Mirrors `instanceOf` but only accepts values branded with SnapshotKindId.\n * Use when the value is known to be a snapshot (e.g. from `getSnapshot` or `useObject`).\n *\n * @example\n * ```ts\n * const snapshot = Obj.getSnapshot(person);\n * if (Obj.snapshotOf(Person, snapshot)) {\n * // snapshot is Obj.Snapshot<Person>\n * }\n * ```\n */\nexport const snapshotOf: {\n <S extends Type.AnyObj>(schema: S): (value: unknown) => value is Snapshot<Type.InstanceType<S>>;\n <S extends Type.AnyObj>(schema: S, value: unknown): value is Snapshot<Type.InstanceType<S>>;\n} = ((...args: [schema: Type.AnyObj, value: unknown] | [schema: Type.AnyObj]) => {\n const check = (entity: unknown) =>\n entity != null &&\n typeof entity === 'object' &&\n Entity.SnapshotKindId in entity &&\n internal.isInstanceOf(args[0], entity);\n\n if (args.length === 1) {\n return (entity: unknown) => check(entity);\n }\n\n return check(args[1]);\n}) as any;\n\nexport type { GetURIOptions } from './internal';\n\n// TODO(dmaretskyi): Allow returning undefined.\n/**\n * Get the URI of the object.\n * Accepts both reactive objects and snapshots.\n *\n * @param options.prefer - Controls the URI form (see {@link GetURIOptions}).\n */\nexport const getURI = (entity: Unknown | Snapshot, options?: internal.GetURIOptions): URI.URI => {\n assertArgument(!Schema.isSchema(entity), 'obj', 'Object should not be a schema.');\n return internal.getUri(entity, options);\n};\n\n/**\n * @returns The DXN of the object's type.\n * @example dxn:com.example.type.person:1.0.0\n * @throws If the object is missing its type (corrupted object).\n */\nexport const getTypeURI = (obj: Unknown | Snapshot): URI.URI => {\n const type = internal.getTypeURI(obj);\n invariant(type != null, 'Corrupted object: missing type.');\n return type;\n};\n\n/**\n * Get the type entity (`Type.AnyObj`) the object was created from.\n *\n * Returns `undefined` when the object's type isn't registered in this runtime\n * (e.g. a freshly deserialized snapshot whose type entity hasn't been wired\n * up yet, or an object loaded from storage before its schema is known). To\n * get the Effect Schema from the returned entity, use `Type.getSchema(...)`.\n */\nexport const getType = (obj: Unknown | Snapshot): Type.AnyObj | undefined =>\n internal.getType(obj) as Type.AnyObj | undefined;\n\n/**\n * @returns The typename of the object's type.\n * Accepts both reactive objects and snapshots.\n * @example `com.example.type.person`\n */\nexport const getTypename = (entity: Unknown | Snapshot): string | undefined => internal.getTypename(entity);\n\n//\n// Database\n//\n\n/**\n * Get the database the object belongs to.\n * Accepts both reactive objects and snapshots.\n *\n * @idiom org.dxos.echo.objGetDatabase\n * applies: Reaching an object's database — to query, add, or remove — when the surrounding Space is not otherwise needed\n * instead-of: `getSpace(obj)?.db` (resolving the whole Space just to read its `.db`)\n * uses: {@link getDatabase}\n */\nexport const getDatabase = (entity: Entity.Unknown | Entity.Snapshot): Database.Database | undefined =>\n internal.getDatabase(entity);\n\n/**\n * Get the branch this object instance is bound to: `'main'` for the canonical object, or the branch of\n * a `db.branch()` independent instance. The branch is a property of the instance — two instances of the\n * same object id on different branches each report their own branch.\n */\nexport const getBranch = (obj: Unknown): string => internal.getBranch(obj);\n\n/**\n * Get an immutable snapshot of the object at the given historical heads — a detached instance, not a\n * pin on the live object. Only the surface that asks for it sees the historical value; the live\n * object and every other surface are unaffected. The functional alternative to a read-time-travel pin.\n */\nexport const getVersion = <T extends Unknown>(obj: T, heads: readonly string[]): Snapshot<T> => {\n const db = getDatabase(obj);\n invariant(db, 'object is not bound to a database');\n return db.getVersion(obj, heads);\n};\n\n//\n// Meta\n//\n\n/**\n * Property that accesses metadata for an entity.\n *\n * Alias for `Entity.Meta`.\n */\nexport const Meta = internal.MetaId;\n\n/**\n * Deeply read-only version of EntityMeta.\n * Prevents mutation at all nesting levels (e.g., `meta.keys.push()` is a TypeScript error).\n */\nexport type ReadonlyMeta = internal.ReadonlyMeta;\n\n/**\n * Mutable meta type returned by `Obj.getMeta` inside an `Obj.update` callback.\n */\nexport type Meta = internal.Meta;\n\n// TODO(burdon): Narrow type.\n// TODO(dmaretskyi): Allow returning undefined.\n/**\n * Get the metadata for an object.\n * Returns mutable meta when passed a mutable object (inside `Obj.update` callback).\n * Returns read-only meta when passed a regular object or snapshot.\n *\n * @example\n * ```ts\n * // Read-only access outside change callback\n * const meta = Obj.getMeta(person); // ReadonlyMeta\n *\n * // Mutable access inside change callback\n * Obj.update(person, (obj) => {\n * const meta = Obj.getMeta(obj); // EntityMeta (mutable)\n * meta.tags.push(Ref.make(tag)); // tags are refs to Tag objects\n * });\n * ```\n */\n// TODO(wittjosiah): When passed a Snapshot, should return a snapshot of meta, not the live meta proxy.\nexport function getMeta(entity: Mutable<Unknown>): Meta;\nexport function getMeta(entity: Unknown | Snapshot): ReadonlyMeta;\nexport function getMeta(entity: Unknown | Snapshot | Mutable<Unknown>): Meta | ReadonlyMeta {\n return internal.getMetaChecked(entity);\n}\n\n/**\n * @returns Foreign keys for the object from the specified source.\n * Accepts both reactive objects and snapshots.\n */\nexport const getKeys: {\n (entity: Unknown | Snapshot, source: string): ForeignKey[];\n (source: string): (entity: Unknown | Snapshot) => ForeignKey[];\n} = Function.dual(2, (entity: Unknown | Snapshot, source?: string): ForeignKey[] => internal.getKeys(entity, source!));\n\n/**\n * Delete all keys from the object for the specified source.\n * Must be called within an `Obj.update` callback.\n *\n * NOTE: TypeScript's structural typing allows readonly objects to be passed to `Mutable<T>`\n * parameters, so there is no compile-time error. Enforcement is runtime-only.\n */\nexport const deleteKeys = (entity: Mutable<Unknown>, source: string): void => internal.deleteKeys(entity, source);\n\n/**\n * Add a tag to the object.\n * Must be called within an `Obj.update` callback.\n *\n * NOTE: TypeScript's structural typing allows readonly objects to be passed to `Mutable<T>`\n * parameters, so there is no compile-time error. Enforcement is runtime-only.\n */\nexport const addTag = (entity: Mutable<Unknown>, tag: Ref.Ref<Tag.Tag>): void => internal.addTag(entity, tag);\n\n/**\n * Remove a tag from the object.\n * Must be called within an `Obj.update` callback.\n *\n * NOTE: TypeScript's structural typing allows readonly objects to be passed to `Mutable<T>`\n * parameters, so there is no compile-time error. Enforcement is runtime-only.\n */\nexport const removeTag = (entity: Mutable<Unknown>, tag: Ref.Ref<Tag.Tag>): void => internal.removeTag(entity, tag);\n\n/**\n * Check if the object is deleted.\n * Accepts both reactive objects and snapshots.\n */\n// TODO(dmaretskyi): Default to `false`.\nexport const isDeleted = (entity: Unknown | Snapshot): boolean => objInternal.isDeleted(entity);\n\n//\n// Annotations\n//\n\n/**\n * Get the label of the object.\n * Accepts both reactive objects and snapshots.\n *\n * @param options.fallback `'typename'` returns the object's typename when no\n * label is set (e.g. `org.dxos.type.table`).\n */\nexport const getLabel = (entity: Unknown | Snapshot, options?: internal.GetLabelOptions): string | undefined =>\n internal.getLabel(entity, options);\n\n/**\n * Set the label of the object.\n * Must be called within an `Obj.update` callback.\n *\n * NOTE: TypeScript's structural typing allows readonly objects to be passed to `Mutable<T>`\n * parameters, so there is no compile-time error. Enforcement is runtime-only.\n */\nexport const setLabel = (entity: Mutable<Unknown>, label: string): void => internal.setLabel(entity, label);\n\n/**\n * Get the description of the object.\n * Accepts both reactive objects and snapshots.\n */\nexport const getDescription = (entity: Unknown | Snapshot): string | undefined => internal.getDescription(entity);\n\n/**\n * Get the icon annotation for the object (or any entity), resolved via its type-level\n * `IconAnnotation`. Accepts both reactive entities and snapshots, and either Objects or\n * Relations — the underlying schema-based lookup works for both.\n *\n * Returns the full `{ icon, hue }` annotation; callers wanting just the icon name typically\n * write `Obj.getIcon(obj)?.icon ?? 'ph--cube--regular'`.\n */\nexport const getIcon = (entity: Entity.Unknown | Entity.Snapshot): internal.IconAnnotation | undefined =>\n internal.getIcon(entity);\n\n/**\n * Set the description of the object.\n * Must be called within an `Obj.update` callback.\n *\n * NOTE: TypeScript's structural typing allows readonly objects to be passed to `Mutable<T>`\n * parameters, so there is no compile-time error. Enforcement is runtime-only.\n */\nexport const setDescription = (entity: Mutable<Unknown>, description: string): void =>\n internal.setDescription(entity, description);\n\n/**\n * Symbol to set parent when creating objects with `Obj.make`.\n * @example\n * ```ts\n * Obj.make(TestSchema.Person, {\n * [Obj.Parent]: parentObject,\n * name: 'John',\n * })\n * ```\n */\nexport const Parent: unique symbol = internal.ParentId as any;\n\n/**\n * Get the parent of an object.\n * The parent is always loaded together with the object.\n * Only objects are allowed to have a parent\n * @returns The parent object, or undefined if the object has no parent.\n */\nexport const getParent = (entity: Unknown | Snapshot): Unknown | undefined => {\n assertArgument(isObject(entity) || isSnapshot(entity), 'Expected an object');\n assumeType<internal.InternalObjectProps>(entity);\n return entity[internal.ParentId] as Unknown | undefined;\n};\n\n/**\n * Sets the parent of an object.\n * If a parent (or any transitive parent) is deleted, the object will be deleted.\n * Only objects are allowed to have a parent.\n */\nexport const setParent = (entity: Unknown, parent: Any | undefined) => {\n assertArgument(isObject(entity), 'Expected an object');\n assertArgument(parent === undefined || isObject(parent), 'Expected an object');\n assumeType<internal.InternalObjectProps>(entity);\n assumeType<internal.InternalObjectProps | undefined>(parent);\n entity[internal.ParentId] = parent;\n return entity;\n};\n\ninterface UpdateFromOptions<T> {\n exclude?: (keyof T)[];\n include?: (keyof T)[];\n}\n\nconst valuesEqual = (left: unknown, right: unknown): boolean => {\n if (left === right) {\n return true;\n }\n if (left === null || right === null) {\n return left === right;\n }\n if (typeof left !== 'object' || typeof right !== 'object') {\n return Utils.structuralRegion(() => Equal.equals(left, right));\n }\n if (Ref.isRef(left) && Ref.isRef(right)) {\n return left.uri === right.uri;\n }\n if (Ref.isRef(left) || Ref.isRef(right)) {\n return false;\n }\n if (Array.isArray(left) && Array.isArray(right)) {\n if (left.length !== right.length) {\n return false;\n }\n for (let index = 0; index < left.length; index++) {\n if (!valuesEqual(left[index], right[index])) {\n return false;\n }\n }\n return true;\n }\n if (Array.isArray(left) || Array.isArray(right)) {\n return false;\n }\n const leftRecord = left as Record<string, unknown>;\n const rightRecord = right as Record<string, unknown>;\n const keys = new Set([\n ...Object.keys(leftRecord).filter((key) => key !== 'id'),\n ...Object.keys(rightRecord).filter((key) => key !== 'id'),\n ]);\n for (const key of keys) {\n const leftHas = Object.hasOwn(leftRecord, key);\n const rightHas = Object.hasOwn(rightRecord, key);\n const leftValue = leftHas ? leftRecord[key] : undefined;\n const rightValue = rightHas ? rightRecord[key] : undefined;\n if (!valuesEqual(leftValue, rightValue)) {\n return false;\n }\n }\n return true;\n};\n\n/**\n * Breaks reactive proxies on assigned values so echo-db assignment accepts nested structs (same idea as link assignment).\n */\nconst prepareAssignValue = (value: unknown): unknown =>\n deepMapValues(value, (nested, recurse) => {\n if (nested === null || typeof nested !== 'object') {\n return nested;\n }\n if (Ref.isRef(nested)) {\n return nested;\n }\n if (Array.isArray(nested)) {\n return recurse(nested);\n }\n if (isProxy(nested)) {\n return recurse({ ...getProxyTarget(nested) });\n }\n return recurse(nested);\n });\n\n/**\n * For each key present on `source` (except `id`), assigns `target[key]` when the current value differs.\n * References are compared by target DXN; other values use Effect `Equal.equals` inside a structural region,\n * with recursive comparison for arrays and plain object-shaped property bags (excluding `id`).\n *\n * Must be called within an `Obj.update` callback.\n *\n * @returns Whether any property was updated.\n */\nexport const updateFrom = <T extends Unknown>(\n target: Mutable<T>,\n source: T,\n options?: UpdateFromOptions<T>,\n): boolean => {\n assertArgument(isObject(target), 'Expected an echo object target.');\n assertArgument(isObject(source), 'Expected an echo object source.');\n let keys = Object.keys(source as Record<string, unknown>).filter((key) => key !== 'id');\n if (options?.include !== undefined) {\n const include = new Set(options.include.map((key) => String(key)));\n keys = keys.filter((key) => include.has(key));\n }\n if (options?.exclude !== undefined) {\n const exclude = new Set(options.exclude.map((key) => String(key)));\n keys = keys.filter((key) => !exclude.has(key));\n }\n let updated = false;\n const sourceRecord = source as Record<string, unknown>;\n const targetRecord = target as Record<string, unknown>;\n for (const key of keys) {\n if (!Object.hasOwn(sourceRecord, key)) {\n continue;\n }\n const nextValue = sourceRecord[key];\n const prevValue = Object.hasOwn(targetRecord, key) ? targetRecord[key] : undefined;\n if (valuesEqual(prevValue, nextValue)) {\n continue;\n }\n targetRecord[key] = prepareAssignValue(nextValue) as never;\n updated = true;\n }\n return updated;\n};\n\n//\n// JSON\n//\n\n/**\n * JSON representation of an object.\n */\nexport type JSON = internal.ObjectJSON;\n\n/**\n * Converts object to its JSON representation.\n * Accepts both reactive objects and snapshots.\n *\n * The same algorithm is used when calling the standard `JSON.stringify(obj)` function.\n */\nexport const toJSON = (entity: Unknown | Snapshot): JSON => objInternal.objectToJSON(entity);\n\n/**\n * Creates an object from its json representation, performing schema validation.\n * References and schemas will be resolvable if the `refResolver` is provided.\n *\n * The function must be async to support resolving the schema as well as the relation endpoints.\n *\n * @param options.refResolver - Resolver for references. Produces hydrated references that can be resolved.\n * @param options.uri - Override object URI. Changes the result of `Obj.getURI`.\n * @param options.database - Database to associate with the object.\n * @param options.parent - Parent entity to associate with the object (used when the JSON has no `@parent`). Changes the result of `Obj.getParent`.\n */\nexport const fromJSON: (\n json: unknown,\n options?: { refResolver?: Ref.Resolver; uri?: URI.URI; database?: Database.Database; parent?: Unknown },\n) => Promise<Unknown> = objInternal.objectFromJSON as any;\n\n/**\n * Comparator function type for sorting objects.\n * Accepts both reactive objects and snapshots.\n */\nexport type Comparator = internal.Comparator<Unknown | Snapshot>;\n\nexport const sortByLabel: Comparator = internal.sortByLabel as Comparator;\nexport const sortByTypename: Comparator = internal.sortByTypename as Comparator;\nexport const sort = (...comparators: Comparator[]): Comparator => internal.sort(...comparators) as Comparator;\n\n//\n// Version\n//\n\nexport const VersionTypeId = internal.VersionTypeId;\nexport type VersionCompareResult = internal.VersionCompareResult;\n\n/**\n * Represent object version.\n * May be backed by Automerge.\n * Objects with no history are not versioned.\n */\nexport type Version = internal.EntityVersion;\n\nexport const isVersion = internal.isVersion;\nexport const versionValid = internal.versionValid;\nexport const compareVersions = internal.compareVersions;\nexport const encodeVersion = internal.encodeVersion;\nexport const decodeVersion = internal.decodeVersion;\n\n/**\n * Returns the version of the object.\n * Accepts both reactive objects and snapshots.\n */\nexport const version = (entity: Unknown | Snapshot): Version => internal.version(entity);\n\n//\n// Atoms\n//\n\n/**\n * Create a reactive snapshot atom for an ECHO object or ref.\n * Use inside atom computations (e.g. `Atom.make((get) => get(Obj.atom(ref)))`) to subscribe\n * to a ref's target — the atom re-fires when the target loads or changes.\n *\n * @idiom org.dxos.echo.objAtomReactive\n * applies: Subscribing to a ref's target inside an atom computation or a non-React reactive context\n * instead-of: `ref.target` — synchronous and not reactive; returns `undefined` when the target isn't loaded yet and never notifies when it becomes available\n * uses: {@link atom}\n * related: org.dxos.echo-react.useObjectReactive\n */\nexport const atom = objInternal.makeAtom;\nexport const atomReactive = objInternal.makeWithReactive;\nexport const atomProperty = objInternal.makeProperty;\nexport const labelAtom = objInternal.makeLabelAtom;\nexport const labelProperty = internal.getLabelProperty;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,IAAa,gBAAgB"}
@@ -0,0 +1,65 @@
1
+ import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
2
+ //#region src/Order.ts
3
+ var Order_exports = /* @__PURE__ */ __exportAll({
4
+ OrderTypeId: () => OrderTypeId,
5
+ created: () => created,
6
+ natural: () => natural,
7
+ property: () => property,
8
+ rank: () => rank,
9
+ updated: () => updated
10
+ });
11
+ var OrderTypeId = "~@dxos/echo/Order";
12
+ var OrderClass = class OrderClass {
13
+ ast;
14
+ static "variance" = {};
15
+ static is(value) {
16
+ return typeof value === "object" && value !== null && "~@dxos/echo/Order" in value;
17
+ }
18
+ constructor(ast) {
19
+ this.ast = ast;
20
+ }
21
+ [OrderTypeId] = OrderClass.variance;
22
+ };
23
+ /**
24
+ * Order by the database's default order. For non-feed sources this is by id; for feed sources
25
+ * this is insertion order, so `desc` reads newest-first. Defaults to `asc`.
26
+ */
27
+ var natural = (direction = "asc") => new OrderClass({
28
+ kind: "natural",
29
+ direction
30
+ });
31
+ var property = (property, direction) => new OrderClass({
32
+ kind: "property",
33
+ property,
34
+ direction
35
+ });
36
+ /**
37
+ * Order by relevance rank (for FTS/vector search results).
38
+ * Higher rank = better match. Default direction is 'desc' (best matches first).
39
+ */
40
+ var rank = (direction = "desc") => new OrderClass({
41
+ kind: "rank",
42
+ direction
43
+ });
44
+ /**
45
+ * Order by the system `updatedAt` timestamp (last re-indexed). Default direction is 'desc'
46
+ * (most-recently-updated first). Mirrors {@link Filter.updated}.
47
+ */
48
+ var updated = (direction = "desc") => new OrderClass({
49
+ kind: "timestamp",
50
+ field: "updatedAt",
51
+ direction
52
+ });
53
+ /**
54
+ * Order by the system `createdAt` timestamp (first indexed). Default direction is 'desc'
55
+ * (most-recently-created first). Mirrors {@link Filter.created}.
56
+ */
57
+ var created = (direction = "desc") => new OrderClass({
58
+ kind: "timestamp",
59
+ field: "createdAt",
60
+ direction
61
+ });
62
+ //#endregion
63
+ export { OrderTypeId, created, natural, property, rank, Order_exports as t, updated };
64
+
65
+ //# sourceMappingURL=Order.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Order.mjs","names":[],"sources":["../../src/Order.ts"],"sourcesContent":["//\n// Copyright 2025 DXOS.org\n//\n\n// @import-as-namespace\n\nimport { type QueryAST } from '@dxos/echo-protocol';\n\nexport const OrderTypeId = '~@dxos/echo/Order' as const;\nexport type OrderTypeId = typeof OrderTypeId;\n\nexport interface Order<T> {\n readonly [OrderTypeId]: { 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>[OrderTypeId] = {} as Order<any>[OrderTypeId];\n\n static is(value: unknown): value is Any {\n return typeof value === 'object' && value !== null && OrderTypeId in value;\n }\n\n constructor(public readonly ast: QueryAST.Order) {}\n\n [OrderTypeId] = OrderClass.variance;\n}\n\n/**\n * Order by the database's default order. For non-feed sources this is by id; for feed sources\n * this is insertion order, so `desc` reads newest-first. Defaults to `asc`.\n */\nexport const natural = (direction: QueryAST.OrderDirection = 'asc'): Order<any> =>\n new OrderClass({ kind: 'natural', direction });\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"],"mappings":";;;;;;;;;;AAQA,IAAa,cAAc;AAW3B,IAAM,aAAN,MAAM,WAAiC;CAOT;CAN5B,OAAe,aAAsC,CAAC;CAEtD,OAAO,GAAG,OAA8B;EACtC,OAAO,OAAO,UAAU,YAAY,UAAU,QAAA,uBAAuB;CACvE;CAEA,YAAY,KAAqC;EAArB,KAAA,MAAA;CAAsB;CAElD,CAAC,eAAe,WAAW;AAC7B;;;;;AAMA,IAAa,WAAW,YAAqC,UAC3D,IAAI,WAAW;CAAE,MAAM;CAAW;AAAU,CAAC;AAC/C,IAAa,YAAe,UAA4B,cACtD,IAAI,WAAW;CACb,MAAM;CACN;CACA;AACF,CAAC;;;;;AAMH,IAAa,QAAW,YAAqC,WAC3D,IAAI,WAAW;CACb,MAAM;CACN;AACF,CAAC;;;;;AAMH,IAAa,WAAc,YAAqC,WAC9D,IAAI,WAAW;CACb,MAAM;CACN,OAAO;CACP;AACF,CAAC;;;;;AAMH,IAAa,WAAc,YAAqC,WAC9D,IAAI,WAAW;CACb,MAAM;CACN,OAAO;CACP;AACF,CAAC"}
@@ -0,0 +1,336 @@
1
+ import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
2
+ import { Ot as makeProjection, yt as prettyQuery } from "./chunk-internal.mjs";
3
+ import { d as isDatabase, x as getTypeURIFromSpecifier } from "./chunk-Database.mjs";
4
+ import { getTypename, getURI } from "./Obj.mjs";
5
+ import { everything, is as is$1, props, type as type$1 } from "./Filter.mjs";
6
+ import { EID } from "@dxos/keys";
7
+ //#region src/Query.ts
8
+ var Query_exports = /* @__PURE__ */ __exportAll({
9
+ QueryTypeId: () => QueryTypeId,
10
+ all: () => all,
11
+ from: () => from,
12
+ fromAst: () => fromAst,
13
+ is: () => is,
14
+ pretty: () => pretty,
15
+ project: () => project,
16
+ select: () => select,
17
+ type: () => type,
18
+ without: () => without
19
+ });
20
+ var QueryTypeId = "~@dxos/echo/Query";
21
+ var QueryClass = class QueryClass {
22
+ ast;
23
+ static "variance" = {};
24
+ constructor(ast) {
25
+ this.ast = ast;
26
+ }
27
+ [QueryTypeId] = QueryClass.variance;
28
+ select(filter) {
29
+ if (is$1(filter)) return new QueryClass({
30
+ type: "filter",
31
+ selection: this.ast,
32
+ filter: filter.ast
33
+ });
34
+ else return new QueryClass({
35
+ type: "filter",
36
+ selection: this.ast,
37
+ filter: props(filter).ast
38
+ });
39
+ }
40
+ project(property) {
41
+ return makeProjection(this.ast, property);
42
+ }
43
+ reference(key) {
44
+ return new QueryClass({
45
+ type: "reference-traversal",
46
+ anchor: this.ast,
47
+ property: key
48
+ });
49
+ }
50
+ referencedBy(target, key) {
51
+ const uri = target !== void 0 ? getTypeURIFromSpecifier(target) : null;
52
+ return new QueryClass({
53
+ type: "incoming-references",
54
+ anchor: this.ast,
55
+ property: key ?? null,
56
+ typename: uri ?? null
57
+ });
58
+ }
59
+ sourceOf(relation, predicates) {
60
+ return new QueryClass({
61
+ type: "relation",
62
+ anchor: this.ast,
63
+ direction: "outgoing",
64
+ filter: relation !== void 0 ? type$1(relation, predicates).ast : void 0
65
+ });
66
+ }
67
+ targetOf(relation, predicates) {
68
+ return new QueryClass({
69
+ type: "relation",
70
+ anchor: this.ast,
71
+ direction: "incoming",
72
+ filter: relation !== void 0 ? type$1(relation, predicates).ast : void 0
73
+ });
74
+ }
75
+ source() {
76
+ return new QueryClass({
77
+ type: "relation-traversal",
78
+ anchor: this.ast,
79
+ direction: "source"
80
+ });
81
+ }
82
+ target() {
83
+ return new QueryClass({
84
+ type: "relation-traversal",
85
+ anchor: this.ast,
86
+ direction: "target"
87
+ });
88
+ }
89
+ parent() {
90
+ return new QueryClass({
91
+ type: "hierarchy-traversal",
92
+ anchor: this.ast,
93
+ direction: "to-parent"
94
+ });
95
+ }
96
+ children() {
97
+ return new QueryClass({
98
+ type: "hierarchy-traversal",
99
+ anchor: this.ast,
100
+ direction: "to-children"
101
+ });
102
+ }
103
+ orderBy(...order) {
104
+ return new QueryClass({
105
+ type: "order",
106
+ query: this.ast,
107
+ order: order.map((o) => o.ast)
108
+ });
109
+ }
110
+ aggregate(aggregates) {
111
+ return new QueryClass({
112
+ type: "aggregate",
113
+ query: this.ast,
114
+ aggregates: Object.entries(aggregates).map(([name, aggregate]) => ({
115
+ name,
116
+ ...aggregate.spec
117
+ }))
118
+ });
119
+ }
120
+ limit(limit) {
121
+ return new QueryClass({
122
+ type: "limit",
123
+ query: this.ast,
124
+ limit
125
+ });
126
+ }
127
+ skip(skip) {
128
+ return new QueryClass({
129
+ type: "skip",
130
+ query: this.ast,
131
+ skip
132
+ });
133
+ }
134
+ from(...args) {
135
+ if (args.length > 1 && args.every(_isRawScope)) return new QueryClass({
136
+ type: "from",
137
+ query: this.ast,
138
+ from: {
139
+ _tag: "scope",
140
+ scopes: args
141
+ }
142
+ });
143
+ const [arg, options] = args;
144
+ if (arg == null) throw new TypeError("Query.from() requires a valid data source argument (database, feed, query, scope, or \"all-accessible-spaces\").");
145
+ if (is(arg)) return new QueryClass({
146
+ type: "from",
147
+ query: this.ast,
148
+ from: {
149
+ _tag: "query",
150
+ query: arg.ast
151
+ }
152
+ });
153
+ if (arg === "all-accessible-spaces") return new QueryClass({
154
+ type: "from",
155
+ query: this.ast,
156
+ from: {
157
+ _tag: "scope",
158
+ scopes: []
159
+ }
160
+ });
161
+ if (Array.isArray(arg) && arg.every(_isRawScope)) return new QueryClass({
162
+ type: "from",
163
+ query: this.ast,
164
+ from: {
165
+ _tag: "scope",
166
+ scopes: arg
167
+ }
168
+ });
169
+ if (_isRawScope(arg)) return new QueryClass({
170
+ type: "from",
171
+ query: this.ast,
172
+ from: {
173
+ _tag: "scope",
174
+ scopes: [arg]
175
+ }
176
+ });
177
+ const items = Array.isArray(arg) ? arg : [arg];
178
+ if (items.length > 0 && isDatabase(items[0])) {
179
+ const databases = items;
180
+ return new QueryClass({
181
+ type: "from",
182
+ query: this.ast,
183
+ from: {
184
+ _tag: "scope",
185
+ scopes: databases.map((db) => ({
186
+ _tag: "space",
187
+ spaceId: db.spaceId,
188
+ ...options?.includeFeeds ? { includeAllFeeds: true } : {}
189
+ }))
190
+ }
191
+ });
192
+ }
193
+ if (items.length > 0) {
194
+ const typename = getTypename(items[0]);
195
+ if (typename === "org.dxos.type.view") throw new Error("Query.from(view) is not yet supported.");
196
+ if (typename === "org.dxos.type.collection") throw new Error("Query.from(collection) is not yet supported.");
197
+ for (const item of items) {
198
+ const itemTypename = getTypename(item);
199
+ if (itemTypename !== "org.dxos.type.feed") throw new TypeError(`Query.from() expects Feed objects (org.dxos.type.feed), but received an object with typename '${itemTypename ?? "unknown"}'.`);
200
+ }
201
+ }
202
+ const feedScopes = items.map((feed) => {
203
+ const uri = EID.tryParse(getURI(feed));
204
+ if (!uri) throw new TypeError(`Query.from() expects persisted Feed objects with a feed URI; got feed without a space (id=${getURI(feed)}).`);
205
+ return {
206
+ _tag: "feed",
207
+ feedUri: String(uri)
208
+ };
209
+ });
210
+ return new QueryClass({
211
+ type: "from",
212
+ query: this.ast,
213
+ from: {
214
+ _tag: "scope",
215
+ scopes: feedScopes
216
+ }
217
+ });
218
+ }
219
+ options(options) {
220
+ return new QueryClass({
221
+ type: "options",
222
+ query: this.ast,
223
+ options
224
+ });
225
+ }
226
+ debugLabel(label) {
227
+ if (this.ast.type === "options") return new QueryClass({
228
+ type: "options",
229
+ query: this.ast.query,
230
+ options: {
231
+ ...this.ast.options,
232
+ debugLabel: label
233
+ }
234
+ });
235
+ return new QueryClass({
236
+ type: "options",
237
+ query: this.ast,
238
+ options: { debugLabel: label }
239
+ });
240
+ }
241
+ };
242
+ var is = (value) => {
243
+ return typeof value === "object" && value !== null && "~@dxos/echo/Query" in value;
244
+ };
245
+ /** Construct a query from an ast. */
246
+ var fromAst = (ast) => {
247
+ return new QueryClass(ast);
248
+ };
249
+ /**
250
+ * Select objects based on a filter.
251
+ * @param filter - Filter to select the objects.
252
+ * @returns Query for the selected objects.
253
+ */
254
+ var select = (filter) => {
255
+ return new QueryClass({
256
+ type: "select",
257
+ filter: filter.ast
258
+ });
259
+ };
260
+ /**
261
+ * Query for objects of a given schema.
262
+ * @param schema - Schema of the objects.
263
+ * @param predicates - Predicates to filter the objects.
264
+ * @returns Query for the objects.
265
+ *
266
+ * Shorthand for: `Query.select(Filter.type(schema, predicates))`.
267
+ */
268
+ var type = (type, predicates) => {
269
+ return new QueryClass({
270
+ type: "select",
271
+ filter: type$1(type, predicates).ast
272
+ });
273
+ };
274
+ /**
275
+ * Project a query's results to a single scalar property, for use as a membership set in
276
+ * `Filter.in(Query.project(query, 'col'))`.
277
+ * @param query - Query to project.
278
+ * @param property - Property path to project.
279
+ * @returns Projection for use in `Filter.in`.
280
+ */
281
+ var project = (query, property) => makeProjection(query.ast, property);
282
+ /**
283
+ * Combine results of multiple queries.
284
+ * @param queries - Queries to combine.
285
+ * @returns Query for the combined results.
286
+ */
287
+ var all = (...queries) => {
288
+ if (queries.length === 0) throw new TypeError("Query.all combines results of multiple queries, to query all objects use Query.select(Filter.everything())");
289
+ return new QueryClass({
290
+ type: "union",
291
+ queries: queries.map((q) => q.ast)
292
+ });
293
+ };
294
+ /**
295
+ * Subtract one query from another.
296
+ * @param source - Query to subtract from.
297
+ * @param exclude - Query to subtract.
298
+ * @returns Query for the results of the source query minus the results of the exclude query.
299
+ */
300
+ var without = (source, exclude) => {
301
+ return new QueryClass({
302
+ type: "set-difference",
303
+ source: source.ast,
304
+ exclude: exclude.ast
305
+ });
306
+ };
307
+ /**
308
+ * Create a query scoped to a data source.
309
+ * The returned query selects everything from the source; chain `.select()` to narrow results.
310
+ *
311
+ * @param source - Data source: database, feed, 'all-accessible-spaces', or another query.
312
+ * @returns Query scoped to the given source.
313
+ */
314
+ var from = (...args) => {
315
+ return new QueryClass({
316
+ type: "select",
317
+ filter: everything().ast
318
+ }).from(...args);
319
+ };
320
+ var SCOPE_TAGS = /* @__PURE__ */ new Set([
321
+ "space",
322
+ "feed",
323
+ "registry"
324
+ ]);
325
+ /** Detect a raw Scope tagged-union object. */
326
+ var _isRawScope = (value) => {
327
+ return typeof value === "object" && value !== null && !Array.isArray(value) && "_tag" in value && typeof value._tag === "string" && SCOPE_TAGS.has(value._tag);
328
+ };
329
+ /**
330
+ * Returns a human-readable string representation of a Query AST.
331
+ */
332
+ var pretty = (query) => prettyQuery(query.ast);
333
+ //#endregion
334
+ export { QueryTypeId, all, from, fromAst, is, pretty, project, select, Query_exports as t, type, without };
335
+
336
+ //# sourceMappingURL=Query.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Query.mjs","names":[],"sources":["../../src/Query.ts"],"sourcesContent":["//\n// Copyright 2025 DXOS.org\n//\n\n// @import-as-namespace\n\nimport type * as EffectArray from 'effect/Array';\nimport type * as Schema from 'effect/Schema';\n\nimport { type QueryAST } from '@dxos/echo-protocol';\nimport { EID, type URI } from '@dxos/keys';\n\nimport type * as Aggregate from './Aggregate';\nimport type * as Collection from './Collection';\nimport * as Database from './Database';\nimport type * as Dataset from './Dataset';\nimport type * as Feed from './Feed';\nimport * as Filter from './Filter';\nimport * as internal from './internal';\nimport * as Obj from './Obj';\nimport type * as Order from './Order';\nimport type * as Ref from './Ref';\nimport type * as Relation from './Relation';\n// eslint-disable-next-line @dxos/rules/import-as-namespace\nimport type * as Type$ from './Type';\nimport type * as View from './View';\n\n// TODO(dmaretskyi): Split up into interfaces for objects and relations so they can have separate verbs.\n// TODO(dmaretskyi): Undirected relation traversals.\n// TODO(wittjosiah): Make Filter & Query pipeable.\n\n/**\n * All property paths inside T that are references.\n */\n// TODO(dmaretskyi): Filter only properties that are references (or optional references, or unions that include references).\ntype RefPropKey<T> = keyof T & string;\n\ntype RefArrayElement<A> = A extends readonly (infer E)[] ? E : A extends (infer E)[] ? E : never;\n\n/** Target entity when traversing an outgoing ref or array-of-refs property. */\ntype ReferenceTraversalTarget<P> = P extends Ref.Unknown\n ? Ref.Target<P>\n : P extends Ref.Unknown | undefined\n ? Ref.Target<Exclude<P, undefined>>\n : RefArrayElement<P> extends Ref.Unknown\n ? Ref.Target<RefArrayElement<P>>\n : never;\n\n/**\n * Phantom brand on the flat row produced by {@link Query.aggregate}. Present only at the type level\n * (never at runtime), it lets hooks like `useQuery`/`usePagination` distinguish an aggregate-row\n * query from an entity query and avoid wrapping the row in `Entity.Entity`. The brand is a required\n * property so `T extends AggregateResult` discriminates — an optional one would be satisfied by any\n * type. Consumers never read it.\n */\nexport interface AggregateResult {\n readonly '~@dxos/echo/Query.AggregateResult': true;\n}\n\nexport const QueryTypeId = '~@dxos/echo/Query' as const;\nexport type QueryTypeId = typeof QueryTypeId;\n\n// TODO(burdon): Narrow T to Entity.Unknown?\nexport interface Query<T> {\n readonly [QueryTypeId]: { value: T };\n\n ast: QueryAST.Query;\n\n /**\n * Filter the current selection based on a filter.\n * @param filter - Filter to select the objects.\n * @returns Query for the selected objects.\n */\n select(filter: Filter.Filter<T>): Query<T>;\n select(props: Filter.Props<T>): Query<T>;\n\n /**\n * Project the query's results to a single scalar property, for use as a membership set in\n * `Filter.in(query.project('col'))` — an uncorrelated `col IN (SELECT property FROM ...)`\n * semi-join. The subquery is resolved once at execution time. A projection is a terminal\n * value, not a `Query`, so it cannot be chained further.\n * @param property - Property path to project.\n */\n project<K extends RefPropKey<T>>(property: K): Projection<T[K]>;\n\n /**\n * Traverse an outgoing reference.\n * @param key - Property path inside T that is a reference or optional reference.\n * @returns Query for the target of the reference.\n */\n reference<K extends RefPropKey<T>>(key: K): Query<ReferenceTraversalTarget<T[K]>>;\n\n /**\n * Find objects referencing this object.\n * @param target - Schema of the referencing object. If not provided, matches any type.\n * @param key - Property path inside the referencing object that is a reference. If not provided, matches any property.\n * @returns Query for the referencing objects.\n */\n // TODO(dmaretskyi): any way to enforce `Ref.Target<Schema.Schema.Type<S>[key]> == T`?\n // TODO(dmaretskyi): Ability to go through arrays of references.\n referencedBy<S extends Type$.AnyEntity>(\n target: S | URI.URI,\n key: RefPropKey<Type$.InstanceType<S>>,\n ): Query<Type$.InstanceType<S>>;\n referencedBy<S extends Type$.AnyEntity>(target: S | URI.URI): Query<Type$.InstanceType<S>>;\n referencedBy(): Query<any>;\n\n /**\n * Find relations where this object is the source.\n * @returns Query for the relation objects.\n * @param relation - Schema of the relation.\n * @param predicates - Predicates to filter the relation objects.\n */\n sourceOf<R extends Type$.AnyRelation>(\n relation?: R | URI.URI,\n predicates?: Filter.Props<Type$.InstanceType<R>>,\n ): Query<Type$.InstanceType<R>>;\n\n /**\n * Find relations where this object is the target.\n * @returns Query for the relation objects.\n * @param relation - Type entity of the relation.\n * @param predicates - Predicates to filter the relation objects.\n */\n targetOf<R extends Type$.AnyRelation>(\n relation?: R | URI.URI,\n predicates?: Filter.Props<Type$.InstanceType<R>>,\n ): Query<Type$.InstanceType<R>>;\n\n /**\n * For a query for relations, get the source objects.\n * @returns Query for the source objects.\n */\n source(): Query<Relation.SourceOf<T>>;\n\n /**\n * For a query for relations, get the target objects.\n * @returns Query for the target objects.\n */\n target(): Query<Relation.TargetOf<T>>;\n\n /**\n * Get the parent object of the current selection.\n * @returns Query for the parent objects.\n */\n parent(): Query<any>;\n\n /**\n * Get all child objects of the current selection.\n * @returns Query for the child objects.\n */\n children(): Query<any>;\n\n /**\n * Order the query results.\n * Orders are specified in priority order. The first order will be applied first, etc.\n *\n * `Order.property` orders by the current result shape's fields, so it works both before and after\n * an {@link aggregate}: before, by member (row) properties; after, by the flat record's fields\n * (any group or aggregate field — e.g. `Order.property('lastMessageAt')` reorders the groups by\n * that aggregate).\n * @param order - Order to sort the results.\n * @returns Query for the ordered results.\n */\n orderBy(...order: EffectArray.NonEmptyArray<Order.Order<T>>): Query<T>;\n\n /**\n * Aggregate the query results into flat records. {@link Aggregate.group} entries partition the\n * results into contiguous groups (one record each), keyed by the record field the group is named\n * after; with no `group` entries the entire input aggregates into a single record. Each declared\n * aggregate becomes a top-level field and can be ordered by with a following {@link orderBy} using\n * {@link Order.property}.\n *\n * Groups are ordered by the first occurrence of their key in the incoming stream, so a preceding\n * `orderBy` controls group order in the absence of a following one. {@link Aggregate.items}'s own\n * `order` option is a separate, explicit per-group member ordering — pass it there rather than\n * relying on a preceding `orderBy`, whose only well-defined job once `aggregate` follows is\n * establishing initial group order. For example, message threads ordered by their most recent\n * message, each retaining up to 20 members newest-first:\n *\n * ```ts\n * Query.type(Message)\n * .aggregate({\n * threadId: Aggregate.group('threadId'),\n * lastMessageAt: Aggregate.max('created'),\n * items: Aggregate.items({ limit: 20, order: [Order.property('created', 'desc')] }),\n * })\n * .orderBy(Order.property('lastMessageAt', 'desc'));\n * ```\n *\n * Must be the last data-selecting clause in the chain — only `from`/`options`/`orderBy`/`limit`/\n * `skip` may follow.\n * @param aggregates - Record of aggregate declarations keyed by result field name.\n * @returns Query whose flat result records carry the named aggregates as fields.\n */\n aggregate<const A extends Record<string, Aggregate.Aggregate<T, any>>>(\n aggregates: A,\n ): Query<Aggregate.AggregationResult<A>>;\n\n /**\n * Limit the number of results.\n * @param limit - Maximum number of results to return.\n * @returns Query for the limited results.\n */\n limit(limit: number): Query<T>;\n\n /**\n * Skip a number of results (offset). Combined with `orderBy` and `limit`, expresses a windowed\n * (paginated) read.\n * @param skip - Number of leading results to skip.\n * @returns Query for the remaining results.\n */\n skip(skip: number): Query<T>;\n\n /**\n * Query from selected databases only.\n *\n * Example:\n *\n * ```ts\n * Query.select(Filter.type(Person)).from(db);\n * ```\n *\n * @param options.includeFeeds [false] - Whether to include feeds in the query. Default is to query from automerge documents only.\n */\n from(database: Database.Database | Database.Database[], options?: { includeFeeds?: boolean }): Query<T>;\n\n /**\n * Query from selected feeds only.\n *\n * Example:\n *\n * ```ts\n * Query.select(Filter.type(Person)).from(feed);\n * ```\n *\n */\n from(feeds: Feed.Feed | Feed.Feed[]): Query<T>;\n\n /**\n * Query from all accessible spaces.\n *\n * Example:\n *\n * ```ts\n * Query.select(Filter.type(Person)).from('all-accessible-spaces');\n * ```\n *\n * @param options.includeFeeds [false] - Whether to include feeds in the query. Default is to query from automerge documents only.\n */\n from(allSpaces: 'all-accessible-spaces', options?: { includeFeeds?: boolean }): Query<T>;\n\n /**\n * Query from a dataset.\n * Currently only feeds are supported.\n *\n * Example:\n *\n * ```ts\n * Query.type(Person).from(feed);\n * ```\n */\n from(dataset: Dataset.Dataset): Query<T>;\n\n /**\n * Query from the results of another query.\n *\n * Example:\n *\n * ```ts\n * Query.select(Filter.props({ foo: 'foo' })).from(Query.select(Filter.type(Contact)).reference('org'));\n * ```\n */\n from(query: Any): Query<T>;\n\n /**\n * Query from one or more raw scopes.\n *\n * Use the {@link Scope} constructors rather than raw tagged objects:\n *\n * ```ts\n * Query.select(Filter.type(Type.Type)).from(Scope.space(), Scope.registry());\n * ```\n */\n from(...scopes: QueryAST.Scope[]): Query<T>;\n\n /**\n * Query from a raw scope or array of scopes.\n */\n from(scope: QueryAST.Scope | QueryAST.Scope[]): Query<T>;\n\n /**\n * Add options to a query.\n */\n options(options: QueryAST.QueryOptions): Query<T>;\n\n /**\n * Attach a diagnostic label for logs and tooling (execution semantics unchanged).\n */\n debugLabel(label: string): Query<T>;\n}\n\nexport type Any = Query<any>;\n\nexport type Type<Q extends Any> = Q extends Query<infer T> ? T : never;\n\n/**\n * A query projected to a single scalar property (see {@link Query.project}).\n */\nexport type Projection<V = unknown> = internal.Projection<V>;\n\n/**\n * Brand key for {@link Projection}. Re-exported (like {@link QueryTypeId}) so the sandboxed\n * `query-lite` mirror can declare its own local constant with the same string literal and\n * construct structurally-compatible projections without importing this module's runtime.\n */\nexport type ProjectionTypeId = internal.ProjectionTypeId;\n\nclass QueryClass implements Any {\n private static 'variance': Any[QueryTypeId] = {} as Any[QueryTypeId];\n\n constructor(public readonly ast: QueryAST.Query) {}\n\n [QueryTypeId] = QueryClass.variance;\n\n select(filter: Filter.Any | Filter.Props<any>): Any {\n if (Filter.is(filter)) {\n return new QueryClass({\n type: 'filter',\n selection: this.ast,\n filter: filter.ast,\n });\n } else {\n return new QueryClass({\n type: 'filter',\n selection: this.ast,\n filter: Filter.props(filter).ast,\n });\n }\n }\n\n project(property: string): Projection<any> {\n return internal.makeProjection(this.ast, property);\n }\n\n reference(key: string): Any {\n return new QueryClass({\n type: 'reference-traversal',\n anchor: this.ast,\n property: key,\n });\n }\n\n referencedBy(target?: Type$.AnyEntity | URI.URI, key?: string): Any {\n const uri = target !== undefined ? internal.getTypeURIFromSpecifier(target) : null;\n return new QueryClass({\n type: 'incoming-references',\n anchor: this.ast,\n property: key ?? null,\n typename: uri ?? null,\n });\n }\n\n sourceOf(relation?: Type$.AnyRelation | URI.URI, predicates?: Filter.Props<unknown> | undefined): Any {\n return new QueryClass({\n type: 'relation',\n anchor: this.ast,\n direction: 'outgoing',\n filter: relation !== undefined ? Filter.type(relation, predicates).ast : undefined,\n });\n }\n\n targetOf(relation?: Type$.AnyRelation | URI.URI, predicates?: Filter.Props<unknown> | undefined): Any {\n return new QueryClass({\n type: 'relation',\n anchor: this.ast,\n direction: 'incoming',\n filter: relation !== undefined ? Filter.type(relation, predicates).ast : undefined,\n });\n }\n\n source(): Any {\n return new QueryClass({\n type: 'relation-traversal',\n anchor: this.ast,\n direction: 'source',\n });\n }\n\n target(): Any {\n return new QueryClass({\n type: 'relation-traversal',\n anchor: this.ast,\n direction: 'target',\n });\n }\n\n parent(): Any {\n return new QueryClass({\n type: 'hierarchy-traversal',\n anchor: this.ast,\n direction: 'to-parent',\n });\n }\n\n children(): Any {\n return new QueryClass({\n type: 'hierarchy-traversal',\n anchor: this.ast,\n direction: 'to-children',\n });\n }\n\n orderBy(...order: Order.Any[]): Any {\n return new QueryClass({\n type: 'order',\n query: this.ast,\n order: order.map((o) => o.ast),\n });\n }\n\n aggregate(aggregates: Record<string, Aggregate.Any>): Any {\n return new QueryClass({\n type: 'aggregate',\n query: this.ast,\n aggregates: Object.entries(aggregates).map(([name, aggregate]) => ({ name, ...aggregate.spec })),\n });\n }\n\n limit(limit: number): Any {\n return new QueryClass({\n type: 'limit',\n query: this.ast,\n limit,\n });\n }\n\n skip(skip: number): Any {\n return new QueryClass({\n type: 'skip',\n query: this.ast,\n skip,\n });\n }\n\n from(\n ...args:\n | [\n (\n | Database.Database\n | Database.Database[]\n | Feed.Feed\n | Feed.Feed[]\n | Collection.Collection\n | View.View\n | Any\n | QueryAST.Scope\n | QueryAST.Scope[]\n | 'all-accessible-spaces'\n ),\n { includeFeeds?: boolean }?,\n ]\n | QueryAST.Scope[]\n ): Any {\n // Variadic raw scopes: `.from(Scope.space(), Scope.registry())`.\n if (args.length > 1 && args.every(_isRawScope)) {\n return new QueryClass({\n type: 'from',\n query: this.ast,\n from: { _tag: 'scope', scopes: args as QueryAST.Scope[] },\n });\n }\n\n const [arg, options] = args as [\n (\n | Database.Database\n | Database.Database[]\n | Feed.Feed\n | Feed.Feed[]\n | Collection.Collection\n | View.View\n | Any\n | QueryAST.Scope\n | QueryAST.Scope[]\n | 'all-accessible-spaces'\n ),\n { includeFeeds?: boolean }?,\n ];\n if (arg == null) {\n throw new TypeError(\n 'Query.from() requires a valid data source argument (database, feed, query, scope, or \"all-accessible-spaces\").',\n );\n }\n\n if (is(arg)) {\n return new QueryClass({\n type: 'from',\n query: this.ast,\n from: { _tag: 'query', query: arg.ast },\n });\n }\n\n if (arg === 'all-accessible-spaces') {\n return new QueryClass({\n type: 'from',\n query: this.ast,\n from: { _tag: 'scope', scopes: [] },\n });\n }\n\n // Raw scope(s): tagged union objects with _tag 'space' | 'feed' | 'registry'.\n if (Array.isArray(arg) && arg.every(_isRawScope)) {\n return new QueryClass({\n type: 'from',\n query: this.ast,\n from: { _tag: 'scope', scopes: arg as QueryAST.Scope[] },\n });\n }\n if (_isRawScope(arg)) {\n return new QueryClass({\n type: 'from',\n query: this.ast,\n from: { _tag: 'scope', scopes: [arg] },\n });\n }\n\n const items = Array.isArray(arg) ? arg : [arg];\n\n if (items.length > 0 && Database.isDatabase(items[0])) {\n const databases = items as Database.Database[];\n return new QueryClass({\n type: 'from',\n query: this.ast,\n from: {\n _tag: 'scope',\n scopes: databases.map((db) => ({\n _tag: 'space' as const,\n spaceId: db.spaceId,\n ...(options?.includeFeeds ? { includeAllFeeds: true } : {}),\n })),\n },\n });\n }\n\n if (items.length > 0) {\n const typename = Obj.getTypename(items[0] as Obj.Unknown);\n // TODO(dmaretskyi): Support querying from views.\n if (typename === 'org.dxos.type.view') {\n throw new Error('Query.from(view) is not yet supported.');\n }\n // TODO(dmaretskyi): Support querying from collections.\n if (typename === 'org.dxos.type.collection') {\n throw new Error('Query.from(collection) is not yet supported.');\n }\n // Validate that the items are feed objects. Checked by typename rather than schema instanceof\n // to keep this module free of a runtime dependency on the Feed module (avoids an import cycle).\n for (const item of items) {\n const itemTypename = Obj.getTypename(item as Obj.Unknown);\n if (itemTypename !== 'org.dxos.type.feed') {\n throw new TypeError(\n `Query.from() expects Feed objects (org.dxos.type.feed), but received an object with typename '${itemTypename ?? 'unknown'}'.`,\n );\n }\n }\n }\n\n const feedItems = items as Feed.Feed[];\n const feedScopes = feedItems.map((feed) => {\n // Inlined Feed.getFeedUri to avoid a runtime import cycle with the Feed module.\n const uri = EID.tryParse(Obj.getURI(feed));\n if (!uri) {\n throw new TypeError(\n `Query.from() expects persisted Feed objects with a feed URI; got feed without a space (id=${Obj.getURI(feed)}).`,\n );\n }\n return { _tag: 'feed' as const, feedUri: String(uri) };\n });\n return new QueryClass({\n type: 'from',\n query: this.ast,\n from: { _tag: 'scope', scopes: feedScopes },\n });\n }\n\n options(options: QueryAST.QueryOptions): Any {\n return new QueryClass({\n type: 'options',\n query: this.ast,\n options,\n });\n }\n\n debugLabel(label: string): Any {\n if (this.ast.type === 'options') {\n return new QueryClass({\n type: 'options',\n query: this.ast.query,\n options: { ...this.ast.options, debugLabel: label },\n });\n }\n return new QueryClass({\n type: 'options',\n query: this.ast,\n options: { debugLabel: label },\n });\n }\n}\n\nexport const is = (value: unknown): value is Any => {\n return typeof value === 'object' && value !== null && QueryTypeId in value;\n};\n\n/** Construct a query from an ast. */\nexport const fromAst = (ast: QueryAST.Query): Any => {\n return new QueryClass(ast);\n};\n\n/**\n * Select objects based on a filter.\n * @param filter - Filter to select the objects.\n * @returns Query for the selected objects.\n */\nexport const select = <F extends Filter.Any>(filter: F): Query<Filter.Type<F>> => {\n return new QueryClass({\n type: 'select',\n filter: filter.ast,\n });\n};\n\n/**\n * Query for objects of a given schema.\n * @param schema - Schema of the objects.\n * @param predicates - Predicates to filter the objects.\n * @returns Query for the objects.\n *\n * Shorthand for: `Query.select(Filter.type(schema, predicates))`.\n */\nexport const type: {\n <T extends Type$.AnyEntity>(type: T, predicates?: Filter.Props<Type$.InstanceType<T>>): Query<Type$.InstanceType<T>>;\n // Brand-narrowed schema overload — only well-known unknown schemas pass.\n <S extends internal.UnknownTypeSchema<any, any>>(\n schema: S,\n predicates?: Filter.Props<Schema.Schema.Type<S>>,\n ): Query<Schema.Schema.Type<S>>;\n <S extends Schema.Union<readonly Schema.Schema.AnyNoContext[]>>(\n union: S,\n predicates?: Filter.Props<Schema.Schema.Type<S>>,\n ): Query<Schema.Schema.Type<S>>;\n (uri: URI.URI, predicates?: Filter.Props<unknown>): Query<any>;\n} = (type: Type$.AnyEntity | URI.URI, predicates?: Filter.Props<unknown>): Any => {\n return new QueryClass({\n type: 'select',\n filter: Filter.type(type, predicates).ast,\n });\n};\n\n/**\n * Project a query's results to a single scalar property, for use as a membership set in\n * `Filter.in(Query.project(query, 'col'))`.\n * @param query - Query to project.\n * @param property - Property path to project.\n * @returns Projection for use in `Filter.in`.\n */\nexport const project = <T, K extends RefPropKey<T>>(query: Query<T>, property: K): Projection<T[K]> =>\n internal.makeProjection<T[K]>(query.ast, property);\n\n/**\n * Combine results of multiple queries.\n * @param queries - Queries to combine.\n * @returns Query for the combined results.\n */\n// TODO(dmaretskyi): Rename to `combine` or `union`.\nexport const all = (...queries: Any[]): Any => {\n if (queries.length === 0) {\n throw new TypeError(\n 'Query.all combines results of multiple queries, to query all objects use Query.select(Filter.everything())',\n );\n }\n return new QueryClass({\n type: 'union',\n queries: queries.map((q) => q.ast),\n });\n};\n\n/**\n * Subtract one query from another.\n * @param source - Query to subtract from.\n * @param exclude - Query to subtract.\n * @returns Query for the results of the source query minus the results of the exclude query.\n */\nexport const without = <T>(source: Query<T>, exclude: Query<T>): Query<T> => {\n return new QueryClass({\n type: 'set-difference',\n source: source.ast,\n exclude: exclude.ast,\n });\n};\n\n/**\n * Create a query scoped to a data source.\n * The returned query selects everything from the source; chain `.select()` to narrow results.\n *\n * @param source - Data source: database, feed, 'all-accessible-spaces', or another query.\n * @returns Query scoped to the given source.\n */\nexport const from = (\n ...args:\n | [\n (\n | Database.Database\n | Database.Database[]\n | Feed.Feed\n | Feed.Feed[]\n | Any\n | QueryAST.Scope\n | QueryAST.Scope[]\n | 'all-accessible-spaces'\n ),\n { includeFeeds?: boolean }?,\n ]\n | QueryAST.Scope[]\n): Any => {\n const baseQuery: QueryAST.Query = {\n type: 'select',\n filter: Filter.everything().ast,\n };\n const wrapper = new QueryClass(baseQuery);\n return (wrapper.from as (...args: unknown[]) => Any)(...args);\n};\n\nconst SCOPE_TAGS = new Set<string>(['space', 'feed', 'registry']);\n\n/** Detect a raw Scope tagged-union object. */\nconst _isRawScope = (value: unknown): value is QueryAST.Scope => {\n return (\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n '_tag' in value &&\n typeof value._tag === 'string' &&\n SCOPE_TAGS.has(value._tag)\n );\n};\n\n/**\n * Returns a human-readable string representation of a Query AST.\n */\nexport const pretty = (query: Any): string => internal.prettyQuery(query.ast);\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA2DA,IAAa,cAAc;AAmQ3B,IAAM,aAAN,MAAM,WAA0B;CAGF;CAF5B,OAAe,aAA+B,CAAC;CAE/C,YAAY,KAAqC;EAArB,KAAA,MAAA;CAAsB;CAElD,CAAC,eAAe,WAAW;CAE3B,OAAO,QAA6C;EAClD,IAAI,KAAU,MAAM,GAClB,OAAO,IAAI,WAAW;GACpB,MAAM;GACN,WA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AAC9D;AAEA,IAAM,6BAAa,IAAI,IAAY;CAAC;CAAS;CAAQ;AAAU,CAAC;;AAGhE,IAAM,eAAe,UAA4C;CAC/D,OACE,OAAO,UAAU,YACjB,UAAU,QACV,CAAC,MAAM,QAAQ,KAAK,KACpB,UAAU,SACV,OAAO,MAAM,SAAS,YACtB,WAAW,IAAI,MAAM,IAAI;AAE7B;;;;AAKA,IAAa,UAAU,UAAuB,YAAqB,MAAM,GAAG"}
@@ -0,0 +1,7 @@
1
+ import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
2
+ //#region src/QueryResult.ts
3
+ var QueryResult_exports = /* @__PURE__ */ __exportAll({});
4
+ //#endregion
5
+ export { QueryResult_exports as t };
6
+
7
+ //# sourceMappingURL=QueryResult.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"QueryResult.mjs","names":[],"sources":["../../src/QueryResult.ts"],"sourcesContent":["//\n// Copyright 2025 DXOS.org\n//\n\nimport type * as Atom from '@effect-atom/atom/Atom';\nimport type * as Effect from 'effect/Effect';\nimport type * as Option from 'effect/Option';\n\nimport { type CleanupFn } from '@dxos/async';\n\nimport type * as Entity from './Entity';\n\n/**\n * Individual query result entry.\n */\nexport type Entry<T> = {\n id: string;\n\n /**\n * May not be present for remote results.\n */\n result?: T;\n\n match?: {\n // TODO(dmaretskyi): text positional info.\n\n /**\n * Higher means better match.\n */\n rank: number;\n };\n\n /**\n * Query resolution metadata.\n */\n // TODO(dmaretskyi): Rename to meta?\n resolution?: {\n // TODO(dmaretskyi): Make this more generic.\n source: 'remote' | 'local' | 'index';\n\n /**\n * Query resolution time in milliseconds.\n */\n time: number;\n };\n};\n\n/**\n * Invidual query result entry for a database Entity.\n */\nexport type EntityEntry<T extends Entity.Unknown = Entity.Unknown> = Entry<T>;\n\nexport type RunOptions = {\n timeout?: number;\n};\n\nexport type SubscriptionOptions = {\n /**\n * Fire the callback immediately.\n */\n fire?: boolean;\n};\n\n// TODO(burdon): Should T be constrained to Entity.Any?\nexport interface QueryResult<T> {\n /**\n * Currently available results along with their match metadata.\n */\n readonly entries: Entry<T>[];\n\n /**\n * Currently available results.\n */\n readonly results: T[];\n\n /**\n * Returns all known results.\n */\n run(opts?: RunOptions): Promise<T[]>;\n\n /**\n * Returns all known results along with their match metadata.\n */\n runEntries(opts?: RunOptions): Promise<Entry<T>[]>;\n\n /**\n * Returns currently available results synchronously.\n */\n runSync(): T[];\n\n /**\n * Returns currently available results synchronously along with their match metadata.\n */\n runSyncEntries(): Entry<T>[];\n\n /**\n * Returns first result.\n */\n first(opts?: RunOptions): Promise<T>;\n\n /**\n * Returns first result if there is one.\n */\n firstOrUndefined(opts?: RunOptions): Promise<T | undefined>;\n\n /**\n * Subscribes to changes in query results.\n */\n subscribe(callback?: (query: QueryResult<T>) => void, opts?: SubscriptionOptions): CleanupFn;\n\n /**\n * Self-updating atom. Updates automatically when query results change.\n *\n * Memoized per QueryResult instance — repeated accesses on the same instance return the same\n * Atom. Safe only when the QueryResult is itself held stable across re-renders (e.g. behind a\n * `useMemo`). It must NOT be used in graph-builder connectors/actions or other atom computes,\n * where `db.query(...)` is called fresh on each re-evaluation: every run constructs a new\n * QueryResult and so a new atom + subscription, leaking the previous ones. Use the memoized\n * {@link atom} family there instead.\n */\n readonly atom: Atom.Atom<T[]>;\n}\n\n/**\n * Effect that returns a QueryResult when evaluated, but also has shorthand methods for running the query or getting the first result.\n */\nexport interface QueryResultEffect<T, E, R> extends Effect.Effect<QueryResult<T>, E, R> {\n run: Effect.Effect<T[], E, R>;\n first: Effect.Effect<Option.Option<T>, E, R>;\n\n // TODO(dmaretskyi): Considering adding `atom`, but since `Database.query` is used in imperative code only, I dont think it will be useful.\n}\n"],"mappings":""}
@@ -0,0 +1,44 @@
1
+ import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
2
+ import { n as Ref$1, u as getSchemaReference } from "./chunk-ref.mjs";
3
+ import { t as RefArray } from "./chunk-ref-array.mjs";
4
+ import * as Option from "effect/Option";
5
+ import * as SchemaAST from "effect/SchemaAST";
6
+ //#region src/Ref.ts
7
+ var Ref_exports = /* @__PURE__ */ __exportAll({
8
+ Array: () => Array,
9
+ Ref: () => Ref,
10
+ fromURI: () => fromURI,
11
+ hasEntityId: () => hasEntityId,
12
+ isRef: () => isRef,
13
+ isRefType: () => isRefType,
14
+ make: () => make
15
+ });
16
+ /**
17
+ * Factory function to create a Ref schema for the given target schema.
18
+ * Use this in schema definitions to declare reference fields.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * class Task extends Type.makeObject<Task>(DXN.make('com.example.type.task', '0.1.0'))(
23
+ * Schema.Struct({
24
+ * assignee: Ref.Ref(Person), // Creates a Ref schema
25
+ * }),
26
+ * ) {}
27
+ * ```
28
+ */
29
+ var Ref = Ref$1;
30
+ var Array = RefArray;
31
+ var isRef = Ref$1.isRef;
32
+ var make = Ref$1.make;
33
+ var fromURI = (uri) => Ref$1.fromURI(uri);
34
+ var hasEntityId = Ref$1.hasEntityId;
35
+ var isRefType = (ast) => {
36
+ return SchemaAST.getAnnotation(ast, SchemaAST.JSONSchemaAnnotationId).pipe(Option.flatMap((jsonSchema) => "$id" in jsonSchema ? Option.some(jsonSchema) : Option.none()), Option.flatMap((jsonSchema) => {
37
+ const { typename } = getSchemaReference(jsonSchema) ?? {};
38
+ return typename ? Option.some(true) : Option.some(false);
39
+ }), Option.getOrElse(() => false));
40
+ };
41
+ //#endregion
42
+ export { Array, Ref, fromURI, hasEntityId, isRef, isRefType, make, Ref_exports as t };
43
+
44
+ //# sourceMappingURL=Ref.mjs.map